{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: allocate\n\nDocumentation:\nHelper function to allocate memory with the given allocator (may crash if the `len` is 0).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn allocate>(alloc: &mut A, len: usize) -> A::AllocatedMemory {\n A::alloc_cell(alloc, len)\n}\n```"}], "func_name": "allocate", "docstring": "Helper function to allocate memory with the given allocator (may crash if the `len` is 0).", "repo": "dropbox/rust-brotli", "path": "src/enc/combined_alloc.rs", "url": "https://github.com/dropbox/rust-brotli/blob/master/src/enc/combined_alloc.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "010d79275a1cae37e50abf23731d0a3e0517f2ad3212f968459155e62fee7e60"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: alloc_if\n\nDocumentation:\nHelper function to allocate memory or return a default value if the condition is false\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn alloc_if>(\n condition: bool,\n alloc: &mut A,\n len: usize,\n) -> A::AllocatedMemory {\n if condition {\n allocate(alloc, len)\n } else {\n alloc_default::()\n }\n}\n```"}], "func_name": "alloc_if", "docstring": "Helper function to allocate memory or return a default value if the condition is false", "repo": "dropbox/rust-brotli", "path": "src/enc/combined_alloc.rs", "url": "https://github.com/dropbox/rust-brotli/blob/master/src/enc/combined_alloc.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e2072924cbe2833bcceb1ac8ec8f1e19a267c6fa07036780535b39eec13fe4c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: alloc_or_default\n\nDocumentation:\nHelper function to allocate memory or return a default value when the size is 0.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn alloc_or_default>(\n alloc: &mut A,\n len: usize,\n) -> A::AllocatedMemory {\n alloc_if(len > 0, alloc, len)\n}\n```"}], "func_name": "alloc_or_default", "docstring": "Helper function to allocate memory or return a default value when the size is 0.", "repo": "dropbox/rust-brotli", "path": "src/enc/combined_alloc.rs", "url": "https://github.com/dropbox/rust-brotli/blob/master/src/enc/combined_alloc.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f38ed34a66eb37072b7d35990a13e539f3417d238d4d7218f5c2d7ef7fa4fc0d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fix_unbroken_len\n\nDocumentation:\nThis code takes a length and checks if there's an \"end of dictionary\" marker at the\n\"ring_buffer_break\"point. This marks where a backwards reference cannot pull data through.\nA match must stop at the end of the dictionary and cannot span the end of the dictionary\nand beginning of the file. ring_buffer_break is only set true for custom LZ77 dictionary.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fix_unbroken_len(unbroken_len: usize, prev_ix: usize, _cur_ix_masked: usize, ring_buffer_break: Option) -> usize\n{\n if let Some(br) = ring_buffer_break {\n if prev_ix < usize::from(br) && prev_ix + unbroken_len > usize::from(br)\n {\n return usize::from(br) - prev_ix;\n }\n }\n return unbroken_len;\n}\n```"}], "func_name": "fix_unbroken_len", "docstring": "This code takes a length and checks if there's an \"end of dictionary\" marker at the\n\"ring_buffer_break\"point. This marks where a backwards reference cannot pull data through.\nA match must stop at the end of the dictionary and cannot span the end of the dictionary\nand beginning of the file. ring_buffer_break is only set true for custom LZ77 dictionary.", "repo": "dropbox/rust-brotli", "path": "src/enc/backward_references/mod.rs", "url": "https://github.com/dropbox/rust-brotli/blob/master/src/enc/backward_references/mod.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b74e228d6538055062274ef2c2e940a948880cd687698c59e9f0b0b911cb336"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new usage error with `message`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new>(message: T) -> Self {\n Self { message: message.into() }\n }\n```"}], "func_name": "new", "docstring": "Creates a new usage error with `message`.", "repo": "endbasic/endbasic", "path": "cli/src/main.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ce4b598c7213e795ab33167b9aa0dbc915f650ed281a87a98edf1232dd106641"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: program_name\n\nDocumentation:\nConsumes and returns the program name from `env::Args`.\n\nIf the program name cannot be obtained, return `default_name` instead.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn program_name(mut args: env::Args, default_name: &'static str) -> (String, env::Args) {\n let name = match args.next() {\n Some(arg0) => match Path::new(&arg0).file_stem() {\n Some(basename) => match basename.to_str() {\n Some(s) => s.to_owned(),\n None => default_name.to_owned(),\n },\n None => default_name.to_owned(),\n },\n None => default_name.to_owned(),\n };\n (name, args)\n}\n```"}], "func_name": "program_name", "docstring": "Consumes and returns the program name from `env::Args`.\n\nIf the program name cannot be obtained, return `default_name` instead.", "repo": "endbasic/endbasic", "path": "cli/src/main.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f11e478773fb47da2f6b54a7f2be8b72a3b36143421d5c9abf093c4254878314"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: help\n\nDocumentation:\nPrints usage information for program `name` with `opts` following the GNU Standards format.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn help(name: &str, opts: &Options) {\n let brief = format!(\"Usage: {} [options] [program-file]\", name);\n println!(\"{}\", opts.usage(&brief));\n println!(\"CONSOLE-SPEC can be one of the following:\");\n if cfg!(feature = \"sdl\") {\n println!(\" sdl[:SPEC] enables the graphical console and configures it\");\n println!(\" with the settings in SPEC, which is of the form:\");\n println!(\" resolution=RESOLUTION,fg_color=COLOR,bg_color=COLOR,\");\n println!(\" font_path=TTF,font_size=SIZE\");\n println!(\" individual components of the SPEC can be omitted\");\n println!(\" RESOLUTION can be one of 'fs' (for full screen),\");\n println!(\" 'WIDTHxHEIGHT' or 'WIDTHxHEIGHTfs'\");\n }\n if cfg!(feature = \"rpi\") {\n println!(\" st7735s[:SPEC] enables the ST7735S LCD console and configures it\");\n println!(\" with the settings in SPEC, which is of the form:\");\n println!(\" fg_color=COLOR,bg_color=COLOR,font=NAME\");\n }\n println!(\" text enables the text-based console\");\n println!();\n println!(\"Report bugs to: https://github.com/endbasic/endbasic/issues\");\n println!(\"EndBASIC home page: https://www.endbasic.dev/\");\n}\n```"}], "func_name": "help", "docstring": "Prints usage information for program `name` with `opts` following the GNU Standards format.", "repo": "endbasic/endbasic", "path": "cli/src/main.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7779d2824362534d971a8733eaaf9bde155b79a636488f45cc6708af9d926d02"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: version\n\nDocumentation:\nPrints version information following the GNU Standards format.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn version() {\n println!(\"EndBASIC {}\", env!(\"CARGO_PKG_VERSION\"));\n println!(\"Copyright 2020-2025 Julio Merino\");\n println!(\"License Apache Version 2.0 \");\n}\n```"}], "func_name": "version", "docstring": "Prints version information following the GNU Standards format.", "repo": "endbasic/endbasic", "path": "cli/src/main.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f9a7814f01360041818a477aeb420de0e8aae74abd745ddac6252b86baa9218f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_machine_builder\n\nDocumentation:\nCreates a new EndBASIC machine builder based on the features enabled in this crate.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_machine_builder(console_spec: Option<&str>) -> io::Result {\n /// Obtains the default set of pins for a Raspberry Pi.\n #[cfg(feature = \"rpi\")]\n fn add_gpio_pins(builder: endbasic_std::MachineBuilder) -> endbasic_std::MachineBuilder {\n // TODO(jmmv): If st7735s is in use, this basically creates a secondary set of pins.\n // Which... should work OK, but then the user can interfere with the display in ways that\n // should not be allowed, probably.\n builder.with_gpio_pins(Rc::from(RefCell::from(endbasic_rpi::RppalPins::default())))\n }\n\n /// Obtains the default set of pins for a platform without GPIO support.\n #[cfg(not(feature = \"rpi\"))]\n fn add_gpio_pins(builder: endbasic_std::MachineBuilder) -> endbasic_std::MachineBuilder {\n builder\n }\n\n let signals_chan = async_channel::unbounded();\n let mut builder = endbasic_std::MachineBuilder::default();\n builder = builder.with_console(setup_console(console_spec, signals_chan.0.clone())?);\n builder = builder.with_signals_chan(signals_chan);\n builder = add_gpio_pins(builder);\n Ok(builder)\n}\n```"}], "func_name": "new_machine_builder", "docstring": "Creates a new EndBASIC machine builder based on the features enabled in this crate.", "repo": "endbasic/endbasic", "path": "cli/src/main.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a028f5740fba01a6dc28e9e32bb4c7c12ca432ca3a3f699f0f32b85b19d1fe83"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_interactive\n\nDocumentation:\nTurns a regular machine builder into an interactive builder ensuring common features for all\ncallers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn make_interactive(\n builder: endbasic_std::MachineBuilder,\n) -> endbasic_std::InteractiveMachineBuilder {\n builder\n .make_interactive()\n .with_program(Rc::from(RefCell::from(endbasic_repl::editor::Editor::default())))\n}\n```"}], "func_name": "make_interactive", "docstring": "Turns a regular machine builder into an interactive builder ensuring common features for all\ncallers.", "repo": "endbasic/endbasic", "path": "cli/src/main.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b7740d633ee5b2ba5e51f30f2b4df17d274a84aae0f746105eac5772035a906a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish_interactive_build\n\nDocumentation:\nCompletes the build of an interactive machine by taking a partial builder and running post-build\nsteps on it.\n\n`service_url` is the base URL of the cloud service.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn finish_interactive_build(\n mut builder: endbasic_std::InteractiveMachineBuilder,\n service_url: &str,\n) -> Result {\n let console = builder.get_console();\n let storage = builder.get_storage();\n\n let mut machine = builder.build()?;\n\n let service = Rc::from(RefCell::from(endbasic_client::CloudService::new(service_url)?));\n endbasic_client::add_all(&mut machine, service, console, storage, \"https://repl.endbasic.dev/\");\n\n Ok(machine)\n}\n```"}], "func_name": "finish_interactive_build", "docstring": "Completes the build of an interactive machine by taking a partial builder and running post-build\nsteps on it.\n\n`service_url` is the base URL of the cloud service.", "repo": "endbasic/endbasic", "path": "cli/src/main.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "70f5a337dc4c6d78f398ad23c2f6ff7a4a2b9a9d20d9545f7795d9fa074d922c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_local_drive_spec\n\nDocumentation:\nReturns `flag` if present, or else returns the URI of the default `LOCAL` drive.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_local_drive_spec(flag: Option) -> Result {\n let dir = flag.or_else(|| {\n dirs::document_dir().map(|d| format!(\"file://{}\", d.join(\"endbasic\").display())).or_else(\n || {\n // On Linux, dirs::document_dir() seems to return None whenever user-dirs.dirs is\n // not present... which is suboptimal. Compute a reasonable default based on the\n // home directory.\n dirs::home_dir()\n .map(|h| format!(\"file://{}\", h.join(\"Documents/endbasic\").display()))\n },\n )\n });\n\n // Instead of aborting on a missing programs directory, we could disable the LOAD/SAVE commands\n // when we cannot compute this folder, but that seems like hiding a corner case that is unlikely\n // to surface. A good reason to do this, however, would be to allow the user to explicitly\n // disable this functionality to keep the interpreter from touching the disk.\n match dir {\n Some(dir) => Ok(dir),\n None => Err(anyhow!(\"Cannot compute default path to the Documents folder\")),\n }\n}\n```"}], "func_name": "get_local_drive_spec", "docstring": "Returns `flag` if present, or else returns the URI of the default `LOCAL` drive.", "repo": "endbasic/endbasic", "path": "cli/src/main.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e0033e0416a980b101e4c8300fd1cbfed72a1fee7b76b0994f0e2c27ffcd8434"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: setup_storage\n\nDocumentation:\nSets up the common storage drives.\n\nThis instantiates non-optional drives, such as `MEMORY:` and `DEMOS:`, maps `LOCAL` the\nlocation given in `local_drive_spec`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn setup_storage(storage: &mut Storage, local_drive_spec: &str) -> io::Result<()> {\n storage.register_scheme(\"demos\", Box::from(endbasic_repl::demos::DemoDriveFactory::default()));\n storage.mount(\"demos\", \"demos://\").expect(\"Demos drive shouldn't fail to mount\");\n storage.register_scheme(\n \"file\",\n Box::from(endbasic_std::storage::DirectoryDriveFactory::default()),\n );\n storage.mount(\"local\", local_drive_spec)?;\n storage.cd(\"local:\").expect(\"Local drive was just registered\");\n Ok(())\n}\n```"}], "func_name": "setup_storage", "docstring": "Sets up the common storage drives.\n\nThis instantiates non-optional drives, such as `MEMORY:` and `DEMOS:`, maps `LOCAL` the\nlocation given in `local_drive_spec`.", "repo": "endbasic/endbasic", "path": "cli/src/main.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d3042927320f778717b9f8ce35e0a845c57e14b031d63565688437de649bf260"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_repl_loop\n\nDocumentation:\nEnters the interactive interpreter.\n\n`local_drive` is the optional local drive to mount and use as the default location.\n`service_url` is the base URL of the cloud service.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_repl_loop(\n console_spec: Option<&str>,\n local_drive_spec: &str,\n service_url: &str,\n) -> Result {\n let mut builder = make_interactive(new_machine_builder(console_spec)?);\n\n let console = builder.get_console();\n let program = builder.get_program();\n\n let storage = builder.get_storage();\n setup_storage(&mut storage.borrow_mut(), local_drive_spec)?;\n\n let mut machine = finish_interactive_build(builder, service_url)?;\n endbasic_repl::print_welcome(console.clone())?;\n endbasic_repl::try_load_autoexec(&mut machine, console.clone(), storage).await?;\n Ok(endbasic_repl::run_repl_loop(&mut machine, console, program).await?)\n}\n```"}], "func_name": "run_repl_loop", "docstring": "Enters the interactive interpreter.\n\n`local_drive` is the optional local drive to mount and use as the default location.\n`service_url` is the base URL of the cloud service.", "repo": "endbasic/endbasic", "path": "cli/src/main.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "91ad9aa6cae568d6e332ef707920421e5cb83326505852343113a1d45dfbb80c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_script\n\nDocumentation:\nExecutes the `path` program in a fresh machine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_script>(path: P, console_spec: Option<&str>) -> Result {\n let mut machine = new_machine_builder(console_spec)?.build()?;\n let mut input = File::open(path)?;\n Ok(machine.exec(&mut input).await?.as_exit_code())\n}\n```"}], "func_name": "run_script", "docstring": "Executes the `path` program in a fresh machine.", "repo": "endbasic/endbasic", "path": "cli/src/main.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3b4b95928ade91b9fe5a148bac113272637c9c5d4d8024ea0294385ab527b5b9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_interactive\n\nDocumentation:\nExecutes the `path` program in a fresh machine allowing any interactive-only calls.\n\n`local_drive` is the optional local drive to mount and use as the default location.\n`service_url` is the base URL of the cloud service.\n\nIf `path` starts with `cloud://`, this uses the same auto-run features that the web UI\nexposes. The presence of this here is kind of a hack but avoids having too much logic\njust in the web and helps test this feature.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_interactive(\n path: &str,\n console_spec: Option<&str>,\n local_drive_spec: &str,\n service_url: &str,\n) -> Result {\n let mut builder = make_interactive(new_machine_builder(console_spec)?);\n\n let console = builder.get_console();\n let program = builder.get_program();\n\n let storage = builder.get_storage();\n setup_storage(&mut storage.borrow_mut(), local_drive_spec)?;\n\n let mut machine = finish_interactive_build(builder, service_url)?;\n\n match path.strip_prefix(\"cloud://\") {\n Some(username_path) => {\n let code = endbasic_repl::run_from_cloud(\n &mut machine,\n console.clone(),\n storage.clone(),\n program.clone(),\n username_path,\n false,\n )\n .await?;\n Ok(code)\n }\n None => {\n let mut input = File::open(path)?;\n Ok(machine.exec(&mut input).await?.as_exit_code())\n }\n }\n}\n```"}], "func_name": "run_interactive", "docstring": "Executes the `path` program in a fresh machine allowing any interactive-only calls.\n\n`local_drive` is the optional local drive to mount and use as the default location.\n`service_url` is the base URL of the cloud service.\n\nIf `path` starts with `cloud://`, this uses the same auto-run features that the web UI\nexposes. The presence of this here is kind of a hack but avoids having too much logic\njust in the web and helps test this feature.", "repo": "endbasic/endbasic", "path": "cli/src/main.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "88f8357d909b812b0f52739f72f25ce6bdccb303155bfe9fd0235ab71a69354d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: safe_main\n\nDocumentation:\nVersion of `main` that returns errors to the caller for reporting.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn safe_main(name: &str, args: env::Args) -> Result {\n let args: Vec = args.collect();\n\n let mut opts = Options::new();\n opts.optopt(\"\", \"console\", \"type and properties of the console to use\", \"CONSOLE-SPEC\");\n opts.optflag(\"h\", \"help\", \"show command-line usage information and exit\");\n opts.optflag(\"i\", \"interactive\", \"force interactive mode when running a script\");\n opts.optopt(\"\", \"local-drive\", \"location of the drive to mount as LOCAL\", \"URI\");\n opts.optopt(\"\", \"service-url\", \"base URL of the cloud service\", \"URL\");\n opts.optflag(\"\", \"version\", \"show version information and exit\");\n let matches = opts.parse(args)?;\n\n if matches.opt_present(\"help\") {\n help(name, &opts);\n return Ok(0);\n }\n\n if matches.opt_present(\"version\") {\n version();\n return Ok(0);\n }\n\n let console_spec = matches.opt_str(\"console\");\n\n let service_url = matches\n .opt_str(\"service-url\")\n .unwrap_or_else(|| endbasic_client::PROD_API_ADDRESS.to_owned());\n\n match matches.free.as_slice() {\n [] => {\n let local_drive = get_local_drive_spec(matches.opt_str(\"local-drive\"))?;\n Ok(run_repl_loop(console_spec.as_deref(), &local_drive, &service_url).await?)\n }\n [file] => {\n if matches.opt_present(\"interactive\") {\n let local_drive = get_local_drive_spec(matches.opt_str(\"local-drive\"))?;\n Ok(run_interactive(file, console_spec.as_deref(), &local_drive, &service_url)\n .await?)\n } else {\n Ok(run_script(file, console_spec.as_deref()).await?)\n }\n }\n [_, ..] => Err(UsageError::new(\"Too many arguments\").into()),\n }\n}\n```"}], "func_name": "safe_main", "docstring": "Version of `main` that returns errors to the caller for reporting.", "repo": "endbasic/endbasic", "path": "cli/src/main.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0f7cb7b5e094cf957ba95b30f61b087525ff3e93a530320225fddb4a949637ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: self_dir\n\nDocumentation:\nComputes the path to the directory where this test's binary lives.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn self_dir() -> PathBuf {\n let self_exe = env::current_exe().expect(\"Cannot get self's executable path\");\n let dir = self_exe.parent().expect(\"Cannot get self's directory\");\n assert!(dir.ends_with(\"target/debug/deps\") || dir.ends_with(\"target/release/deps\"));\n dir.to_owned()\n}\n```"}], "func_name": "self_dir", "docstring": "Computes the path to the directory where this test's binary lives.", "repo": "endbasic/endbasic", "path": "cli/tests/integration_test.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/tests/integration_test.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aebcbf80a547cdf4ce98bffc4c31e646b9c3c1a1c640ca176ec4bcd5b791b95e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bin_path\n\nDocumentation:\nComputes the path to the built binary `name`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn bin_path>(name: P) -> PathBuf {\n let test_dir = self_dir();\n let debug_or_release_dir = test_dir.parent().expect(\"Failed to get parent directory\");\n debug_or_release_dir.join(name).with_extension(env::consts::EXE_EXTENSION)\n}\n```"}], "func_name": "bin_path", "docstring": "Computes the path to the built binary `name`.", "repo": "endbasic/endbasic", "path": "cli/tests/integration_test.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/tests/integration_test.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "28991f5d639df8af2d75719fd2d8d4ff9bd4ef349f8f1d0f2d74883b17496440"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: src_path\n\nDocumentation:\nComputes the path to the source file `name`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn src_path(name: &str) -> PathBuf {\n let test_dir = self_dir();\n let debug_or_release_dir = test_dir.parent().expect(\"Failed to get parent directory\");\n let target_dir = debug_or_release_dir.parent().expect(\"Failed to get parent directory\");\n let dir = target_dir.parent().expect(\"Failed to get parent directory\");\n\n // Sanity-check that we landed in the right location.\n assert!(dir.join(\"Cargo.toml\").exists());\n\n dir.join(name)\n}\n```"}], "func_name": "src_path", "docstring": "Computes the path to the source file `name`.", "repo": "endbasic/endbasic", "path": "cli/tests/integration_test.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/tests/integration_test.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "409fe1d7475bce7da814f1f694267e46b7d7ac5d3a621a5db896707e9832f45c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: src_str\n\nDocumentation:\nSame as `src_path` but returns a string reference for the few places where we need this.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn src_str(p: &str) -> String {\n src_path(p).to_str().expect(\"Need paths to be valid strings\").to_owned()\n}\n```"}], "func_name": "src_str", "docstring": "Same as `src_path` but returns a string reference for the few places where we need this.", "repo": "endbasic/endbasic", "path": "cli/tests/integration_test.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/tests/integration_test.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51c5e0cb73c552c55905bc03f4a40b7bc5c73d89e23e34dabd3185266c9373a1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_golden\n\nDocumentation:\nReads the contents of a golden data file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_golden(path: &Path) -> String {\n let mut f = File::open(path).expect(\"Failed to open golden data file\");\n let mut golden = vec![];\n f.read_to_end(&mut golden).expect(\"Failed to read golden data file\");\n let raw = String::from_utf8(golden).expect(\"Golden data file is not valid UTF-8\");\n let golden = if cfg!(target_os = \"windows\") { raw.replace(\"\\r\\n\", \"\\n\") } else { raw };\n\n // This is the opposite of apply_mocks and ensures we don't leak actual values into the golden\n // files by mistake.\n let version_re = regex::Regex::new(VERSION_RE).unwrap();\n assert!(\n !version_re.is_match(&golden),\n \"Golden file {} contains a version number\",\n path.display()\n );\n let date_re = regex::Regex::new(DATE_RE).unwrap();\n assert!(!date_re.is_match(&golden), \"Golden file {} contains a date\", path.display());\n let year_range_re = regex::Regex::new(YEAR_RANGE_RE).unwrap();\n assert!(\n !year_range_re.is_match(&golden),\n \"Golden file {} contains a year range\",\n path.display()\n );\n\n golden\n}\n```"}], "func_name": "read_golden", "docstring": "Reads the contents of a golden data file.", "repo": "endbasic/endbasic", "path": "cli/tests/integration_test.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/tests/integration_test.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "958546e32e83f1d2843b23b7e7aa826c6c6f634b72f0f74626fa7970cc479393"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: apply_mocks\n\nDocumentation:\nReplaces the parts of the output that can change due to the environment with placeholders.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn apply_mocks(input: String) -> String {\n let version_re = regex::Regex::new(VERSION_RE).unwrap();\n let input = version_re.replace_all(&input, \"X.Y.Z\").into_owned();\n\n let date_re = regex::Regex::new(DATE_RE).unwrap();\n let input = date_re.replace_all(&input, \"YYYY-MM-DD HH:MM\").into_owned();\n\n let year_range_re = regex::Regex::new(YEAR_RANGE_RE).unwrap();\n let input = year_range_re.replace_all(&input, \"YYYY-YYYY\").into_owned();\n\n let file_uri_re = regex::Regex::new(FILE_URI_RE).unwrap();\n file_uri_re.replace_all(&input, \"file:///PATH/TO/TMPDIR\").into()\n}\n```"}], "func_name": "apply_mocks", "docstring": "Replaces the parts of the output that can change due to the environment with placeholders.", "repo": "endbasic/endbasic", "path": "cli/tests/integration_test.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/tests/integration_test.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "59167ca26e4c1dadc2a24fef6c9b53d4b597e8ffb316c588b74df20f117098e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check\n\nDocumentation:\nRuns `bin` with arguments `args` and checks its behavior against expectations.\n\n`exp_code` is the expected error code from the program. `stdin_behavior` indicates what to feed\nto the program's stdin. `stdout_behavior` and `stderr_behavior` indicate what to expect from\nthe program's textual output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check>(\n bin: P,\n args: &[&str],\n exp_code: i32,\n stdin_behavior: Behavior,\n stdout_behavior: Behavior,\n stderr_behavior: Behavior,\n) {\n let golden_stdin = match stdin_behavior {\n Behavior::Null => process::Stdio::null(),\n Behavior::File(path) => File::open(path).unwrap().into(),\n Behavior::Literal(_) => panic!(\"Literals not supported for stdin\"),\n };\n\n let exp_stdout = match stdout_behavior {\n Behavior::Null => \"\".to_owned(),\n Behavior::File(path) => read_golden(&path),\n Behavior::Literal(text) => text,\n };\n\n let exp_stderr = match stderr_behavior {\n Behavior::Null => \"\".to_owned(),\n Behavior::File(path) => read_golden(&path),\n Behavior::Literal(text) => text,\n };\n\n let result = process::Command::new(bin.as_ref())\n .args(args)\n .stdin(golden_stdin)\n .env(\"LINES\", \"24\")\n .env(\"COLUMNS\", \"80\")\n .output()\n .expect(\"Failed to execute subprocess\");\n let code = result.status.code().expect(\"Subprocess didn't exit cleanly\");\n let stdout =\n apply_mocks(String::from_utf8(result.stdout).expect(\"Stdout not is not valid UTF-8\"));\n let stderr =\n apply_mocks(String::from_utf8(result.stderr).expect(\"Stderr not is not valid UTF-8\"));\n\n if exp_code != code || exp_stdout != stdout || exp_stderr != stderr {\n eprintln!(\"Exit code: {}\", code);\n eprintln!(\"stdout:\\n{}\", stdout);\n eprintln!(\"stderr:\\n{}\", stderr);\n assert_eq!(exp_code, code);\n assert_eq!(exp_stdout, stdout);\n assert_eq!(exp_stderr, stderr);\n }\n}\n```"}], "func_name": "check", "docstring": "Runs `bin` with arguments `args` and checks its behavior against expectations.\n\n`exp_code` is the expected error code from the program. `stdin_behavior` indicates what to feed\nto the program's stdin. `stdout_behavior` and `stderr_behavior` indicate what to expect from\nthe program's textual output.", "repo": "endbasic/endbasic", "path": "cli/tests/integration_test.rs", "url": "https://github.com/endbasic/endbasic/blob/master/cli/tests/integration_test.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b39245b25fed1f3b40554d0f70b6aad9738819d22582a130b7495e74a07f4d78"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: http_response_to_io_error\n\nDocumentation:\nConverts a `reqwest::Response` to an `io::Error`. The response should have a non-OK status.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn http_response_to_io_error(response: Response) -> io::Error {\n let status = response.status();\n\n let kind = match status {\n StatusCode::OK => panic!(\"Should not have been called on a successful request\"),\n\n // Match against the codes we know the server explicitly hands us.\n StatusCode::BAD_REQUEST => io::ErrorKind::InvalidInput,\n StatusCode::FORBIDDEN => io::ErrorKind::PermissionDenied,\n StatusCode::INSUFFICIENT_STORAGE => io::ErrorKind::Other,\n StatusCode::INTERNAL_SERVER_ERROR => io::ErrorKind::Other,\n StatusCode::NOT_FOUND => io::ErrorKind::NotFound,\n StatusCode::PAYLOAD_TOO_LARGE => io::ErrorKind::InvalidInput,\n StatusCode::SERVICE_UNAVAILABLE => io::ErrorKind::AddrNotAvailable,\n StatusCode::UNAUTHORIZED => io::ErrorKind::PermissionDenied,\n\n _ => io::ErrorKind::Other,\n };\n\n match response.text().await {\n Ok(text) => match serde_json::from_str::(&text) {\n Ok(response) => io::Error::new(\n kind,\n format!(\"{} (server code: {})\", remove_control_chars(response.message), status),\n ),\n _ => io::Error::new(\n kind,\n format!(\n \"HTTP request returned status {} with text '{}'\",\n status,\n remove_control_chars(text)\n ),\n ),\n },\n Err(e) => io::Error::new(\n kind,\n format!(\n \"HTTP request returned status {} and failed to get text due to {}\",\n status,\n remove_control_chars(e.to_string())\n ),\n ),\n }\n}\n```"}], "func_name": "http_response_to_io_error", "docstring": "Converts a `reqwest::Response` to an `io::Error`. The response should have a non-OK status.", "repo": "endbasic/endbasic", "path": "client/src/cloud.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cloud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94b92e02b88b59d5ba480eeec9e26643c6bbb4b57586397bb8b4fb6572822f88"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reqwest_error_to_io_error\n\nDocumentation:\nConverts a `reqwest::Error` to an `io::Error`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reqwest_error_to_io_error(e: reqwest::Error) -> io::Error {\n io::Error::other(format!(\"{}\", e))\n}\n```"}], "func_name": "reqwest_error_to_io_error", "docstring": "Converts a `reqwest::Error` to an `io::Error`.", "repo": "endbasic/endbasic", "path": "client/src/cloud.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cloud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a012179ec5afdb8d559287b0190eb19a97b53420e79357767deb4212d8b646be"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new client for the cloud service that talks to `api_address`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(api_address: &str) -> io::Result {\n let url = match Url::parse(api_address) {\n Ok(url) => url,\n Err(e) => {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n format!(\"Invalid base API address: {}\", e),\n ))\n }\n };\n\n if !(url.path().is_empty() || url.path() == \"/\") {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n \"Invalid base API address: cannot contain a path\".to_owned(),\n ));\n }\n\n let auth_data = Rc::from(RefCell::from(None));\n\n Ok(Self { api_address: url, client: reqwest::Client::default(), auth_data })\n }\n```"}], "func_name": "new", "docstring": "Creates a new client for the cloud service that talks to `api_address`.", "repo": "endbasic/endbasic", "path": "client/src/cloud.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cloud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d2958328226ac778d83cbe1137193201afe0c51623ff72b16e7dba71d752636f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_url\n\nDocumentation:\nGenerates a service URL with the given `path`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn make_url(&self, path: &str) -> Url {\n assert!(path.starts_with(\"api/\"));\n let mut url = self.api_address.clone();\n assert!(url.path().is_empty() || url.path() == \"/\");\n url.set_path(path);\n url\n }\n```"}], "func_name": "make_url", "docstring": "Generates a service URL with the given `path`.", "repo": "endbasic/endbasic", "path": "client/src/cloud.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cloud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf79c827407c7dc727f2b5de7c409e35d9d287697865ade9be0b7022bf54a795"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_headers\n\nDocumentation:\nReturns the default headers to add to every request.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn default_headers(&self) -> HeaderMap {\n let mut headers = HeaderMap::new();\n headers.insert(\n \"x-endbasic-client-version\",\n env!(\"CARGO_PKG_VERSION\")\n .parse()\n .expect(\"Package version should have been serializable\"),\n );\n headers\n }\n```"}], "func_name": "default_headers", "docstring": "Returns the default headers to add to every request.", "repo": "endbasic/endbasic", "path": "client/src/cloud.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cloud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b928061d0c3bf38f6643bc7b934f51e79b573e30697a1e78cf974b82ac8f8a39"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: require_auth_data\n\nDocumentation:\nChecks if the given auth data object is present and returns it, or else returns a permission\ndenied error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn require_auth_data(data: Option<&AuthData>) -> io::Result<&AuthData> {\n match data.as_ref() {\n Some(data) => Ok(data),\n None => {\n Err(io::Error::new(io::ErrorKind::PermissionDenied, \"Not logged in yet\".to_owned()))\n }\n }\n }\n```"}], "func_name": "require_auth_data", "docstring": "Checks if the given auth data object is present and returns it, or else returns a permission\ndenied error.", "repo": "endbasic/endbasic", "path": "client/src/cloud.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cloud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7f1ec39bd40f9a9e3340f85f631c51b19c97b888d151d3aebf34c4d77f41849e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_service_from_env\n\nDocumentation:\nCreates a new service that talks to the configured API service for testing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new_service_from_env() -> CloudService {\n let service_api = env::var(\"SERVICE_URL\").expect(\"Expected env config not found\");\n CloudService::new(&service_api).unwrap()\n }\n```"}], "func_name": "new_service_from_env", "docstring": "Creates a new service that talks to the configured API service for testing.", "repo": "endbasic/endbasic", "path": "client/src/cloud.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cloud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dad496e45389a70f191e96b7a31b47484f084ee4449da276ac9d181a2a7ad129"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_from_env\n\nDocumentation:\nCreates a new test context that talks to the configured API service.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new_from_env() -> Self {\n TestContext { service: new_service_from_env(), username: None, files_to_delete: vec![] }\n }\n```"}], "func_name": "new_from_env", "docstring": "Creates a new test context that talks to the configured API service.", "repo": "endbasic/endbasic", "path": "client/src/cloud.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cloud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b47c681049e07edc412098e05b89fa65bf3accb4e729f700e1c352298a5d72fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_username\n\nDocumentation:\nReturns the username of the selected test account.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn get_username(&self, i: u8) -> String {\n env::var(format!(\"TEST_ACCOUNT_{}_USERNAME\", i)).expect(\"Expected env config not found\")\n }\n```"}], "func_name": "get_username", "docstring": "Returns the username of the selected test account.", "repo": "endbasic/endbasic", "path": "client/src/cloud.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cloud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "56775f64499de824c0bf07dae2738d39f9dcd2bf14232941e89e4f6546a23b37"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_login\n\nDocumentation:\nAuthenticates against the server using the username and password passed in via\nenvironment variables. We need to support multiple test accounts at the same time, so\nthis performs authentication for the test account `i`.\n\nReturns the username of the selected test account for convenience.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn do_login(&mut self, i: u8) -> String {\n let username = self.get_username(i);\n let password = env::var(format!(\"TEST_ACCOUNT_{}_PASSWORD\", i))\n .expect(\"Expected env config not found\");\n let _response = self.service.login(&username, &password).await.unwrap();\n self.username = Some(username.clone());\n username\n }\n```"}], "func_name": "do_login", "docstring": "Authenticates against the server using the username and password passed in via\nenvironment variables. We need to support multiple test accounts at the same time, so\nthis performs authentication for the test account `i`.\n\nReturns the username of the selected test account for convenience.", "repo": "endbasic/endbasic", "path": "client/src/cloud.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cloud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cbb719a16e8addaf13f93aa98db61f1038b55ced97909b838775d18cc09ae32c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_logout\n\nDocumentation:\nClears the authentication token to represent a log out.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn do_logout(&mut self) {\n self.service.logout().await.unwrap();\n self.username = None;\n }\n```"}], "func_name": "do_logout", "docstring": "Clears the authentication token to represent a log out.", "repo": "endbasic/endbasic", "path": "client/src/cloud.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cloud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "575c12fa3ad1162b536373a1067b743cb4c078d27cd4f056eddcdb93092243d7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: random_file\n\nDocumentation:\nGenerates a random filename and its content for testing, and makes sure the file gets\ndeleted during cleanup in case the test didn't do it on its own.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn random_file(&mut self) -> (String, Vec) {\n let filename = format!(\"file-{}\", rand::random::());\n let content = format!(\"Test content for {}\", filename);\n self.files_to_delete.push(filename.clone());\n (filename, content.into_bytes())\n }\n```"}], "func_name": "random_file", "docstring": "Generates a random filename and its content for testing, and makes sure the file gets\ndeleted during cleanup in case the test didn't do it on its own.", "repo": "endbasic/endbasic", "path": "client/src/cloud.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cloud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f75a01377253ba7305fe2f74f2c3514bc8ed8f6a7f50baa75a602eb996fdaf1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_login\n\nDocumentation:\nPerforms the login workflow against the server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn do_login(&self, username: &str, password: &str) -> io::Result<()> {\n let response = self.service.borrow_mut().login(username, password).await?;\n\n {\n let console = &mut *self.console.borrow_mut();\n if !is_narrow(&*console) && !response.motd.is_empty() {\n console.print(\"\")?;\n console.print(\"----- BEGIN SERVER MOTD -----\")?;\n for line in response.motd {\n refill_and_print(console, [line], \"\")?;\n }\n console.print(\"----- END SERVER MOTD -----\")?;\n console.print(\"\")?;\n }\n }\n\n let mut storage = self.storage.borrow_mut();\n storage.mount(\"CLOUD\", &format!(\"cloud://{}\", username))?;\n\n Ok(())\n }\n```"}], "func_name": "do_login", "docstring": "Performs the login workflow against the server.", "repo": "endbasic/endbasic", "path": "client/src/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6611b6a3598981c6a349987f22fcc13336cc11f23ac228d6460e2ea5a3cb34f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_acl\n\nDocumentation:\nParses a textual ACL specification and adds it to `add` or `remove.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_acl(\n mut acl: String,\n acl_pos: LineCol,\n add: &mut FileAcls,\n remove: &mut FileAcls,\n ) -> Result<()> {\n let change = if acl.len() < 3 { String::new() } else { acl.split_off(acl.len() - 2) };\n let username = acl; // For clarity after splitting off the ACL change request.\n match (username, change.as_str()) {\n (username, \"+r\") if !username.is_empty() => add.add_reader(username),\n (username, \"+R\") if !username.is_empty() => add.add_reader(username),\n (username, \"-r\") if !username.is_empty() => remove.add_reader(username),\n (username, \"-R\") if !username.is_empty() => remove.add_reader(username),\n (username, change) => {\n return Err(Error::SyntaxError(\n acl_pos,\n format!(\n \"Invalid ACL '{}{}': must be of the form \\\"username+r\\\" or \\\"username-r\\\"\",\n username, change\n ),\n ))\n }\n }\n Ok(())\n }\n```"}], "func_name": "parse_acl", "docstring": "Parses a textual ACL specification and adds it to `add` or `remove.", "repo": "endbasic/endbasic", "path": "client/src/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f93c747b6331ef825e7d790b350e8b6571506b0b4a49802fd48569afccd2dd77"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_public_acl\n\nDocumentation:\nChecks if a file is publicly readable by inspecting a set of ACLs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn has_public_acl(acls: &FileAcls) -> bool {\n for reader in acls.readers() {\n if reader.to_lowercase() == \"public\" {\n return true;\n }\n }\n false\n }\n```"}], "func_name": "has_public_acl", "docstring": "Checks if a file is publicly readable by inspecting a set of ACLs.", "repo": "endbasic/endbasic", "path": "client/src/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f3a8f5645ad6e7831b1c3ebaa6c1d133dde4eb01b8d16942c015e75647e6bb24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: show_acls\n\nDocumentation:\nFetches and prints the ACLs for `filename`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn show_acls(&self, filename: &str) -> io::Result<()> {\n let acls = self.storage.borrow().get_acls(filename).await?;\n\n let mut console = self.console.borrow_mut();\n console.print(\"\")?;\n if acls.readers().is_empty() {\n console.print(&format!(\" No ACLs on {}\", filename))?;\n } else {\n console.print(&format!(\" Reader ACLs on {}:\", filename))?;\n for acl in acls.readers() {\n console.print(&format!(\" {}\", acl))?;\n }\n }\n console.print(\"\")\n }\n```"}], "func_name": "show_acls", "docstring": "Fetches and prints the ACLs for `filename`.", "repo": "endbasic/endbasic", "path": "client/src/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d04efa4ec11592a7f6ae91afaf839b3a290e0e800ad8679d2787ba6fc7328243"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: validate_password_complexity\n\nDocumentation:\nChecks if a password is sufficiently complex and returns an error when it isn't.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn validate_password_complexity(password: &str) -> std::result::Result<(), &'static str> {\n if password.len() < 8 {\n return Err(\"Must be at least 8 characters long\");\n }\n\n let mut alphabetic = false;\n let mut numeric = false;\n for ch in password.chars() {\n if ch.is_alphabetic() {\n alphabetic = true;\n } else if ch.is_numeric() {\n numeric = true;\n }\n }\n\n if !alphabetic || !numeric {\n return Err(\"Must contain letters and numbers\");\n }\n\n Ok(())\n}\n```"}], "func_name": "validate_password_complexity", "docstring": "Checks if a password is sufficiently complex and returns an error when it isn't.", "repo": "endbasic/endbasic", "path": "client/src/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2eab90de0fef219b0ad9b78d170cdf19a76904ed72fad71323398b5a73773815"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_bool\n\nDocumentation:\nTries to read a boolean value until it is valid. Returns `default` if the user hits enter.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn read_bool(console: &mut dyn Console, prompt: &str, default: bool) -> io::Result {\n loop {\n match read_line(console, prompt, \"\", None).await? {\n s if s.is_empty() => return Ok(default),\n s => match parse_boolean(s.trim_end()) {\n Ok(b) => return Ok(b),\n Err(_) => {\n console.print(\"Invalid input; try again.\")?;\n continue;\n }\n },\n }\n }\n }\n```"}], "func_name": "read_bool", "docstring": "Tries to read a boolean value until it is valid. Returns `default` if the user hits enter.", "repo": "endbasic/endbasic", "path": "client/src/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7d5cabe0b246e8aca74e86ee25b7a6e0a6749906457a55598c5878122fbca93a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_password\n\nDocumentation:\nTries to get a password from the user until it is valid.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn read_password(console: &mut dyn Console) -> io::Result {\n loop {\n let password = read_line_secure(console, \"Password: \").await?;\n match validate_password_complexity(&password) {\n Ok(()) => (),\n Err(e) => {\n console.print(&format!(\"Invalid password: {}; try again.\", e))?;\n continue;\n }\n }\n\n let second_password = read_line_secure(console, \"Retype password: \").await?;\n if second_password != password {\n console.print(\"Passwords do not match; try again.\")?;\n continue;\n }\n\n return Ok(password);\n }\n }\n```"}], "func_name": "read_password", "docstring": "Tries to get a password from the user until it is valid.", "repo": "endbasic/endbasic", "path": "client/src/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ebc83deb6eb82355c0bb32c89556ca4c92fe55e4926f6a9c955a382546b5626"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_all\n\nDocumentation:\nAdds all remote manipulation commands for `service` to the `machine`, using `console` to\ndisplay information and `storage` to manipulate the remote drives.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_all>(\n machine: &mut Machine,\n service: Rc>,\n console: Rc>,\n storage: Rc>,\n exec_base_url: S,\n) {\n storage\n .borrow_mut()\n .register_scheme(\"cloud\", Box::from(CloudDriveFactory::new(service.clone())));\n\n machine.add_callable(LoginCommand::new(service.clone(), console.clone(), storage.clone()));\n machine.add_callable(LogoutCommand::new(service.clone(), console.clone(), storage.clone()));\n machine.add_callable(ShareCommand::new(\n service.clone(),\n console.clone(),\n storage,\n exec_base_url,\n ));\n machine.add_callable(SignupCommand::new(service, console));\n}\n```"}], "func_name": "add_all", "docstring": "Adds all remote manipulation commands for `service` to the `machine`, using `console` to\ndisplay information and `storage` to manipulate the remote drives.", "repo": "endbasic/endbasic", "path": "client/src/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cdb38f9bf2e7bcb69284635cdc56dbf479609ec7687838cd475512ee48de32bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new cloud drive against `service` to access the files owned by `username`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new>(service: Rc>, username: S) -> Self {\n let username = username.into();\n Self { service, username }\n }\n```"}], "func_name": "new", "docstring": "Creates a new cloud drive against `service` to access the files owned by `username`.", "repo": "endbasic/endbasic", "path": "client/src/drive.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/drive.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ce27d9f50b99daf1985348eff1c37242b9847ceb6d460ecf59122a963935012d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new cloud drive factory that uses `service` to connect to the remote service.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new(service: Rc>) -> Self {\n Self { service }\n }\n```"}], "func_name": "new", "docstring": "Creates a new cloud drive factory that uses `service` to connect to the remote service.", "repo": "endbasic/endbasic", "path": "client/src/drive.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/drive.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8eb3deb28036cc120bc9d567f05e6ddf75ac3a3971cdae80e77b048a28c70c59"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: verify_all_used\n\nDocumentation:\nEnsures that all requests and responses have been consumed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn verify_all_used(&mut self) {\n assert!(self.mock_signup.is_empty(), \"Mock requests not fully consumed\");\n assert!(self.mock_login.is_empty(), \"Mock requests not fully consumed\");\n assert!(self.mock_get_files.is_empty(), \"Mock requests not fully consumed\");\n assert!(self.mock_get_file.is_empty(), \"Mock requests not fully consumed\");\n assert!(self.mock_get_file_acls.is_empty(), \"Mock requests not fully consumed\");\n assert!(self.mock_patch_file_content.is_empty(), \"Mock requests not fully consumed\");\n assert!(self.mock_patch_file_acls.is_empty(), \"Mock requests not fully consumed\");\n assert!(self.mock_delete_file.is_empty(), \"Mock requests not fully consumed\");\n }\n```"}], "func_name": "verify_all_used", "docstring": "Ensures that all requests and responses have been consumed.", "repo": "endbasic/endbasic", "path": "client/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf43b2be70f684aa354ce86749e60df4fb47f4682ca235d3fddca15cbd9c8af0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_input_chars\n\nDocumentation:\nSee the wrapped `Tester::add_input_chars` function for details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_input_chars(self, golden_in: &str) -> Self {\n ClientTester { tester: self.tester.add_input_chars(golden_in), service: self.service }\n }\n```"}], "func_name": "add_input_chars", "docstring": "See the wrapped `Tester::add_input_chars` function for details.", "repo": "endbasic/endbasic", "path": "client/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f2094bbd65155c4697d7da525d5ab51719b81ca600e0cb07c73117b0dc9ce499"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nSee the wrapped `Tester::run` function for details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn run>(&mut self, script: S) -> ClientChecker {\n let checker = self.tester.run(script);\n ClientChecker { checker, service: self.service.clone(), exp_access_token: None }\n }\n```"}], "func_name": "run", "docstring": "See the wrapped `Tester::run` function for details.", "repo": "endbasic/endbasic", "path": "client/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "65471588c6858baaea77c9d4e8aab81d6b095422022ecc7d47316333c2654dcb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_access_token\n\nDocumentation:\nExpects the mock service to have logged in with the access `token`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn expect_access_token>(self, token: S) -> Self {\n Self {\n checker: self.checker,\n service: self.service,\n exp_access_token: Some(AccessToken::new(token.into())),\n }\n }\n```"}], "func_name": "expect_access_token", "docstring": "Expects the mock service to have logged in with the access `token`.", "repo": "endbasic/endbasic", "path": "client/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e40c1f82384cffd1409baacd7cbe5bbb466d6e420b49e5c367e3852c65aefec7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_compilation_err\n\nDocumentation:\nSee the wrapped `Checker::expect_err` function for details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_compilation_err>(self, message: S) -> Self {\n Self {\n checker: self.checker.expect_compilation_err(message),\n service: self.service,\n exp_access_token: self.exp_access_token,\n }\n }\n```"}], "func_name": "expect_compilation_err", "docstring": "See the wrapped `Checker::expect_err` function for details.", "repo": "endbasic/endbasic", "path": "client/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "435ab9a2e9b6f8c2d9daab1e9dca067d96f88bf493777aeb63371dc93297722a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_file\n\nDocumentation:\nSee the wrapped `Checker::expect_file` function for details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_file, C: Into>(self, name: N, content: C) -> Self {\n Self {\n checker: self.checker.expect_file(name, content),\n service: self.service,\n exp_access_token: self.exp_access_token,\n }\n }\n```"}], "func_name": "expect_file", "docstring": "See the wrapped `Checker::expect_file` function for details.", "repo": "endbasic/endbasic", "path": "client/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b94bf85757c03783095cc162f001691be89c32a7906490d6947fdcc6c81c9e74"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_output\n\nDocumentation:\nSee the wrapped `Checker::expect_output` function for details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_output>>(self, out: V) -> Self {\n Self {\n checker: self.checker.expect_output(out),\n service: self.service,\n exp_access_token: self.exp_access_token,\n }\n }\n```"}], "func_name": "expect_output", "docstring": "See the wrapped `Checker::expect_output` function for details.", "repo": "endbasic/endbasic", "path": "client/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9705628e50a010fac76ecaefc5eb3d8b255afa943df8c55a5a3fd9c61a3d67e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_prints\n\nDocumentation:\nSee the wrapped `Checker::expect_prints` function for details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_prints, V: Into>>(self, out: V) -> Self {\n Self {\n checker: self.checker.expect_prints(out),\n service: self.service,\n exp_access_token: self.exp_access_token,\n }\n }\n```"}], "func_name": "expect_prints", "docstring": "See the wrapped `Checker::expect_prints` function for details.", "repo": "endbasic/endbasic", "path": "client/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/client/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f2d30fadc1c93acbce26b53d8db195937820b994d2a7c92379a3530eca04233"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new function that queries the `lights` state.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(lights: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"NUM_LIGHTS\")\n .with_return_type(ExprType::Integer)\n .with_syntax(&[(&[], None)])\n .with_category(\"Demonstration\")\n .with_description(\"Returns the number of available lights.\")\n .build(),\n lights,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new function that queries the `lights` state.", "repo": "endbasic/endbasic", "path": "core/examples/dsl.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/examples/dsl.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb83018120c9ba346152c57e9be641fcb58ebbd248ebc4625e2689f7f36df0ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new command that modifies the `lights` state.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(lights: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"SWITCH_LIGHT\")\n .with_syntax(&[(\n &[SingularArgSyntax::RequiredValue(\n RequiredValueSyntax { name: Cow::Borrowed(\"id\"), vtype: ExprType::Integer },\n ArgSepSyntax::End,\n )],\n None,\n )])\n .with_category(\"Demonstration\")\n .with_description(\"Turns the light identified by 'id' on or off.\")\n .build(),\n lights,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new command that modifies the `lights` state.", "repo": "endbasic/endbasic", "path": "core/examples/dsl.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/examples/dsl.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d56fb65f398345985b3d1fc4e5aa2d188f9f9264196668a45e2b6bbfd6478c37"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_pos\n\nDocumentation:\nReturns the start position of the expression.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start_pos(&self) -> LineCol {\n match self {\n Expr::Boolean(span) => span.pos,\n Expr::Double(span) => span.pos,\n Expr::Integer(span) => span.pos,\n Expr::Text(span) => span.pos,\n\n Expr::Symbol(span) => span.pos,\n\n Expr::And(span) => span.lhs.start_pos(),\n Expr::Or(span) => span.lhs.start_pos(),\n Expr::Xor(span) => span.lhs.start_pos(),\n Expr::Not(span) => span.pos,\n\n Expr::ShiftLeft(span) => span.lhs.start_pos(),\n Expr::ShiftRight(span) => span.lhs.start_pos(),\n\n Expr::Equal(span) => span.lhs.start_pos(),\n Expr::NotEqual(span) => span.lhs.start_pos(),\n Expr::Less(span) => span.lhs.start_pos(),\n Expr::LessEqual(span) => span.lhs.start_pos(),\n Expr::Greater(span) => span.lhs.start_pos(),\n Expr::GreaterEqual(span) => span.lhs.start_pos(),\n\n Expr::Add(span) => span.lhs.start_pos(),\n Expr::Subtract(span) => span.lhs.start_pos(),\n Expr::Multiply(span) => span.lhs.start_pos(),\n Expr::Divide(span) => span.lhs.start_pos(),\n Expr::Modulo(span) => span.lhs.start_pos(),\n Expr::Power(span) => span.lhs.start_pos(),\n Expr::Negate(span) => span.pos,\n\n Expr::Call(span) => span.vref_pos,\n }\n }\n```"}], "func_name": "start_pos", "docstring": "Returns the start position of the expression.", "repo": "endbasic/endbasic", "path": "core/src/ast.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/ast.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "de0967b0a1f8df78aa9faba01069e1e42e55d618d716b99f460312ea9d1a2269"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_numerical\n\nDocumentation:\nReturns true if this expression type is numerical.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn is_numerical(self) -> bool {\n self == Self::Double || self == Self::Integer\n }\n```"}], "func_name": "is_numerical", "docstring": "Returns true if this expression type is numerical.", "repo": "endbasic/endbasic", "path": "core/src/ast.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/ast.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bee3ae95257e66f3f1e99b0f6b86e07022f068961009dc382e3558bbfbb75fd2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: annotation\n\nDocumentation:\nReturns the textual representation of the annotation for this type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn annotation(&self) -> char {\n match self {\n ExprType::Boolean => '?',\n ExprType::Double => '#',\n ExprType::Integer => '%',\n ExprType::Text => '$',\n }\n }\n```"}], "func_name": "annotation", "docstring": "Returns the textual representation of the annotation for this type.", "repo": "endbasic/endbasic", "path": "core/src/ast.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/ast.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "39c5fdd185dfca1addcd7396046f41c4c94ee3692eb98f607948f03c09103e0e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_value\n\nDocumentation:\nReturns the default value to assign to this type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn default_value(&self) -> Value {\n match self {\n ExprType::Boolean => Value::Boolean(false),\n ExprType::Double => Value::Double(0.0),\n ExprType::Integer => Value::Integer(0),\n ExprType::Text => Value::Text(\"\".to_owned()),\n }\n }\n```"}], "func_name": "default_value", "docstring": "Returns the default value to assign to this type.", "repo": "endbasic/endbasic", "path": "core/src/ast.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/ast.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "95c6abbee7917831829f2404f043a2aeca1a6821dfa5406f39a3e8076bd0c836"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new reference to the variable with `name` and the optional `ref_type` type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new>(name: T, ref_type: Option) -> Self {\n Self { name: name.into(), ref_type }\n }\n```"}], "func_name": "new", "docstring": "Creates a new reference to the variable with `name` and the optional `ref_type` type.", "repo": "endbasic/endbasic", "path": "core/src/ast.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/ast.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9646b2ef64ca18210f114fec2369d0a8ef4a23c4102412ad4a18bcfba5371107"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accepts\n\nDocumentation:\nReturns true if this reference is compatible with the given type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn accepts(&self, other: ExprType) -> bool {\n match self.ref_type {\n None => true,\n Some(vtype) => vtype == other,\n }\n }\n```"}], "func_name": "accepts", "docstring": "Returns true if this reference is compatible with the given type.", "repo": "endbasic/endbasic", "path": "core/src/ast.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/ast.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2fadb723453e68eb56fbb7609f513af19f5fa45ba038c0db7ded6c10015be3ee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accepts_callable\n\nDocumentation:\nReturns true if this reference is compatible with the return type of a callable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn accepts_callable(&self, other: Option) -> bool {\n match self.ref_type {\n None => true,\n Some(vtype) => match other {\n Some(other) => vtype == other,\n None => false,\n },\n }\n }\n```"}], "func_name": "accepts_callable", "docstring": "Returns true if this reference is compatible with the return type of a callable.", "repo": "endbasic/endbasic", "path": "core/src/ast.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/ast.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d191d136dc7c9a23521214f48630a7beb13f64045d8e280f508de1a61a254155"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_exprtype\n\nDocumentation:\nReturns the type of the value as an `ExprType`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_exprtype(&self) -> ExprType {\n match self {\n Value::Boolean(_) => ExprType::Boolean,\n Value::Double(_) => ExprType::Double,\n Value::Integer(_) => ExprType::Integer,\n Value::Text(_) => ExprType::Text,\n Value::VarRef(_key, etype) => *etype,\n }\n }\n```"}], "func_name": "as_exprtype", "docstring": "Returns the type of the value as an `ExprType`.", "repo": "endbasic/endbasic", "path": "core/src/ast.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/ast.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "168089024e0af2f49b601bc9147173c93526fa452c1963196ad51839cc47341f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: describe\n\nDocumentation:\nFormats the separator for a syntax specification.\n\nThe return value contains the textual representation of the separator and a boolean that\nindicates whether the separator requires a leading space.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn describe(&self) -> (&str, bool) {\n match self {\n ArgSep::End => (\"\", false),\n ArgSep::Short => (\";\", false),\n ArgSep::Long => (\",\", false),\n ArgSep::As => (\"AS\", true),\n }\n }\n```"}], "func_name": "describe", "docstring": "Formats the separator for a syntax specification.\n\nThe return value contains the textual representation of the separator and a boolean that\nindicates whether the separator requires a leading space.", "repo": "endbasic/endbasic", "path": "core/src/ast.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/ast.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5ef283f86540644f7d6ad03582123de1b1cb13b84f0f986f3b6dfd3a8583840f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: repr\n\nDocumentation:\nReturns the textual representation of the instruction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn repr(&self) -> (&'static str, Option) {\n match self {\n Instruction::BitwiseAnd(_pos) => (\"AND%\", None),\n Instruction::BitwiseOr(_pos) => (\"OR%\", None),\n Instruction::BitwiseXor(_pos) => (\"XOR%\", None),\n Instruction::BitwiseNot(_pos) => (\"NOT%\", None),\n\n Instruction::LogicalAnd(_pos) => (\"AND?\", None),\n Instruction::LogicalOr(_pos) => (\"OR?\", None),\n Instruction::LogicalXor(_pos) => (\"XOR?\", None),\n Instruction::LogicalNot(_pos) => (\"NOT?\", None),\n\n Instruction::ShiftLeft(_pos) => (\"SHL%\", None),\n Instruction::ShiftRight(_pos) => (\"SHR%\", None),\n\n Instruction::EqualBooleans(_pos) => (\"CMPE?\", None),\n Instruction::NotEqualBooleans(_pos) => (\"CMPNE?\", None),\n\n Instruction::EqualDoubles(_pos) => (\"CMPE#\", None),\n Instruction::NotEqualDoubles(_pos) => (\"CMPNE#\", None),\n Instruction::LessDoubles(_pos) => (\"CMPL#\", None),\n Instruction::LessEqualDoubles(_pos) => (\"CMPLE#\", None),\n Instruction::GreaterDoubles(_pos) => (\"CMPG#\", None),\n Instruction::GreaterEqualDoubles(_pos) => (\"CMPGE#\", None),\n\n Instruction::EqualIntegers(_pos) => (\"CMPE%\", None),\n Instruction::NotEqualIntegers(_pos) => (\"CMPNE%\", None),\n Instruction::LessIntegers(_pos) => (\"CMPL%\", None),\n Instruction::LessEqualIntegers(_pos) => (\"CMPLE%\", None),\n Instruction::GreaterIntegers(_pos) => (\"CMPG%\", None),\n Instruction::GreaterEqualIntegers(_pos) => (\"CMPGE%\", None),\n\n Instruction::EqualStrings(_pos) => (\"CMPE$\", None),\n Instruction::NotEqualStrings(_pos) => (\"CMPNE$\", None),\n Instruction::LessStrings(_pos) => (\"CMPL$\", None),\n Instruction::LessEqualStrings(_pos) => (\"CMPLE$\", None),\n Instruction::GreaterStrings(_pos) => (\"CMPG$\", None),\n Instruction::GreaterEqualStrings(_pos) => (\"CMPGE$\", None),\n\n Instruction::AddDoubles(_pos) => (\"ADD#\", None),\n Instruction::SubtractDoubles(_pos) => (\"SUB#\", None),\n Instruction::MultiplyDoubles(_pos) => (\"MUL#\", None),\n Instruction::DivideDoubles(_pos) => (\"DIV#\", None),\n Instruction::ModuloDoubles(_pos) => (\"MOD#\", None),\n Instruction::PowerDoubles(_pos) => (\"POW#\", None),\n Instruction::NegateDouble(_pos) => (\"NEG#\", None),\n\n Instruction::AddIntegers(_pos) => (\"ADD%\", None),\n Instruction::SubtractIntegers(_pos) => (\"SUB%\", None),\n Instruction::MultiplyIntegers(_pos) => (\"MUL%\", None),\n Instruction::DivideIntegers(_pos) => (\"DIV%\", None),\n Instruction::ModuloIntegers(_pos) => (\"MOD%\", None),\n Instruction::PowerIntegers(_pos) => (\"POW%\", None),\n Instruction::NegateInteger(_pos) => (\"NEG%\", None),\n\n Instruction::ConcatStrings(_pos) => (\"CONCAT$\", None),\n\n Instruction::ArrayAssignment(key, _pos, nargs) => {\n (\"SETA\", Some(format!(\"{}, {}\", key, nargs)))\n }\n\n Instruction::ArrayLoad(key, _pos, nargs) => {\n (\"LOADA\", Some(format!(\"{}, {}\", key, nargs)))\n }\n\n Instruction::Assign(key) => (\"SETV\", Some(key.to_string())),\n\n Instruction::BuiltinCall(key, _pos, nargs) => {\n (\"CALLB\", Some(format!(\"{}, {}\", key, nargs)))\n }\n\n Instruction::Call(span) => (\"CALLA\", Some(format!(\"{:04x}\", span.addr))),\n\n Instruction::FunctionCall(key, etype, _pos, nargs) => {\n let opcode = match etype {\n ExprType::Boolean => \"CALLF?\",\n ExprType::Double => \"CALLF#\",\n ExprType::Integer => \"CALLF%\",\n ExprType::Text => \"CALLF$\",\n };\n (opcode, Some(format!(\"{}, {}\", key, nargs)))\n }\n\n Instruction::Dim(span) => {\n let opcode = match (span.shared, span.vtype) {\n (false, ExprType::Boolean) => \"DIMV?\",\n (false, ExprType::Double) => \"DIMV#\",\n (false, ExprType::Integer) => \"DIMV%\",\n (false, ExprType::Text) => \"DIMV$\",\n (true, ExprType::Boolean) => \"DIMSV?\",\n (true, ExprType::Double) => \"DIMSV#\",\n (true, ExprType::Integer) => \"DIMSV%\",\n (true, ExprType::Text) => \"DIMSV$\",\n };\n (opcode, Some(format!(\"{}\", span.name)))\n }\n\n Instruction::DimArray(span) => {\n let opcode = match (span.shared, span.subtype) {\n (false, ExprType::Boolean) => \"DIMA?\",\n (false, ExprType::Double) => \"DIMA#\",\n (false, ExprType::Integer) => \"DIMA%\",\n (false, ExprType::Text) => \"DIMA$\",\n (true, ExprType::Boolean) => \"DIMSA?\",\n (true, ExprType::Double) => \"DIMSA#\",\n (true, ExprType::Integer) => \"DIMSA%\",\n (true, ExprType::Text) => \"DIMSA$\",\n };\n (opcode, Some(format!(\"{}, {}\", span.name, span.dimensions)))\n }\n\n Instruction::End(has_code) => (\"END\", Some(format!(\"{}\", has_code))),\n\n Instruction::EnterScope => (\"ENTER\", None),\n\n Instruction::DoubleToInteger => (\"#TO%\", None),\n Instruction::IntegerToDouble => (\"%TO#\", None),\n\n Instruction::Jump(span) => (\"JMP\", Some(format!(\"{:04x}\", span.addr))),\n Instruction::JumpIfDefined(span) => {\n (\"JMPVD\", Some(format!(\"{}, {:04x}\", span.var, span.addr)))\n }\n Instruction::JumpIfTrue(addr) => (\"JMPT\", Some(format!(\"{:04x}\", addr))),\n Instruction::JumpIfNotTrue(addr) => (\"JMPNT\", Some(format!(\"{:04x}\", addr))),\n\n Instruction::LeaveScope => (\"LEAVE\", None),\n\n Instruction::LoadBoolean(key, _pos) => (\"LOAD?\", Some(key.to_string())),\n Instruction::LoadDouble(key, _pos) => (\"LOAD#\", Some(key.to_string())),\n Instruction::LoadInteger(key, _pos) => (\"LOAD%\", Some(key.to_string())),\n Instruction::LoadString(key, _pos) => (\"LOAD$\", Some(key.to_string())),\n\n Instruction::LoadRef(key, _etype, _pos) => (\"LOADR\", Some(key.to_string())),\n\n Instruction::Nop => (\"NOP\", None),\n\n Instruction::PushBoolean(b, _pos) => (\"PUSH?\", Some(format!(\"{}\", b))),\n Instruction::PushDouble(d, _pos) => (\"PUSH#\", Some(format!(\"{}\", d))),\n Instruction::PushInteger(i, _pos) => (\"PUSH%\", Some(format!(\"{}\", i))),\n Instruction::PushString(s, _pos) => (\"PUSH$\", Some(format!(\"\\\"{}\\\"\", s))),\n\n Instruction::Return(_pos) => (\"RET\", None),\n\n Instruction::SetErrorHandler(span) => match span {\n ErrorHandlerISpan::Jump(addr) => (\"SEHA\", Some(format!(\"{:04x}\", addr))),\n ErrorHandlerISpan::None => (\"SEHN\", None),\n ErrorHandlerISpan::ResumeNext => (\"SEHRN\", None),\n },\n\n Instruction::Unset(span) => (\"UNSETV\", Some(format!(\"{}\", span.name))),\n }\n }\n```"}], "func_name": "repr", "docstring": "Returns the textual representation of the instruction.", "repo": "endbasic/endbasic", "path": "core/src/bytecode.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b8a55fb11c134399857ddbf07f3c7177b20bae5d9d4ca21b056a9fa12770054"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pos\n\nDocumentation:\nReturns the position in the source code where this instruction originated.\n\nFor some instructions, we cannot tell their location right now, so we return None for those.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pos(&self) -> Option {\n match self {\n Instruction::BitwiseAnd(pos) => Some(*pos),\n Instruction::BitwiseOr(pos) => Some(*pos),\n Instruction::BitwiseXor(pos) => Some(*pos),\n Instruction::BitwiseNot(pos) => Some(*pos),\n\n Instruction::LogicalAnd(pos) => Some(*pos),\n Instruction::LogicalOr(pos) => Some(*pos),\n Instruction::LogicalXor(pos) => Some(*pos),\n Instruction::LogicalNot(pos) => Some(*pos),\n\n Instruction::ShiftLeft(pos) => Some(*pos),\n Instruction::ShiftRight(pos) => Some(*pos),\n\n Instruction::EqualBooleans(pos) => Some(*pos),\n Instruction::NotEqualBooleans(pos) => Some(*pos),\n\n Instruction::EqualDoubles(pos) => Some(*pos),\n Instruction::NotEqualDoubles(pos) => Some(*pos),\n Instruction::LessDoubles(pos) => Some(*pos),\n Instruction::LessEqualDoubles(pos) => Some(*pos),\n Instruction::GreaterDoubles(pos) => Some(*pos),\n Instruction::GreaterEqualDoubles(pos) => Some(*pos),\n\n Instruction::EqualIntegers(pos) => Some(*pos),\n Instruction::NotEqualIntegers(pos) => Some(*pos),\n Instruction::LessIntegers(pos) => Some(*pos),\n Instruction::LessEqualIntegers(pos) => Some(*pos),\n Instruction::GreaterIntegers(pos) => Some(*pos),\n Instruction::GreaterEqualIntegers(pos) => Some(*pos),\n\n Instruction::EqualStrings(pos) => Some(*pos),\n Instruction::NotEqualStrings(pos) => Some(*pos),\n Instruction::LessStrings(pos) => Some(*pos),\n Instruction::LessEqualStrings(pos) => Some(*pos),\n Instruction::GreaterStrings(pos) => Some(*pos),\n Instruction::GreaterEqualStrings(pos) => Some(*pos),\n\n Instruction::AddDoubles(pos) => Some(*pos),\n Instruction::SubtractDoubles(pos) => Some(*pos),\n Instruction::MultiplyDoubles(pos) => Some(*pos),\n Instruction::DivideDoubles(pos) => Some(*pos),\n Instruction::ModuloDoubles(pos) => Some(*pos),\n Instruction::PowerDoubles(pos) => Some(*pos),\n Instruction::NegateDouble(pos) => Some(*pos),\n\n Instruction::AddIntegers(pos) => Some(*pos),\n Instruction::SubtractIntegers(pos) => Some(*pos),\n Instruction::MultiplyIntegers(pos) => Some(*pos),\n Instruction::DivideIntegers(pos) => Some(*pos),\n Instruction::ModuloIntegers(pos) => Some(*pos),\n Instruction::PowerIntegers(pos) => Some(*pos),\n Instruction::NegateInteger(pos) => Some(*pos),\n\n Instruction::ConcatStrings(pos) => Some(*pos),\n\n Instruction::ArrayAssignment(_, pos, _) => Some(*pos),\n Instruction::ArrayLoad(_, pos, _) => Some(*pos),\n Instruction::Assign(_) => None,\n Instruction::BuiltinCall(_, pos, _) => Some(*pos),\n Instruction::Call(_) => None,\n Instruction::FunctionCall(_, _, pos, _) => Some(*pos),\n Instruction::Dim(_) => None,\n Instruction::DimArray(span) => Some(span.name_pos),\n Instruction::End(_) => None,\n Instruction::EnterScope => None,\n Instruction::DoubleToInteger => None,\n Instruction::IntegerToDouble => None,\n Instruction::Jump(_) => None,\n Instruction::JumpIfDefined(_) => None,\n Instruction::JumpIfTrue(_) => None,\n Instruction::JumpIfNotTrue(_) => None,\n Instruction::LeaveScope => None,\n Instruction::LoadBoolean(_, pos) => Some(*pos),\n Instruction::LoadDouble(_, pos) => Some(*pos),\n Instruction::LoadInteger(_, pos) => Some(*pos),\n Instruction::LoadString(_, pos) => Some(*pos),\n Instruction::LoadRef(_, _, pos) => Some(*pos),\n Instruction::Nop => None,\n Instruction::PushBoolean(_, pos) => Some(*pos),\n Instruction::PushDouble(_, pos) => Some(*pos),\n Instruction::PushInteger(_, pos) => Some(*pos),\n Instruction::PushString(_, pos) => Some(*pos),\n Instruction::Return(pos) => Some(*pos),\n Instruction::SetErrorHandler(_) => None,\n Instruction::Unset(span) => Some(span.pos),\n }\n }\n```"}], "func_name": "pos", "docstring": "Returns the position in the source code where this instruction originated.\n\nFor some instructions, we cannot tell their location right now, so we return None for those.", "repo": "endbasic/endbasic", "path": "core/src/bytecode.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c02da61cc28038886eeea3d9f2f7785a870fc0b6d937782b8f3239df54dc9f55"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_statement\n\nDocumentation:\nReturns true if this instruction represents the execution of a statement.\n\nThis is a heuristic to implement `ON ERROR RESUME NEXT`. It works for now without\nadditional tracking, but maybe this needs to change in the future if we add some\ninstruction that cannot be disambiguated.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn is_statement(&self) -> bool {\n match self {\n Instruction::LogicalAnd(_)\n | Instruction::LogicalOr(_)\n | Instruction::LogicalXor(_)\n | Instruction::LogicalNot(_)\n | Instruction::BitwiseAnd(_)\n | Instruction::BitwiseOr(_)\n | Instruction::BitwiseXor(_)\n | Instruction::BitwiseNot(_)\n | Instruction::ArrayLoad(_, _, _)\n | Instruction::ShiftLeft(_)\n | Instruction::ShiftRight(_)\n | Instruction::EqualBooleans(_)\n | Instruction::NotEqualBooleans(_)\n | Instruction::EqualDoubles(_)\n | Instruction::NotEqualDoubles(_)\n | Instruction::LessDoubles(_)\n | Instruction::LessEqualDoubles(_)\n | Instruction::GreaterDoubles(_)\n | Instruction::GreaterEqualDoubles(_)\n | Instruction::EqualIntegers(_)\n | Instruction::NotEqualIntegers(_)\n | Instruction::LessIntegers(_)\n | Instruction::LessEqualIntegers(_)\n | Instruction::GreaterIntegers(_)\n | Instruction::GreaterEqualIntegers(_)\n | Instruction::EqualStrings(_)\n | Instruction::NotEqualStrings(_)\n | Instruction::LessStrings(_)\n | Instruction::LessEqualStrings(_)\n | Instruction::GreaterStrings(_)\n | Instruction::GreaterEqualStrings(_)\n | Instruction::AddDoubles(_)\n | Instruction::SubtractDoubles(_)\n | Instruction::MultiplyDoubles(_)\n | Instruction::DivideDoubles(_)\n | Instruction::ModuloDoubles(_)\n | Instruction::PowerDoubles(_)\n | Instruction::NegateDouble(_)\n | Instruction::AddIntegers(_)\n | Instruction::SubtractIntegers(_)\n | Instruction::MultiplyIntegers(_)\n | Instruction::DivideIntegers(_)\n | Instruction::ModuloIntegers(_)\n | Instruction::PowerIntegers(_)\n | Instruction::NegateInteger(_)\n | Instruction::ConcatStrings(_)\n | Instruction::FunctionCall(_, _, _, _)\n | Instruction::DoubleToInteger\n | Instruction::IntegerToDouble\n | Instruction::LoadBoolean(_, _)\n | Instruction::LoadDouble(_, _)\n | Instruction::LoadInteger(_, _)\n | Instruction::LoadString(_, _)\n | Instruction::LoadRef(_, _, _)\n | Instruction::PushBoolean(_, _)\n | Instruction::PushDouble(_, _)\n | Instruction::PushInteger(_, _)\n | Instruction::PushString(_, _)\n | Instruction::EnterScope\n | Instruction::LeaveScope => false,\n\n Instruction::ArrayAssignment(_, _, _)\n | Instruction::Assign(_)\n | Instruction::BuiltinCall(_, _, _)\n | Instruction::Call(_)\n | Instruction::Dim(_)\n | Instruction::DimArray(_)\n | Instruction::End(_)\n | Instruction::Jump(_)\n | Instruction::JumpIfDefined(_)\n | Instruction::JumpIfTrue(_)\n | Instruction::JumpIfNotTrue(_)\n | Instruction::Nop\n | Instruction::Return(_)\n | Instruction::SetErrorHandler(_)\n | Instruction::Unset(_) => true,\n }\n }\n```"}], "func_name": "is_statement", "docstring": "Returns true if this instruction represents the execution of a statement.\n\nThis is a heuristic to implement `ON ERROR RESUME NEXT`. It works for now without\nadditional tracking, but maybe this needs to change in the future if we add some\ninstruction that cannot be disambiguated.", "repo": "endbasic/endbasic", "path": "core/src/bytecode.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "08b0e463292f25be537064c71caa9938b76bc1db75abd834b53c053b333c4ed0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_value_error\n\nDocumentation:\nAnnotates a value computation error with a position.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_value_error(e: value::Error, pos: LineCol) -> Self {\n Self::EvalError(pos, e.message)\n }\n```"}], "func_name": "from_value_error", "docstring": "Annotates a value computation error with a position.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b231bfd6efee63f8b7a5270a43ce07929e11ddfc64b76929eddd3ca6d1149fc3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_catchable\n\nDocumentation:\nReturns true if this type of error can be caught by `ON ERROR`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_catchable(&self) -> bool {\n match self {\n Error::CompilerError(_) => false,\n Error::EvalError(..) => true,\n Error::InternalError(..) => true,\n Error::IoError(..) => true,\n Error::SyntaxError(..) => true,\n }\n }\n```"}], "func_name": "is_catchable", "docstring": "Returns true if this type of error can be caught by `ON ERROR`.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c575f3f6f3f78c478c6be525a5a8b0b5bc5fa6ace31a9178c7a6c1f6060b8cc9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_syntax_error\n\nDocumentation:\nInstantiates a new `Err(Error::SyntaxError(...))` from a message. Syntactic sugar.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_syntax_error>(pos: LineCol, message: S) -> Result {\n Err(Error::SyntaxError(pos, message.into()))\n}\n```"}], "func_name": "new_syntax_error", "docstring": "Instantiates a new `Err(Error::SyntaxError(...))` from a message. Syntactic sugar.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8893f9ededb2d96dc0053293c182a0e4921367345616c5f7f3aa5157435a5360"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_exit_code\n\nDocumentation:\nConverts the stop reason into a process exit code.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_exit_code(&self) -> i32 {\n match self {\n StopReason::Eof => 0,\n StopReason::Exited(i) => *i as i32,\n StopReason::Break => {\n // This mimics the behavior of typical Unix shells, which translate a signal to a\n // numerical exit code, but this is not accurate. First, because a CTRL+C sequence\n // should be exposed as a SIGINT signal to whichever process is waiting for us, and\n // second because this is not meaningful on Windows. But for now this will do.\n const SIGINT: i32 = 2;\n 128 + SIGINT\n }\n }\n }\n```"}], "func_name": "as_exit_code", "docstring": "Converts the stop reason into a process exit code.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a9496eadad8dc1e3803d36ab9f2543478418d6e1e6ab86464e67c07b3953c3e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: discard\n\nDocumentation:\nDiscards the given number of elements from the top of the stack.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn discard(&mut self, n: usize) {\n self.values.truncate(self.values.len() - n)\n }\n```"}], "func_name": "discard", "docstring": "Discards the given number of elements from the top of the stack.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea8090aefc99c3a58d39fefc7c69613892b8623b6b4dcd47a73ed4b0bdebade0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_integer\n\nDocumentation:\nPushes an integer onto the stack.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn push_integer(&mut self, i: i32, pos: LineCol) {\n self.values.push((Value::Integer(i), pos));\n }\n```"}], "func_name": "push_integer", "docstring": "Pushes an integer onto the stack.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "da4379d0fcc37e7984f6a092e5f48ffe49f3a4313070fc501977db6ee563f1d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_varref\n\nDocumentation:\nPushes a variable reference onto the stack.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn push_varref(&mut self, key: SymbolKey, etype: ExprType, pos: LineCol) {\n self.values.push((Value::VarRef(key, etype), pos));\n }\n```"}], "func_name": "push_varref", "docstring": "Pushes a variable reference onto the stack.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0eda740ae1955db3b04805a295a009585a9b6131f9ee01a3881a807473ea325e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new scope that wraps `nargs` arguments at the top of `stack`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(stack: &'s mut Stack, nargs: usize, fref_pos: LineCol) -> Self {\n debug_assert!(nargs <= stack.len());\n Self { stack, nargs, fref_pos }\n }\n```"}], "func_name": "new", "docstring": "Creates a new scope that wraps `nargs` arguments at the top of `stack`.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba295fcb500c7ae890b5aa622eebacef2ebd55eb10e1dc2275dbdb70672c7856"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: drain\n\nDocumentation:\nRemoves all remaining arguments from the stack tracked by this scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn drain(&mut self) {\n self.stack.discard(self.nargs);\n self.nargs = 0;\n }\n```"}], "func_name": "drain", "docstring": "Removes all remaining arguments from the stack tracked by this scope.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "40f51df4f2892dd3bd3230a5bc7ef89fbc43a43e5bccc53b33d52d611ec9a5d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: io_error\n\nDocumentation:\nAnnotates an I/O error with the position of the callable that generated it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn io_error(&self, e: io::Error) -> Error {\n Error::IoError(self.fref_pos, e)\n }\n```"}], "func_name": "io_error", "docstring": "Annotates an I/O error with the position of the callable that generated it.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b54dbb0a57f75a91d18751246436cbf0a9f3aa6eea5c7aa3149a4d7aea402524"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: internal_error\n\nDocumentation:\nCreates an internal error with the position of the callable that generated it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn internal_error>(&self, msg: S) -> Error {\n Error::InternalError(self.fref_pos, msg.into())\n }\n```"}], "func_name": "internal_error", "docstring": "Creates an internal error with the position of the callable that generated it.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ecbe79d7e9faaf4c62d2cbb829ef4ce4e4d39fc4f1d4b79976a846d126e05f9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pop_sep_tag\n\nDocumentation:\nPops the top of the stack as a separator tag.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pop_sep_tag(&mut self) -> ArgSep {\n const END_I32: i32 = ArgSep::End as i32;\n const SHORT_I32: i32 = ArgSep::Short as i32;\n const LONG_I32: i32 = ArgSep::Long as i32;\n const AS_I32: i32 = ArgSep::As as i32;\n\n match self.pop_integer() {\n END_I32 => ArgSep::End,\n SHORT_I32 => ArgSep::Short,\n LONG_I32 => ArgSep::Long,\n AS_I32 => ArgSep::As,\n _ => unreachable!(),\n }\n }\n```"}], "func_name": "pop_sep_tag", "docstring": "Pops the top of the stack as a separator tag.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "12e88e70e015448d422850eb5bf5679c86e6d461e7800a1dcfdcae6ac3c4a6cb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pop_value_tag\n\nDocumentation:\nPops the top of the stack as a value tag.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pop_value_tag(&mut self) -> ValueTag {\n const MISSING_I32: i32 = ValueTag::Missing as i32;\n const BOOLEAN_I32: i32 = ValueTag::Boolean as i32;\n const DOUBLE_I32: i32 = ValueTag::Double as i32;\n const INTEGER_I32: i32 = ValueTag::Integer as i32;\n const TEXT_I32: i32 = ValueTag::Text as i32;\n\n match self.pop_integer() {\n MISSING_I32 => ValueTag::Missing,\n BOOLEAN_I32 => ValueTag::Boolean,\n DOUBLE_I32 => ValueTag::Double,\n INTEGER_I32 => ValueTag::Integer,\n TEXT_I32 => ValueTag::Text,\n _ => unreachable!(),\n }\n }\n```"}], "func_name": "pop_value_tag", "docstring": "Pops the top of the stack as a value tag.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aaf5778d910a3bc173c3c000867587f268cb7c69c31a5c8922a9172d99d879e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pop_varref\n\nDocumentation:\nPops the top of the stack as a variable reference.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pop_varref(&mut self) -> (SymbolKey, ExprType) {\n let (key, etype, _pos) = self.pop_varref_with_pos();\n (key, etype)\n }\n```"}], "func_name": "pop_varref", "docstring": "Pops the top of the stack as a variable reference.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc70fb458d73f07b8a6569f2557cd7b946ffdd54759df2a860e6287b0f10b0bc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: return_any\n\nDocumentation:\nSets the return value of this function to `value`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn return_any(mut self, value: Value) -> Result<()> {\n self.drain();\n self.stack.push((value, self.fref_pos));\n Ok(())\n }\n```"}], "func_name": "return_any", "docstring": "Sets the return value of this function to `value`.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "717e7af09ceea45c4cfb544d32f99a338b53b2631b198846a5c501cc85587be8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: return_boolean\n\nDocumentation:\nSets the return value of this function to the boolean `value`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn return_boolean(mut self, value: bool) -> Result<()> {\n self.drain();\n self.stack.push((Value::Boolean(value), self.fref_pos));\n Ok(())\n }\n```"}], "func_name": "return_boolean", "docstring": "Sets the return value of this function to the boolean `value`.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5ec7122ed2c9afc6e4bd1bfec0fe82736a5822b69f0208b5869845fc5a164a1a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: return_double\n\nDocumentation:\nSets the return value of this function to the double `value`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn return_double(mut self, value: f64) -> Result<()> {\n self.drain();\n self.stack.push((Value::Double(value), self.fref_pos));\n Ok(())\n }\n```"}], "func_name": "return_double", "docstring": "Sets the return value of this function to the double `value`.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fcab8d8eed68e45318d70765ad2bc4e97886a0324d4ade0f925af283da51daed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: return_integer\n\nDocumentation:\nSets the return value of this function to the integer `value`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn return_integer(mut self, value: i32) -> Result<()> {\n self.drain();\n self.stack.push((Value::Integer(value), self.fref_pos));\n Ok(())\n }\n```"}], "func_name": "return_integer", "docstring": "Sets the return value of this function to the integer `value`.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a4d950e5bcbb49058d5da7c6ba9cc3bdc2fd0e462f258857ea79e175b4b1aa94"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: return_string\n\nDocumentation:\nSets the return value of this function to the string `value`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn return_string>(mut self, value: S) -> Result<()> {\n self.drain();\n self.stack.push((Value::Text(value.into()), self.fref_pos));\n Ok(())\n }\n```"}], "func_name": "return_string", "docstring": "Sets the return value of this function to the string `value`.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2c66b1ff2e6404ff1ad8c797a29b2067adb1e3a4f67435f7c530423774d3bb57"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_signals_chan\n\nDocumentation:\nConstructs a new empty machine with the given signals communication channel.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_signals_chan(signals: (Sender, Receiver)) -> Self {\n Self::with_signals_chan_and_yield_now_fn(signals, None)\n }\n```"}], "func_name": "with_signals_chan", "docstring": "Constructs a new empty machine with the given signals communication channel.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf836b422bba45d6b7b6a5f81d751ac04cd6f42a622c6f1697cd316c9967837a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_signals_chan_and_yield_now_fn\n\nDocumentation:\nConstructs a new empty machine with the given signals communication channel and yielding\nfunction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_signals_chan_and_yield_now_fn(\n signals: (Sender, Receiver),\n yield_now_fn: Option,\n ) -> Self {\n Self {\n symbols: Symbols::default(),\n clearables: vec![],\n yield_now_fn,\n signals_chan: signals,\n last_error: None,\n data: vec![],\n }\n }\n```"}], "func_name": "with_signals_chan_and_yield_now_fn", "docstring": "Constructs a new empty machine with the given signals communication channel and yielding\nfunction.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d5c9401674f4e9e984fea680b180f4a4c6c54a36fd76ad7be031d9a4a64380c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clear\n\nDocumentation:\nResets the state of the machine by clearing all variable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clear(&mut self) {\n for clearable in self.clearables.as_slice() {\n clearable.reset_state(&mut self.symbols);\n }\n self.symbols.clear();\n self.last_error = None;\n }\n```"}], "func_name": "clear", "docstring": "Resets the state of the machine by clearing all variable.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d699a7439779c8e086026275747cdd124b6fc8de2538d71a2150e5e6d2cb6f3e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_mut_symbols\n\nDocumentation:\nObtains mutable access to the state of the symbols.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_mut_symbols(&mut self) -> &mut Symbols {\n &mut self.symbols\n }\n```"}], "func_name": "get_mut_symbols", "docstring": "Obtains mutable access to the state of the symbols.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c434dc6121fd7555677c8f56060433f356afe9ec8bff592fe9d6e0a17bbd6c38"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: should_stop\n\nDocumentation:\nReturns true if execution should stop because we have hit a stop condition.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn should_stop(&mut self) -> bool {\n if let Some(yield_now) = self.yield_now_fn.as_ref() {\n (yield_now)().await;\n }\n\n match self.signals_chan.1.try_recv() {\n Ok(Signal::Break) => true,\n Err(TryRecvError::Empty) => false,\n Err(TryRecvError::Closed) => panic!(\"Channel unexpectedly closed\"),\n }\n }\n```"}], "func_name": "should_stop", "docstring": "Returns true if execution should stop because we have hit a stop condition.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e5de60947a5c06f1ec21e153856af12487ae8512082826f582944e0f5585d5ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dim_array\n\nDocumentation:\nHandles an array definition. The array must not yet exist, and the name may not overlap\nfunction or variable names.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn dim_array(&mut self, context: &mut Context, span: &DimArrayISpan) -> Result<()> {\n let mut ds = Vec::with_capacity(span.dimensions);\n for _ in 0..span.dimensions {\n let (i, pos) = context.value_stack.pop_integer_with_pos();\n if i <= 0 {\n return new_syntax_error(pos, \"Dimensions in DIM array must be positive\");\n }\n ds.push(i as usize);\n }\n if span.shared {\n self.symbols.dim_shared_array(span.name.clone(), span.subtype, ds);\n } else {\n self.symbols.dim_array(span.name.clone(), span.subtype, ds);\n }\n Ok(())\n }\n```"}], "func_name": "dim_array", "docstring": "Handles an array definition. The array must not yet exist, and the name may not overlap\nfunction or variable names.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b54ce131544de23d2afb6a2fba65b8c4408f701e6604180595ca88f9d8d8f8b5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: drain_signals\n\nDocumentation:\nConsumes any pending signals so that they don't interfere with an upcoming execution.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn drain_signals(&mut self) {\n while self.signals_chan.1.try_recv().is_ok() {\n // Do nothing.\n }\n }\n```"}], "func_name": "drain_signals", "docstring": "Consumes any pending signals so that they don't interfere with an upcoming execution.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27b04a7a2dda4d8295a5e3d9ee33ecd5595c25ed7732af366a71f375cd86997e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: end\n\nDocumentation:\nTells the machine to stop execution at the next statement boundary.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn end(&mut self, context: &mut Context, has_code: bool) -> Result {\n let code = if has_code {\n let (code, code_pos) = context.value_stack.pop_integer_with_pos();\n if code < 0 {\n return new_syntax_error(\n code_pos,\n \"Exit code must be a positive integer\".to_owned(),\n );\n }\n if code >= 128 {\n return new_syntax_error(\n code_pos,\n \"Exit code cannot be larger than 127\".to_owned(),\n );\n }\n code as u8\n } else {\n 0\n };\n Ok(InternalStopReason::Exited(code))\n }\n```"}], "func_name": "end", "docstring": "Tells the machine to stop execution at the next statement boundary.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "62c6502f7dd3b537477b31f2371901cb148d54d6d0748865b76a0aca77c67db0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_logical_op1\n\nDocumentation:\nHandles a unary logical operator that cannot fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_logical_op1 bool>(context: &mut Context, op: F, pos: LineCol) {\n let rhs = context.value_stack.pop_boolean();\n context.value_stack.push_boolean(op(rhs), pos);\n }\n```"}], "func_name": "exec_logical_op1", "docstring": "Handles a unary logical operator that cannot fail.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f14d5a6f9acf0ca48e598c3a06764e793cf40d877f777e2bf8c00f9879537e2d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_logical_op2\n\nDocumentation:\nHandles a binary logical operator that cannot fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_logical_op2 bool>(context: &mut Context, op: F, pos: LineCol) {\n let rhs = context.value_stack.pop_boolean();\n let lhs = context.value_stack.pop_boolean();\n context.value_stack.push_boolean(op(lhs, rhs), pos);\n }\n```"}], "func_name": "exec_logical_op2", "docstring": "Handles a binary logical operator that cannot fail.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "95cb6fb090dad8d6ef44196e4629e7bb0e1701bdfdeccce87478666008df3ef5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_bitwise_op1\n\nDocumentation:\nHandles a unary bitwise operator that cannot fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_bitwise_op1 i32>(context: &mut Context, op: F, pos: LineCol) {\n let rhs = context.value_stack.pop_integer();\n context.value_stack.push_integer(op(rhs), pos);\n }\n```"}], "func_name": "exec_bitwise_op1", "docstring": "Handles a unary bitwise operator that cannot fail.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a7fa8ea54125e693840419d80317bf6e24fb92fddb25271145bfa02a44767704"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_bitwise_op2\n\nDocumentation:\nHandles a binary bitwise operator that cannot fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_bitwise_op2 i32>(context: &mut Context, op: F, pos: LineCol) {\n let rhs = context.value_stack.pop_integer();\n let lhs = context.value_stack.pop_integer();\n context.value_stack.push_integer(op(lhs, rhs), pos);\n }\n```"}], "func_name": "exec_bitwise_op2", "docstring": "Handles a binary bitwise operator that cannot fail.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51b5d1b0ccf1d974aa05ea1a1ff230065d9d5f8400c6c9c5f7e0ece1fa057216"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_bitwise_op2_err\n\nDocumentation:\nHandles a binary bitwise operator that can fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_bitwise_op2_err value::Result>(\n context: &mut Context,\n op: F,\n pos: LineCol,\n ) -> Result<()> {\n let rhs = context.value_stack.pop_integer();\n let lhs = context.value_stack.pop_integer();\n let result = op(lhs, rhs).map_err(|e| Error::from_value_error(e, pos))?;\n context.value_stack.push_integer(result, pos);\n Ok(())\n }\n```"}], "func_name": "exec_bitwise_op2_err", "docstring": "Handles a binary bitwise operator that can fail.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa363c105ce37569a36d127af8267ba0171c17abeab2ed27be90995d5f900090"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_equality_boolean_op2\n\nDocumentation:\nHandles a binary equality operator for booleans that cannot fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_equality_boolean_op2 bool>(\n context: &mut Context,\n op: F,\n pos: LineCol,\n ) {\n let rhs = context.value_stack.pop_boolean();\n let lhs = context.value_stack.pop_boolean();\n context.value_stack.push_boolean(op(lhs, rhs), pos);\n }\n```"}], "func_name": "exec_equality_boolean_op2", "docstring": "Handles a binary equality operator for booleans that cannot fail.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "509aba03a6631cd7f8e208ad1a50b5519505f498319dd0d82b20f5461ddc240f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_equality_double_op2\n\nDocumentation:\nHandles a binary equality operator for doubles that cannot fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_equality_double_op2 bool>(\n context: &mut Context,\n op: F,\n pos: LineCol,\n ) {\n let rhs = context.value_stack.pop_double();\n let lhs = context.value_stack.pop_double();\n context.value_stack.push_boolean(op(lhs, rhs), pos);\n }\n```"}], "func_name": "exec_equality_double_op2", "docstring": "Handles a binary equality operator for doubles that cannot fail.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a4bc8963d1bf7cbf3871e36303867e6dd5c3f35cd4c09ddd6462b9368dec141"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_equality_integer_op2\n\nDocumentation:\nHandles a binary equality operator for integers that cannot fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_equality_integer_op2 bool>(\n context: &mut Context,\n op: F,\n pos: LineCol,\n ) {\n let rhs = context.value_stack.pop_integer();\n let lhs = context.value_stack.pop_integer();\n context.value_stack.push_boolean(op(lhs, rhs), pos);\n }\n```"}], "func_name": "exec_equality_integer_op2", "docstring": "Handles a binary equality operator for integers that cannot fail.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "109837f4a89a739dc14e5fe942e7621ce5e481c275a6af8a764f250298650665"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_equality_string_op2\n\nDocumentation:\nHandles a binary equality operator for strings that cannot fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_equality_string_op2 bool>(\n context: &mut Context,\n op: F,\n pos: LineCol,\n ) {\n let rhs = context.value_stack.pop_string();\n let lhs = context.value_stack.pop_string();\n context.value_stack.push_boolean(op(&lhs, &rhs), pos);\n }\n```"}], "func_name": "exec_equality_string_op2", "docstring": "Handles a binary equality operator for strings that cannot fail.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "db4951e9741fbe220a4e635a030686e1c7d661428c48ce511835bd098221477c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_arithmetic_double_op1\n\nDocumentation:\nHandles a unary arithmetic operator for doubles that cannot fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_arithmetic_double_op1 f64>(context: &mut Context, op: F, pos: LineCol) {\n let rhs = context.value_stack.pop_double();\n context.value_stack.push_double(op(rhs), pos);\n }\n```"}], "func_name": "exec_arithmetic_double_op1", "docstring": "Handles a unary arithmetic operator for doubles that cannot fail.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0435065f74cb14021f56a711ad9242277d872771501645f02eb58e2b2ad724f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_arithmetic_double_op2\n\nDocumentation:\nHandles a binary arithmetic operator for doubles that cannot fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_arithmetic_double_op2 f64>(\n context: &mut Context,\n op: F,\n pos: LineCol,\n ) {\n let rhs = context.value_stack.pop_double();\n let lhs = context.value_stack.pop_double();\n context.value_stack.push_double(op(lhs, rhs), pos);\n }\n```"}], "func_name": "exec_arithmetic_double_op2", "docstring": "Handles a binary arithmetic operator for doubles that cannot fail.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "052e8934b98cd01a6fe0c756198150eaad9d80e91b33027c2f8490f7df5ed296"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_arithmetic_integer_op1\n\nDocumentation:\nHandles a unary arithmetic operator for doubles that can fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_arithmetic_integer_op1 value::Result>(\n context: &mut Context,\n op: F,\n pos: LineCol,\n ) -> Result<()> {\n let rhs = context.value_stack.pop_integer();\n let result = op(rhs).map_err(|e| Error::from_value_error(e, pos))?;\n context.value_stack.push_integer(result, pos);\n Ok(())\n }\n```"}], "func_name": "exec_arithmetic_integer_op1", "docstring": "Handles a unary arithmetic operator for doubles that can fail.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "68b75dcae9e75453622833b774b2a57c82a08824a3efa1f12ef034532239e4e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_arithmetic_integer_op2\n\nDocumentation:\nHandles a binary arithmetic operator for doubles that can fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_arithmetic_integer_op2 value::Result>(\n context: &mut Context,\n op: F,\n pos: LineCol,\n ) -> Result<()> {\n let rhs = context.value_stack.pop_integer();\n let lhs = context.value_stack.pop_integer();\n let result = op(lhs, rhs).map_err(|e| Error::from_value_error(e, pos))?;\n context.value_stack.push_integer(result, pos);\n Ok(())\n }\n```"}], "func_name": "exec_arithmetic_integer_op2", "docstring": "Handles a binary arithmetic operator for doubles that can fail.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d370a67b4a8db8897aa9b3ddaa43e712c402fcb98d12a9a2ee904d392581493"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_array_args\n\nDocumentation:\nEvaluates the subscripts of an array reference.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_array_args(&self, context: &mut Context, nargs: usize) -> Result> {\n let mut subscripts = Vec::with_capacity(nargs);\n for _ in 0..nargs {\n let i = context.value_stack.pop_integer();\n subscripts.push(i);\n }\n Ok(subscripts)\n }\n```"}], "func_name": "get_array_args", "docstring": "Evaluates the subscripts of an array reference.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "97462962d5b93f42f5998a23929b9ee32a8556a7c6d80ffcf886c3ae63168a5f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_function_call\n\nDocumentation:\nEvaluates a function call specified by `fref` and arguments `args` on the function `f`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn do_function_call(\n &mut self,\n context: &mut Context,\n return_type: ExprType,\n fref_pos: LineCol,\n nargs: usize,\n f: Rc,\n ) -> Result<()> {\n let metadata = f.metadata();\n debug_assert_eq!(return_type, metadata.return_type().unwrap());\n\n let scope = Scope::new(&mut context.value_stack, nargs, fref_pos);\n f.exec(scope, self).await?;\n if cfg!(debug_assertions) {\n match context.value_stack.top() {\n Some((value, _pos)) => {\n debug_assert_eq!(\n return_type,\n value.as_exprtype(),\n \"Value returned by function is incompatible with its type definition\",\n )\n }\n None => unreachable!(\"Functions must return one value\"),\n }\n }\n Ok(())\n }\n```"}], "func_name": "do_function_call", "docstring": "Evaluates a function call specified by `fref` and arguments `args` on the function `f`.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e1c049b7511af67a51b2889cfb9e853012d51074189615a8d96448f25148ccda"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: argless_function_call\n\nDocumentation:\nEvaluates a call to an argless function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn argless_function_call(\n &mut self,\n context: &mut Context,\n fname: &SymbolKey,\n ftype: ExprType,\n fpos: LineCol,\n f: Rc,\n ) -> Result<()> {\n let scope = Scope::new(&mut context.value_stack, 0, fpos);\n f.exec(scope, self).await?;\n if cfg!(debug_assertions) {\n match context.value_stack.top() {\n Some((value, _pos)) => {\n let fref_checker = VarRef::new(fname.to_string(), Some(ftype));\n debug_assert!(\n fref_checker.accepts(value.as_exprtype()),\n \"Value returned by function is incompatible with its type definition\",\n )\n }\n None => unreachable!(\"Functions must return one value\"),\n }\n }\n Ok(())\n }\n```"}], "func_name": "argless_function_call", "docstring": "Evaluates a call to an argless function.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1cbd7ab1a2314d7fe666a8c92922b889049389396a963563c19dad6b10edcbe6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_until_stop\n\nDocumentation:\nExecutes as many instructions as possible from `instrs`, starting at `context.pc`, until an\ninstruction asks to stop or execution reaches the end of the program.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn exec_until_stop(\n &mut self,\n context: &mut Context,\n instrs: &[Instruction],\n ) -> Result {\n while context.pc < instrs.len() {\n let instr = &instrs[context.pc];\n match instr {\n Instruction::LogicalAnd(pos) => {\n Machine::exec_logical_op2(context, |lhs, rhs| lhs && rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::LogicalOr(pos) => {\n Machine::exec_logical_op2(context, |lhs, rhs| lhs || rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::LogicalXor(pos) => {\n Machine::exec_logical_op2(context, |lhs, rhs| lhs ^ rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::LogicalNot(pos) => {\n Machine::exec_logical_op1(context, |rhs| !rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::BitwiseAnd(pos) => {\n Machine::exec_bitwise_op2(context, |lhs, rhs| lhs & rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::BitwiseOr(pos) => {\n Machine::exec_bitwise_op2(context, |lhs, rhs| lhs | rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::BitwiseXor(pos) => {\n Machine::exec_bitwise_op2(context, |lhs, rhs| lhs ^ rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::BitwiseNot(pos) => {\n Machine::exec_bitwise_op1(context, |rhs| !rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::ShiftLeft(pos) => {\n Machine::exec_bitwise_op2_err(context, value::bitwise_shl, *pos)?;\n context.pc += 1;\n }\n\n Instruction::ShiftRight(pos) => {\n Machine::exec_bitwise_op2_err(context, value::bitwise_shr, *pos)?;\n context.pc += 1;\n }\n\n Instruction::EqualBooleans(pos) => {\n Machine::exec_equality_boolean_op2(context, |lhs, rhs| lhs == rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::NotEqualBooleans(pos) => {\n Machine::exec_equality_boolean_op2(context, |lhs, rhs| lhs != rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::EqualDoubles(pos) => {\n Machine::exec_equality_double_op2(context, |lhs, rhs| lhs == rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::NotEqualDoubles(pos) => {\n Machine::exec_equality_double_op2(context, |lhs, rhs| lhs != rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::LessDoubles(pos) => {\n Machine::exec_equality_double_op2(context, |lhs, rhs| lhs < rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::LessEqualDoubles(pos) => {\n Machine::exec_equality_double_op2(context, |lhs, rhs| lhs <= rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::GreaterDoubles(pos) => {\n Machine::exec_equality_double_op2(context, |lhs, rhs| lhs > rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::GreaterEqualDoubles(pos) => {\n Machine::exec_equality_double_op2(context, |lhs, rhs| lhs >= rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::EqualIntegers(pos) => {\n Machine::exec_equality_integer_op2(context, |lhs, rhs| lhs == rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::NotEqualIntegers(pos) => {\n Machine::exec_equality_integer_op2(context, |lhs, rhs| lhs != rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::LessIntegers(pos) => {\n Machine::exec_equality_integer_op2(context, |lhs, rhs| lhs < rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::LessEqualIntegers(pos) => {\n Machine::exec_equality_integer_op2(context, |lhs, rhs| lhs <= rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::GreaterIntegers(pos) => {\n Machine::exec_equality_integer_op2(context, |lhs, rhs| lhs > rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::GreaterEqualIntegers(pos) => {\n Machine::exec_equality_integer_op2(context, |lhs, rhs| lhs >= rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::EqualStrings(pos) => {\n Machine::exec_equality_string_op2(context, |lhs, rhs| lhs == rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::NotEqualStrings(pos) => {\n Machine::exec_equality_string_op2(context, |lhs, rhs| lhs != rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::LessStrings(pos) => {\n Machine::exec_equality_string_op2(context, |lhs, rhs| lhs < rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::LessEqualStrings(pos) => {\n Machine::exec_equality_string_op2(context, |lhs, rhs| lhs <= rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::GreaterStrings(pos) => {\n Machine::exec_equality_string_op2(context, |lhs, rhs| lhs > rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::GreaterEqualStrings(pos) => {\n Machine::exec_equality_string_op2(context, |lhs, rhs| lhs >= rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::AddDoubles(pos) => {\n Machine::exec_arithmetic_double_op2(context, |lhs, rhs| lhs + rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::SubtractDoubles(pos) => {\n Machine::exec_arithmetic_double_op2(context, |lhs, rhs| lhs - rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::MultiplyDoubles(pos) => {\n Machine::exec_arithmetic_double_op2(context, |lhs, rhs| lhs * rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::DivideDoubles(pos) => {\n Machine::exec_arithmetic_double_op2(context, |lhs, rhs| lhs / rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::ModuloDoubles(pos) => {\n Machine::exec_arithmetic_double_op2(context, |lhs, rhs| lhs % rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::PowerDoubles(pos) => {\n Machine::exec_arithmetic_double_op2(context, |lhs, rhs| lhs.powf(rhs), *pos);\n context.pc += 1;\n }\n\n Instruction::NegateDouble(pos) => {\n Machine::exec_arithmetic_double_op1(context, |rhs| -rhs, *pos);\n context.pc += 1;\n }\n\n Instruction::AddIntegers(pos) => {\n Machine::exec_arithmetic_integer_op2(context, value::add_integer, *pos)?;\n context.pc += 1;\n }\n\n Instruction::SubtractIntegers(pos) => {\n Machine::exec_arithmetic_integer_op2(context, value::sub_integer, *pos)?;\n context.pc += 1;\n }\n\n Instruction::MultiplyIntegers(pos) => {\n Machine::exec_arithmetic_integer_op2(context, value::mul_integer, *pos)?;\n context.pc += 1;\n }\n\n Instruction::DivideIntegers(pos) => {\n Machine::exec_arithmetic_integer_op2(context, value::div_integer, *pos)?;\n context.pc += 1;\n }\n\n Instruction::ModuloIntegers(pos) => {\n Machine::exec_arithmetic_integer_op2(context, value::modulo_integer, *pos)?;\n context.pc += 1;\n }\n\n Instruction::PowerIntegers(pos) => {\n Machine::exec_arithmetic_integer_op2(context, value::pow_integer, *pos)?;\n context.pc += 1;\n }\n\n Instruction::NegateInteger(pos) => {\n Machine::exec_arithmetic_integer_op1(context, value::neg_integer, *pos)?;\n context.pc += 1;\n }\n\n Instruction::ConcatStrings(pos) => {\n Machine::exec_arithmetic_string_op2(\n context,\n |lhs, rhs| lhs.to_owned() + rhs,\n *pos,\n );\n context.pc += 1;\n }\n\n Instruction::Assign(key) => {\n let (value, _pos) = context.value_stack.pop().unwrap();\n self.symbols.assign(key, value);\n context.pc += 1;\n }\n\n Instruction::ArrayAssignment(name, vref_pos, nargs) => {\n self.assign_array(context, name, *vref_pos, *nargs)?;\n context.pc += 1;\n }\n\n Instruction::ArrayLoad(name, pos, nargs) => {\n self.array_ref(context, name, *pos, *nargs)?;\n context.pc += 1;\n }\n\n Instruction::BuiltinCall(name, bref_pos, nargs) => {\n return Ok(InternalStopReason::Upcall(UpcallData {\n name: name.clone(),\n return_type: None,\n pos: *bref_pos,\n nargs: *nargs,\n }));\n }\n\n Instruction::Call(span) => {\n context.addr_stack.push(context.pc + 1);\n context.pc = span.addr;\n }\n\n Instruction::DoubleToInteger => {\n let (d, pos) = context.value_stack.pop_double_with_pos();\n let i = double_to_integer(d.round())\n .map_err(|e| Error::from_value_error(e, pos))?;\n context.value_stack.push_integer(i, pos);\n context.pc += 1;\n }\n\n Instruction::FunctionCall(name, return_type, pos, nargs) => {\n return Ok(InternalStopReason::Upcall(UpcallData {\n name: name.clone(),\n return_type: Some(*return_type),\n pos: *pos,\n nargs: *nargs,\n }));\n }\n\n Instruction::Dim(span) => {\n if span.shared {\n self.symbols.dim_shared(span.name.clone(), span.vtype);\n } else {\n self.symbols.dim(span.name.clone(), span.vtype);\n }\n context.pc += 1;\n }\n\n Instruction::DimArray(span) => {\n self.dim_array(context, span)?;\n context.pc += 1;\n }\n\n Instruction::End(has_code) => {\n context.pc += 1;\n return self.end(context, *has_code);\n }\n\n Instruction::EnterScope => {\n self.symbols.enter_scope();\n context.pc += 1;\n }\n\n Instruction::IntegerToDouble => {\n let (i, pos) = context.value_stack.pop_integer_with_pos();\n context.value_stack.push_double(i as f64, pos);\n context.pc += 1;\n }\n\n Instruction::Jump(span) => {\n let old_pc = context.pc;\n context.pc = span.addr;\n if span.addr <= old_pc {\n return Ok(InternalStopReason::CheckStop);\n }\n }\n\n Instruction::JumpIfDefined(span) => {\n if self.symbols.load(&span.var).is_some() {\n let old_pc = context.pc;\n context.pc = span.addr;\n if span.addr <= old_pc {\n return Ok(InternalStopReason::CheckStop);\n }\n } else {\n context.pc += 1;\n }\n }\n\n Instruction::JumpIfTrue(addr) => {\n let cond = context.value_stack.pop_boolean();\n if cond {\n let old_pc = context.pc;\n context.pc = *addr;\n if *addr <= old_pc {\n return Ok(InternalStopReason::CheckStop);\n }\n } else {\n context.pc += 1;\n }\n }\n\n Instruction::JumpIfNotTrue(addr) => {\n let cond = context.value_stack.pop_boolean();\n if cond {\n context.pc += 1;\n } else {\n let old_pc = context.pc;\n context.pc = *addr;\n if *addr <= old_pc {\n return Ok(InternalStopReason::CheckStop);\n }\n }\n }\n\n Instruction::LeaveScope => {\n self.symbols.leave_scope();\n context.pc += 1;\n }\n\n Instruction::LoadBoolean(key, pos) => {\n let b = match self.load(key, *pos)? {\n Value::Boolean(b) => b,\n _ => unreachable!(\"Types are validated at compilation time\"),\n };\n context.value_stack.push_boolean(*b, *pos);\n context.pc += 1;\n }\n\n Instruction::LoadDouble(key, pos) => {\n let d = match self.load(key, *pos)? {\n Value::Double(d) => d,\n _ => unreachable!(\"Types are validated at compilation time\"),\n };\n context.value_stack.push_double(*d, *pos);\n context.pc += 1;\n }\n\n Instruction::LoadInteger(key, pos) => {\n let i = match self.load(key, *pos)? {\n Value::Integer(i) => i,\n _ => unreachable!(\"Types are validated at compilation time\"),\n };\n context.value_stack.push_integer(*i, *pos);\n context.pc += 1;\n }\n\n Instruction::LoadString(key, pos) => {\n let s = match self.load(key, *pos)? {\n Value::Text(s) => s,\n _ => unreachable!(\"Types are validated at compilation time\"),\n };\n context.value_stack.push_string(s.clone(), *pos);\n context.pc += 1;\n }\n\n Instruction::LoadRef(key, etype, pos) => {\n let sym = self.symbols.load(key);\n if let Some(Symbol::Callable(f)) = sym {\n if f.metadata().is_argless() {\n return Ok(InternalStopReason::Upcall(UpcallData {\n name: key.clone(),\n return_type: Some(*etype),\n pos: *pos,\n nargs: 0,\n }));\n }\n };\n\n context.value_stack.push_varref(key.clone(), *etype, *pos);\n context.pc += 1;\n }\n\n Instruction::Nop => {\n context.pc += 1;\n }\n\n Instruction::PushBoolean(value, pos) => {\n context.value_stack.push((Value::Boolean(*value), *pos));\n context.pc += 1;\n }\n\n Instruction::PushDouble(value, pos) => {\n context.value_stack.push((Value::Double(*value), *pos));\n context.pc += 1;\n }\n\n Instruction::PushInteger(value, pos) => {\n context.value_stack.push((Value::Integer(*value), *pos));\n context.pc += 1;\n }\n\n Instruction::PushString(value, pos) => {\n context.value_stack.push((Value::Text(value.clone()), *pos));\n context.pc += 1;\n }\n\n Instruction::Return(pos) => match context.addr_stack.pop() {\n Some(addr) => {\n context.pc = addr;\n return Ok(InternalStopReason::CheckStop);\n }\n None => return new_syntax_error(*pos, \"No address to return to\".to_owned()),\n },\n\n Instruction::SetErrorHandler(span) => {\n context.err_handler = *span;\n context.pc += 1;\n }\n\n Instruction::Unset(span) => {\n self.symbols\n .unset(&span.name)\n .expect(\"Should only unset variables that were set\");\n context.pc += 1;\n }\n }\n }\n\n Ok(InternalStopReason::Eof)\n }\n```"}], "func_name": "exec_until_stop", "docstring": "Executes as many instructions as possible from `instrs`, starting at `context.pc`, until an\ninstruction asks to stop or execution reaches the end of the program.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c3cdb4d08ceba8acc50fd4df7eb312c4e1cd827d200e5a3ce5fe40471edb26c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_error\n\nDocumentation:\nHandles the given error `e` according to the current error handler previously set by\n`ON ERROR`. If the error can be handled gracefully, returns `Ok`; otherwise, returns the\ninput error unmodified.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_error(\n &mut self,\n instrs: &[Instruction],\n context: &mut Context,\n e: Error,\n ) -> Result<()> {\n if !e.is_catchable() {\n return Err(e);\n }\n\n self.last_error = Some(format!(\"{}\", e));\n\n match context.err_handler {\n ErrorHandlerISpan::Jump(addr) => {\n context.pc = addr;\n Ok(())\n }\n ErrorHandlerISpan::None => Err(e),\n ErrorHandlerISpan::ResumeNext => {\n if instrs[context.pc].is_statement() {\n context.pc += 1;\n } else {\n loop {\n context.pc += 1;\n if context.pc >= instrs.len() {\n break;\n } else if instrs[context.pc].is_statement() {\n context.pc += 1;\n break;\n }\n }\n }\n Ok(())\n }\n }\n }\n```"}], "func_name": "handle_error", "docstring": "Handles the given error `e` according to the current error handler previously set by\n`ON ERROR`. If the error can be handled gracefully, returns `Ok`; otherwise, returns the\ninput error unmodified.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b5d0153c003073693a961a95926551c9f38b530f39d4ae3e8d7a378821a7e62a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_with_data\n\nDocumentation:\nExecutes the instructions given in `instr`.\n\nThis is a helper to `exec`, which prepares the machine with the program's data upfront.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn exec_with_data(&mut self, instrs: &[Instruction]) -> Result {\n let mut context = Context::default();\n while context.pc < instrs.len() {\n match self.exec_until_stop(&mut context, instrs) {\n Ok(InternalStopReason::CheckStop) => {\n if self.should_stop().await {\n return Ok(StopReason::Break);\n }\n }\n\n Ok(InternalStopReason::Upcall(data)) => {\n let result;\n if let Some(return_type) = data.return_type {\n result = self\n .function_call(\n &mut context,\n &data.name,\n return_type,\n data.pos,\n data.nargs,\n )\n .await;\n } else {\n result =\n self.builtin_call(&mut context, &data.name, data.pos, data.nargs).await;\n }\n match result {\n Ok(()) => context.pc += 1,\n Err(e) => self.handle_error(instrs, &mut context, e)?,\n }\n }\n\n Ok(InternalStopReason::Eof) => {\n return Ok(StopReason::Eof);\n }\n\n Ok(InternalStopReason::Exited(code)) => {\n return Ok(StopReason::Exited(code));\n }\n\n Err(e) => self.handle_error(instrs, &mut context, e)?,\n }\n }\n Ok(StopReason::Eof)\n }\n```"}], "func_name": "exec_with_data", "docstring": "Executes the instructions given in `instr`.\n\nThis is a helper to `exec`, which prepares the machine with the program's data upfront.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "50f87ff1f1b705163dd483cf21cf97fa455895db0bdae4855ca7df87ec407831"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec\n\nDocumentation:\nExecutes a program extracted from the `input` readable.\n\nNote that this does not consume `self`. As a result, it is possible to execute multiple\ndifferent programs on the same machine, all sharing state.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn exec(&mut self, input: &mut dyn io::Read) -> Result {\n let image = compiler::compile(input, &self.symbols)?;\n\n assert!(self.data.is_empty());\n self.data = image.data;\n let result = self.exec_with_data(&image.instrs).await;\n self.data.clear();\n result\n }\n```"}], "func_name": "exec", "docstring": "Executes a program extracted from the `input` readable.\n\nNote that this does not consume `self`. As a result, it is possible to execute multiple\ndifferent programs on the same machine, all sharing state.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a5f18f146bb035717058e645623053e2c33a2eec017b4e910fe61b00d382e4a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRuns the `input` code on a new test machine.\n\n`golden_in` is the sequence of values to yield by `IN`.\n`expected_out` is updated with the sequence of calls to `OUT`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn run(\n input: &str,\n golden_in: &'static [&'static str],\n captured_out: Rc>>,\n ) -> Result {\n let mut machine = Machine::default();\n machine.add_callable(ArglessFunction::new(Value::Integer(1234)));\n machine.add_callable(ClearCommand::new());\n machine.add_callable(CountFunction::new());\n machine.add_callable(LastErrorFunction::new());\n machine.add_callable(InCommand::new(Box::from(RefCell::from(golden_in.iter()))));\n machine.add_callable(OutCommand::new(captured_out.clone()));\n machine.add_callable(OutfFunction::new(captured_out));\n machine.add_callable(RaiseCommand::new());\n machine.add_callable(RaisefFunction::new());\n machine.add_callable(SumFunction::new());\n machine.add_callable(TypeCheckFunction::new(Value::Integer(5)));\n block_on(machine.exec(&mut input.as_bytes()))\n }\n```"}], "func_name": "run", "docstring": "Runs the `input` code on a new test machine.\n\n`golden_in` is the sequence of values to yield by `IN`.\n`expected_out` is updated with the sequence of calls to `OUT`.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "537acdcd9735812291f62e4f7edf8018bf23bc313455b9b3363ae6770d4b93d8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_ok_test\n\nDocumentation:\nRuns the `input` code on a new test machine and verifies its output.\n\n`golden_in` is the sequence of values to yield by `IN`.\n`expected_out` is the sequence of expected calls to `OUT`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_ok_test(\n input: &str,\n golden_in: &'static [&'static str],\n expected_out: &'static [&'static str],\n ) {\n let captured_out = Rc::from(RefCell::from(vec![]));\n assert_eq!(\n StopReason::Eof,\n run(input, golden_in, captured_out.clone()).expect(\"Execution failed\")\n );\n assert_eq!(expected_out, captured_out.borrow().as_slice());\n }\n```"}], "func_name": "do_ok_test", "docstring": "Runs the `input` code on a new test machine and verifies its output.\n\n`golden_in` is the sequence of values to yield by `IN`.\n`expected_out` is the sequence of expected calls to `OUT`.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "063c751e3c290a5be47006ba0a579b3556ff07726ff780419e921139ee8dc36b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_error_test\n\nDocumentation:\nRuns the `input` code on a new test machine and verifies that it fails with `expected_err`.\n\nGiven that the code has side-effects until it fails, this follows the same process as\n`do_ok_test` regarding `golden_in` and `expected_out`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_error_test(\n input: &str,\n golden_in: &'static [&'static str],\n expected_out: &'static [&'static str],\n expected_err: &str,\n ) {\n let captured_out = Rc::from(RefCell::from(vec![]));\n let err = run(input, golden_in, captured_out.clone()).expect_err(\"Execution did not fail\");\n assert_eq!(expected_err, format!(\"{}\", err));\n assert_eq!(expected_out, captured_out.borrow().as_slice());\n }\n```"}], "func_name": "do_error_test", "docstring": "Runs the `input` code on a new test machine and verifies that it fails with `expected_err`.\n\nGiven that the code has side-effects until it fails, this follows the same process as\n`do_ok_test` regarding `golden_in` and `expected_out`.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bde40c70eb7664835cd9c0a9d648d01e3921b8f862b5ce6a2012e502057f5651"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_simple_error_test\n\nDocumentation:\nRuns the `input` code on a new machine and verifies that it fails with `expected_err`.\n\nThis is a syntactic wrapper over `do_error_test` to simplify those tests that are not\nexpected to request any input nor generate any output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_simple_error_test(input: &str, expected_err: &str) {\n do_error_test(input, &[], &[], expected_err);\n }\n```"}], "func_name": "do_simple_error_test", "docstring": "Runs the `input` code on a new machine and verifies that it fails with `expected_err`.\n\nThis is a syntactic wrapper over `do_error_test` to simplify those tests that are not\nexpected to request any input nor generate any output.", "repo": "endbasic/endbasic", "path": "core/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f950993ef947b24df3aedce5147fdb60bf1eb9c31e11cef2b08f77061a56960"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `TokenSpan` from its parts.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(token: Token, pos: LineCol, length: usize) -> Self {\n Self { token, pos, length }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `TokenSpan` from its parts.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9828ca1c11da7bbe32ed1968aeecd085ff212edf44c772572ebe08ad92033336"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nCreates a new lexer from the given readable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from(input: &'a mut dyn io::Read) -> Self {\n Self { input: CharReader::from(input) }\n }\n```"}], "func_name": "from", "docstring": "Creates a new lexer from the given readable.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2660f0a42b5ed26a6c628bb70a71425ebc156133b514e83bed28d76cd75dbc0c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_bad_read\n\nDocumentation:\nHandles an `input.next()` call that returned an unexpected character.\n\nThis returns a `Token::Bad` with the provided `msg` and skips characters in the input\nstream until a field separator is found.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_bad_read>(\n &mut self,\n msg: S,\n first_pos: LineCol,\n ) -> io::Result {\n let mut len = 1;\n loop {\n match self.input.peek() {\n Some(Ok(ch_span)) if ch_span.ch.is_separator() => break,\n Some(Ok(_)) => {\n self.input.next().unwrap()?;\n len += 1;\n }\n Some(Err(_)) => return Err(self.input.next().unwrap().unwrap_err()),\n None => break,\n }\n }\n Ok(TokenSpan::new(Token::Bad(msg.into()), first_pos, len))\n }\n```"}], "func_name": "handle_bad_read", "docstring": "Handles an `input.next()` call that returned an unexpected character.\n\nThis returns a `Token::Bad` with the provided `msg` and skips characters in the input\nstream until a field separator is found.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "08f3832fe23031d8131b595363724f1de7b8614f29a6fae2f4e912471c2320a9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: consume_number\n\nDocumentation:\nConsumes the number at the current position, whose first digit is `first`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn consume_number(&mut self, first: CharSpan) -> io::Result {\n let mut s = String::new();\n let mut found_dot = false;\n s.push(first.ch);\n loop {\n match self.input.peek() {\n Some(Ok(ch_span)) => match ch_span.ch {\n '.' => {\n if found_dot {\n self.input.next().unwrap()?;\n return self\n .handle_bad_read(\"Too many dots in numeric literal\", first.pos);\n }\n s.push(self.input.next().unwrap()?.ch);\n found_dot = true;\n }\n ch if ch.is_ascii_digit() => s.push(self.input.next().unwrap()?.ch),\n ch if ch.is_separator() => break,\n ch => {\n self.input.next().unwrap()?;\n let msg = format!(\"Unexpected character in numeric literal: {}\", ch);\n return self.handle_bad_read(msg, first.pos);\n }\n },\n Some(Err(_)) => return Err(self.input.next().unwrap().unwrap_err()),\n None => break,\n }\n }\n if found_dot {\n if s.ends_with('.') {\n // TODO(jmmv): Reconsider supporting double literals with a . that is not prefixed\n // by a number or not followed by a number. For now, mimic the error we get when\n // we encounter a dot not prefixed by a number.\n return self.handle_bad_read(\"Unknown character: .\", first.pos);\n }\n match s.parse::() {\n Ok(d) => Ok(TokenSpan::new(Token::Double(d), first.pos, s.len())),\n Err(e) => self.handle_bad_read(format!(\"Bad double {}: {}\", s, e), first.pos),\n }\n } else {\n match s.parse::() {\n Ok(i) => Ok(TokenSpan::new(Token::Integer(i), first.pos, s.len())),\n Err(e) => self.handle_bad_read(format!(\"Bad integer {}: {}\", s, e), first.pos),\n }\n }\n }\n```"}], "func_name": "consume_number", "docstring": "Consumes the number at the current position, whose first digit is `first`.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "414e3f6f9ffb127e7600b5e1b642a270d8ba360f66d8c534d8429e6b1e1b8238"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: consume_integer\n\nDocumentation:\nConsumes the integer at the current position, whose first digit is `first` and which is\nexpected to be expressed in the given `base`. `prefix_len` indicates how many characters\nwere already consumed for this token, without counting `first`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn consume_integer(\n &mut self,\n base: u8,\n pos: LineCol,\n prefix_len: usize,\n ) -> io::Result {\n let mut s = String::new();\n loop {\n match self.input.peek() {\n Some(Ok(ch_span)) => match ch_span.ch {\n '.' => {\n self.input.next().unwrap()?;\n return self\n .handle_bad_read(\"Numbers in base syntax must be integers\", pos);\n }\n ch if ch.is_ascii_digit() => s.push(self.input.next().unwrap()?.ch),\n 'a'..='f' | 'A'..='F' => s.push(self.input.next().unwrap()?.ch),\n ch if ch.is_separator() => break,\n ch => {\n self.input.next().unwrap()?;\n let msg = format!(\"Unexpected character in numeric literal: {}\", ch);\n return self.handle_bad_read(msg, pos);\n }\n },\n Some(Err(_)) => return Err(self.input.next().unwrap().unwrap_err()),\n None => break,\n }\n }\n if s.is_empty() {\n return self.handle_bad_read(\"No digits in integer literal\", pos);\n }\n\n match u32::from_str_radix(&s, u32::from(base)) {\n Ok(i) => Ok(TokenSpan::new(Token::Integer(i as i32), pos, s.len() + prefix_len)),\n Err(e) => self.handle_bad_read(format!(\"Bad integer {}: {}\", s, e), pos),\n }\n }\n```"}], "func_name": "consume_integer", "docstring": "Consumes the integer at the current position, whose first digit is `first` and which is\nexpected to be expressed in the given `base`. `prefix_len` indicates how many characters\nwere already consumed for this token, without counting `first`.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1601a51e4e493e61ca17c5bcf3dd0b30beb4c3c756d3323150a27b616d8ae408"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: consume_integer_with_base\n\nDocumentation:\nConsumes the integer at the current position `pos`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn consume_integer_with_base(&mut self, pos: LineCol) -> io::Result {\n let mut prefix_len = 1; // Count '&'.\n\n let base = match self.input.peek() {\n Some(Ok(ch_span)) => {\n let base = match ch_span.ch {\n 'b' | 'B' => 2,\n 'd' | 'D' => 10,\n 'o' | 'O' => 8,\n 'x' | 'X' => 16,\n ch if ch.is_separator() => {\n return self.handle_bad_read(\"Missing base in integer literal\", pos);\n }\n _ => {\n let ch_span = self.input.next().unwrap()?;\n return self.handle_bad_read(\n format!(\"Unknown base {} in integer literal\", ch_span.ch),\n pos,\n );\n }\n };\n self.input.next().unwrap()?;\n base\n }\n Some(Err(_)) => return Err(self.input.next().unwrap().unwrap_err()),\n None => {\n return self.handle_bad_read(\"Incomplete integer due to EOF\", pos);\n }\n };\n prefix_len += 1; // Count the base.\n\n match self.input.peek() {\n Some(Ok(ch_span)) if ch_span.ch == '_' => {\n self.input.next().unwrap().unwrap();\n prefix_len += 1; // Count the '_'.\n }\n Some(Ok(_ch_span)) => (),\n Some(Err(_)) => return Err(self.input.next().unwrap().unwrap_err()),\n None => return self.handle_bad_read(\"Incomplete integer due to EOF\", pos),\n }\n\n self.consume_integer(base, pos, prefix_len)\n }\n```"}], "func_name": "consume_integer_with_base", "docstring": "Consumes the integer at the current position `pos`.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ff939c0f14b46054b2f8c78eb144fd684ec17cef6e9dcc14bbf5626c8afc53de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: consume_operator\n\nDocumentation:\nConsumes the operator at the current position, whose first character is `first`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn consume_operator(&mut self, first: CharSpan) -> io::Result {\n match (first.ch, self.input.peek()) {\n (_, Some(Err(_))) => Err(self.input.next().unwrap().unwrap_err()),\n\n ('<', Some(Ok(ch_span))) if ch_span.ch == '>' => {\n self.input.next().unwrap()?;\n Ok(TokenSpan::new(Token::NotEqual, first.pos, 2))\n }\n\n ('<', Some(Ok(ch_span))) if ch_span.ch == '=' => {\n self.input.next().unwrap()?;\n Ok(TokenSpan::new(Token::LessEqual, first.pos, 2))\n }\n ('<', Some(Ok(ch_span))) if ch_span.ch == '<' => {\n self.input.next().unwrap()?;\n Ok(TokenSpan::new(Token::ShiftLeft, first.pos, 2))\n }\n ('<', _) => Ok(TokenSpan::new(Token::Less, first.pos, 1)),\n\n ('>', Some(Ok(ch_span))) if ch_span.ch == '=' => {\n self.input.next().unwrap()?;\n Ok(TokenSpan::new(Token::GreaterEqual, first.pos, 2))\n }\n ('>', Some(Ok(ch_span))) if ch_span.ch == '>' => {\n self.input.next().unwrap()?;\n Ok(TokenSpan::new(Token::ShiftRight, first.pos, 2))\n }\n ('>', _) => Ok(TokenSpan::new(Token::Greater, first.pos, 1)),\n\n (_, _) => panic!(\"Should not have been called\"),\n }\n }\n```"}], "func_name": "consume_operator", "docstring": "Consumes the operator at the current position, whose first character is `first`.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e451a9fd0d31727553d6d4f6afd634e3b1b3562004b04562b90e4fa3b7372df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: consume_symbol\n\nDocumentation:\nConsumes the symbol or keyword at the current position, whose first letter is `first`.\n\nThe symbol may be a bare name, but it may also contain an optional type annotation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn consume_symbol(&mut self, first: CharSpan) -> io::Result {\n let mut s = String::new();\n s.push(first.ch);\n let mut vtype = None;\n let mut token_len = 0;\n loop {\n match self.input.peek() {\n Some(Ok(ch_span)) => match ch_span.ch {\n ch if ch.is_word() => s.push(self.input.next().unwrap()?.ch),\n ch if ch.is_separator() => break,\n '?' => {\n vtype = Some(ExprType::Boolean);\n self.input.next().unwrap()?;\n token_len += 1;\n break;\n }\n '#' => {\n vtype = Some(ExprType::Double);\n self.input.next().unwrap()?;\n token_len += 1;\n break;\n }\n '%' => {\n vtype = Some(ExprType::Integer);\n self.input.next().unwrap()?;\n token_len += 1;\n break;\n }\n '$' => {\n vtype = Some(ExprType::Text);\n self.input.next().unwrap()?;\n token_len += 1;\n break;\n }\n ch => {\n self.input.next().unwrap()?;\n let msg = format!(\"Unexpected character in symbol: {}\", ch);\n return self.handle_bad_read(msg, first.pos);\n }\n },\n Some(Err(_)) => return Err(self.input.next().unwrap().unwrap_err()),\n None => break,\n }\n }\n debug_assert!(token_len <= 1);\n\n token_len += s.len();\n let token = match s.to_uppercase().as_str() {\n \"AND\" => Token::And,\n \"AS\" => Token::As,\n \"BOOLEAN\" => Token::BooleanName,\n \"CASE\" => Token::Case,\n \"DATA\" => Token::Data,\n \"DIM\" => Token::Dim,\n \"DO\" => Token::Do,\n \"DOUBLE\" => Token::DoubleName,\n \"ELSE\" => Token::Else,\n \"ELSEIF\" => Token::Elseif,\n \"END\" => Token::End,\n \"ERROR\" => Token::Error,\n \"EXIT\" => Token::Exit,\n \"FALSE\" => Token::Boolean(false),\n \"FOR\" => Token::For,\n \"FUNCTION\" => Token::Function,\n \"GOSUB\" => Token::Gosub,\n \"GOTO\" => Token::Goto,\n \"IF\" => Token::If,\n \"IS\" => Token::Is,\n \"INTEGER\" => Token::IntegerName,\n \"LOOP\" => Token::Loop,\n \"MOD\" => Token::Modulo,\n \"NEXT\" => Token::Next,\n \"NOT\" => Token::Not,\n \"ON\" => Token::On,\n \"OR\" => Token::Or,\n \"REM\" => return self.consume_rest_of_line(),\n \"RESUME\" => Token::Resume,\n \"RETURN\" => Token::Return,\n \"SELECT\" => Token::Select,\n \"SHARED\" => Token::Shared,\n \"STEP\" => Token::Step,\n \"STRING\" => Token::TextName,\n \"SUB\" => Token::Sub,\n \"THEN\" => Token::Then,\n \"TO\" => Token::To,\n \"TRUE\" => Token::Boolean(true),\n \"UNTIL\" => Token::Until,\n \"WEND\" => Token::Wend,\n \"WHILE\" => Token::While,\n \"XOR\" => Token::Xor,\n _ => Token::Symbol(VarRef::new(s, vtype)),\n };\n Ok(TokenSpan::new(token, first.pos, token_len))\n }\n```"}], "func_name": "consume_symbol", "docstring": "Consumes the symbol or keyword at the current position, whose first letter is `first`.\n\nThe symbol may be a bare name, but it may also contain an optional type annotation.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51b2c9557d2e8468e485ba1b964798d31ceca49913e12b05aff963520ca767a1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: consume_text\n\nDocumentation:\nConsumes the string at the current position, which was has to end with the same opening\ncharacter as specified by `delim`.\n\nThis handles quoted characters within the string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn consume_text(&mut self, delim: CharSpan) -> io::Result {\n let mut s = String::new();\n let mut escaping = false;\n loop {\n match self.input.peek() {\n Some(Ok(ch_span)) => {\n if escaping {\n s.push(self.input.next().unwrap()?.ch);\n escaping = false;\n } else if ch_span.ch == '\\\\' {\n self.input.next().unwrap()?;\n escaping = true;\n } else if ch_span.ch == delim.ch {\n self.input.next().unwrap()?;\n break;\n } else {\n s.push(self.input.next().unwrap()?.ch);\n }\n }\n Some(Err(_)) => return Err(self.input.next().unwrap().unwrap_err()),\n None => {\n return self.handle_bad_read(\n format!(\"Incomplete string due to EOF: {}\", s),\n delim.pos,\n );\n }\n }\n }\n let token_len = s.len() + 2;\n Ok(TokenSpan::new(Token::Text(s), delim.pos, token_len))\n }\n```"}], "func_name": "consume_text", "docstring": "Consumes the string at the current position, which was has to end with the same opening\ncharacter as specified by `delim`.\n\nThis handles quoted characters within the string.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d62d9f5c67729042436925fc5eb431aef86eab240f6dcb5d72b142c8fb02a00b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: consume_label\n\nDocumentation:\nConsumes the label definition at the current position.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn consume_label(&mut self, first: CharSpan) -> io::Result {\n let mut s = String::new();\n\n match self.input.peek() {\n Some(Ok(ch_span)) => match ch_span.ch {\n ch if ch.is_word() && !ch.is_numeric() => s.push(self.input.next().unwrap()?.ch),\n _ch => (),\n },\n Some(Err(_)) => return Err(self.input.next().unwrap().unwrap_err()),\n None => (),\n }\n if s.is_empty() {\n return Ok(TokenSpan::new(Token::Bad(\"Empty label name\".to_owned()), first.pos, 1));\n }\n\n loop {\n match self.input.peek() {\n Some(Ok(ch_span)) => match ch_span.ch {\n ch if ch.is_word() => s.push(self.input.next().unwrap()?.ch),\n ch if ch.is_separator() => break,\n ch => {\n let msg = format!(\"Unexpected character in label: {}\", ch);\n return self.handle_bad_read(msg, first.pos);\n }\n },\n Some(Err(_)) => return Err(self.input.next().unwrap().unwrap_err()),\n None => break,\n }\n }\n\n let token_len = s.len() + 1;\n Ok(TokenSpan::new(Token::Label(s), first.pos, token_len))\n }\n```"}], "func_name": "consume_label", "docstring": "Consumes the label definition at the current position.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ded51e221dc701b3e97be203afcef0f0705942ecc5e6e52c6d07c4729c165b10"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: consume_rest_of_line\n\nDocumentation:\nConsumes the remainder of the line and returns the token that was encountered at the end\n(which may be EOF or end of line).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn consume_rest_of_line(&mut self) -> io::Result {\n loop {\n match self.input.next() {\n None => {\n let last_pos = self.input.next_pos();\n return Ok(TokenSpan::new(Token::Eof, last_pos, 0));\n }\n Some(Ok(ch_span)) if ch_span.ch == '\\n' => {\n return Ok(TokenSpan::new(Token::Eol, ch_span.pos, 1))\n }\n Some(Err(e)) => return Err(e),\n Some(Ok(_)) => (),\n }\n }\n }\n```"}], "func_name": "consume_rest_of_line", "docstring": "Consumes the remainder of the line and returns the token that was encountered at the end\n(which may be EOF or end of line).", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "864c55e1e17d6260848c02998a82c5f94ed9866a5fdd365df3adbc319427ef18"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: advance_and_read_next\n\nDocumentation:\nSkips whitespace until it finds the beginning of the next token, and returns its first\ncharacter.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn advance_and_read_next(&mut self) -> io::Result> {\n loop {\n match self.input.next() {\n Some(Ok(ch_span)) if ch_span.ch.is_space() => (),\n Some(Ok(ch_span)) => return Ok(Some(ch_span)),\n Some(Err(e)) => return Err(e),\n None => return Ok(None),\n }\n }\n }\n```"}], "func_name": "advance_and_read_next", "docstring": "Skips whitespace until it finds the beginning of the next token, and returns its first\ncharacter.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e4516ceebbbb9f3083a4774708b125fa3b0a0ccedd98400a1459e00ff7217e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read\n\nDocumentation:\nReads the next token from the input stream.\n\nNote that this returns errors only on fatal I/O conditions. EOF and malformed tokens are\nboth returned as the special token types `Token::Eof` and `Token::Bad` respectively.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read(&mut self) -> io::Result {\n let ch_span = self.advance_and_read_next()?;\n if ch_span.is_none() {\n let last_pos = self.input.next_pos();\n return Ok(TokenSpan::new(Token::Eof, last_pos, 0));\n }\n let ch_span = ch_span.unwrap();\n match ch_span.ch {\n '\\n' | ':' => Ok(TokenSpan::new(Token::Eol, ch_span.pos, 1)),\n '\\'' => self.consume_rest_of_line(),\n\n '\"' => self.consume_text(ch_span),\n\n ';' => Ok(TokenSpan::new(Token::Semicolon, ch_span.pos, 1)),\n ',' => Ok(TokenSpan::new(Token::Comma, ch_span.pos, 1)),\n\n '(' => Ok(TokenSpan::new(Token::LeftParen, ch_span.pos, 1)),\n ')' => Ok(TokenSpan::new(Token::RightParen, ch_span.pos, 1)),\n\n '+' => Ok(TokenSpan::new(Token::Plus, ch_span.pos, 1)),\n '-' => Ok(TokenSpan::new(Token::Minus, ch_span.pos, 1)),\n '*' => Ok(TokenSpan::new(Token::Multiply, ch_span.pos, 1)),\n '/' => Ok(TokenSpan::new(Token::Divide, ch_span.pos, 1)),\n '^' => Ok(TokenSpan::new(Token::Exponent, ch_span.pos, 1)),\n\n '=' => Ok(TokenSpan::new(Token::Equal, ch_span.pos, 1)),\n '<' | '>' => self.consume_operator(ch_span),\n\n '@' => self.consume_label(ch_span),\n\n '&' => self.consume_integer_with_base(ch_span.pos),\n\n ch if ch.is_ascii_digit() => self.consume_number(ch_span),\n ch if ch.is_word() => self.consume_symbol(ch_span),\n ch => self.handle_bad_read(format!(\"Unknown character: {}\", ch), ch_span.pos),\n }\n }\n```"}], "func_name": "read", "docstring": "Reads the next token from the input stream.\n\nNote that this returns errors only on fatal I/O conditions. EOF and malformed tokens are\nboth returned as the special token types `Token::Eof` and `Token::Bad` respectively.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0046ff69d2606abd01947b8abe8d780a9c9196939a8719120a51a8718f481caa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: peekable\n\nDocumentation:\nReturns a peekable adaptor for this lexer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn peekable(self) -> PeekableLexer<'a> {\n PeekableLexer { lexer: self, peeked: None }\n }\n```"}], "func_name": "peekable", "docstring": "Returns a peekable adaptor for this lexer.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a577b0fb3323b4fdb6985eec0ae0fea30b8f2d60153216221df4e717c0759c31"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: consume_peeked\n\nDocumentation:\nReads the previously-peeked token.\n\nBecause `peek` reports read errors, this assumes that the caller already handled those\nerrors and is thus not going to call this when an error is present.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn consume_peeked(&mut self) -> TokenSpan {\n assert!(self.peeked.is_some());\n self.peeked.take().unwrap()\n }\n```"}], "func_name": "consume_peeked", "docstring": "Reads the previously-peeked token.\n\nBecause `peek` reports read errors, this assumes that the caller already handled those\nerrors and is thus not going to call this when an error is present.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f8a3a8119f643a8b9d365b73cfd2ade437c5d5b5cd2c633c4a147e25fac3540a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: peek\n\nDocumentation:\nPeeks the upcoming token.\n\nIt is OK to call this function several times on the same token before extracting it from\nthe lexer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn peek(&mut self) -> Result<&TokenSpan> {\n if self.peeked.is_none() {\n let span = self.read()?;\n self.peeked.replace(span);\n }\n Ok(self.peeked.as_ref().unwrap())\n }\n```"}], "func_name": "peek", "docstring": "Peeks the upcoming token.\n\nIt is OK to call this function several times on the same token before extracting it from\nthe lexer.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "59d518eb8a698767bc1b58d21c0ab0b821f0c54d2db9b69e4fa8df04f64080d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read\n\nDocumentation:\nReads the next token.\n\nIf the next token is invalid and results in a read error, the stream will remain valid and\nfurther tokens can be obtained with subsequent calls.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read(&mut self) -> Result {\n match self.peeked.take() {\n Some(t) => Ok(t),\n None => match self.lexer.read() {\n Ok(span) => Ok(span),\n Err(e) => Err((self.lexer.input.next_pos(), e)),\n },\n }\n }\n```"}], "func_name": "read", "docstring": "Reads the next token.\n\nIf the next token is invalid and results in a read error, the stream will remain valid and\nfurther tokens can be obtained with subsequent calls.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3e9a93160f460eb83d3d4cdea8ac47681453aad59ca2a83569051801fb7efea3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ts\n\nDocumentation:\nSyntactic sugar to instantiate a `TokenSpan` for testing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn ts(token: Token, line: usize, col: usize, length: usize) -> TokenSpan {\n TokenSpan::new(token, LineCol { line, col }, length)\n }\n```"}], "func_name": "ts", "docstring": "Syntactic sugar to instantiate a `TokenSpan` for testing.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c7305f2eadecb09d0c897a393320ebb52a3f11494967ac1b6cbb10c0b07e93ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fmt\n\nDocumentation:\nMimic the way we write the tests with the `ts` helper in `TokenSpan` dumps.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(\n f,\n \"ts(Token::{:?}, {}, {}, {})\",\n self.token, self.pos.line, self.pos.col, self.length\n )\n }\n```"}], "func_name": "fmt", "docstring": "Mimic the way we write the tests with the `ts` helper in `TokenSpan` dumps.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ea2c8fba0addf51994becfa002ad1d396a32535a95ef0e2525c32efac4e1c24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_ok_test\n\nDocumentation:\nRuns the lexer on the given `input` and expects the returned tokens to match\n`exp_token_spans`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_ok_test(input: &str, exp_token_spans: &[TokenSpan]) {\n let mut input = input.as_bytes();\n let mut lexer = Lexer::from(&mut input);\n\n let mut token_spans: Vec = vec![];\n let mut eof = false;\n while !eof {\n let token_span = lexer.read().expect(\"Lexing failed\");\n eof = token_span.token == Token::Eof;\n token_spans.push(token_span);\n }\n\n assert_eq!(exp_token_spans, token_spans.as_slice());\n }\n```"}], "func_name": "do_ok_test", "docstring": "Runs the lexer on the given `input` and expects the returned tokens to match\n`exp_token_spans`.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9414ffef7204e227a1e55246597aeb447ff2f05c31575f1786f3854ebaf37ddd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_auto_symbol\n\nDocumentation:\nSyntactic sugar to instantiate a `VarRef` without an explicit type annotation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_auto_symbol(name: &str) -> Token {\n Token::Symbol(VarRef::new(name, None))\n }\n```"}], "func_name": "new_auto_symbol", "docstring": "Syntactic sugar to instantiate a `VarRef` without an explicit type annotation.", "repo": "endbasic/endbasic", "path": "core/src/lexer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f4ee3aa880969ecd0d82e287de41e561d0529d7a3759a61b28631e018c08e65"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: vref_to_unannotated_string\n\nDocumentation:\nTransforms a `VarRef` into an unannotated name.\n\nThis is only valid for references that have no annotations in them.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn vref_to_unannotated_string(vref: VarRef, pos: LineCol) -> Result {\n if vref.ref_type().is_some() {\n return Err(Error::Bad(pos, format!(\"Type annotation not allowed in {}\", vref)));\n }\n Ok(vref.take_name())\n}\n```"}], "func_name": "vref_to_unannotated_string", "docstring": "Transforms a `VarRef` into an unannotated name.\n\nThis is only valid for references that have no annotations in them.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25a5651e5ced41fcb17cb33f81d5e17be74e29ddc47890e3215a015fe3a20042"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: argspans_to_exprs\n\nDocumentation:\nConverts a collection of `ArgSpan`s passed to a function or array reference to a collection\nof expressions with proper validation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn argspans_to_exprs(spans: Vec) -> Vec {\n let nargs = spans.len();\n let mut exprs = Vec::with_capacity(spans.len());\n for (i, span) in spans.into_iter().enumerate() {\n debug_assert!(\n (span.sep == ArgSep::End || i < nargs - 1)\n || (span.sep != ArgSep::End || i == nargs - 1)\n );\n match span.expr {\n Some(expr) => exprs.push(expr),\n None => unreachable!(),\n }\n }\n exprs\n}\n```"}], "func_name": "argspans_to_exprs", "docstring": "Converts a collection of `ArgSpan`s passed to a function or array reference to a collection\nof expressions with proper validation.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e31ffa3b7929a70f16d2b6921f599a74e7dc8eb2424e0e6487918e181f847c6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nConstructs a new operator based on a token, which must have a valid correspondence.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from(t: Token) -> Self {\n match t {\n Token::Equal => ExprOp::Equal,\n Token::NotEqual => ExprOp::NotEqual,\n Token::Less => ExprOp::Less,\n Token::LessEqual => ExprOp::LessEqual,\n Token::Greater => ExprOp::Greater,\n Token::GreaterEqual => ExprOp::GreaterEqual,\n Token::Plus => ExprOp::Add,\n Token::Multiply => ExprOp::Multiply,\n Token::Divide => ExprOp::Divide,\n Token::Modulo => ExprOp::Modulo,\n Token::Exponent => ExprOp::Power,\n Token::And => ExprOp::And,\n Token::Or => ExprOp::Or,\n Token::Xor => ExprOp::Xor,\n Token::ShiftLeft => ExprOp::ShiftLeft,\n Token::ShiftRight => ExprOp::ShiftRight,\n Token::Minus => panic!(\"Ambiguous token; cannot derive ExprOp\"),\n _ => panic!(\"Called on an non-operator\"),\n }\n }\n```"}], "func_name": "from", "docstring": "Constructs a new operator based on a token, which must have a valid correspondence.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a09061fe5c9d787d7cce9c2c85228a0e9123d54d1a42800261e7e99bb280ecc2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: priority\n\nDocumentation:\nReturns the priority of this operator. The specific number's meaning is only valid when\ncomparing it against other calls to this function. Higher number imply higher priority.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn priority(&self) -> i8 {\n match self {\n ExprOp::LeftParen => 6,\n ExprOp::Power => 6,\n\n ExprOp::Negate => 5,\n ExprOp::Not => 5,\n\n ExprOp::Multiply => 4,\n ExprOp::Divide => 4,\n ExprOp::Modulo => 4,\n\n ExprOp::Add => 3,\n ExprOp::Subtract => 3,\n\n ExprOp::ShiftLeft => 2,\n ExprOp::ShiftRight => 2,\n\n ExprOp::Equal => 1,\n ExprOp::NotEqual => 1,\n ExprOp::Less => 1,\n ExprOp::LessEqual => 1,\n ExprOp::Greater => 1,\n ExprOp::GreaterEqual => 1,\n\n ExprOp::And => 0,\n ExprOp::Or => 0,\n ExprOp::Xor => 0,\n }\n }\n```"}], "func_name": "priority", "docstring": "Returns the priority of this operator. The specific number's meaning is only valid when\ncomparing it against other calls to this function. Higher number imply higher priority.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "41363e7ccac193eeb428f2eb579c8e4339aedf2922a26bb8d9089928ee7e5747"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new span from its parts.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(op: ExprOp, pos: LineCol) -> Self {\n Self { op, pos }\n }\n```"}], "func_name": "new", "docstring": "Creates a new span from its parts.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad81fc52e1d4111daa6b7105f469ee02597a6cdbf6a83abaa61330891126c463"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: apply\n\nDocumentation:\nPops operands from the `expr` stack, applies this operation, and pushes the result back.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn apply(&self, exprs: &mut Vec) -> Result<()> {\n fn apply1(\n exprs: &mut Vec,\n pos: LineCol,\n f: fn(Box) -> Expr,\n ) -> Result<()> {\n if exprs.is_empty() {\n return Err(Error::Bad(pos, \"Not enough values to apply operator\".to_owned()));\n }\n let expr = exprs.pop().unwrap();\n exprs.push(f(Box::from(UnaryOpSpan { expr, pos })));\n Ok(())\n }\n\n fn apply2(\n exprs: &mut Vec,\n pos: LineCol,\n f: fn(Box) -> Expr,\n ) -> Result<()> {\n if exprs.len() < 2 {\n return Err(Error::Bad(pos, \"Not enough values to apply operator\".to_owned()));\n }\n let rhs = exprs.pop().unwrap();\n let lhs = exprs.pop().unwrap();\n exprs.push(f(Box::from(BinaryOpSpan { lhs, rhs, pos })));\n Ok(())\n }\n\n match self.op {\n ExprOp::Add => apply2(exprs, self.pos, Expr::Add),\n ExprOp::Subtract => apply2(exprs, self.pos, Expr::Subtract),\n ExprOp::Multiply => apply2(exprs, self.pos, Expr::Multiply),\n ExprOp::Divide => apply2(exprs, self.pos, Expr::Divide),\n ExprOp::Modulo => apply2(exprs, self.pos, Expr::Modulo),\n ExprOp::Power => apply2(exprs, self.pos, Expr::Power),\n\n ExprOp::Equal => apply2(exprs, self.pos, Expr::Equal),\n ExprOp::NotEqual => apply2(exprs, self.pos, Expr::NotEqual),\n ExprOp::Less => apply2(exprs, self.pos, Expr::Less),\n ExprOp::LessEqual => apply2(exprs, self.pos, Expr::LessEqual),\n ExprOp::Greater => apply2(exprs, self.pos, Expr::Greater),\n ExprOp::GreaterEqual => apply2(exprs, self.pos, Expr::GreaterEqual),\n\n ExprOp::And => apply2(exprs, self.pos, Expr::And),\n ExprOp::Or => apply2(exprs, self.pos, Expr::Or),\n ExprOp::Xor => apply2(exprs, self.pos, Expr::Xor),\n\n ExprOp::ShiftLeft => apply2(exprs, self.pos, Expr::ShiftLeft),\n ExprOp::ShiftRight => apply2(exprs, self.pos, Expr::ShiftRight),\n\n ExprOp::Negate => apply1(exprs, self.pos, Expr::Negate),\n ExprOp::Not => apply1(exprs, self.pos, Expr::Not),\n\n ExprOp::LeftParen => Ok(()),\n }\n }\n```"}], "func_name": "apply", "docstring": "Pops operands from the `expr` stack, applies this operation, and pushes the result back.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "05cc88f0a1981cecc05701a199fc32453167c912f94f3f937ae84e2e41180d43"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nCreates a new parser from the given readable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from(input: &'a mut dyn io::Read) -> Self {\n Self { lexer: Lexer::from(input).peekable() }\n }\n```"}], "func_name": "from", "docstring": "Creates a new parser from the given readable.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b2ea031b91b0ae816bb2a6d1f51d98c8415742755599d9259fad12b372ca9e92"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_and_consume\n\nDocumentation:\nExpects the peeked token to be `t` and consumes it. Otherwise, leaves the token in the\nstream and fails with error `err`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn expect_and_consume>(&mut self, t: Token, err: E) -> Result {\n let peeked = self.lexer.peek()?;\n if peeked.token != t {\n return Err(Error::Bad(peeked.pos, err.into()));\n }\n Ok(self.lexer.consume_peeked())\n }\n```"}], "func_name": "expect_and_consume", "docstring": "Expects the peeked token to be `t` and consumes it. Otherwise, leaves the token in the\nstream and fails with error `err`.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "40274e5afbefcf90aa95c10612d295e8247310b2f47907fc42bf901623e463b7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_and_consume_with_pos\n\nDocumentation:\nExpects the peeked token to be `t` and consumes it. Otherwise, leaves the token in the\nstream and fails with error `err`, pointing at `pos` as the original location of the\nproblem.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn expect_and_consume_with_pos>(\n &mut self,\n t: Token,\n pos: LineCol,\n err: E,\n ) -> Result<()> {\n let peeked = self.lexer.peek()?;\n if peeked.token != t {\n return Err(Error::Bad(pos, err.into()));\n }\n self.lexer.consume_peeked();\n Ok(())\n }\n```"}], "func_name": "expect_and_consume_with_pos", "docstring": "Expects the peeked token to be `t` and consumes it. Otherwise, leaves the token in the\nstream and fails with error `err`, pointing at `pos` as the original location of the\nproblem.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6829d75ade951773e3dba19f66407aa129959678768e936da16c6dfc8b7265ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_assignment\n\nDocumentation:\nParses an assignment for the variable reference `vref` already read.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_assignment(&mut self, vref: VarRef, vref_pos: LineCol) -> Result {\n let expr = self.parse_required_expr(\"Missing expression in assignment\")?;\n\n let next = self.lexer.peek()?;\n match &next.token {\n Token::Eof | Token::Eol | Token::Else => (),\n t => return Err(Error::Bad(next.pos, format!(\"Unexpected {} in assignment\", t))),\n }\n Ok(Statement::Assignment(AssignmentSpan { vref, vref_pos, expr }))\n }\n```"}], "func_name": "parse_assignment", "docstring": "Parses an assignment for the variable reference `vref` already read.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1459bd7aa8c727340cabcbb99dc5b30e8f5f9a248481b38d5dec4ff9f6db2c85"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_array_assignment\n\nDocumentation:\nParses an assignment to the array `varref` with `subscripts`, both of which have already\nbeen read.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_array_assignment(\n &mut self,\n vref: VarRef,\n vref_pos: LineCol,\n subscripts: Vec,\n ) -> Result {\n let expr = self.parse_required_expr(\"Missing expression in array assignment\")?;\n\n let next = self.lexer.peek()?;\n match &next.token {\n Token::Eof | Token::Eol | Token::Else => (),\n t => return Err(Error::Bad(next.pos, format!(\"Unexpected {} in array assignment\", t))),\n }\n Ok(Statement::ArrayAssignment(ArrayAssignmentSpan { vref, vref_pos, subscripts, expr }))\n }\n```"}], "func_name": "parse_array_assignment", "docstring": "Parses an assignment to the array `varref` with `subscripts`, both of which have already\nbeen read.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b302008b908b2f64ec2d8a763d4ec14622f3e14d54330d3dff19f3f862e9f7ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_builtin_call\n\nDocumentation:\nParses a builtin call (things of the form `INPUT a`).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_builtin_call(\n &mut self,\n vref: VarRef,\n vref_pos: LineCol,\n mut first: Option,\n ) -> Result {\n let mut name = vref_to_unannotated_string(vref, vref_pos)?;\n name.make_ascii_uppercase();\n\n let mut args = vec![];\n loop {\n let expr = self.parse_expr(first.take())?;\n\n let peeked = self.lexer.peek()?;\n match peeked.token {\n Token::Eof | Token::Eol | Token::Else => {\n if expr.is_some() || !args.is_empty() {\n args.push(ArgSpan { expr, sep: ArgSep::End, sep_pos: peeked.pos });\n }\n break;\n }\n Token::Semicolon => {\n let peeked = self.lexer.consume_peeked();\n args.push(ArgSpan { expr, sep: ArgSep::Short, sep_pos: peeked.pos });\n }\n Token::Comma => {\n let peeked = self.lexer.consume_peeked();\n args.push(ArgSpan { expr, sep: ArgSep::Long, sep_pos: peeked.pos });\n }\n Token::As => {\n let peeked = self.lexer.consume_peeked();\n args.push(ArgSpan { expr, sep: ArgSep::As, sep_pos: peeked.pos });\n }\n _ => {\n return Err(Error::Bad(\n peeked.pos,\n \"Expected comma, semicolon, or end of statement\".to_owned(),\n ))\n }\n }\n }\n Ok(Statement::Call(CallSpan { vref: VarRef::new(name, None), vref_pos, args }))\n }\n```"}], "func_name": "parse_builtin_call", "docstring": "Parses a builtin call (things of the form `INPUT a`).", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c70520d521dba9e07299c7dd0443de514213dec103ecf5c641ea1bfc5102ba9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_array_or_builtin_call\n\nDocumentation:\nStarts processing either an array reference or a builtin call and disambiguates between the\ntwo.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_array_or_builtin_call(\n &mut self,\n vref: VarRef,\n vref_pos: LineCol,\n ) -> Result {\n match self.lexer.peek()?.token {\n Token::LeftParen => {\n let left_paren = self.lexer.consume_peeked();\n let spans = self.parse_comma_separated_exprs()?;\n let mut exprs = spans.into_iter().map(|span| span.expr.unwrap()).collect();\n match self.lexer.peek()?.token {\n Token::Equal => {\n self.lexer.consume_peeked();\n self.parse_array_assignment(vref, vref_pos, exprs)\n }\n _ => {\n if exprs.len() != 1 {\n return Err(Error::Bad(\n left_paren.pos,\n \"Expected expression\".to_owned(),\n ));\n }\n self.parse_builtin_call(vref, vref_pos, Some(exprs.remove(0)))\n }\n }\n }\n _ => self.parse_builtin_call(vref, vref_pos, None),\n }\n }\n```"}], "func_name": "parse_array_or_builtin_call", "docstring": "Starts processing either an array reference or a builtin call and disambiguates between the\ntwo.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f7c301e328322a3557ca8b5dd9850f157077316c2274160d97776c8865224e30"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_as_type\n\nDocumentation:\nParses the type name of an `AS` type definition.\n\nThe `AS` token has already been consumed, so all this does is read a literal type name and\nconvert it to the corresponding expression type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_as_type(&mut self) -> Result<(ExprType, LineCol)> {\n let token_span = self.lexer.read()?;\n match token_span.token {\n Token::BooleanName => Ok((ExprType::Boolean, token_span.pos)),\n Token::DoubleName => Ok((ExprType::Double, token_span.pos)),\n Token::IntegerName => Ok((ExprType::Integer, token_span.pos)),\n Token::TextName => Ok((ExprType::Text, token_span.pos)),\n t => Err(Error::Bad(\n token_span.pos,\n format!(\"Invalid type name {} in AS type definition\", t),\n )),\n }\n }\n```"}], "func_name": "parse_as_type", "docstring": "Parses the type name of an `AS` type definition.\n\nThe `AS` token has already been consumed, so all this does is read a literal type name and\nconvert it to the corresponding expression type.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c9773c3cfc23bcd00829ea9e84b356b08a661f355cf271fa3ab0af3367774b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_dim_as\n\nDocumentation:\nParses the `AS typename` clause of a `DIM` statement. The caller has already consumed the\n`AS` token.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_dim_as(&mut self) -> Result<(ExprType, LineCol)> {\n let peeked = self.lexer.peek()?;\n let (vtype, vtype_pos) = match peeked.token {\n Token::Eof | Token::Eol => (ExprType::Integer, peeked.pos),\n Token::As => {\n self.lexer.consume_peeked();\n self.parse_as_type()?\n }\n _ => return Err(Error::Bad(peeked.pos, \"Expected AS or end of statement\".to_owned())),\n };\n\n let next = self.lexer.peek()?;\n match &next.token {\n Token::Eof | Token::Eol => (),\n t => return Err(Error::Bad(next.pos, format!(\"Unexpected {} in DIM statement\", t))),\n }\n\n Ok((vtype, vtype_pos))\n }\n```"}], "func_name": "parse_dim_as", "docstring": "Parses the `AS typename` clause of a `DIM` statement. The caller has already consumed the\n`AS` token.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e513e7f2417b7095c5c6e7be973db4aebd199ab5152627fb94e8068723081654"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_do_guard\n\nDocumentation:\nParses the `UNTIL` or `WHILE` clause of a `DO` loop.\n\n`part` is a string indicating where the clause is expected (either after `DO` or after\n`LOOP`).\n\nReturns the guard expression and a boolean indicating if this is an `UNTIL` clause.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_do_guard(&mut self, part: &str) -> Result> {\n let peeked = self.lexer.peek()?;\n match peeked.token {\n Token::Until => {\n self.lexer.consume_peeked();\n let expr = self.parse_required_expr(\"No expression in UNTIL clause\")?;\n Ok(Some((expr, true)))\n }\n Token::While => {\n self.lexer.consume_peeked();\n let expr = self.parse_required_expr(\"No expression in WHILE clause\")?;\n Ok(Some((expr, false)))\n }\n Token::Eof | Token::Eol => Ok(None),\n _ => {\n let token_span = self.lexer.consume_peeked();\n Err(Error::Bad(\n token_span.pos,\n format!(\"Expecting newline, UNTIL or WHILE after {}\", part),\n ))\n }\n }\n }\n```"}], "func_name": "parse_do_guard", "docstring": "Parses the `UNTIL` or `WHILE` clause of a `DO` loop.\n\n`part` is a string indicating where the clause is expected (either after `DO` or after\n`LOOP`).\n\nReturns the guard expression and a boolean indicating if this is an `UNTIL` clause.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "877b721b9560946633f57037aadd5e63f4f440761ee242cad6c02d382340c552"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_do\n\nDocumentation:\nAdvances until the next statement after failing to parse a `DO` statement.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reset_do(&mut self) -> Result<()> {\n loop {\n match self.lexer.peek()?.token {\n Token::Eof => break,\n Token::Loop => {\n self.lexer.consume_peeked();\n loop {\n match self.lexer.peek()?.token {\n Token::Eof | Token::Eol => break,\n _ => {\n self.lexer.consume_peeked();\n }\n }\n }\n break;\n }\n _ => {\n self.lexer.consume_peeked();\n }\n }\n }\n self.reset()\n }\n```"}], "func_name": "reset_do", "docstring": "Advances until the next statement after failing to parse a `DO` statement.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7dd8b226b5a498a7738e5878d37d136112865b05860c17bcae7f7223e4000016"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: maybe_parse_end\n\nDocumentation:\nParses a potential `END` statement but, if this corresponds to a statement terminator such\nas `END IF`, returns the token that followed `END`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn maybe_parse_end(&mut self) -> Result> {\n match self.lexer.peek()?.token {\n Token::Function => Ok(Err(Token::Function)),\n Token::If => Ok(Err(Token::If)),\n Token::Select => Ok(Err(Token::Select)),\n Token::Sub => Ok(Err(Token::Sub)),\n _ => {\n let code = self.parse_expr(None)?;\n Ok(Ok(Statement::End(EndSpan { code })))\n }\n }\n }\n```"}], "func_name": "maybe_parse_end", "docstring": "Parses a potential `END` statement but, if this corresponds to a statement terminator such\nas `END IF`, returns the token that followed `END`.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e350226b5fd7077a66b39bfa7c904dd6f535117410d3d20acd754eafd9f12e3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_comma_separated_exprs\n\nDocumentation:\nParses a variable list of comma-separated expressions. The caller must have consumed the\nopen parenthesis and we stop processing when we encounter the terminating parenthesis (and\nconsume it). We expect at least one expression.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_comma_separated_exprs(&mut self) -> Result> {\n let mut spans = vec![];\n\n // The first expression is optional to support calls to functions without arguments.\n let mut is_first = true;\n let mut prev_expr = self.parse_expr(None)?;\n\n loop {\n let peeked = self.lexer.peek()?;\n let pos = peeked.pos;\n match &peeked.token {\n Token::RightParen => {\n self.lexer.consume_peeked();\n\n if let Some(expr) = prev_expr.take() {\n spans.push(ArgSpan { expr: Some(expr), sep: ArgSep::End, sep_pos: pos });\n } else {\n if !is_first {\n return Err(Error::Bad(pos, \"Missing expression\".to_owned()));\n }\n }\n\n break;\n }\n Token::Comma => {\n self.lexer.consume_peeked();\n\n if let Some(expr) = prev_expr.take() {\n // The first expression is optional to support calls to functions without\n // arguments.\n spans.push(ArgSpan { expr: Some(expr), sep: ArgSep::Long, sep_pos: pos });\n } else {\n return Err(Error::Bad(pos, \"Missing expression\".to_owned()));\n }\n\n prev_expr = self.parse_expr(None)?;\n }\n t => return Err(Error::Bad(pos, format!(\"Unexpected {}\", t))),\n }\n\n is_first = false;\n }\n\n Ok(spans)\n }\n```"}], "func_name": "parse_comma_separated_exprs", "docstring": "Parses a variable list of comma-separated expressions. The caller must have consumed the\nopen parenthesis and we stop processing when we encounter the terminating parenthesis (and\nconsume it). We expect at least one expression.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6253c301ed0aa1f7b6b0a852acd631b2bc6c9da340b62ae9a0cbbd0a932d5341"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_expr\n\nDocumentation:\nParses an expression.\n\nReturns `None` if no expression was found. This is necessary to treat the case of empty\narguments to statements, as is the case in `PRINT a , , b`.\n\nIf the caller has already processed a parenthesized term of an expression like\n`(first) + second`, then that term must be provided in `first`.\n\nThis is an implementation of the Shunting Yard Algorithm by Edgar Dijkstra.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_expr(&mut self, first: Option) -> Result> {\n let mut exprs: Vec = vec![];\n let mut op_spans: Vec = vec![];\n\n let mut need_operand = true; // Also tracks whether an upcoming minus is unary.\n if let Some(e) = first {\n exprs.push(e);\n need_operand = false;\n }\n\n loop {\n let mut handle_operand = |e, pos| {\n if !need_operand {\n return Err(Error::Bad(pos, \"Unexpected value in expression\".to_owned()));\n }\n need_operand = false;\n exprs.push(e);\n Ok(())\n };\n\n // Stop processing if we encounter an expression separator, but don't consume it because\n // the caller needs to have access to it.\n match self.lexer.peek()?.token {\n Token::Eof\n | Token::Eol\n | Token::As\n | Token::Comma\n | Token::Else\n | Token::Semicolon\n | Token::Then\n | Token::To\n | Token::Step => break,\n Token::RightParen => {\n if !op_spans.iter().any(|eos| eos.op == ExprOp::LeftParen) {\n // We encountered an unbalanced parenthesis but we don't know if this is\n // because we were called from within an argument list (in which case the\n // caller consumed the opening parenthesis and is expecting to consume the\n // closing parenthesis) or because we really found an invalid expression.\n // Only the caller can know, so avoid consuming the token and exit.\n break;\n }\n }\n _ => (),\n };\n\n let ts = self.lexer.consume_peeked();\n match ts.token {\n Token::Boolean(value) => {\n handle_operand(Expr::Boolean(BooleanSpan { value, pos: ts.pos }), ts.pos)?\n }\n Token::Double(value) => {\n handle_operand(Expr::Double(DoubleSpan { value, pos: ts.pos }), ts.pos)?\n }\n Token::Integer(value) => {\n handle_operand(Expr::Integer(IntegerSpan { value, pos: ts.pos }), ts.pos)?\n }\n Token::Text(value) => {\n handle_operand(Expr::Text(TextSpan { value, pos: ts.pos }), ts.pos)?\n }\n Token::Symbol(vref) => {\n handle_operand(Expr::Symbol(SymbolSpan { vref, pos: ts.pos }), ts.pos)?\n }\n\n Token::LeftParen => {\n // If the last operand we encountered was a symbol, collapse it and the left\n // parenthesis into the beginning of a function call.\n match exprs.pop() {\n Some(Expr::Symbol(span)) => {\n if !need_operand {\n exprs.push(Expr::Call(CallSpan {\n vref: span.vref,\n vref_pos: span.pos,\n args: self.parse_comma_separated_exprs()?,\n }));\n need_operand = false;\n } else {\n // We popped out the last expression to see if it this left\n // parenthesis started a function call... but it did not (it is a\n // symbol following a parenthesis) so put both the expression and\n // the token back.\n op_spans.push(ExprOpSpan::new(ExprOp::LeftParen, ts.pos));\n exprs.push(Expr::Symbol(span));\n need_operand = true;\n }\n }\n e => {\n if let Some(e) = e {\n // We popped out the last expression to see if this left\n // parenthesis started a function call... but if it didn't, we have\n // to put the expression back.\n exprs.push(e);\n }\n if !need_operand {\n return Err(Error::Bad(\n ts.pos,\n format!(\"Unexpected {} in expression\", ts.token),\n ));\n }\n op_spans.push(ExprOpSpan::new(ExprOp::LeftParen, ts.pos));\n need_operand = true;\n }\n };\n }\n Token::RightParen => {\n let mut found = false;\n while let Some(eos) = op_spans.pop() {\n eos.apply(&mut exprs)?;\n if eos.op == ExprOp::LeftParen {\n found = true;\n break;\n }\n }\n assert!(found, \"Unbalanced parenthesis should have been handled above\");\n need_operand = false;\n }\n\n Token::Not => {\n op_spans.push(ExprOpSpan::new(ExprOp::Not, ts.pos));\n need_operand = true;\n }\n Token::Minus => {\n let op;\n if need_operand {\n op = ExprOp::Negate;\n } else {\n op = ExprOp::Subtract;\n while let Some(eos2) = op_spans.last() {\n if eos2.op == ExprOp::LeftParen || eos2.op.priority() < op.priority() {\n break;\n }\n let eos2 = op_spans.pop().unwrap();\n eos2.apply(&mut exprs)?;\n }\n }\n op_spans.push(ExprOpSpan::new(op, ts.pos));\n need_operand = true;\n }\n\n Token::Equal\n | Token::NotEqual\n | Token::Less\n | Token::LessEqual\n | Token::Greater\n | Token::GreaterEqual\n | Token::Plus\n | Token::Multiply\n | Token::Divide\n | Token::Modulo\n | Token::Exponent\n | Token::And\n | Token::Or\n | Token::Xor\n | Token::ShiftLeft\n | Token::ShiftRight => {\n let op = ExprOp::from(ts.token);\n while let Some(eos2) = op_spans.last() {\n if eos2.op == ExprOp::LeftParen || eos2.op.priority() < op.priority() {\n break;\n }\n let eos2 = op_spans.pop().unwrap();\n eos2.apply(&mut exprs)?;\n }\n op_spans.push(ExprOpSpan::new(op, ts.pos));\n need_operand = true;\n }\n\n Token::Bad(e) => return Err(Error::Bad(ts.pos, e)),\n\n Token::Eof\n | Token::Eol\n | Token::As\n | Token::Comma\n | Token::Else\n | Token::Semicolon\n | Token::Then\n | Token::To\n | Token::Step => {\n panic!(\"Field separators handled above\")\n }\n\n Token::BooleanName\n | Token::Case\n | Token::Data\n | Token::Do\n | Token::Dim\n | Token::DoubleName\n | Token::Elseif\n | Token::End\n | Token::Error\n | Token::Exit\n | Token::For\n | Token::Function\n | Token::Gosub\n | Token::Goto\n | Token::If\n | Token::Is\n | Token::IntegerName\n | Token::Label(_)\n | Token::Loop\n | Token::Next\n | Token::On\n | Token::Resume\n | Token::Return\n | Token::Select\n | Token::Shared\n | Token::Sub\n | Token::TextName\n | Token::Until\n | Token::Wend\n | Token::While => {\n return Err(Error::Bad(ts.pos, \"Unexpected keyword in expression\".to_owned()));\n }\n };\n }\n\n while let Some(eos) = op_spans.pop() {\n match eos.op {\n ExprOp::LeftParen => {\n return Err(Error::Bad(eos.pos, \"Unbalanced parenthesis\".to_owned()))\n }\n _ => eos.apply(&mut exprs)?,\n }\n }\n\n if let Some(expr) = exprs.pop() {\n Ok(Some(expr))\n } else {\n Ok(None)\n }\n }\n```"}], "func_name": "parse_expr", "docstring": "Parses an expression.\n\nReturns `None` if no expression was found. This is necessary to treat the case of empty\narguments to statements, as is the case in `PRINT a , , b`.\n\nIf the caller has already processed a parenthesized term of an expression like\n`(first) + second`, then that term must be provided in `first`.\n\nThis is an implementation of the Shunting Yard Algorithm by Edgar Dijkstra.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0b31ecd56090c1114f739609c59bedf1a6456bb2b7fc7a2e802d6493e8bd0c6a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_required_expr\n\nDocumentation:\nWrapper over `parse_expr` that requires an expression to be present and returns an error\nwith `msg` otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_required_expr(&mut self, msg: &'static str) -> Result {\n let next_pos = self.lexer.peek()?.pos;\n match self.parse_expr(None)? {\n Some(expr) => Ok(expr),\n None => Err(Error::Bad(next_pos, msg.to_owned())),\n }\n }\n```"}], "func_name": "parse_required_expr", "docstring": "Wrapper over `parse_expr` that requires an expression to be present and returns an error\nwith `msg` otherwise.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf9b1a8ce3049b4e504e0db3013b1eb5eb8299d880707a34400bcc11ef404e26"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_if_uniline\n\nDocumentation:\nParses the branches of a uniline `IF` statement.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_if_uniline(&mut self, branches: &mut Vec) -> Result<()> {\n debug_assert!(!branches.is_empty(), \"Caller must populate the guard of the first branch\");\n\n let mut has_else = false;\n let peeked = self.lexer.peek()?;\n match peeked.token {\n Token::Else => has_else = true,\n _ => {\n let stmt = self\n .parse_uniline()?\n .expect(\"The caller already checked for a non-empty token\");\n branches[0].body.push(stmt);\n }\n }\n\n let peeked = self.lexer.peek()?;\n has_else |= peeked.token == Token::Else;\n\n if has_else {\n let else_span = self.lexer.consume_peeked();\n let expr = Expr::Boolean(BooleanSpan { value: true, pos: else_span.pos });\n branches.push(IfBranchSpan { guard: expr, body: vec![] });\n if let Some(stmt) = self.parse_uniline()? {\n branches[1].body.push(stmt);\n }\n }\n\n Ok(())\n }\n```"}], "func_name": "parse_if_uniline", "docstring": "Parses the branches of a uniline `IF` statement.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "026b21b35bcda887ea0debeb86f2d38b97e3525261f84fe0be036de9e1e1d7ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_if_multiline\n\nDocumentation:\nParses the branches of a multiline `IF` statement.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_if_multiline(\n &mut self,\n if_pos: LineCol,\n branches: &mut Vec,\n ) -> Result<()> {\n debug_assert!(!branches.is_empty(), \"Caller must populate the guard of the first branch\");\n\n let mut i = 0;\n let mut last = false;\n loop {\n let peeked = self.lexer.peek()?;\n match peeked.token {\n Token::Eol => {\n self.lexer.consume_peeked();\n }\n\n Token::Elseif => {\n if last {\n return Err(Error::Bad(\n peeked.pos,\n \"Unexpected ELSEIF after ELSE\".to_owned(),\n ));\n }\n\n self.lexer.consume_peeked();\n let expr = self.parse_required_expr(\"No expression in ELSEIF statement\")?;\n self.expect_and_consume(Token::Then, \"No THEN in ELSEIF statement\")?;\n self.expect_and_consume(Token::Eol, \"Expecting newline after THEN\")?;\n branches.push(IfBranchSpan { guard: expr, body: vec![] });\n i += 1;\n }\n\n Token::Else => {\n if last {\n return Err(Error::Bad(peeked.pos, \"Duplicate ELSE after ELSE\".to_owned()));\n }\n\n let else_span = self.lexer.consume_peeked();\n self.expect_and_consume(Token::Eol, \"Expecting newline after ELSE\")?;\n\n let expr = Expr::Boolean(BooleanSpan { value: true, pos: else_span.pos });\n branches.push(IfBranchSpan { guard: expr, body: vec![] });\n i += 1;\n\n last = true;\n }\n\n Token::End => {\n let token_span = self.lexer.consume_peeked();\n match self.maybe_parse_end()? {\n Ok(stmt) => {\n branches[i].body.push(stmt);\n }\n Err(Token::If) => {\n break;\n }\n Err(token) => {\n return Err(Error::Bad(\n token_span.pos,\n format!(\"END {} without {}\", token, token),\n ));\n }\n }\n }\n\n _ => match self.parse_one_safe()? {\n Some(stmt) => {\n branches[i].body.push(stmt);\n }\n None => {\n break;\n }\n },\n }\n }\n\n self.expect_and_consume_with_pos(Token::If, if_pos, \"IF without END IF\")\n }\n```"}], "func_name": "parse_if_multiline", "docstring": "Parses the branches of a multiline `IF` statement.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5308aa3fe66e1fddb155f937135b0181db50e42e063ea8e89b79cf95909aefd5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_if\n\nDocumentation:\nAdvances until the next statement after failing to parse an `IF` statement.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reset_if(&mut self, if_pos: LineCol) -> Result<()> {\n loop {\n match self.lexer.peek()?.token {\n Token::Eof => break,\n Token::End => {\n self.lexer.consume_peeked();\n self.expect_and_consume_with_pos(Token::If, if_pos, \"IF without END IF\")?;\n break;\n }\n _ => {\n self.lexer.consume_peeked();\n }\n }\n }\n self.reset()\n }\n```"}], "func_name": "reset_if", "docstring": "Advances until the next statement after failing to parse an `IF` statement.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c7e4f574d102f6c5799da76816f35a92697774933dab1ff33973864e4c4d3a26"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_step\n\nDocumentation:\nExtracts the optional `STEP` part of a `FOR` statement, with a default of 1.\n\nReturns the step as an expression, an `Ordering` value representing how the step value\ncompares to zero, and whether the step is a double or not.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_step(&mut self) -> Result<(Expr, Ordering, bool)> {\n let peeked = self.lexer.peek()?;\n match peeked.token {\n Token::Step => self.lexer.consume_peeked(),\n _ => {\n // The position we return here for the step isn't truly the right value, but given\n // that we know the hardcoded step of 1 is valid, the caller will not error out and\n // will not print the slightly invalid position.\n return Ok((\n Expr::Integer(IntegerSpan { value: 1, pos: peeked.pos }),\n Ordering::Greater,\n false,\n ));\n }\n };\n\n let peeked = self.lexer.peek()?;\n match peeked.token {\n Token::Double(d) => {\n let peeked = self.lexer.consume_peeked();\n let sign = if d == 0.0 { Ordering::Equal } else { Ordering::Greater };\n Ok((Expr::Double(DoubleSpan { value: d, pos: peeked.pos }), sign, true))\n }\n Token::Integer(i) => {\n let peeked = self.lexer.consume_peeked();\n Ok((Expr::Integer(IntegerSpan { value: i, pos: peeked.pos }), i.cmp(&0), false))\n }\n Token::Minus => {\n self.lexer.consume_peeked();\n let peeked = self.lexer.peek()?;\n match peeked.token {\n Token::Double(d) => {\n let peeked = self.lexer.consume_peeked();\n let sign = if d == 0.0 { Ordering::Equal } else { Ordering::Less };\n Ok((Expr::Double(DoubleSpan { value: -d, pos: peeked.pos }), sign, true))\n }\n Token::Integer(i) => {\n let peeked = self.lexer.consume_peeked();\n Ok((\n Expr::Integer(IntegerSpan { value: -i, pos: peeked.pos }),\n (-i).cmp(&0),\n false,\n ))\n }\n _ => Err(Error::Bad(peeked.pos, \"STEP needs a literal number\".to_owned())),\n }\n }\n _ => Err(Error::Bad(peeked.pos, \"STEP needs a literal number\".to_owned())),\n }\n }\n```"}], "func_name": "parse_step", "docstring": "Extracts the optional `STEP` part of a `FOR` statement, with a default of 1.\n\nReturns the step as an expression, an `Ordering` value representing how the step value\ncompares to zero, and whether the step is a double or not.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c82fdecb60c03d19fc7609e15c43622c67c31303b3da9566b6c2e87900680d1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_for\n\nDocumentation:\nAdvances until the next statement after failing to parse a `FOR` statement.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reset_for(&mut self) -> Result<()> {\n loop {\n match self.lexer.peek()?.token {\n Token::Eof => break,\n Token::Next => {\n self.lexer.consume_peeked();\n break;\n }\n _ => {\n self.lexer.consume_peeked();\n }\n }\n }\n self.reset()\n }\n```"}], "func_name": "reset_for", "docstring": "Advances until the next statement after failing to parse a `FOR` statement.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4aca95b5452433c25f2e1cef32037791df44b65e5b47be60dcac5a6fb303ff7e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_callable_args\n\nDocumentation:\nParses the optional parameter list that may appear after a `FUNCTION` or `SUB` definition,\nincluding the opening and closing parenthesis.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_callable_args(&mut self) -> Result> {\n let mut params = vec![];\n let peeked = self.lexer.peek()?;\n if peeked.token == Token::LeftParen {\n self.lexer.consume_peeked();\n\n loop {\n let token_span = self.lexer.read()?;\n match token_span.token {\n Token::Symbol(param) => {\n let peeked = self.lexer.peek()?;\n if peeked.token == Token::As {\n self.lexer.consume_peeked();\n\n let name = vref_to_unannotated_string(param, token_span.pos)?;\n let (vtype, _pos) = self.parse_as_type()?;\n params.push(VarRef::new(name, Some(vtype)));\n } else {\n params.push(param);\n }\n }\n _ => {\n return Err(Error::Bad(\n token_span.pos,\n \"Expected a parameter name\".to_owned(),\n ));\n }\n }\n\n let token_span = self.lexer.read()?;\n match token_span.token {\n Token::Comma => (),\n Token::RightParen => break,\n _ => {\n return Err(Error::Bad(\n token_span.pos,\n \"Expected comma, AS, or end of parameters list\".to_owned(),\n ));\n }\n }\n }\n }\n Ok(params)\n }\n```"}], "func_name": "parse_callable_args", "docstring": "Parses the optional parameter list that may appear after a `FUNCTION` or `SUB` definition,\nincluding the opening and closing parenthesis.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef550afdf247e6bd8a9a092e42035b57599a66301d2f4ee14c5a221a2c814a24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_callable_body\n\nDocumentation:\nParses the body of a callable and returns the collection of statements and the position\nof the end of the body.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_callable_body(\n &mut self,\n start_pos: LineCol,\n exp_token: Token,\n ) -> Result<(Vec, LineCol)> {\n debug_assert!(matches!(exp_token, Token::Function | Token::Sub));\n\n let mut body = vec![];\n let end_pos;\n loop {\n let peeked = self.lexer.peek()?;\n match peeked.token {\n Token::Eof => {\n end_pos = peeked.pos;\n break;\n }\n\n Token::Eol => {\n self.lexer.consume_peeked();\n }\n\n Token::Function | Token::Sub => {\n return Err(Error::Bad(\n peeked.pos,\n \"Cannot nest FUNCTION or SUB definitions\".to_owned(),\n ));\n }\n\n Token::End => {\n let end_span = self.lexer.consume_peeked();\n match self.maybe_parse_end()? {\n Ok(stmt) => {\n body.push(stmt);\n }\n Err(token) if token == exp_token => {\n end_pos = end_span.pos;\n break;\n }\n Err(token) => {\n return Err(Error::Bad(\n end_span.pos,\n format!(\"END {} without {}\", token, token),\n ));\n }\n }\n }\n\n // TODO(jmmv): Handle `EXIT FUNCTION` or `EXIT SUB`.\n _ => match self.parse_one_safe()? {\n Some(stmt) => body.push(stmt),\n None => {\n return Err(Error::Bad(\n start_pos,\n format!(\"{} without END {}\", exp_token, exp_token),\n ));\n }\n },\n }\n }\n\n self.expect_and_consume_with_pos(\n exp_token.clone(),\n start_pos,\n format!(\"{} without END {}\", exp_token, exp_token),\n )?;\n\n Ok((body, end_pos))\n }\n```"}], "func_name": "parse_callable_body", "docstring": "Parses the body of a callable and returns the collection of statements and the position\nof the end of the body.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80dd889b56954582cfe34d9ee6cddecefd745d7f97e5541d1b99e4e10c0c8c57"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_callable\n\nDocumentation:\nAdvances until the next statement after failing to parse a `FUNCTION` or `SUB` definition.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reset_callable(&mut self, exp_token: Token) -> Result<()> {\n loop {\n match self.lexer.peek()?.token {\n Token::Eof => break,\n Token::End => {\n self.lexer.consume_peeked();\n\n let token_span = self.lexer.read()?;\n if token_span.token == exp_token {\n break;\n }\n }\n _ => {\n self.lexer.consume_peeked();\n }\n }\n }\n self.reset()\n }\n```"}], "func_name": "reset_callable", "docstring": "Advances until the next statement after failing to parse a `FUNCTION` or `SUB` definition.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "544b4ce10e147575ac085ea4d05868a5e3498accffffeb3bb131e9aa861b0afa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_on\n\nDocumentation:\nParses an `ON ERROR` statement. Only `ON` has been consumed so far.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_on(&mut self) -> Result {\n self.expect_and_consume(Token::Error, \"Expected ERROR after ON\")?;\n\n let token_span = self.lexer.read()?;\n match token_span.token {\n Token::Goto => {\n let token_span = self.lexer.read()?;\n match token_span.token {\n Token::Integer(0) => Ok(Statement::OnError(OnErrorSpan::Reset)),\n Token::Integer(i) => Ok(Statement::OnError(OnErrorSpan::Goto(GotoSpan {\n target: format!(\"{}\", i),\n target_pos: token_span.pos,\n }))),\n Token::Label(target) => Ok(Statement::OnError(OnErrorSpan::Goto(GotoSpan {\n target,\n target_pos: token_span.pos,\n }))),\n _ => Err(Error::Bad(\n token_span.pos,\n \"Expected label name or 0 after ON ERROR GOTO\".to_owned(),\n )),\n }\n }\n Token::Resume => {\n self.expect_and_consume(Token::Next, \"Expected NEXT after ON ERROR RESUME\")?;\n Ok(Statement::OnError(OnErrorSpan::ResumeNext))\n }\n _ => {\n Err(Error::Bad(token_span.pos, \"Expected GOTO or RESUME after ON ERROR\".to_owned()))\n }\n }\n }\n```"}], "func_name": "parse_on", "docstring": "Parses an `ON ERROR` statement. Only `ON` has been consumed so far.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "801dfef735966355016a3dc7e29e8d56d5ac69dc4dd459ccaf7c0d4ef656faca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_case_guards\n\nDocumentation:\nParses the guards after a `CASE` keyword.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_case_guards(&mut self) -> Result> {\n let mut guards = vec![];\n\n loop {\n let peeked = self.lexer.peek()?;\n match peeked.token {\n Token::Else => {\n let token_span = self.lexer.consume_peeked();\n\n if !guards.is_empty() {\n return Err(Error::Bad(\n token_span.pos,\n \"CASE ELSE must be on its own\".to_owned(),\n ));\n }\n\n let peeked = self.lexer.peek()?;\n if peeked.token != Token::Eol && peeked.token != Token::Eof {\n return Err(Error::Bad(\n peeked.pos,\n \"Expected newline after CASE ELSE\".to_owned(),\n ));\n }\n\n break;\n }\n\n Token::Is => {\n self.lexer.consume_peeked();\n\n let token_span = self.lexer.read()?;\n let rel_op = match token_span.token {\n Token::Equal => CaseRelOp::Equal,\n Token::NotEqual => CaseRelOp::NotEqual,\n Token::Less => CaseRelOp::Less,\n Token::LessEqual => CaseRelOp::LessEqual,\n Token::Greater => CaseRelOp::Greater,\n Token::GreaterEqual => CaseRelOp::GreaterEqual,\n _ => {\n return Err(Error::Bad(\n token_span.pos,\n \"Expected relational operator\".to_owned(),\n ));\n }\n };\n\n let expr =\n self.parse_required_expr(\"Missing expression after relational operator\")?;\n guards.push(CaseGuardSpan::Is(rel_op, expr));\n }\n\n _ => {\n let from_expr = self.parse_required_expr(\"Missing expression in CASE guard\")?;\n\n let peeked = self.lexer.peek()?;\n match peeked.token {\n Token::Eol | Token::Comma => {\n guards.push(CaseGuardSpan::Is(CaseRelOp::Equal, from_expr));\n }\n Token::To => {\n self.lexer.consume_peeked();\n let to_expr = self\n .parse_required_expr(\"Missing expression after TO in CASE guard\")?;\n guards.push(CaseGuardSpan::To(from_expr, to_expr));\n }\n _ => {\n return Err(Error::Bad(\n peeked.pos,\n \"Expected comma, newline, or TO after expression\".to_owned(),\n ));\n }\n }\n }\n }\n\n let peeked = self.lexer.peek()?;\n match peeked.token {\n Token::Eol => {\n break;\n }\n Token::Comma => {\n self.lexer.consume_peeked();\n }\n _ => {\n return Err(Error::Bad(\n peeked.pos,\n \"Expected comma, newline, or TO after expression\".to_owned(),\n ));\n }\n }\n }\n\n Ok(guards)\n }\n```"}], "func_name": "parse_case_guards", "docstring": "Parses the guards after a `CASE` keyword.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f3d54dedb8ab150b2b12ec1d7b2df40d86eade77ed050a07bacb7c50c2f5fb1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_select\n\nDocumentation:\nAdvances until the next statement after failing to parse a `SELECT` statement.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reset_select(&mut self, select_pos: LineCol) -> Result<()> {\n loop {\n match self.lexer.peek()?.token {\n Token::Eof => break,\n Token::End => {\n self.lexer.consume_peeked();\n self.expect_and_consume_with_pos(\n Token::Select,\n select_pos,\n \"SELECT without END SELECT\",\n )?;\n break;\n }\n _ => {\n self.lexer.consume_peeked();\n }\n }\n }\n self.reset()\n }\n```"}], "func_name": "reset_select", "docstring": "Advances until the next statement after failing to parse a `SELECT` statement.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a98a33928a67b7451b2c8a711ab28b80a4f5ca071b26e828c4d6b6b944968734"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_while\n\nDocumentation:\nAdvances until the next statement after failing to parse a `WHILE` statement.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reset_while(&mut self) -> Result<()> {\n loop {\n match self.lexer.peek()?.token {\n Token::Eof => break,\n Token::Wend => {\n self.lexer.consume_peeked();\n break;\n }\n _ => {\n self.lexer.consume_peeked();\n }\n }\n }\n self.reset()\n }\n```"}], "func_name": "reset_while", "docstring": "Advances until the next statement after failing to parse a `WHILE` statement.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ca2b43d12b5559630790124eeb500a9ef93b68856c78d007dcfc7c5592afa86"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_uniline\n\nDocumentation:\nExtracts the next available uniline statement from the input stream, or `None` if none is\navailable.\n\nThe statement must be specifiable in a single line as part of a uniline `IF` statement, and\nwe currently expect this to only be used while parsing an `IF`.\n\nOn success, the stream is left in a position where the next statement can be extracted.\nOn failure, the caller must advance the stream to the next statement by calling `reset`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_uniline(&mut self) -> Result> {\n let token_span = self.lexer.read()?;\n match token_span.token {\n Token::Data => Ok(Some(self.parse_data()?)),\n Token::End => Ok(Some(self.parse_end(token_span.pos)?)),\n Token::Eof | Token::Eol => Ok(None),\n Token::Exit => Ok(Some(self.parse_exit_do(token_span.pos)?)),\n Token::Gosub => Ok(Some(self.parse_gosub()?)),\n Token::Goto => Ok(Some(self.parse_goto()?)),\n Token::On => Ok(Some(self.parse_on()?)),\n Token::Return => Ok(Some(Statement::Return(ReturnSpan { pos: token_span.pos }))),\n Token::Symbol(vref) => {\n let peeked = self.lexer.peek()?;\n if peeked.token == Token::Equal {\n self.lexer.consume_peeked();\n Ok(Some(self.parse_assignment(vref, token_span.pos)?))\n } else {\n Ok(Some(self.parse_array_or_builtin_call(vref, token_span.pos)?))\n }\n }\n Token::Bad(msg) => Err(Error::Bad(token_span.pos, msg)),\n t => Err(Error::Bad(token_span.pos, format!(\"Unexpected {} in uniline IF branch\", t))),\n }\n }\n```"}], "func_name": "parse_uniline", "docstring": "Extracts the next available uniline statement from the input stream, or `None` if none is\navailable.\n\nThe statement must be specifiable in a single line as part of a uniline `IF` statement, and\nwe currently expect this to only be used while parsing an `IF`.\n\nOn success, the stream is left in a position where the next statement can be extracted.\nOn failure, the caller must advance the stream to the next statement by calling `reset`.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7fc40e043beefa335982f4cb3854bc31e3107d079de380368624e7ca179bcc84"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_one\n\nDocumentation:\nExtracts the next available statement from the input stream, or `None` if none is available.\n\nOn success, the stream is left in a position where the next statement can be extracted.\nOn failure, the caller must advance the stream to the next statement by calling `reset`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_one(&mut self) -> Result> {\n loop {\n match self.lexer.peek()?.token {\n Token::Eol => {\n self.lexer.consume_peeked();\n }\n Token::Eof => return Ok(None),\n _ => break,\n }\n }\n let token_span = self.lexer.read()?;\n let res = match token_span.token {\n Token::Data => Ok(Some(self.parse_data()?)),\n Token::Dim => Ok(Some(self.parse_dim()?)),\n Token::Do => {\n let result = self.parse_do(token_span.pos);\n if result.is_err() {\n self.reset_do()?;\n }\n Ok(Some(result?))\n }\n Token::End => Ok(Some(self.parse_end(token_span.pos)?)),\n Token::Eof => return Ok(None),\n Token::Eol => Ok(None),\n Token::Exit => Ok(Some(self.parse_exit_do(token_span.pos)?)),\n Token::If => {\n let result = self.parse_if(token_span.pos);\n if result.is_err() {\n self.reset_if(token_span.pos)?;\n }\n Ok(Some(result?))\n }\n Token::For => {\n let result = self.parse_for(token_span.pos);\n if result.is_err() {\n self.reset_for()?;\n }\n Ok(Some(result?))\n }\n Token::Function => {\n let result = self.parse_function(token_span.pos);\n if result.is_err() {\n self.reset_callable(Token::Function)?;\n }\n Ok(Some(result?))\n }\n Token::Gosub => {\n let result = self.parse_gosub();\n Ok(Some(result?))\n }\n Token::Goto => {\n let result = self.parse_goto();\n Ok(Some(result?))\n }\n Token::Integer(i) => {\n let name = format!(\"{}\", i);\n // When we encounter a line number, we must return early to avoid looking for a line\n // ending given that the next statement may start after the label we found.\n return Ok(Some(Statement::Label(LabelSpan { name, name_pos: token_span.pos })));\n }\n Token::Label(name) => {\n // When we encounter a label, we must return early to avoid looking for a line\n // ending given that the next statement may start after the label we found.\n return Ok(Some(Statement::Label(LabelSpan { name, name_pos: token_span.pos })));\n }\n Token::On => Ok(Some(self.parse_on()?)),\n Token::Return => Ok(Some(Statement::Return(ReturnSpan { pos: token_span.pos }))),\n Token::Select => {\n let result = self.parse_select(token_span.pos);\n if result.is_err() {\n self.reset_select(token_span.pos)?;\n }\n Ok(Some(result?))\n }\n Token::Sub => {\n let result = self.parse_sub(token_span.pos);\n if result.is_err() {\n self.reset_callable(Token::Sub)?;\n }\n Ok(Some(result?))\n }\n Token::Symbol(vref) => {\n let peeked = self.lexer.peek()?;\n if peeked.token == Token::Equal {\n self.lexer.consume_peeked();\n Ok(Some(self.parse_assignment(vref, token_span.pos)?))\n } else {\n Ok(Some(self.parse_array_or_builtin_call(vref, token_span.pos)?))\n }\n }\n Token::While => {\n let result = self.parse_while(token_span.pos);\n if result.is_err() {\n self.reset_while()?;\n }\n Ok(Some(result?))\n }\n Token::Bad(msg) => return Err(Error::Bad(token_span.pos, msg)),\n t => return Err(Error::Bad(token_span.pos, format!(\"Unexpected {} in statement\", t))),\n };\n\n let token_span = self.lexer.peek()?;\n match token_span.token {\n Token::Eof => (),\n Token::Eol => {\n self.lexer.consume_peeked();\n }\n _ => {\n return Err(Error::Bad(\n token_span.pos,\n format!(\"Expected newline but found {}\", token_span.token),\n ))\n }\n };\n\n res\n }\n```"}], "func_name": "parse_one", "docstring": "Extracts the next available statement from the input stream, or `None` if none is available.\n\nOn success, the stream is left in a position where the next statement can be extracted.\nOn failure, the caller must advance the stream to the next statement by calling `reset`.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "49aad5b5bdd189d17670d0693a27d9c81a91008c8c5b4e453481d561776cb88a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset\n\nDocumentation:\nAdvances until the next statement after failing to parse a single statement.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reset(&mut self) -> Result<()> {\n loop {\n match self.lexer.peek()?.token {\n Token::Eof => break,\n Token::Eol => {\n self.lexer.consume_peeked();\n break;\n }\n _ => {\n self.lexer.consume_peeked();\n }\n }\n }\n Ok(())\n }\n```"}], "func_name": "reset", "docstring": "Advances until the next statement after failing to parse a single statement.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "862b50d7d521aa4efb8bb3e1ec62b21718e3a6c39f309f95747823c47bbc59a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_one_safe\n\nDocumentation:\nExtracts the next available statement from the input stream, or `None` if none is available.\n\nThe stream is always left in a position where the next statement extraction can be tried.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_one_safe(&mut self) -> Result> {\n let result = self.parse_one();\n if result.is_err() {\n self.reset()?;\n }\n result\n }\n```"}], "func_name": "parse_one_safe", "docstring": "Extracts the next available statement from the input stream, or `None` if none is available.\n\nThe stream is always left in a position where the next statement extraction can be tried.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f01e6dc0cced2e7d04a9a12355cd63ddbdff81c6e9b61addccead36bfa51fd27"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse\n\nDocumentation:\nExtracts all statements from the input stream.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn parse(input: &mut dyn io::Read) -> StatementIter {\n StatementIter { parser: Parser::from(input) }\n}\n```"}], "func_name": "parse", "docstring": "Extracts all statements from the input stream.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa953f76dba307d3be20d4ed01bbff2d52b5b1cf22538feac91d0a57adc6b145"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lc\n\nDocumentation:\nSyntactic sugar to instantiate a `LineCol` for testing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn lc(line: usize, col: usize) -> LineCol {\n LineCol { line, col }\n }\n```"}], "func_name": "lc", "docstring": "Syntactic sugar to instantiate a `LineCol` for testing.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2cadfb3e02147132f60cc47024d7d0061be593754fa5cdf74666550b8f1a9652"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expr_boolean\n\nDocumentation:\nSyntactic sugar to instantiate an `Expr::Boolean` for testing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn expr_boolean(value: bool, line: usize, col: usize) -> Expr {\n Expr::Boolean(BooleanSpan { value, pos: LineCol { line, col } })\n }\n```"}], "func_name": "expr_boolean", "docstring": "Syntactic sugar to instantiate an `Expr::Boolean` for testing.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "99659d6683d7e8e9c303154a42e24420c94f762e6adec687a75c19ac03d236f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expr_double\n\nDocumentation:\nSyntactic sugar to instantiate an `Expr::Double` for testing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn expr_double(value: f64, line: usize, col: usize) -> Expr {\n Expr::Double(DoubleSpan { value, pos: LineCol { line, col } })\n }\n```"}], "func_name": "expr_double", "docstring": "Syntactic sugar to instantiate an `Expr::Double` for testing.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9d83308479930113ec355faca70a255bd9c2023f83def8710c4e2498b7ec6343"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expr_integer\n\nDocumentation:\nSyntactic sugar to instantiate an `Expr::Integer` for testing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn expr_integer(value: i32, line: usize, col: usize) -> Expr {\n Expr::Integer(IntegerSpan { value, pos: LineCol { line, col } })\n }\n```"}], "func_name": "expr_integer", "docstring": "Syntactic sugar to instantiate an `Expr::Integer` for testing.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "741ee2af24509e7c327414e2f62156da21952bdab22f6641db1b135e3ff3e428"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expr_text\n\nDocumentation:\nSyntactic sugar to instantiate an `Expr::Text` for testing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn expr_text>(value: S, line: usize, col: usize) -> Expr {\n Expr::Text(TextSpan { value: value.into(), pos: LineCol { line, col } })\n }\n```"}], "func_name": "expr_text", "docstring": "Syntactic sugar to instantiate an `Expr::Text` for testing.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4687465b2786f55ef94af7daa226ff049049e6b43f0f8d4273cf7e5375e9ee60"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expr_symbol\n\nDocumentation:\nSyntactic sugar to instantiate an `Expr::Symbol` for testing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn expr_symbol(vref: VarRef, line: usize, col: usize) -> Expr {\n Expr::Symbol(SymbolSpan { vref, pos: LineCol { line, col } })\n }\n```"}], "func_name": "expr_symbol", "docstring": "Syntactic sugar to instantiate an `Expr::Symbol` for testing.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cfdee4509462a8434d5c6fe3470c0e0aff9ec09b1641fc7e0a8593206ab75bb4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_ok_test\n\nDocumentation:\nRuns the parser on the given `input` and expects the returned statements to match\n`exp_statements`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_ok_test(input: &str, exp_statements: &[Statement]) {\n let mut input = input.as_bytes();\n let statements =\n parse(&mut input).map(|r| r.expect(\"Parsing failed\")).collect::>();\n assert_eq!(exp_statements, statements.as_slice());\n }\n```"}], "func_name": "do_ok_test", "docstring": "Runs the parser on the given `input` and expects the returned statements to match\n`exp_statements`.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "91a0edf8f04b8a7f255dc39e559011fb4a52f80c63acc7fc98891a77a2a9c3e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_error_test\n\nDocumentation:\nRuns the parser on the given `input` and expects the `err` error message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_error_test(input: &str, expected_err: &str) {\n let mut input = input.as_bytes();\n let mut parser = Parser::from(&mut input);\n assert_eq!(\n expected_err,\n format!(\"{}\", parser.parse_one_safe().expect_err(\"Parsing did not fail\"))\n );\n assert!(parser.parse_one_safe().unwrap().is_none());\n }\n```"}], "func_name": "do_error_test", "docstring": "Runs the parser on the given `input` and expects the `err` error message.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc37b3cadb50d6e3dc166009305c6f64a7b4e666578152a7b8ce0c9106fbf59f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_expr_ok_test\n\nDocumentation:\nWrapper around `do_ok_test` to parse an expression. Given that expressions alone are not\nvalid statements, we have to put them in a statement to parse them. In doing so, we can\nalso put an extra statement after them to ensure we detect their end properly.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_expr_ok_test(input: &str, expr: Expr) {\n do_ok_test(\n &format!(\"PRINT {}, 1\", input),\n &[Statement::Call(CallSpan {\n vref: VarRef::new(\"PRINT\", None),\n vref_pos: lc(1, 1),\n args: vec![\n ArgSpan {\n expr: Some(expr),\n sep: ArgSep::Long,\n sep_pos: lc(1, 7 + input.len()),\n },\n ArgSpan {\n expr: Some(expr_integer(1, 1, 6 + input.len() + 3)),\n sep: ArgSep::End,\n sep_pos: lc(1, 10 + input.len()),\n },\n ],\n })],\n );\n }\n```"}], "func_name": "do_expr_ok_test", "docstring": "Wrapper around `do_ok_test` to parse an expression. Given that expressions alone are not\nvalid statements, we have to put them in a statement to parse them. In doing so, we can\nalso put an extra statement after them to ensure we detect their end properly.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ceb0c884cf55d3edd2f78761a14b7ed5bf75741c0ca531f8200998472734b22"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_expr_error_test\n\nDocumentation:\nWrapper around `do_error_test` to parse an expression. Given that expressions alone are not\nvalid statements, we have to put them in a statement to parse them. In doing so, we can\nalso put an extra statement after them to ensure we detect their end properly.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_expr_error_test(input: &str, msg: &str) {\n do_error_test(&format!(\"PRINT {}, 1\", input), msg)\n }\n```"}], "func_name": "do_expr_error_test", "docstring": "Wrapper around `do_error_test` to parse an expression. Given that expressions alone are not\nvalid statements, we have to put them in a statement to parse them. In doing so, we can\nalso put an extra statement after them to ensure we detect their end properly.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c2944e12a687e28a225822703a5ff921d58f5a628299aff470171a2c9aafc705"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_bare_builtin_call\n\nDocumentation:\nHelper to instantiate a trivial `Statement::BuiltinCall` that has no arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn make_bare_builtin_call(name: &str, line: usize, col: usize) -> Statement {\n Statement::Call(CallSpan {\n vref: VarRef::new(name, None),\n vref_pos: LineCol { line, col },\n args: vec![],\n })\n }\n```"}], "func_name": "make_bare_builtin_call", "docstring": "Helper to instantiate a trivial `Statement::BuiltinCall` that has no arguments.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2d29c6c5ab10987d0e72b56e016906dfb9b6b6bc891b421dac100abee7a0b4a9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_if_uniline_allowed_test\n\nDocumentation:\nPerforms a test of a uniline if statement followed by a specific allowed statement type.\n\n`text` is the literal statement to append to the if statement, and `stmt` contains the\nexpected parsed statement. The expected positions for the parsed statement are line 1 and\ncolumns offset by 11 characters.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_if_uniline_allowed_test(text: &str, stmt: Statement) {\n do_ok_test(\n &format!(\"IF 1 THEN {}\\nZ\", text),\n &[\n Statement::If(IfSpan {\n branches: vec![IfBranchSpan { guard: expr_integer(1, 1, 4), body: vec![stmt] }],\n }),\n make_bare_builtin_call(\"Z\", 2, 1),\n ],\n );\n }\n```"}], "func_name": "do_if_uniline_allowed_test", "docstring": "Performs a test of a uniline if statement followed by a specific allowed statement type.\n\n`text` is the literal statement to append to the if statement, and `stmt` contains the\nexpected parsed statement. The expected positions for the parsed statement are line 1 and\ncolumns offset by 11 characters.", "repo": "endbasic/endbasic", "path": "core/src/parser.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "12bcb0b685571ca7f2736a3f4737cb1121e72d2b8df6da3f6101e91f4f1d819f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nConstructs a new character reader from an `io::Read`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from(reader: &'a mut dyn io::Read) -> Self {\n Self {\n reader: io::BufReader::new(reader),\n pending: Pending::Unknown,\n peeked: None,\n next_pos: LineCol { line: 1, col: 1 },\n }\n }\n```"}], "func_name": "from", "docstring": "Constructs a new character reader from an `io::Read`.", "repo": "endbasic/endbasic", "path": "core/src/reader.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/reader.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a55773b1b2b3fb25f4caeb9ba95c2a90607897158dc9857ecb53881dc16ec431"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: refill_and_next\n\nDocumentation:\nReplenishes `pending` with the next line to process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn refill_and_next(&mut self) -> Option> {\n self.pending = {\n let mut line = String::new();\n match self.reader.read_line(&mut line) {\n Ok(0) => Pending::Eof,\n Ok(_) => Pending::Chars(line.chars().collect(), 0),\n Err(e) => Pending::Error(Some(e)),\n }\n };\n self.next()\n }\n```"}], "func_name": "refill_and_next", "docstring": "Replenishes `pending` with the next line to process.", "repo": "endbasic/endbasic", "path": "core/src/reader.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/reader.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d189bdd805707591aadce78bda28dd38b4788bd96537d5cc10d3e5cf204d0c9e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: peek\n\nDocumentation:\nPeeks into the next character without consuming it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn peek(&mut self) -> Option<&io::Result> {\n if self.peeked.is_none() {\n let next = self.next();\n self.peeked.replace(next);\n }\n self.peeked.as_ref().unwrap().as_ref()\n }\n```"}], "func_name": "peek", "docstring": "Peeks into the next character without consuming it.", "repo": "endbasic/endbasic", "path": "core/src/reader.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/reader.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4da64c0d33ca995c900e60dd1ce0cdf96da91fc0b83ab01dc20f6cc9841f5bb3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cs\n\nDocumentation:\nSyntactic sugar to instantiate a `CharSpan` for testing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn cs(ch: char, line: usize, col: usize) -> CharSpan {\n CharSpan { ch, pos: LineCol { line, col } }\n }\n```"}], "func_name": "cs", "docstring": "Syntactic sugar to instantiate a `CharSpan` for testing.", "repo": "endbasic/endbasic", "path": "core/src/reader.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/reader.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "30058d2c8b860dbc874170aa44373b4f4107888adb1619802f3fa0496d46d14f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new array of the given `subtype` and `dimensions`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(subtype: ExprType, dimensions: Vec) -> Self {\n assert!(!dimensions.is_empty());\n let mut n = 1;\n for dim in &dimensions {\n assert!(n > 0);\n n *= dim;\n }\n let mut values = Vec::with_capacity(n);\n let value = subtype.default_value();\n for _ in 0..n {\n values.push(value.clone());\n }\n Self { subtype, dimensions, values }\n }\n```"}], "func_name": "new", "docstring": "Creates a new array of the given `subtype` and `dimensions`.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8004053a4b92422361a87e3887c6f529e0e79fbc25c2c870e4ea1d3ccb4bf0c0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: validate_subscript\n\nDocumentation:\nValidates that the subscript `i` is in the `[0,max)` range and converts it to an `usize`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn validate_subscript(i: i32, max: usize) -> value::Result {\n if i < 0 {\n Err(value::Error::new(format!(\"Subscript {} cannot be negative\", i)))\n } else if (i as usize) >= max {\n Err(value::Error::new(format!(\"Subscript {} exceeds limit of {}\", i, max)))\n } else {\n Ok(i as usize)\n }\n }\n```"}], "func_name": "validate_subscript", "docstring": "Validates that the subscript `i` is in the `[0,max)` range and converts it to an `usize`.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac78abbc297e800a623cd0ab04fdbc17babeb6abe39e315a13f0bc8198d20689"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: native_index\n\nDocumentation:\nComputes the index to access the flat `values` array given a list of `subscripts`.\n\nIt is an error if `dimensions` and `subscripts` have different sizes, or if the values in\n`subscripts` are negative.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn native_index(dimensions: &[usize], subscripts: &[i32]) -> value::Result {\n debug_assert_eq!(\n subscripts.len(),\n dimensions.len(),\n \"Invalid number of subscripts; guaranteed valid by the compiler\"\n );\n\n let mut offset = 0;\n let mut multiplier = 1;\n let mut k = dimensions.len() - 1;\n while k > 0 {\n offset += Array::validate_subscript(subscripts[k], dimensions[k])? * multiplier;\n debug_assert!(dimensions[k] > 0);\n multiplier *= dimensions[k];\n k -= 1;\n }\n offset += Array::validate_subscript(subscripts[k], dimensions[k])? * multiplier;\n Ok(offset)\n }\n```"}], "func_name": "native_index", "docstring": "Computes the index to access the flat `values` array given a list of `subscripts`.\n\nIt is an error if `dimensions` and `subscripts` have different sizes, or if the values in\n`subscripts` are negative.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b9817df65249f8a5e801685300a678e277509156eee93e771764d399b0fd735b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: assign\n\nDocumentation:\nAssings the `value` to the array position indicated by the `subscripts`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn assign(&mut self, subscripts: &[i32], value: Value) -> value::Result<()> {\n debug_assert_eq!(\n subscripts.len(),\n self.dimensions.len(),\n \"Invalid number of subscripts; guaranteed valid by the compiler\"\n );\n\n debug_assert_eq!(\n value.as_exprtype(),\n self.subtype,\n \"Invalid types in assignment; guaranteed valid by the compiler\"\n );\n\n let i = Array::native_index(&self.dimensions, subscripts)?;\n self.values[i] = value;\n Ok(())\n }\n```"}], "func_name": "assign", "docstring": "Assings the `value` to the array position indicated by the `subscripts`.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "37d6e7685836ca90b6d87119216dc4802eb7200280a631f32e51b8ceba09e926"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: index\n\nDocumentation:\nObtains the value contained in the array position indicated by the `subscripts`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn index(&self, subscripts: &[i32]) -> value::Result<&Value> {\n let i = Array::native_index(&self.dimensions, subscripts)?;\n let value = &self.values[i];\n debug_assert!(value.as_exprtype() == self.subtype);\n Ok(value)\n }\n```"}], "func_name": "index", "docstring": "Obtains the value contained in the array position indicated by the `subscripts`.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "813be98753499064ba3a6d49e4cf3218ee638b5a589b1f386da82a299bc3cfc7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: eval_type\n\nDocumentation:\nReturns the type the symbol evaluates as.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn eval_type(&self) -> Option {\n match self {\n Symbol::Array(array) => Some(array.subtype()),\n Symbol::Callable(callable) => callable.metadata().return_type(),\n Symbol::Variable(value) => Some(value.as_exprtype()),\n }\n }\n```"}], "func_name": "eval_type", "docstring": "Returns the type the symbol evaluates as.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c7ab93c73e39c43f0f0c96374547b31acd8a250d871fa7ebcb84e440f7d6570e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: metadata\n\nDocumentation:\nReturns the metadata for the symbol, if any.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn metadata(&self) -> Option<&CallableMetadata> {\n match self {\n Symbol::Array(_) => None,\n Symbol::Callable(callable) => Some(callable.metadata()),\n Symbol::Variable(_) => None,\n }\n }\n```"}], "func_name": "metadata", "docstring": "Returns the metadata for the symbol, if any.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d99de273e46ee2b3b27c679a69e94c5a5e630bc9dcb7ad95e05e38a0aeb7e65c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: user_defined\n\nDocumentation:\nReturns whether the symbol was defined by the user or not.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn user_defined(&self) -> bool {\n match self {\n Symbol::Array(_) => true,\n Symbol::Callable(_) => false,\n Symbol::Variable(_) => true,\n }\n }\n```"}], "func_name": "user_defined", "docstring": "Returns whether the symbol was defined by the user or not.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80f57ac80efdbea564cf6731f59780e3bc0d51f031ab103674a63219047b2595"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_callable\n\nDocumentation:\nRegisters the given builtin callable as a global symbol.\n\nGiven that callables cannot be defined at runtime, specifying a non-unique name results in\na panic.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_callable(&mut self, callable: Rc) {\n let key = SymbolKey::from(callable.metadata().name());\n assert!(!self.globals.contains_key(&key));\n self.globals.insert(key.to_owned(), Symbol::Callable(callable));\n }\n```"}], "func_name": "add_callable", "docstring": "Registers the given builtin callable as a global symbol.\n\nGiven that callables cannot be defined at runtime, specifying a non-unique name results in\na panic.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f5a9885c932a712557f460a014948cc24e1ff2f926e9c16420ea50f6a9437fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: callables\n\nDocumentation:\nReturns the mapping of all callables.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn callables(&self) -> HashMap<&SymbolKey, Rc> {\n let mut callables = HashMap::with_capacity(self.globals.len());\n for (key, symbol) in &self.globals {\n if let Symbol::Callable(c) = symbol {\n callables.insert(key, c.clone());\n }\n }\n callables\n }\n```"}], "func_name": "callables", "docstring": "Returns the mapping of all callables.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "126fb88a205f84b1b0ca646dc7b3accce7bd3503b702429ddf1f82c9eab1ecde"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dim\n\nDocumentation:\nDefines a new local variable `key` of type `etype`. The variable must not yet exist.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn dim(&mut self, key: SymbolKey, etype: ExprType) {\n debug_assert!(\n !self.globals.contains_key(&key) && !self.scopes.last_mut().unwrap().contains_key(&key),\n \"Pre-existence of variables is checked at compilation time\"\n );\n self.scopes.last_mut().unwrap().insert(key, Symbol::Variable(etype.default_value()));\n }\n```"}], "func_name": "dim", "docstring": "Defines a new local variable `key` of type `etype`. The variable must not yet exist.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00af05ae4985f12825cdcb23062b19a43777934a2dc2ca357efa7b6d1038c263"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dim_shared\n\nDocumentation:\nDefines a new global variable `key` of type `etype`. The variable must not yet exist.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn dim_shared(&mut self, key: SymbolKey, etype: ExprType) {\n debug_assert!(\n !self.globals.contains_key(&key) && !self.scopes.last_mut().unwrap().contains_key(&key),\n \"Pre-existence of variables is checked at compilation time\"\n );\n self.globals.insert(key, Symbol::Variable(etype.default_value()));\n }\n```"}], "func_name": "dim_shared", "docstring": "Defines a new global variable `key` of type `etype`. The variable must not yet exist.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "190d006e6ede4ac8e3d8c1f3c30d60b7ca0502a4b150d49a052e09f8e09ea019"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dim_array\n\nDocumentation:\nDefines a new array `key` of type `subtype` with `dimensions`. The array must not yet\nexist, and the name may not overlap function or variable names.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn dim_array(&mut self, key: SymbolKey, subtype: ExprType, dimensions: Vec) {\n debug_assert!(\n !self.globals.contains_key(&key) && !self.scopes.last_mut().unwrap().contains_key(&key),\n \"Pre-existence of variables is checked at compilation time\"\n );\n self.scopes.last_mut().unwrap().insert(key, Symbol::Array(Array::new(subtype, dimensions)));\n }\n```"}], "func_name": "dim_array", "docstring": "Defines a new array `key` of type `subtype` with `dimensions`. The array must not yet\nexist, and the name may not overlap function or variable names.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8ae83caefba69192e24f949acc10266d3a45246a2e352b6b21ad627ed6269e8b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dim_shared_array\n\nDocumentation:\nDefines a new global array `key` of type `subtype` with `dimensions`. The array must not yet\nexist, and the name may not overlap function or variable names.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn dim_shared_array(&mut self, key: SymbolKey, subtype: ExprType, dimensions: Vec) {\n debug_assert!(\n !self.globals.contains_key(&key) && !self.scopes.last_mut().unwrap().contains_key(&key),\n \"Pre-existence of variables is checked at compilation time\"\n );\n self.globals.insert(key, Symbol::Array(Array::new(subtype, dimensions)));\n }\n```"}], "func_name": "dim_shared_array", "docstring": "Defines a new global array `key` of type `subtype` with `dimensions`. The array must not yet\nexist, and the name may not overlap function or variable names.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "487df7efcbabf153c32504dcb849a4e829ad0a4eaf405f494a8dbf51b7d8799e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load\n\nDocumentation:\nObtains the value of a symbol or `None` if it is not defined.\n\nThis is meant to use by the compiler only. All other users should call `get` instead\nto do the necessary runtime validity checks.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn load(&self, key: &SymbolKey) -> Option<&Symbol> {\n let local = self.scopes.last().unwrap().get(key);\n if local.is_some() {\n return local;\n }\n self.globals.get(key)\n }\n```"}], "func_name": "load", "docstring": "Obtains the value of a symbol or `None` if it is not defined.\n\nThis is meant to use by the compiler only. All other users should call `get` instead\nto do the necessary runtime validity checks.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f31152364f0a32dc2f9524a81eb8cc2c1ba89bee2dceff5e709add352239059"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nObtains the value of a symbol or `None` if it is not defined.\n\nReturns an error if the type annotation in the symbol reference does not match its type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(&self, vref: &VarRef) -> value::Result> {\n let key = SymbolKey::from(vref.name());\n let symbol = self.load(&key);\n if let Some(symbol) = symbol {\n let stype = symbol.eval_type();\n if !vref.accepts_callable(stype) {\n return Err(value::Error::new(format!(\n \"Incompatible type annotation in {} reference\",\n vref\n )));\n }\n }\n Ok(symbol)\n }\n```"}], "func_name": "get", "docstring": "Obtains the value of a symbol or `None` if it is not defined.\n\nReturns an error if the type annotation in the symbol reference does not match its type.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "642e838cb88a5ccebe44b7d793265e1781bc73b3b57fc65cd48145f196e389c1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_auto\n\nDocumentation:\nObtains the value of a symbol or `None` if it is not defined.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_auto(&self, var: &str) -> Option<&Symbol> {\n let key = SymbolKey::from(var);\n self.load(&key)\n }\n```"}], "func_name": "get_auto", "docstring": "Obtains the value of a symbol or `None` if it is not defined.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6e1088b4e0f586ec699e40d4927000be7590f78ece116ef37495d5f23f1a177"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: assign\n\nDocumentation:\nSets the value of a variable without type promotion nor type checking.\n\nThis is meant to use by the compiler only. All other users should call `set_var` instead\nto do the necessary runtime validity checks.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn assign(&mut self, key: &SymbolKey, value: Value) {\n let old_value = match self.globals.get_mut(key) {\n Some(value) => Some(value),\n None => self.scopes.last_mut().unwrap().get_mut(key),\n };\n\n match old_value {\n Some(Symbol::Variable(old_value)) => {\n debug_assert_eq!(\n mem::discriminant(old_value),\n mem::discriminant(&value),\n \"Type consistency is validated at compilation time\"\n );\n *old_value = value;\n }\n Some(_) => unreachable!(\"Type consistency is validated at compilation time\"),\n None => {\n self.scopes.last_mut().unwrap().insert(key.clone(), Symbol::Variable(value));\n }\n }\n }\n```"}], "func_name": "assign", "docstring": "Sets the value of a variable without type promotion nor type checking.\n\nThis is meant to use by the compiler only. All other users should call `set_var` instead\nto do the necessary runtime validity checks.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c35ab3c73f20d5a3f922de9724c694758596a2453bd8441065e2a7d972f463e0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_var\n\nDocumentation:\nSets the value of a variable.\n\nIf `vref` contains a type annotation, the type of the value must be compatible with that\ntype annotation.\n\nIf the variable is already defined, then the type of the new value must be compatible with\nthe existing variable. In other words: a variable cannot change types while it's alive.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_var(&mut self, vref: &VarRef, value: Value) -> value::Result<()> {\n let key = vref.as_symbol_key();\n let value = value.maybe_cast(vref.ref_type())?;\n match self.get_mut(vref)? {\n Some(Symbol::Variable(old_value)) => {\n let value = value.maybe_cast(Some(old_value.as_exprtype()))?;\n if mem::discriminant(&value) != mem::discriminant(old_value) {\n return Err(value::Error::new(format!(\n \"Cannot assign value of type {} to variable of type {}\",\n value.as_exprtype(),\n old_value.as_exprtype(),\n )));\n }\n self.assign(&key, value);\n Ok(())\n }\n Some(_) => Err(value::Error::new(format!(\"Cannot redefine {} as a variable\", vref))),\n None => {\n if let Some(ref_type) = vref.ref_type() {\n if !vref.accepts(value.as_exprtype()) {\n return Err(value::Error::new(format!(\n \"Cannot assign value of type {} to variable of type {}\",\n value.as_exprtype(),\n ref_type,\n )));\n }\n }\n self.scopes.last_mut().unwrap().insert(key, Symbol::Variable(value));\n Ok(())\n }\n }\n }\n```"}], "func_name": "set_var", "docstring": "Sets the value of a variable.\n\nIf `vref` contains a type annotation, the type of the value must be compatible with that\ntype annotation.\n\nIf the variable is already defined, then the type of the new value must be compatible with\nthe existing variable. In other words: a variable cannot change types while it's alive.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "66a7d15661d0877e76261e1cdf4344ba33f45ed304bd4090d659b5a42c5f7449"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unset\n\nDocumentation:\nUnsets the symbol `key` irrespective of its type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn unset(&mut self, key: &SymbolKey) -> value::Result<()> {\n match self.scopes.last_mut().unwrap().remove(key) {\n Some(_) => Ok(()),\n None => Err(value::Error::new(format!(\"{} is not defined\", key))),\n }\n }\n```"}], "func_name": "unset", "docstring": "Unsets the symbol `key` irrespective of its type.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c4bce8959aa79be70f1daf5cfe3162f9f088ec6c52f15a086bc723815d01dfa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConstructs a new metadata builder with the minimum information necessary.\n\nAll code except tests must populate the whole builder with details. This is enforced at\nconstruction time, where we only allow some fields to be missing under the test\nconfiguration.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(name: &'static str) -> Self {\n assert!(name == name.to_ascii_uppercase(), \"Callable name must be in uppercase\");\n\n Self {\n name: Cow::Borrowed(name),\n return_type: None,\n syntaxes: vec![],\n category: None,\n description: None,\n }\n }\n```"}], "func_name": "new", "docstring": "Constructs a new metadata builder with the minimum information necessary.\n\nAll code except tests must populate the whole builder with details. This is enforced at\nconstruction time, where we only allow some fields to be missing under the test\nconfiguration.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d80798b732d43eaca678e5072b139af45d314914da1c07a28edb4704686d51b9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_dynamic\n\nDocumentation:\nConstructs a new metadata builder with the minimum information necessary.\n\nThis is the same as `new` but using a dynamically-allocated name, which is necessary for\nuser-defined symbols.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_dynamic(name: String) -> Self {\n Self {\n name: Cow::Owned(name.to_ascii_uppercase()),\n return_type: None,\n syntaxes: vec![],\n category: None,\n description: None,\n }\n }\n```"}], "func_name": "new_dynamic", "docstring": "Constructs a new metadata builder with the minimum information necessary.\n\nThis is the same as `new` but using a dynamically-allocated name, which is necessary for\nuser-defined symbols.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69e303f60f901b86c4b7597023df174342e1a3cd37c8e40f31fbaa228fd74c33"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_return_type\n\nDocumentation:\nSets the return type of the callable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_return_type(mut self, return_type: ExprType) -> Self {\n self.return_type = Some(return_type);\n self\n }\n```"}], "func_name": "with_return_type", "docstring": "Sets the return type of the callable.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b1c7ba77fd2aee6b5ecfa0907978267315e09c6b4c57bda2818bbad9e657f814"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_syntax\n\nDocumentation:\nSets the syntax specifications for this callable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_syntax(\n mut self,\n syntaxes: &'static [(&'static [SingularArgSyntax], Option<&'static RepeatedSyntax>)],\n ) -> Self {\n self.syntaxes = syntaxes\n .iter()\n .map(|s| CallableSyntax::new_static(s.0, s.1))\n .collect::>();\n self\n }\n```"}], "func_name": "with_syntax", "docstring": "Sets the syntax specifications for this callable.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7afa77157bc23b624e854c28de8d6dc598cdbdaa03b17b71e0593c1f7192522b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_category\n\nDocumentation:\nSets the category for this callable. All callables with the same category name will be\ngrouped together in help messages.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_category(mut self, category: &'static str) -> Self {\n self.category = Some(category);\n self\n }\n```"}], "func_name": "with_category", "docstring": "Sets the category for this callable. All callables with the same category name will be\ngrouped together in help messages.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3d144715d1586d6d5f9273a80bc7b2d211a2c29a2ef1444953b4660f6d2ff63f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_description\n\nDocumentation:\nSets the description for this callable. The `description` is a collection of paragraphs\nseparated by a single newline character, where the first paragraph is taken as the summary\nof the description. The summary must be a short sentence that is descriptive enough to be\nunderstood without further details. Empty lines (paragraphs) are not allowed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_description(mut self, description: &'static str) -> Self {\n for l in description.lines() {\n assert!(!l.is_empty(), \"Description cannot contain empty lines\");\n }\n self.description = Some(description);\n self\n }\n```"}], "func_name": "with_description", "docstring": "Sets the description for this callable. The `description` is a collection of paragraphs\nseparated by a single newline character, where the first paragraph is taken as the summary\nof the description. The summary must be a short sentence that is descriptive enough to be\nunderstood without further details. Empty lines (paragraphs) are not allowed.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba71d3931f1c0d2674d1cb464d747b3c619c59a49a571cd3376a0dfa36661246"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nGenerates the final `CallableMetadata` object, ensuring all values are present.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> CallableMetadata {\n assert!(!self.syntaxes.is_empty(), \"All callables must specify a syntax\");\n CallableMetadata {\n name: self.name,\n return_type: self.return_type,\n syntaxes: self.syntaxes,\n category: self.category.expect(\"All callables must specify a category\"),\n description: self.description.expect(\"All callables must specify a description\"),\n }\n }\n```"}], "func_name": "build", "docstring": "Generates the final `CallableMetadata` object, ensuring all values are present.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9d05a6fa044717a118f7a971410a13ad8b589a69da385e110fc09ec03ae45f84"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: test_build\n\nDocumentation:\nGenerates the final `CallableMetadata` object, ensuring the minimal set of values are\npresent. Only useful for testing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn test_build(mut self) -> CallableMetadata {\n if self.syntaxes.is_empty() {\n self.syntaxes.push(CallableSyntax::new_static(&[], None));\n }\n CallableMetadata {\n name: self.name,\n return_type: self.return_type,\n syntaxes: self.syntaxes,\n category: self.category.unwrap_or(\"\"),\n description: self.description.unwrap_or(\"\"),\n }\n }\n```"}], "func_name": "test_build", "docstring": "Generates the final `CallableMetadata` object, ensuring the minimal set of values are\npresent. Only useful for testing.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a798d20dac5c8c4fd5faaa7c2cfb0143967af65129ce069771349addb67c8c6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_argless\n\nDocumentation:\nReturns true if this is a callable that takes no arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_argless(&self) -> bool {\n self.syntaxes.is_empty() || (self.syntaxes.len() == 1 && self.syntaxes[0].is_empty())\n }\n```"}], "func_name": "is_argless", "docstring": "Returns true if this is a callable that takes no arguments.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "573c5f76d51b83b8beb6579fe10401d441bde974c87e931ac8d6ae7a9dd5738e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_var\n\nDocumentation:\nChecks that the variable `name` in `syms` has the value in `exp_value`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_var(syms: &Symbols, name: &str, exp_value: Value) {\n match syms.get(&VarRef::new(name, None)).unwrap().unwrap() {\n Symbol::Variable(value) => assert_eq!(exp_value, *value),\n _ => panic!(\"Got something that is not the variable we asked for\"),\n }\n }\n```"}], "func_name": "check_var", "docstring": "Checks that the variable `name` in `syms` has the value in `exp_value`.", "repo": "endbasic/endbasic", "path": "core/src/syms.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/syms.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "01c28abab90571d7ef46e6c97a0f637744df555fc1dd8aca99f48b200c9d389f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new command that sets aside all data values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new() -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"LAST_ERROR\")\n .with_return_type(ExprType::Text)\n .test_build(),\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new command that sets aside all data values.", "repo": "endbasic/endbasic", "path": "core/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3ea24a31304f3cf00fc92a5098e62b2a3006692f23157387d1be3273c4eba1e7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new command with the golden `data`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(data: Box>>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"IN\")\n .with_syntax(&[(\n &[SingularArgSyntax::RequiredRef(\n RequiredRefSyntax {\n name: Cow::Borrowed(\"vref\"),\n require_array: false,\n define_undefined: true,\n },\n ArgSepSyntax::End,\n )],\n None,\n )])\n .test_build(),\n data,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new command with the golden `data`.", "repo": "endbasic/endbasic", "path": "core/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8b25f77394e173b8988cb2840fc3b72e096cb0d61a26e86316a647aa03028b78"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new command that captures all calls into `data`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(data: Rc>>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"OUT\")\n .with_syntax(&[(\n &[],\n Some(&RepeatedSyntax {\n name: Cow::Borrowed(\"arg\"),\n type_syn: RepeatedTypeSyntax::AnyValue,\n sep: ArgSepSyntax::Exactly(ArgSep::Short),\n require_one: false,\n allow_missing: false,\n }),\n )])\n .test_build(),\n data,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new command that captures all calls into `data`.", "repo": "endbasic/endbasic", "path": "core/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e70739e76a7019baf370683a5e7b379349035e3c026d931e827ed3266fb2f1c7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new function that captures all calls into `data`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(data: Rc>>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"OUTF\")\n .with_return_type(ExprType::Integer)\n .with_syntax(&[(\n &[],\n Some(&RepeatedSyntax {\n name: Cow::Borrowed(\"expr\"),\n type_syn: RepeatedTypeSyntax::TypedValue(ExprType::Integer),\n sep: ArgSepSyntax::Exactly(ArgSep::Long),\n require_one: false,\n allow_missing: false,\n }),\n )])\n .test_build(),\n data,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new function that captures all calls into `data`.", "repo": "endbasic/endbasic", "path": "core/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d8d7cd23c0b2b6c030bd943ea73d3d6a0de07efc891e9dc683a78b7eec0b33a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_array\n\nDocumentation:\nAdds the array named `name` of type `subtype` to the list of symbols. The dimensions\nand contents of the array are unspecified.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_array>(mut self, name: S, subtype: ExprType) -> Self {\n let key = SymbolKey::from(name);\n let array = Array::new(subtype, vec![10]);\n self.scope.insert(key, Symbol::Array(array));\n self\n }\n```"}], "func_name": "add_array", "docstring": "Adds the array named `name` of type `subtype` to the list of symbols. The dimensions\nand contents of the array are unspecified.", "repo": "endbasic/endbasic", "path": "core/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "981c17aa47ad1a1361241f547fb85032a31f55871d4e93439bd09101a16416cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_callable\n\nDocumentation:\nAdds the `callable` to the list of symbols.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_callable(mut self, callable: Rc) -> Self {\n let name = callable.metadata().name();\n self.globals.insert(SymbolKey::from(name), Symbol::Callable(callable));\n self\n }\n```"}], "func_name": "add_callable", "docstring": "Adds the `callable` to the list of symbols.", "repo": "endbasic/endbasic", "path": "core/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4b84448f43d81e0d0fcd9a9c4dd3f7f18101cce9b75b864f3e5f33246ce2c1fc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_var\n\nDocumentation:\nAdds the variable named `name` with an initial `value` to the list of symbols.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_var>(mut self, name: S, value: Value) -> Self {\n let key = SymbolKey::from(name);\n self.scope.insert(key, Symbol::Variable(value));\n self\n }\n```"}], "func_name": "add_var", "docstring": "Adds the variable named `name` with an initial `value` to the list of symbols.", "repo": "endbasic/endbasic", "path": "core/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad4b9c9fb632e00abdce9b3317b30a955e2abfcf0f881ff0104d30d192991643"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_global_var\n\nDocumentation:\nAdds the variable named `name` with an initial `value` to the global list of symbols.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn add_global_var>(mut self, name: S, value: Value) -> Self {\n let key = SymbolKey::from(name);\n self.globals.insert(key, Symbol::Variable(value));\n self\n }\n```"}], "func_name": "add_global_var", "docstring": "Adds the variable named `name` with an initial `value` to the global list of symbols.", "repo": "endbasic/endbasic", "path": "core/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "01a7c70d6bdf8dcb0d63e1459576423ab6284b4d5f8f27440cfe42f3f4fb1554"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConstructs a new evaluation error from a textual `message`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new>(message: S) -> Self {\n Self { message: message.into() }\n }\n```"}], "func_name": "new", "docstring": "Constructs a new evaluation error from a textual `message`.", "repo": "endbasic/endbasic", "path": "core/src/value.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf7e14f191caa3bcd6616792c0cecaa796f710ebf7fb44feb533aaf8f053833e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: maybe_cast\n\nDocumentation:\nGiven a `target` variable type, tries to convert the value to that type if they are\ncompatible or otherwise returns self.\n\nCan return an error when the conversion is feasible but it is not possible, such as trying\nto cast a NaN to an integer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn maybe_cast(self, target: Option) -> Result {\n match (target, self) {\n (Some(ExprType::Integer), Value::Double(d)) => {\n Ok(Value::Integer(double_to_integer(d)?))\n }\n (Some(ExprType::Double), Value::Integer(i)) => Ok(Value::Double(integer_to_double(i))),\n (_, v) => Ok(v),\n }\n }\n```"}], "func_name": "maybe_cast", "docstring": "Given a `target` variable type, tries to convert the value to that type if they are\ncompatible or otherwise returns self.\n\nCan return an error when the conversion is feasible but it is not possible, such as trying\nto cast a NaN to an integer.", "repo": "endbasic/endbasic", "path": "core/src/value.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "047df4783085a870d1490c1b3cf85200abe9613301e4da9bcb5ef5a4d89c4fff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: double_to_integer\n\nDocumentation:\nConverts the double `d` to an integer and fails if the conversion is not possible.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn double_to_integer(d: f64) -> Result {\n let d = d.round();\n if d.is_finite() && d >= (i32::MIN as f64) && (d <= i32::MAX as f64) {\n Ok(d as i32)\n } else {\n Err(Error::new(format!(\"Cannot cast {} to integer due to overflow\", d)))\n }\n}\n```"}], "func_name": "double_to_integer", "docstring": "Converts the double `d` to an integer and fails if the conversion is not possible.", "repo": "endbasic/endbasic", "path": "core/src/value.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "816b1c028b74d0ee02d1283e305e5f54f3cc3bcf5467a35948d9a851d9497ea1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_integer\n\nDocumentation:\nPerforms an arithmetic addition of integers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_integer(lhs: i32, rhs: i32) -> Result {\n match lhs.checked_add(rhs) {\n Some(i) => Ok(i),\n None => Err(Error::new(\"Integer overflow\".to_owned())),\n }\n}\n```"}], "func_name": "add_integer", "docstring": "Performs an arithmetic addition of integers.", "repo": "endbasic/endbasic", "path": "core/src/value.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0809dcedeeb1cb051d3a5f5b9af03efcebd404218f3145d90c140ed9f7e787c6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sub_integer\n\nDocumentation:\nPerforms an arithmetic subtraction of integers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sub_integer(lhs: i32, rhs: i32) -> Result {\n match lhs.checked_sub(rhs) {\n Some(i) => Ok(i),\n None => Err(Error::new(\"Integer underflow\".to_owned())),\n }\n}\n```"}], "func_name": "sub_integer", "docstring": "Performs an arithmetic subtraction of integers.", "repo": "endbasic/endbasic", "path": "core/src/value.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "848181fc46d9115b39da0e8e4f3adcd7463be06c89d2802cd1eae2d2b9ab60ca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: div_integer\n\nDocumentation:\nPerforms an arithmetic division of integers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn div_integer(lhs: i32, rhs: i32) -> Result {\n if rhs == 0 {\n return Err(Error::new(\"Division by zero\"));\n }\n match lhs.checked_div(rhs) {\n Some(i) => Ok(i),\n None => Err(Error::new(\"Integer underflow\".to_owned())),\n }\n}\n```"}], "func_name": "div_integer", "docstring": "Performs an arithmetic division of integers.", "repo": "endbasic/endbasic", "path": "core/src/value.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dca87857e5e13c9874c1fdec2fbf267dba3358f7e157151fa0ad729402ef2d70"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: neg_integer\n\nDocumentation:\nPerforms an arithmetic negation of an integer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn neg_integer(i: i32) -> Result {\n match i.checked_neg() {\n Some(i) => Ok(i),\n None => Err(Error::new(\"Integer underflow\".to_owned())),\n }\n}\n```"}], "func_name": "neg_integer", "docstring": "Performs an arithmetic negation of an integer.", "repo": "endbasic/endbasic", "path": "core/src/value.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "129a8440fcadbf1ad06d1d650b66b74f26c7bbc1c2cdc3f8de7ce75b0bab34a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: describe\n\nDocumentation:\nFormats the repeated argument syntax for help purposes into `output`.\n\n`last_singular_sep` contains the separator of the last singular argument syntax, if any,\nwhich we need to place inside of the optional group.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn describe(&self, output: &mut String, last_singular_sep: Option<&ArgSepSyntax>) {\n if !self.require_one {\n output.push('[');\n }\n\n if let Some(sep) = last_singular_sep {\n sep.describe(output);\n }\n\n output.push_str(&self.name);\n output.push('1');\n if let RepeatedTypeSyntax::TypedValue(vtype) = self.type_syn {\n output.push(vtype.annotation());\n }\n\n if self.require_one {\n output.push('[');\n }\n\n self.sep.describe(output);\n output.push_str(\"..\");\n self.sep.describe(output);\n\n output.push_str(&self.name);\n output.push('N');\n if let RepeatedTypeSyntax::TypedValue(vtype) = self.type_syn {\n output.push(vtype.annotation());\n }\n\n output.push(']');\n }\n```"}], "func_name": "describe", "docstring": "Formats the repeated argument syntax for help purposes into `output`.\n\n`last_singular_sep` contains the separator of the last singular argument syntax, if any,\nwhich we need to place inside of the optional group.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "84ead477d3814829ba5c7c70ef535281b119e002f7ce2aca1618a10ccc527744"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: describe\n\nDocumentation:\nFormats the argument separator for help purposes into `output`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn describe(&self, output: &mut String) {\n match self {\n ArgSepSyntax::Exactly(sep) => {\n let (text, needs_space) = sep.describe();\n\n if !text.is_empty() && needs_space {\n output.push(' ');\n }\n output.push_str(text);\n if !text.is_empty() {\n output.push(' ');\n }\n }\n\n ArgSepSyntax::OneOf(sep1, sep2) => {\n let (text1, _needs_space1) = sep1.describe();\n let (text2, _needs_space2) = sep2.describe();\n\n output.push(' ');\n output.push_str(&format!(\"<{}|{}>\", text1, text2));\n output.push(' ');\n }\n\n ArgSepSyntax::End => (),\n };\n }\n```"}], "func_name": "describe", "docstring": "Formats the argument separator for help purposes into `output`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "95339b7c80fefbcfbac6c99e5b5f872c172c7dec5f99b59b92b1a74a10228e8f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_static\n\nDocumentation:\nCreates a new callable arguments definition from its parts defined statically in the\ncode.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new_static(\n singular: &'static [SingularArgSyntax],\n repeated: Option<&'static RepeatedSyntax>,\n ) -> Self {\n Self { singular: Cow::Borrowed(singular), repeated: repeated.map(Cow::Borrowed) }\n }\n```"}], "func_name": "new_static", "docstring": "Creates a new callable arguments definition from its parts defined statically in the\ncode.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "078f4130f3be3faebfb8ec1ea1e613832d7b44f165a2a0f167a3c85f4249887d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_dynamic\n\nDocumentation:\nCreates a new callable arguments definition from its parts defined dynamically at\nruntime.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new_dynamic(\n singular: Vec,\n repeated: Option,\n ) -> Self {\n Self { singular: Cow::Owned(singular), repeated: repeated.map(Cow::Owned) }\n }\n```"}], "func_name": "new_dynamic", "docstring": "Creates a new callable arguments definition from its parts defined dynamically at\nruntime.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f3aa34358183a0bdc5069639ca0b1e967015fd151f046b38ee3f1f6d9fc84aef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expected_nargs\n\nDocumentation:\nComputes the range of the expected number of parameters for this syntax.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn expected_nargs(&self) -> RangeInclusive {\n let mut min = self.singular.len();\n let mut max = self.singular.len();\n if let Some(syn) = self.repeated.as_ref() {\n if syn.require_one {\n min += 1;\n }\n max = usize::MAX;\n }\n min..=max\n }\n```"}], "func_name": "expected_nargs", "docstring": "Computes the range of the expected number of parameters for this syntax.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ca00b8a6813f2df562704d544f750200f00d24ef8487c8e013109912b52fbef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_empty\n\nDocumentation:\nReturns true if this syntax represents \"no arguments\".\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn is_empty(&self) -> bool {\n self.singular.is_empty() && self.repeated.is_none()\n }\n```"}], "func_name": "is_empty", "docstring": "Returns true if this syntax represents \"no arguments\".", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "41f891e3a97dcdd1eac7b57180215cdd7d3406ac982b4b30a716548a5bc72116"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: describe\n\nDocumentation:\nProduces a user-friendly description of this callable syntax.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn describe(&self) -> String {\n let mut description = String::new();\n let mut last_singular_sep = None;\n for (i, s) in self.singular.iter().enumerate() {\n let sep = match s {\n SingularArgSyntax::RequiredValue(details, sep) => {\n description.push_str(&details.name);\n description.push(details.vtype.annotation());\n sep\n }\n\n SingularArgSyntax::RequiredRef(details, sep) => {\n description.push_str(&details.name);\n sep\n }\n\n SingularArgSyntax::OptionalValue(details, sep) => {\n description.push('[');\n description.push_str(&details.name);\n description.push(details.vtype.annotation());\n description.push(']');\n sep\n }\n\n SingularArgSyntax::AnyValue(details, sep) => {\n if details.allow_missing {\n description.push('[');\n }\n description.push_str(&details.name);\n if details.allow_missing {\n description.push(']');\n }\n sep\n }\n };\n\n if self.repeated.is_none() || i < self.singular.len() - 1 {\n sep.describe(&mut description);\n }\n if i == self.singular.len() - 1 {\n last_singular_sep = Some(sep);\n }\n }\n\n if let Some(syn) = &self.repeated {\n syn.describe(&mut description, last_singular_sep);\n }\n\n description\n }\n```"}], "func_name": "describe", "docstring": "Produces a user-friendly description of this callable syntax.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f0cfed6ef4e6728d448ed5d01da5cfd7b5cb670ab47ac9917832c437277514a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_required_ref\n\nDocumentation:\nCompiles an argument that requires a reference.\n\nIf the reference does not exist and the syntax allowed undefined symbols, returns the details\nfor the symbol to insert into the symbols table, which the caller must handle because we do\nnot have mutable access to the `symtable` here.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_required_ref(\n instrs: &mut Vec,\n md: &CallableMetadata,\n pos: LineCol,\n symtable: &SymbolsTable,\n require_array: bool,\n define_undefined: bool,\n expr: Option,\n) -> Result> {\n match expr {\n Some(Expr::Symbol(span)) => {\n let key = SymbolKey::from(span.vref.name());\n match symtable.get(&key) {\n None => {\n if !define_undefined {\n return Err(Error::UndefinedSymbol(span.pos, key));\n }\n debug_assert!(!require_array);\n\n let vtype = span.vref.ref_type().unwrap_or(ExprType::Integer);\n\n if !span.vref.accepts(vtype) {\n return Err(Error::IncompatibleTypeAnnotationInReference(\n span.pos, span.vref,\n ));\n }\n\n instrs.push(Instruction::LoadRef(key.clone(), vtype, span.pos));\n Ok(Some((key, SymbolPrototype::Variable(vtype))))\n }\n\n Some(SymbolPrototype::Array(vtype, _)) => {\n let vtype = *vtype;\n\n if !span.vref.accepts(vtype) {\n return Err(Error::IncompatibleTypeAnnotationInReference(\n span.pos, span.vref,\n ));\n }\n\n if !require_array {\n return Err(Error::NotAReference(span.pos));\n }\n\n instrs.push(Instruction::LoadRef(key, vtype, span.pos));\n Ok(None)\n }\n\n Some(SymbolPrototype::Variable(vtype)) => {\n let vtype = *vtype;\n\n if !span.vref.accepts(vtype) {\n return Err(Error::IncompatibleTypeAnnotationInReference(\n span.pos, span.vref,\n ));\n }\n\n if require_array {\n return Err(Error::NotAReference(span.pos));\n }\n\n instrs.push(Instruction::LoadRef(key, vtype, span.pos));\n Ok(None)\n }\n\n Some(SymbolPrototype::Callable(md)) => {\n if !span.vref.accepts_callable(md.return_type()) {\n return Err(Error::IncompatibleTypeAnnotationInReference(\n span.pos, span.vref,\n ));\n }\n\n Err(Error::NotArrayOrFunction(span.pos, key))\n }\n }\n }\n\n Some(expr) => Err(Error::NotAReference(expr.start_pos())),\n\n None => Err(Error::CallableSyntaxError(pos, md.clone())),\n }\n}\n```"}], "func_name": "compile_required_ref", "docstring": "Compiles an argument that requires a reference.\n\nIf the reference does not exist and the syntax allowed undefined symbols, returns the details\nfor the symbol to insert into the symbols table, which the caller must handle because we do\nnot have mutable access to the `symtable` here.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "da84e636b884fc1d245fab853ab09bee733cbd8a06c505aa978c6689e119d4e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: find_syntax\n\nDocumentation:\nLocates the syntax definition that can parse the given number of arguments.\n\nPanics if more than one syntax definition applies.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn find_syntax(md: &CallableMetadata, pos: LineCol, nargs: usize) -> Result<&CallableSyntax> {\n let mut matches = md.syntaxes().iter().filter(|s| s.expected_nargs().contains(&nargs));\n let syntax = matches.next();\n match syntax {\n Some(syntax) => {\n debug_assert!(matches.next().is_none(), \"Ambiguous syntax definitions\");\n Ok(syntax)\n }\n None => Err(Error::CallableSyntaxError(pos, md.clone())),\n }\n}\n```"}], "func_name": "find_syntax", "docstring": "Locates the syntax definition that can parse the given number of arguments.\n\nPanics if more than one syntax definition applies.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5487535263debc1b9d944b5129a47c79bdd2dcae5d923547c9e82503d4ef12dd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_args\n\nDocumentation:\nParses the arguments to a command or a function and generates expressions to compute them.\n\nReturns the number of arguments that the instructions added to `instrs` will push into the\nstack and returns the list of new symbols that need to be inserted into `symtable`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_args(\n md: &CallableMetadata,\n instrs: &mut Vec,\n symtable: &SymbolsTable,\n pos: LineCol,\n args: Vec,\n) -> Result<(usize, Vec<(SymbolKey, SymbolPrototype)>)> {\n let syntax = find_syntax(md, pos, args.len())?;\n\n let input_nargs = args.len();\n let mut aiter = args.into_iter().rev();\n\n let mut nargs = 0;\n let mut to_insert = vec![];\n\n let mut remaining;\n if let Some(syn) = syntax.repeated.as_ref() {\n let mut min_nargs = syntax.singular.len();\n if syn.require_one {\n min_nargs += 1;\n }\n if input_nargs < min_nargs {\n return Err(Error::CallableSyntaxError(pos, md.clone()));\n }\n\n let need_tags = syn.allow_missing || matches!(syn.type_syn, RepeatedTypeSyntax::AnyValue);\n\n remaining = input_nargs;\n while remaining > syntax.singular.len() {\n let span = aiter.next().expect(\"Args and their syntax must advance in unison\");\n\n let sep_tag_pc = instrs.len();\n\n match span.expr {\n Some(expr) => {\n let pos = expr.start_pos();\n match syn.type_syn {\n RepeatedTypeSyntax::AnyValue => {\n debug_assert!(need_tags);\n let etype = compile_expr(instrs, symtable, expr, false)?;\n instrs\n .push(Instruction::PushInteger(ValueTag::from(etype) as i32, pos));\n nargs += 2;\n }\n\n RepeatedTypeSyntax::VariableRef => {\n let to_insert_one = compile_required_ref(\n instrs,\n md,\n pos,\n symtable,\n false,\n true,\n Some(expr),\n )?;\n if let Some(to_insert_one) = to_insert_one {\n to_insert.push(to_insert_one);\n }\n nargs += 1;\n }\n\n RepeatedTypeSyntax::TypedValue(vtype) => {\n compile_expr_as_type(instrs, symtable, expr, vtype)?;\n if need_tags {\n instrs.push(Instruction::PushInteger(\n ValueTag::from(vtype) as i32,\n pos,\n ));\n nargs += 2;\n } else {\n nargs += 1;\n }\n }\n }\n }\n None => {\n if !syn.allow_missing {\n return Err(Error::CallableSyntaxError(pos, md.clone()));\n }\n instrs.push(Instruction::PushInteger(ValueTag::Missing as i32, span.sep_pos));\n nargs += 1;\n }\n }\n\n nargs += compile_syn_argsep(\n instrs,\n md,\n pos,\n &syn.sep,\n input_nargs == remaining,\n span.sep,\n span.sep_pos,\n sep_tag_pc,\n )?;\n\n remaining -= 1;\n }\n } else {\n remaining = syntax.singular.len();\n }\n\n for syn in syntax.singular.iter().rev() {\n let span = aiter.next().expect(\"Args and their syntax must advance in unison\");\n\n let sep_tag_pc = instrs.len();\n\n let exp_sep = match syn {\n SingularArgSyntax::RequiredValue(details, sep) => {\n match span.expr {\n Some(expr) => {\n compile_expr_as_type(instrs, symtable, expr, details.vtype)?;\n nargs += 1;\n }\n None => return Err(Error::CallableSyntaxError(pos, md.clone())),\n }\n sep\n }\n\n SingularArgSyntax::RequiredRef(details, sep) => {\n let to_insert_one = compile_required_ref(\n instrs,\n md,\n pos,\n symtable,\n details.require_array,\n details.define_undefined,\n span.expr,\n )?;\n if let Some(to_insert_one) = to_insert_one {\n to_insert.push(to_insert_one);\n }\n nargs += 1;\n sep\n }\n\n SingularArgSyntax::OptionalValue(details, sep) => {\n let (tag, pos) = match span.expr {\n Some(expr) => {\n let pos = expr.start_pos();\n compile_expr_as_type(instrs, symtable, expr, details.vtype)?;\n nargs += 1;\n (details.present_value, pos)\n }\n None => (details.missing_value, span.sep_pos),\n };\n instrs.push(Instruction::PushInteger(tag, pos));\n nargs += 1;\n sep\n }\n\n SingularArgSyntax::AnyValue(details, sep) => {\n let (tag, pos) = match span.expr {\n Some(expr) => {\n let pos = expr.start_pos();\n let etype = compile_expr(instrs, symtable, expr, false)?;\n nargs += 2;\n (ValueTag::from(etype), pos)\n }\n None => {\n if !details.allow_missing {\n return Err(Error::CallableSyntaxError(span.sep_pos, md.clone()));\n }\n nargs += 1;\n (ValueTag::Missing, span.sep_pos)\n }\n };\n instrs.push(Instruction::PushInteger(tag as i32, pos));\n sep\n }\n };\n\n nargs += compile_syn_argsep(\n instrs,\n md,\n pos,\n exp_sep,\n input_nargs == remaining,\n span.sep,\n span.sep_pos,\n sep_tag_pc,\n )?;\n\n remaining -= 1;\n }\n\n Ok((nargs, to_insert))\n}\n```"}], "func_name": "compile_args", "docstring": "Parses the arguments to a command or a function and generates expressions to compute them.\n\nReturns the number of arguments that the instructions added to `instrs` will push into the\nstack and returns the list of new symbols that need to be inserted into `symtable`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a6b5457e6055cfe11654a6f3ff18e5c547df68ff881f7922ea359f739e2b9d5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_command_args\n\nDocumentation:\nParses the arguments to a buitin command and generates expressions to compute them.\n\nThis can be used to help the runtime by doing type checking during compilation and then\nallowing the runtime to assume that the values on the stack are correctly typed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn compile_command_args(\n md: &CallableMetadata,\n instrs: &mut Vec,\n symtable: &mut SymbolsTable,\n pos: LineCol,\n args: Vec,\n) -> Result {\n let (nargs, to_insert) = compile_args(md, instrs, symtable, pos, args)?;\n for (key, proto) in to_insert {\n if !symtable.contains_key(&key) {\n symtable.insert(key, proto);\n }\n }\n Ok(nargs)\n}\n```"}], "func_name": "compile_command_args", "docstring": "Parses the arguments to a buitin command and generates expressions to compute them.\n\nThis can be used to help the runtime by doing type checking during compilation and then\nallowing the runtime to assume that the values on the stack are correctly typed.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "85b3bed8613860cecf02b11b3a83a0eafd0df7e16ee06adb7c531b54b4b6d118"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_function_args\n\nDocumentation:\nParses the arguments to a function and generates expressions to compute them.\n\nThis can be used to help the runtime by doing type checking during compilation and then\nallowing the runtime to assume that the values on the stack are correctly typed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn compile_function_args(\n md: &CallableMetadata,\n instrs: &mut Vec,\n symtable: &SymbolsTable,\n pos: LineCol,\n args: Vec,\n) -> Result {\n let (nargs, to_insert) = compile_args(md, instrs, symtable, pos, args)?;\n debug_assert!(to_insert.is_empty());\n Ok(nargs)\n}\n```"}], "func_name": "compile_function_args", "docstring": "Parses the arguments to a function and generates expressions to compute them.\n\nThis can be used to help the runtime by doing type checking during compilation and then\nallowing the runtime to assume that the values on the stack are correctly typed.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "37484f61c0e1e635a8a89b57894c8f4a59d1b98c3f070132f0f9de9bcad3d09f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lc\n\nDocumentation:\nSyntactic sugar to instantiate a `LineCol` for tests.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn lc(line: usize, col: usize) -> LineCol {\n LineCol { line, col }\n }\n```"}], "func_name": "lc", "docstring": "Syntactic sugar to instantiate a `LineCol` for tests.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9462896a8c3ac952c3748c10d456be11a690a265007d81b0c4bb50d75eed86f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: syntax\n\nDocumentation:\nRegisters a syntax definition in the arguments compiler.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn syntax(\n mut self,\n singular: &'static [SingularArgSyntax],\n repeated: Option<&'static RepeatedSyntax>,\n ) -> Self {\n self.syntaxes.push(CallableSyntax::new_static(singular, repeated));\n self\n }\n```"}], "func_name": "syntax", "docstring": "Registers a syntax definition in the arguments compiler.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d0783134d07e682d3ed97cfbac3b929c2c4c5be8502f8946db2d85ffaf0334fd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: symbol\n\nDocumentation:\nRegisters a pre-existing symbol in the symbols table.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn symbol(mut self, key: &str, proto: SymbolPrototype) -> Self {\n self.symtable.insert(SymbolKey::from(key), proto);\n self\n }\n```"}], "func_name": "symbol", "docstring": "Registers a pre-existing symbol in the symbols table.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1eee19c907013161f29086f73521aa5970111c0bd396bc0e0fa9e3b1bb9bf436"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_command\n\nDocumentation:\nFeeds command `args` into the arguments compiler and returns a checker to validate\nexpectations.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn compile_command>>(mut self, args: A) -> Checker {\n let args = args.into();\n let mut instrs = vec![\n // Start with one instruction to validate that the args compiler doesn't touch it.\n Instruction::Nop,\n ];\n let md = CallableMetadataBuilder::new(\"TEST\").with_syntaxes(self.syntaxes).test_build();\n let result =\n compile_command_args(&md, &mut instrs, &mut self.symtable, lc(1000, 2000), args);\n Checker {\n result,\n instrs,\n symtable: self.symtable,\n exp_result: Ok(0),\n exp_instrs: vec![Instruction::Nop],\n exp_vars: HashMap::default(),\n }\n }\n```"}], "func_name": "compile_command", "docstring": "Feeds command `args` into the arguments compiler and returns a checker to validate\nexpectations.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4218ed514c3ab0ff0187493ebb608113b266fb7b09049db27468926bb5c9f0f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exp_nargs\n\nDocumentation:\nExpects the compilation to succeeded and produce `nargs` arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn exp_nargs(mut self, nargs: usize) -> Self {\n self.exp_result = Ok(nargs);\n self\n }\n```"}], "func_name": "exp_nargs", "docstring": "Expects the compilation to succeeded and produce `nargs` arguments.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e2bcb5df82de0d3ea4cd067bb7ba7e8ebf466f33987a3c9e28a9f56055fc9da3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exp_error\n\nDocumentation:\nExpects the compilation to fail with the given `error`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn exp_error(mut self, error: Error) -> Self {\n self.exp_result = Err(error);\n self\n }\n```"}], "func_name": "exp_error", "docstring": "Expects the compilation to fail with the given `error`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b1ad28cfd6ef4a533176d9034071b18af2bdd3a95ba4e223994d90a1f8c1d832"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exp_instr\n\nDocumentation:\nAdds the given instruction to the expected instructions on success.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn exp_instr(mut self, instr: Instruction) -> Self {\n self.exp_instrs.push(instr);\n self\n }\n```"}], "func_name": "exp_instr", "docstring": "Adds the given instruction to the expected instructions on success.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b1d92614b0d31bb84aa075219019eb3267c142dfd3303291d882e8aa4f9097cb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exp_symbol\n\nDocumentation:\nExpects the compilation to define a new variable `key` of type `etype`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn exp_symbol>(mut self, key: K, etype: ExprType) -> Self {\n self.exp_vars.insert(SymbolKey::from(key), etype);\n self\n }\n```"}], "func_name": "exp_symbol", "docstring": "Expects the compilation to define a new variable `key` of type `etype`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e948196bbe993b58ca34f0557bd3f47658722cb65c4e590f3428848409b53ba2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check\n\nDocumentation:\nChecks that the compilation ended with the configured expectations.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn check(self) {\n let is_ok = self.result.is_ok();\n assert_eq!(\n self.exp_result.map_err(|e| format!(\"{}\", e)),\n self.result.map_err(|e| format!(\"{}\", e)),\n );\n\n if !is_ok {\n return;\n }\n\n assert_eq!(self.exp_instrs, self.instrs);\n\n let mut exp_keys = self.symtable.keys();\n for (key, exp_etype) in &self.exp_vars {\n match self.symtable.get(key) {\n Some(SymbolPrototype::Variable(etype)) => {\n assert_eq!(\n exp_etype, etype,\n \"Variable {} was defined with the wrong type\",\n key\n );\n }\n Some(_) => panic!(\"Symbol {} was defined but not as a variable\", key),\n None => panic!(\"Symbol {} was not defined\", key),\n }\n exp_keys.insert(key);\n }\n\n assert_eq!(exp_keys, self.symtable.keys(), \"Unexpected variables defined\");\n }\n```"}], "func_name": "check", "docstring": "Checks that the compilation ended with the configured expectations.", "repo": "endbasic/endbasic", "path": "core/src/compiler/args.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "35122e47c72409c7275b93b4c6c52bf5050a1e2ed495ad7c0232c62a714fabe9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_array_indices\n\nDocumentation:\nCompiles the indices used to address an array.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn compile_array_indices(\n instrs: &mut Vec,\n symtable: &SymbolsTable,\n exp_nargs: usize,\n args: Vec,\n name_pos: LineCol,\n) -> Result<()> {\n if exp_nargs != args.len() {\n return Err(Error::ArrayIndexSubscriptsError(name_pos, args.len(), exp_nargs));\n }\n\n for arg in args.into_iter().rev() {\n let arg_pos = arg.start_pos();\n match compile_expr(instrs, symtable, arg, false)? {\n ExprType::Integer => (),\n ExprType::Double => {\n instrs.push(Instruction::DoubleToInteger);\n }\n itype => {\n return Err(Error::NotANumber(arg_pos, itype));\n }\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "compile_array_indices", "docstring": "Compiles the indices used to address an array.", "repo": "endbasic/endbasic", "path": "core/src/compiler/exprs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/exprs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "661bd779d9047e812002bbb0edbf0b91a13c2318a1cf577dd790baa403ac94f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_not_op\n\nDocumentation:\nCompiles a logical or bitwise unary operator and appends its instructions to `instrs`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_not_op(\n instrs: &mut Vec,\n symtable: &SymbolsTable,\n span: UnaryOpSpan,\n) -> Result {\n let expr_type = compile_expr(instrs, symtable, span.expr, false)?;\n match expr_type {\n ExprType::Boolean => {\n instrs.push(Instruction::LogicalNot(span.pos));\n Ok(ExprType::Boolean)\n }\n ExprType::Integer => {\n instrs.push(Instruction::BitwiseNot(span.pos));\n Ok(ExprType::Integer)\n }\n _ => Err(Error::UnaryOpTypeError(span.pos, \"NOT\", expr_type)),\n }\n}\n```"}], "func_name": "compile_not_op", "docstring": "Compiles a logical or bitwise unary operator and appends its instructions to `instrs`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/exprs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/exprs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "96f0ce62cf74233bd735cde09c1e4fc48dea0746de251b99928ed63deaac8ac3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_neg_op\n\nDocumentation:\nCompiles a negate operator and appends its instructions to `instrs`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_neg_op(\n instrs: &mut Vec,\n symtable: &SymbolsTable,\n span: UnaryOpSpan,\n) -> Result {\n let expr_type = compile_expr(instrs, symtable, span.expr, false)?;\n match expr_type {\n ExprType::Double => {\n instrs.push(Instruction::NegateDouble(span.pos));\n Ok(ExprType::Double)\n }\n ExprType::Integer => {\n instrs.push(Instruction::NegateInteger(span.pos));\n Ok(ExprType::Integer)\n }\n _ => Err(Error::UnaryOpTypeError(span.pos, \"negate\", expr_type)),\n }\n}\n```"}], "func_name": "compile_neg_op", "docstring": "Compiles a negate operator and appends its instructions to `instrs`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/exprs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/exprs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b7b13c516398867ead28493983fe295ac5cc5882b81249b5710f6afe046755d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_logical_binary_op\n\nDocumentation:\nCompiles a logical binary operator and appends its instructions to `instrs`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_logical_binary_op Instruction, F2: Fn(LineCol) -> Instruction>(\n instrs: &mut Vec,\n symtable: &SymbolsTable,\n logical_make_inst: F1,\n bitwise_make_inst: F2,\n span: BinaryOpSpan,\n op_name: &'static str,\n) -> Result {\n let lhs_type = compile_expr(instrs, symtable, span.lhs, false)?;\n let rhs_type = compile_expr(instrs, symtable, span.rhs, false)?;\n match (lhs_type, rhs_type) {\n (ExprType::Boolean, ExprType::Boolean) => {\n instrs.push(logical_make_inst(span.pos));\n Ok(ExprType::Boolean)\n }\n (ExprType::Integer, ExprType::Integer) => {\n instrs.push(bitwise_make_inst(span.pos));\n Ok(ExprType::Integer)\n }\n (_, _) => Err(Error::BinaryOpTypeError(span.pos, op_name, lhs_type, rhs_type)),\n }\n}\n```"}], "func_name": "compile_logical_binary_op", "docstring": "Compiles a logical binary operator and appends its instructions to `instrs`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/exprs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/exprs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e991b751a95ec12aeaad2ff14f5cfbcbf81c715226dad53954a092c670baf20e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_relational_binary_op\n\nDocumentation:\nCompiles a relational binary operator and appends its instructions to `instrs`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_relational_binary_op<\n F1: Fn(LineCol) -> Instruction,\n F2: Fn(LineCol) -> Instruction,\n F3: Fn(LineCol) -> Instruction,\n>(\n instrs: &mut Vec,\n symtable: &SymbolsTable,\n double_make_inst: F1,\n integer_make_inst: F2,\n text_make_inst: F3,\n span: BinaryOpSpan,\n op_name: &'static str,\n) -> Result {\n let lhs_type = compile_expr(instrs, symtable, span.lhs, false)?;\n let pc = instrs.len();\n instrs.push(Instruction::Nop);\n\n let mut keep_nop = false;\n let rhs_type = compile_expr(instrs, symtable, span.rhs, false)?;\n let result = match (lhs_type, rhs_type) {\n // Boolean is explicitly excluded here.\n (ExprType::Double, ExprType::Double) => ExprType::Double,\n (ExprType::Integer, ExprType::Integer) => ExprType::Integer,\n (ExprType::Text, ExprType::Text) => ExprType::Text,\n\n (ExprType::Double, ExprType::Integer) => {\n instrs.push(Instruction::IntegerToDouble);\n ExprType::Double\n }\n\n (ExprType::Integer, ExprType::Double) => {\n instrs[pc] = Instruction::IntegerToDouble;\n keep_nop = true;\n ExprType::Double\n }\n\n (_, _) => {\n return Err(Error::BinaryOpTypeError(span.pos, op_name, lhs_type, rhs_type));\n }\n };\n\n if !keep_nop {\n let nop = instrs.remove(pc);\n debug_assert_eq!(std::mem::discriminant(&Instruction::Nop), std::mem::discriminant(&nop));\n }\n\n match result {\n ExprType::Boolean => unreachable!(\"Filtered out above\"),\n ExprType::Double => instrs.push(double_make_inst(span.pos)),\n ExprType::Integer => instrs.push(integer_make_inst(span.pos)),\n ExprType::Text => instrs.push(text_make_inst(span.pos)),\n };\n\n Ok(ExprType::Boolean)\n}\n```"}], "func_name": "compile_relational_binary_op", "docstring": "Compiles a relational binary operator and appends its instructions to `instrs`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/exprs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/exprs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "427586296acf752ca774de4997db67f5116be6dafad140d3a32a8e3d0191eccd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_shift_binary_op\n\nDocumentation:\nCompiles a binary shift operator and appends its instructions to `instrs`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_shift_binary_op Instruction>(\n instrs: &mut Vec,\n symtable: &SymbolsTable,\n make_inst: F,\n span: BinaryOpSpan,\n op_name: &'static str,\n) -> Result {\n let lhs_type = compile_expr(instrs, symtable, span.lhs, false)?;\n match lhs_type {\n ExprType::Integer => (),\n _ => {\n return Err(Error::UnaryOpTypeError(span.pos, op_name, lhs_type));\n }\n };\n\n let rhs_type = compile_expr(instrs, symtable, span.rhs, false)?;\n match rhs_type {\n ExprType::Integer => (),\n _ => {\n return Err(Error::TypeMismatch(span.pos, rhs_type, ExprType::Integer));\n }\n };\n\n instrs.push(make_inst(span.pos));\n\n Ok(ExprType::Integer)\n}\n```"}], "func_name": "compile_shift_binary_op", "docstring": "Compiles a binary shift operator and appends its instructions to `instrs`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/exprs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/exprs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3853b1a3f8b361c0929bd18745cf60113338a32829598205b46407c4df51f23c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_arithmetic_binary_op\n\nDocumentation:\nCompiles the evaluation of an expression, appends its instructions to the\nCompiles a binary operator and appends its instructions to `instrs`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_arithmetic_binary_op Instruction, F2: Fn(LineCol) -> Instruction>(\n instrs: &mut Vec,\n symtable: &SymbolsTable,\n double_make_inst: F1,\n integer_make_inst: F2,\n span: BinaryOpSpan,\n op_name: &'static str,\n) -> Result {\n let lhs_type = compile_expr(instrs, symtable, span.lhs, false)?;\n let pc = instrs.len();\n instrs.push(Instruction::Nop);\n\n let mut keep_nop = false;\n let rhs_type = compile_expr(instrs, symtable, span.rhs, false)?;\n let result = match (lhs_type, rhs_type) {\n (ExprType::Double, ExprType::Double) => ExprType::Double,\n (ExprType::Integer, ExprType::Integer) => ExprType::Integer,\n (ExprType::Text, ExprType::Text) if op_name == \"+\" => ExprType::Text,\n\n (ExprType::Double, ExprType::Integer) => {\n instrs.push(Instruction::IntegerToDouble);\n ExprType::Double\n }\n\n (ExprType::Integer, ExprType::Double) => {\n instrs[pc] = Instruction::IntegerToDouble;\n keep_nop = true;\n ExprType::Double\n }\n\n (_, _) => {\n return Err(Error::BinaryOpTypeError(span.pos, op_name, lhs_type, rhs_type));\n }\n };\n\n if !keep_nop {\n let nop = instrs.remove(pc);\n debug_assert_eq!(std::mem::discriminant(&Instruction::Nop), std::mem::discriminant(&nop));\n }\n\n match result {\n ExprType::Boolean => unreachable!(\"Filtered out above\"),\n ExprType::Double => instrs.push(double_make_inst(span.pos)),\n ExprType::Integer => instrs.push(integer_make_inst(span.pos)),\n ExprType::Text => {\n debug_assert_eq!(\"+\", op_name, \"Filtered out above\");\n instrs.push(Instruction::ConcatStrings(span.pos))\n }\n };\n\n Ok(result)\n}\n```"}], "func_name": "compile_arithmetic_binary_op", "docstring": "Compiles the evaluation of an expression, appends its instructions to the\nCompiles a binary operator and appends its instructions to `instrs`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/exprs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/exprs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "46ace6586cd411f96237938de090dfce9bdef686951598041df2c9801d5b1e45"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_expr_symbol\n\nDocumentation:\nCompiles the load of a symbol in the context of an expression.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_expr_symbol(\n instrs: &mut Vec,\n symtable: &SymbolsTable,\n span: SymbolSpan,\n allow_varrefs: bool,\n) -> Result {\n let key = SymbolKey::from(span.vref.name());\n let (instr, vtype) = match symtable.get(&key) {\n None => return Err(Error::UndefinedSymbol(span.pos, key)),\n\n Some(SymbolPrototype::Array(atype, _dims)) => {\n if allow_varrefs {\n (Instruction::LoadRef(key, *atype, span.pos), *atype)\n } else {\n return Err(Error::NotAVariable(span.pos, span.vref));\n }\n }\n\n Some(SymbolPrototype::Variable(vtype)) => {\n if allow_varrefs {\n (Instruction::LoadRef(key, *vtype, span.pos), *vtype)\n } else {\n let instr = match vtype {\n ExprType::Boolean => Instruction::LoadBoolean,\n ExprType::Double => Instruction::LoadDouble,\n ExprType::Integer => Instruction::LoadInteger,\n ExprType::Text => Instruction::LoadString,\n };\n (instr(key, span.pos), *vtype)\n }\n }\n\n Some(SymbolPrototype::Callable(md)) => {\n let etype = match md.return_type() {\n Some(etype) => etype,\n None => {\n return Err(Error::NotArrayOrFunction(span.pos, key));\n }\n };\n\n if !md.is_argless() {\n return Err(Error::CallableSyntaxError(span.pos, md.clone()));\n }\n\n let nargs = compile_function_args(md, instrs, symtable, span.pos, vec![])?;\n debug_assert_eq!(0, nargs, \"Argless compiler must have returned zero arguments\");\n (Instruction::FunctionCall(key, etype, span.pos, 0), etype)\n }\n };\n if !span.vref.accepts(vtype) {\n return Err(Error::IncompatibleTypeAnnotationInReference(span.pos, span.vref));\n }\n instrs.push(instr);\n Ok(vtype)\n}\n```"}], "func_name": "compile_expr_symbol", "docstring": "Compiles the load of a symbol in the context of an expression.", "repo": "endbasic/endbasic", "path": "core/src/compiler/exprs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/exprs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c50e60eeb7c235bd2b84b844dc62da8c5b37477986bc40c9df2e8a7bd2df9b8e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_expr_symbol_ref\n\nDocumentation:\nCompiles the load of a symbol in the context of a command argument.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_expr_symbol_ref(\n instrs: &mut Vec,\n symtable: &mut SymbolsTable,\n span: SymbolSpan,\n) -> Result {\n let key = SymbolKey::from(span.vref.name());\n match symtable.get(&key) {\n None => {\n let vtype = span.vref.ref_type().unwrap_or(ExprType::Integer);\n\n if !span.vref.accepts(vtype) {\n return Err(Error::IncompatibleTypeAnnotationInReference(span.pos, span.vref));\n }\n\n symtable.insert(key.clone(), SymbolPrototype::Variable(vtype));\n instrs.push(Instruction::LoadRef(key, vtype, span.pos));\n Ok(vtype)\n }\n\n Some(SymbolPrototype::Array(vtype, _)) | Some(SymbolPrototype::Variable(vtype)) => {\n let vtype = *vtype;\n\n if !span.vref.accepts(vtype) {\n return Err(Error::IncompatibleTypeAnnotationInReference(span.pos, span.vref));\n }\n\n instrs.push(Instruction::LoadRef(key, vtype, span.pos));\n Ok(vtype)\n }\n\n Some(SymbolPrototype::Callable(md)) => {\n if !span.vref.accepts_callable(md.return_type()) {\n return Err(Error::IncompatibleTypeAnnotationInReference(span.pos, span.vref));\n }\n\n Err(Error::NotArrayOrFunction(span.pos, key))\n }\n }\n}\n```"}], "func_name": "compile_expr_symbol_ref", "docstring": "Compiles the load of a symbol in the context of a command argument.", "repo": "endbasic/endbasic", "path": "core/src/compiler/exprs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/exprs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5d0399bac76aea22f9a7d1c0639876455d28fe2ce1928b3f059ce6c7cc515e0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_expr\n\nDocumentation:\nCompiles the evaluation of an expression, appends its instructions to `instrs`, and returns\nthe type of the compiled expression.\n\n`allow_varrefs` should be true for top-level expression compilations within function arguments.\nIn that specific case, we must leave bare variable and array references unevaluated because we\ndon't know if the function wants to take the reference or the value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn compile_expr(\n instrs: &mut Vec,\n symtable: &SymbolsTable,\n expr: Expr,\n allow_varrefs: bool,\n) -> Result {\n match expr {\n Expr::Boolean(span) => {\n instrs.push(Instruction::PushBoolean(span.value, span.pos));\n Ok(ExprType::Boolean)\n }\n\n Expr::Double(span) => {\n instrs.push(Instruction::PushDouble(span.value, span.pos));\n Ok(ExprType::Double)\n }\n\n Expr::Integer(span) => {\n instrs.push(Instruction::PushInteger(span.value, span.pos));\n Ok(ExprType::Integer)\n }\n\n Expr::Text(span) => {\n instrs.push(Instruction::PushString(span.value, span.pos));\n Ok(ExprType::Text)\n }\n\n Expr::Symbol(span) => compile_expr_symbol(instrs, symtable, span, allow_varrefs),\n\n Expr::And(span) => compile_logical_binary_op(\n instrs,\n symtable,\n Instruction::LogicalAnd,\n Instruction::BitwiseAnd,\n *span,\n \"AND\",\n ),\n\n Expr::Or(span) => compile_logical_binary_op(\n instrs,\n symtable,\n Instruction::LogicalOr,\n Instruction::BitwiseOr,\n *span,\n \"OR\",\n ),\n\n Expr::Xor(span) => compile_logical_binary_op(\n instrs,\n symtable,\n Instruction::LogicalXor,\n Instruction::BitwiseXor,\n *span,\n \"XOR\",\n ),\n\n Expr::Not(span) => compile_not_op(instrs, symtable, *span),\n\n Expr::ShiftLeft(span) => {\n let result =\n compile_shift_binary_op(instrs, symtable, Instruction::ShiftLeft, *span, \"<<\")?;\n debug_assert_eq!(ExprType::Integer, result);\n Ok(result)\n }\n\n Expr::ShiftRight(span) => {\n let result =\n compile_shift_binary_op(instrs, symtable, Instruction::ShiftRight, *span, \">>\")?;\n debug_assert_eq!(ExprType::Integer, result);\n Ok(result)\n }\n\n Expr::Equal(span) => {\n let result = compile_equality_binary_op(\n instrs,\n symtable,\n Instruction::EqualBooleans,\n Instruction::EqualDoubles,\n Instruction::EqualIntegers,\n Instruction::EqualStrings,\n *span,\n \"=\",\n )?;\n debug_assert_eq!(ExprType::Boolean, result);\n Ok(result)\n }\n\n Expr::NotEqual(span) => {\n let result = compile_equality_binary_op(\n instrs,\n symtable,\n Instruction::NotEqualBooleans,\n Instruction::NotEqualDoubles,\n Instruction::NotEqualIntegers,\n Instruction::NotEqualStrings,\n *span,\n \"<>\",\n )?;\n debug_assert_eq!(ExprType::Boolean, result);\n Ok(result)\n }\n\n Expr::Less(span) => {\n let result = compile_relational_binary_op(\n instrs,\n symtable,\n Instruction::LessDoubles,\n Instruction::LessIntegers,\n Instruction::LessStrings,\n *span,\n \"<\",\n )?;\n debug_assert_eq!(ExprType::Boolean, result);\n Ok(result)\n }\n\n Expr::LessEqual(span) => {\n let result = compile_relational_binary_op(\n instrs,\n symtable,\n Instruction::LessEqualDoubles,\n Instruction::LessEqualIntegers,\n Instruction::LessEqualStrings,\n *span,\n \"<=\",\n )?;\n debug_assert_eq!(ExprType::Boolean, result);\n Ok(result)\n }\n\n Expr::Greater(span) => {\n let result = compile_relational_binary_op(\n instrs,\n symtable,\n Instruction::GreaterDoubles,\n Instruction::GreaterIntegers,\n Instruction::GreaterStrings,\n *span,\n \">\",\n )?;\n debug_assert_eq!(ExprType::Boolean, result);\n Ok(result)\n }\n\n Expr::GreaterEqual(span) => {\n let result = compile_relational_binary_op(\n instrs,\n symtable,\n Instruction::GreaterEqualDoubles,\n Instruction::GreaterEqualIntegers,\n Instruction::GreaterEqualStrings,\n *span,\n \">=\",\n )?;\n debug_assert_eq!(ExprType::Boolean, result);\n Ok(result)\n }\n\n Expr::Add(span) => Ok(compile_arithmetic_binary_op(\n instrs,\n symtable,\n Instruction::AddDoubles,\n Instruction::AddIntegers,\n *span,\n \"+\",\n )?),\n\n Expr::Subtract(span) => Ok(compile_arithmetic_binary_op(\n instrs,\n symtable,\n Instruction::SubtractDoubles,\n Instruction::SubtractIntegers,\n *span,\n \"-\",\n )?),\n\n Expr::Multiply(span) => Ok(compile_arithmetic_binary_op(\n instrs,\n symtable,\n Instruction::MultiplyDoubles,\n Instruction::MultiplyIntegers,\n *span,\n \"*\",\n )?),\n\n Expr::Divide(span) => Ok(compile_arithmetic_binary_op(\n instrs,\n symtable,\n Instruction::DivideDoubles,\n Instruction::DivideIntegers,\n *span,\n \"/\",\n )?),\n\n Expr::Modulo(span) => Ok(compile_arithmetic_binary_op(\n instrs,\n symtable,\n Instruction::ModuloDoubles,\n Instruction::ModuloIntegers,\n *span,\n \"MOD\",\n )?),\n\n Expr::Power(span) => Ok(compile_arithmetic_binary_op(\n instrs,\n symtable,\n Instruction::PowerDoubles,\n Instruction::PowerIntegers,\n *span,\n \"^\",\n )?),\n\n Expr::Negate(span) => Ok(compile_neg_op(instrs, symtable, *span)?),\n\n Expr::Call(span) => {\n let key = SymbolKey::from(span.vref.name());\n match symtable.get(&key) {\n Some(SymbolPrototype::Array(vtype, dims)) => {\n compile_array_ref(instrs, symtable, span, key, *vtype, *dims)\n }\n\n Some(SymbolPrototype::Callable(md)) => {\n if !span.vref.accepts_callable(md.return_type()) {\n return Err(Error::IncompatibleTypeAnnotationInReference(\n span.vref_pos,\n span.vref,\n ));\n }\n\n let vtype = match md.return_type() {\n Some(vtype) => vtype,\n None => {\n return Err(Error::NotArrayOrFunction(span.vref_pos, key));\n }\n };\n\n if md.is_argless() {\n return Err(Error::CallableSyntaxError(span.vref_pos, md.clone()));\n }\n\n let span_pos = span.vref_pos;\n let nargs = compile_function_args(md, instrs, symtable, span_pos, span.args)?;\n instrs.push(Instruction::FunctionCall(key, vtype, span_pos, nargs));\n Ok(vtype)\n }\n\n Some(SymbolPrototype::Variable(_)) => {\n Err(Error::NotArrayOrFunction(span.vref_pos, key))\n }\n\n None => Err(Error::UndefinedSymbol(span.vref_pos, key)),\n }\n }\n }\n}\n```"}], "func_name": "compile_expr", "docstring": "Compiles the evaluation of an expression, appends its instructions to `instrs`, and returns\nthe type of the compiled expression.\n\n`allow_varrefs` should be true for top-level expression compilations within function arguments.\nIn that specific case, we must leave bare variable and array references unevaluated because we\ndon't know if the function wants to take the reference or the value.", "repo": "endbasic/endbasic", "path": "core/src/compiler/exprs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/exprs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ad5de895e494a4d2369ef366766b532ad3e682011beb6c7bfc9e1b1a00c4e54"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_expr_in_command\n\nDocumentation:\nCompiles the evaluation of an expression, appends its instructions to `instrs`, and returns\nthe type of the compiled expression.\n\nThis function should be used only when compiling the arguments to a builtin command, because\nin that context, we need mutable access to the `symtable`in order to define output variables\n(if any).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn compile_expr_in_command(\n instrs: &mut Vec,\n symtable: &mut SymbolsTable,\n expr: Expr,\n) -> Result {\n match expr {\n Expr::Symbol(span) => compile_expr_symbol_ref(instrs, symtable, span),\n expr => compile_expr(instrs, symtable, expr, false),\n }\n}\n```"}], "func_name": "compile_expr_in_command", "docstring": "Compiles the evaluation of an expression, appends its instructions to `instrs`, and returns\nthe type of the compiled expression.\n\nThis function should be used only when compiling the arguments to a builtin command, because\nin that context, we need mutable access to the `symtable`in order to define output variables\n(if any).", "repo": "endbasic/endbasic", "path": "core/src/compiler/exprs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/exprs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f93c7320101fabe154f1a9afb76373c663a9fda616a491e3aefc2cd84a81e7df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_expr_as_type\n\nDocumentation:\nCompiles a single expression, expecting it to be of a `target` type. Applies casts if\npossible.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn compile_expr_as_type(\n instrs: &mut Vec,\n symtable: &SymbolsTable,\n expr: Expr,\n target: ExprType,\n) -> Result<()> {\n let epos = expr.start_pos();\n let etype = compile_expr(instrs, symtable, expr, false)?;\n if etype == ExprType::Double && target.is_numerical() {\n if target == ExprType::Integer {\n instrs.push(Instruction::DoubleToInteger);\n }\n Ok(())\n } else if etype == ExprType::Integer && target.is_numerical() {\n if target == ExprType::Double {\n instrs.push(Instruction::IntegerToDouble);\n }\n Ok(())\n } else if etype == target {\n Ok(())\n } else {\n if target.is_numerical() {\n Err(Error::NotANumber(epos, etype))\n } else {\n Err(Error::TypeMismatch(epos, etype, target))\n }\n }\n}\n```"}], "func_name": "compile_expr_as_type", "docstring": "Compiles a single expression, expecting it to be of a `target` type. Applies casts if\npossible.", "repo": "endbasic/endbasic", "path": "core/src/compiler/exprs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/exprs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "064f6d7d375ac2160c85bb51a7b53d192d7655f0076de76f13478401c4575155"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_op_test\n\nDocumentation:\nTests the behavior of one binary operator.\n\n`op_inst` is the instruction to expect for the operator and `op_name` is the literal name\nof the operator as it appears in EndBASIC code.\n\n`load_inst` and `push_inst` are generators to construct the necessary load and push\noperations for the given type.\n\n`test_value` is a value of the right type to use with the operator call, `test_value_str`\nis the same value as represented in EndBASIC code, and `test_value_type` is the\ncorresponding type definition.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_op_test<\n L: Fn(SymbolKey, LineCol) -> Instruction,\n M: Fn(LineCol) -> Instruction,\n P: Fn(V, LineCol) -> Instruction,\n V,\n >(\n load_inst: L,\n op_inst: M,\n op_name: &str,\n push_inst: P,\n test_value: V,\n test_value_str: &str,\n test_value_type: ExprType,\n ) {\n Tester::default()\n .define(\"a\", SymbolPrototype::Variable(test_value_type))\n .parse(&format!(\"b = a {} {}\", op_name, test_value_str))\n .compile()\n .expect_instr(0, load_inst(SymbolKey::from(\"a\"), lc(1, 5)))\n .expect_instr(1, push_inst(test_value, lc(1, 8 + op_name.len())))\n .expect_instr(2, op_inst(lc(1, 7)))\n .expect_instr(3, Instruction::Assign(SymbolKey::from(\"b\")))\n .check();\n }\n```"}], "func_name": "do_op_test", "docstring": "Tests the behavior of one binary operator.\n\n`op_inst` is the instruction to expect for the operator and `op_name` is the literal name\nof the operator as it appears in EndBASIC code.\n\n`load_inst` and `push_inst` are generators to construct the necessary load and push\noperations for the given type.\n\n`test_value` is a value of the right type to use with the operator call, `test_value_str`\nis the same value as represented in EndBASIC code, and `test_value_type` is the\ncorresponding type definition.", "repo": "endbasic/endbasic", "path": "core/src/compiler/exprs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/exprs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c196a2be3dee2fe8690a58d56bc8d2ab8ab43370f68b19226b7f347cff7ce888"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: contains_key\n\nDocumentation:\nReturns true if the symbols table contains `key`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn contains_key(&mut self, key: &SymbolKey) -> bool {\n self.scopes.last().unwrap().contains_key(key) || self.globals.contains_key(key)\n }\n```"}], "func_name": "contains_key", "docstring": "Returns true if the symbols table contains `key`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "22dc210f1d96976f47531f83f77c7f6c0632169dbe3248c34b9b395331dd8138"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturns the information for the symbol `key` if it exists, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get(&self, key: &SymbolKey) -> Option<&SymbolPrototype> {\n let proto = self.scopes.last().unwrap().get(key);\n if proto.is_some() {\n return proto;\n }\n\n self.globals.get(key)\n }\n```"}], "func_name": "get", "docstring": "Returns the information for the symbol `key` if it exists, otherwise `None`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7a5739b6ad0ec175c83c2a02c76fb7e889fbead0c654e0ad050e726d6bbc3a22"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nInserts the new information `proto` about symbol `key` into the symbols table.\nThe symbol must not yet exist.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn insert(&mut self, key: SymbolKey, proto: SymbolPrototype) {\n debug_assert!(!self.globals.contains_key(&key), \"Cannot redefine a symbol\");\n let previous = self.scopes.last_mut().unwrap().insert(key, proto);\n debug_assert!(previous.is_none(), \"Cannot redefine a symbol\");\n }\n```"}], "func_name": "insert", "docstring": "Inserts the new information `proto` about symbol `key` into the symbols table.\nThe symbol must not yet exist.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d7fac42992f7aa936087728e80494f107bee91e8046d7288d8f32cc6040d1256"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove\n\nDocumentation:\nRemoves information about the symbol `key`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn remove(&mut self, key: SymbolKey) {\n let previous = self.scopes.last_mut().unwrap().remove(&key);\n debug_assert!(previous.is_some(), \"Cannot unset a non-existing symbol\");\n }\n```"}], "func_name": "remove", "docstring": "Removes information about the symbol `key`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dbbbbd9a5b3856da8c333ce770f271fe23873ca669d0586b655e3e8631e96fb1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_exit_do\n\nDocumentation:\nConstructs a `Fixup` for an `EXIT DO` instruction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_exit_do(target: String, span: ExitDoSpan) -> Self {\n Self { target, target_pos: span.pos, ftype: FixupType::Goto }\n }\n```"}], "func_name": "from_exit_do", "docstring": "Constructs a `Fixup` for an `EXIT DO` instruction.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80d2585b2109131baf54f14f96d84f2df4b94013bc82d84f734e82ec2993a6ca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_on_error\n\nDocumentation:\nConstructs a `Fixup` for a `ON ERROR GOTO` instruction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_on_error(span: GotoSpan) -> Self {\n Self { target: span.target, target_pos: span.target_pos, ftype: FixupType::OnError }\n }\n```"}], "func_name": "from_on_error", "docstring": "Constructs a `Fixup` for a `ON ERROR GOTO` instruction.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82322655a39eb00b4b5e8d0714763a541680271ef63e0e10884f864c1ab329d9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: emit\n\nDocumentation:\nAppends an instruction to the bytecode and returns its address.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn emit(&mut self, instr: Instruction) -> Address {\n let pc = self.next_pc;\n self.instrs.push(instr);\n self.next_pc += 1;\n pc\n }\n```"}], "func_name": "emit", "docstring": "Appends an instruction to the bytecode and returns its address.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e2560bc47661eb741e6426e3e5d175e8da5ec9123c7a6319b0686ecb1a5b669f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_label\n\nDocumentation:\nGenerates a fake label for the end of a `DO` loop based on the current nesting `level`.\n\nThis is a little hack to reuse the same machinery that handles `GOTO`s to handle early exits\nin `DO` loops. We can do this because we know that users cannot specify custom labels that\nstart with a digit and all user-provided labels that do start with a digit are also fully\nnumeric.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_label(level: (usize, usize)) -> String {\n format!(\"0do{}_{}\", level.0, level.1)\n }\n```"}], "func_name": "do_label", "docstring": "Generates a fake label for the end of a `DO` loop based on the current nesting `level`.\n\nThis is a little hack to reuse the same machinery that handles `GOTO`s to handle early exits\nin `DO` loops. We can do this because we know that users cannot specify custom labels that\nstart with a digit and all user-provided labels that do start with a digit are also fully\nnumeric.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ed88a1c387ccaabba7101f817e88aca6fb19d4d7f7ac8641cdc984c2ec756ad7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: return_key\n\nDocumentation:\nGenerates the name of the symbol that holds the return value of the function `name`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn return_key(name: &SymbolKey) -> SymbolKey {\n SymbolKey::from(format!(\"0return_{}\", name))\n }\n```"}], "func_name": "return_key", "docstring": "Generates the name of the symbol that holds the return value of the function `name`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c999b8f5b2876a7907099a62db072477c822a01568428ae7617ef67eef7a6fc1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: select_test_var_name\n\nDocumentation:\nGenerates an internal variable name to hold the result of a `SELECT` test evaluation.\n\nThis is a little hack needed because we don't yet have a value stack nor registers. We can\ndo this because we know that users cannot specify custom variable names that start with a\ndigit.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn select_test_var_name(selects: usize) -> String {\n format!(\"0select{}\", selects)\n }\n```"}], "func_name": "select_test_var_name", "docstring": "Generates an internal variable name to hold the result of a `SELECT` test evaluation.\n\nThis is a little hack needed because we don't yet have a value stack nor registers. We can\ndo this because we know that users cannot specify custom variable names that start with a\ndigit.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "897664774d6d8b148dd688e050c31705736f319273ea59fc323959771c915701"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_array_assignment\n\nDocumentation:\nCompiles an assignment to an array position.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_array_assignment(&mut self, span: ArrayAssignmentSpan) -> Result<()> {\n let key = SymbolKey::from(span.vref.name());\n let (atype, dims) = match self.symtable.get(&key) {\n Some(SymbolPrototype::Array(atype, dims)) => (*atype, *dims),\n Some(_) => {\n return Err(Error::IndexNonArray(span.vref_pos, span.vref.take_name()));\n }\n None => {\n return Err(Error::UndefinedSymbol(span.vref_pos, key));\n }\n };\n\n if !span.vref.accepts(atype) {\n return Err(Error::IncompatibleTypeAnnotationInReference(span.vref_pos, span.vref));\n }\n\n let etype = self.compile_expr(span.expr, false)?;\n let etype = self.maybe_cast(atype, etype);\n if etype != atype {\n return Err(Error::IncompatibleTypesInAssignment(span.vref_pos, etype, atype));\n }\n\n let nargs = span.subscripts.len();\n self.compile_array_indices(dims, span.subscripts, span.vref_pos)?;\n\n self.emit(Instruction::ArrayAssignment(key, span.vref_pos, nargs));\n\n Ok(())\n }\n```"}], "func_name": "compile_array_assignment", "docstring": "Compiles an assignment to an array position.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d232bc1da0dad1b32deba28046e682c85c103f6efa0596588471fe22d4074c51"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_do\n\nDocumentation:\nCompiles a `DO` loop and appends its instructions to the compilation context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_do(&mut self, span: DoSpan) -> Result<()> {\n self.exit_do_level.1 += 1;\n\n let end_pc;\n match span.guard {\n DoGuard::Infinite => {\n let start_pc = self.next_pc;\n self.compile_many(span.body)?;\n end_pc = self.emit(Instruction::Jump(JumpISpan { addr: start_pc }));\n }\n\n DoGuard::PreUntil(guard) => {\n let start_pc = self.next_pc;\n self.compile_expr_guard(guard, \"DO\")?;\n let jump_pc = self.emit(Instruction::Nop);\n self.compile_many(span.body)?;\n end_pc = self.emit(Instruction::Jump(JumpISpan { addr: start_pc }));\n self.instrs[jump_pc] = Instruction::JumpIfTrue(self.next_pc);\n }\n\n DoGuard::PreWhile(guard) => {\n let start_pc = self.next_pc;\n self.compile_expr_guard(guard, \"DO\")?;\n let jump_pc = self.emit(Instruction::Nop);\n self.compile_many(span.body)?;\n end_pc = self.emit(Instruction::Jump(JumpISpan { addr: start_pc }));\n self.instrs[jump_pc] = Instruction::JumpIfNotTrue(self.next_pc);\n }\n\n DoGuard::PostUntil(guard) => {\n let start_pc = self.next_pc;\n self.compile_many(span.body)?;\n self.compile_expr_guard(guard, \"LOOP\")?;\n end_pc = self.emit(Instruction::JumpIfNotTrue(start_pc));\n }\n\n DoGuard::PostWhile(guard) => {\n let start_pc = self.next_pc;\n self.compile_many(span.body)?;\n self.compile_expr_guard(guard, \"LOOP\")?;\n end_pc = self.emit(Instruction::JumpIfTrue(start_pc));\n }\n }\n\n let existing = self.labels.insert(Compiler::do_label(self.exit_do_level), end_pc + 1);\n assert!(existing.is_none(), \"Auto-generated label must be unique\");\n self.exit_do_level.1 -= 1;\n if self.exit_do_level.1 == 0 {\n self.exit_do_level.0 += 1;\n }\n\n Ok(())\n }\n```"}], "func_name": "compile_do", "docstring": "Compiles a `DO` loop and appends its instructions to the compilation context.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7cbe7dfceff99cd8a3fc7c0ddbcaf6c7796df5dd25bd70149b5fc7c6b3bc18e0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_for\n\nDocumentation:\nCompiles a `FOR` loop and appends its instructions to the compilation context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_for(&mut self, span: ForSpan) -> Result<()> {\n debug_assert!(\n span.iter.ref_type().is_none()\n || span.iter.ref_type().unwrap() == ExprType::Double\n || span.iter.ref_type().unwrap() == ExprType::Integer\n );\n\n if span.iter_double && span.iter.ref_type().is_none() {\n let key = SymbolKey::from(span.iter.name());\n let skip_pc = self.emit(Instruction::Nop);\n\n let iter_key = SymbolKey::from(span.iter.name());\n if self.symtable.get(&key).is_none() {\n self.emit(Instruction::Dim(DimISpan {\n name: key,\n shared: false,\n vtype: ExprType::Double,\n }));\n self.symtable.insert(iter_key.clone(), SymbolPrototype::Variable(ExprType::Double));\n }\n\n self.instrs[skip_pc] = Instruction::JumpIfDefined(JumpIfDefinedISpan {\n var: iter_key,\n addr: self.next_pc,\n });\n }\n\n self.compile_assignment(span.iter.clone(), span.iter_pos, span.start)?;\n\n let start_pc = self.next_pc;\n let end_etype = self.compile_expr(span.end, false)?;\n match end_etype {\n ExprType::Boolean => (),\n _ => panic!(\"Synthesized end condition for FOR must yield a boolean\"),\n };\n let jump_pc = self.emit(Instruction::Nop);\n\n self.compile_many(span.body)?;\n\n self.compile_assignment(span.iter.clone(), span.iter_pos, span.next)?;\n\n self.emit(Instruction::Jump(JumpISpan { addr: start_pc }));\n\n self.instrs[jump_pc] = Instruction::JumpIfNotTrue(self.next_pc);\n\n Ok(())\n }\n```"}], "func_name": "compile_for", "docstring": "Compiles a `FOR` loop and appends its instructions to the compilation context.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "13732ac5701bb2264474c3c134011118d1b0726e5e8d74c92d50ad41db0a50cb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_if\n\nDocumentation:\nCompiles an `IF` statement and appends its instructions to the compilation context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_if(&mut self, span: IfSpan) -> Result<()> {\n let mut end_pcs = vec![];\n\n let mut iter = span.branches.into_iter();\n let mut next = iter.next();\n while let Some(branch) = next {\n let next2 = iter.next();\n\n self.compile_expr_guard(branch.guard, \"IF/ELSEIF\")?;\n let jump_pc = self.emit(Instruction::Nop);\n self.compile_many(branch.body)?;\n\n if next2.is_some() {\n end_pcs.push(self.next_pc);\n self.emit(Instruction::Nop);\n }\n\n self.instrs[jump_pc] = Instruction::JumpIfNotTrue(self.next_pc);\n\n next = next2;\n }\n\n for end_pc in end_pcs {\n self.instrs[end_pc] = Instruction::Jump(JumpISpan { addr: self.next_pc });\n }\n\n Ok(())\n }\n```"}], "func_name": "compile_if", "docstring": "Compiles an `IF` statement and appends its instructions to the compilation context.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c7b6c057335765396d24403edcd853f6e0aea5e9d00d13b2db982fa5b3bf4e49"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_on_error\n\nDocumentation:\nCompiles an `ON ERROR` statement and appends its instructions to the compilation context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_on_error(&mut self, span: OnErrorSpan) {\n match span {\n OnErrorSpan::Goto(span) => {\n let goto_pc = self.emit(Instruction::Nop);\n self.fixups.insert(goto_pc, Fixup::from_on_error(span));\n }\n OnErrorSpan::Reset => {\n self.emit(Instruction::SetErrorHandler(ErrorHandlerISpan::None));\n }\n OnErrorSpan::ResumeNext => {\n self.emit(Instruction::SetErrorHandler(ErrorHandlerISpan::ResumeNext));\n }\n }\n }\n```"}], "func_name": "compile_on_error", "docstring": "Compiles an `ON ERROR` statement and appends its instructions to the compilation context.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c7f3b7a48d52279814b6ce22a05a39c610daec758979b39a0393f56eebb34e11"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_case_guards\n\nDocumentation:\nGenerates the expression to evaluate a list of `guards`, which are compared against the\ntest expression stored in `test_vref`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_case_guards(test_vref: &VarRef, guards: Vec) -> Option {\n let mut expr = None;\n for guard in guards {\n let one_expr = match guard {\n CaseGuardSpan::Is(relop, expr) => {\n let pos = expr.start_pos();\n let test_expr = Expr::Symbol(SymbolSpan { vref: test_vref.clone(), pos });\n let binop = Box::from(BinaryOpSpan { lhs: test_expr, rhs: expr, pos });\n match relop {\n CaseRelOp::Equal => Expr::Equal(binop),\n CaseRelOp::NotEqual => Expr::NotEqual(binop),\n CaseRelOp::Less => Expr::Less(binop),\n CaseRelOp::LessEqual => Expr::LessEqual(binop),\n CaseRelOp::Greater => Expr::Greater(binop),\n CaseRelOp::GreaterEqual => Expr::GreaterEqual(binop),\n }\n }\n\n CaseGuardSpan::To(from_expr, to_expr) => {\n let from_pos = from_expr.start_pos();\n let to_pos = to_expr.start_pos();\n let test_expr =\n Expr::Symbol(SymbolSpan { vref: test_vref.clone(), pos: from_pos });\n Expr::And(Box::from(BinaryOpSpan {\n lhs: Expr::GreaterEqual(Box::from(BinaryOpSpan {\n lhs: test_expr.clone(),\n rhs: from_expr,\n pos: from_pos,\n })),\n rhs: Expr::LessEqual(Box::from(BinaryOpSpan {\n lhs: test_expr,\n rhs: to_expr,\n pos: to_pos,\n })),\n pos: from_pos,\n }))\n }\n };\n\n expr = match expr {\n None => Some(one_expr),\n Some(expr) => {\n let pos = expr.start_pos();\n Some(Expr::Or(Box::from(BinaryOpSpan { lhs: expr, rhs: one_expr, pos })))\n }\n };\n }\n expr\n }\n```"}], "func_name": "compile_case_guards", "docstring": "Generates the expression to evaluate a list of `guards`, which are compared against the\ntest expression stored in `test_vref`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e8c6ab3c0f62a3194e002eb1b6d42a8b12bc41dc1e9258ac016f54e0cf933b93"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_select\n\nDocumentation:\nCompiles a `SELECT` statement and appends its instructions to the compilation context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_select(&mut self, span: SelectSpan) -> Result<()> {\n let mut end_pcs = vec![];\n\n self.selects += 1;\n let test_vref = VarRef::new(Compiler::select_test_var_name(self.selects), None);\n self.compile_assignment(test_vref.clone(), span.expr.start_pos(), span.expr)?;\n\n let mut iter = span.cases.into_iter();\n let mut next = iter.next();\n while let Some(case) = next {\n let next2 = iter.next();\n\n match Compiler::compile_case_guards(&test_vref, case.guards) {\n None => {\n self.compile_many(case.body)?;\n }\n Some(guard) => {\n self.compile_expr_guard(guard, \"SELECT\")?;\n let jump_pc = self.emit(Instruction::Nop);\n self.compile_many(case.body)?;\n\n if next2.is_some() {\n end_pcs.push(self.next_pc);\n self.emit(Instruction::Nop);\n }\n\n self.instrs[jump_pc] = Instruction::JumpIfNotTrue(self.next_pc);\n }\n }\n\n next = next2;\n }\n\n for end_pc in end_pcs {\n self.instrs[end_pc] = Instruction::Jump(JumpISpan { addr: self.next_pc });\n }\n\n let test_key = SymbolKey::from(test_vref.name());\n self.emit(Instruction::Unset(UnsetISpan { name: test_key.clone(), pos: span.end_pos }));\n self.symtable.remove(test_key);\n\n Ok(())\n }\n```"}], "func_name": "compile_select", "docstring": "Compiles a `SELECT` statement and appends its instructions to the compilation context.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9d46ed2a411a8dcf5602f0ed8ddeebadc432f0aee2c47aabb797fad40a848c97"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_while\n\nDocumentation:\nCompiles a `WHILE` loop and appends its instructions to the compilation context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_while(&mut self, span: WhileSpan) -> Result<()> {\n let start_pc = self.next_pc;\n self.compile_expr_guard(span.expr, \"WHILE\")?;\n let jump_pc = self.emit(Instruction::Nop);\n\n self.compile_many(span.body)?;\n\n self.emit(Instruction::Jump(JumpISpan { addr: start_pc }));\n\n self.instrs[jump_pc] = Instruction::JumpIfNotTrue(self.next_pc);\n\n Ok(())\n }\n```"}], "func_name": "compile_while", "docstring": "Compiles a `WHILE` loop and appends its instructions to the compilation context.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "015a9ef7c4bf48683ab44fb43a74d3b097c7bae8dd3c2a2e3e8739b92c43875b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_expr\n\nDocumentation:\nCompiles the evaluation of an expression, appends its instructions to the\ncompilation context, and returns the type of the compiled expression.\n\n`allow_varrefs` should be true for top-level expression compilations within\nfunction arguments. In that specific case, we must leave bare variable\nreferences unevaluated because we don't know if the function wants to take\nthe reference or the value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_expr(&mut self, expr: Expr, allow_varrefs: bool) -> Result {\n let result = if allow_varrefs {\n compile_expr_in_command(&mut self.instrs, &mut self.symtable, expr)\n } else {\n compile_expr(&mut self.instrs, &self.symtable, expr, false)\n };\n match result {\n Ok(result) => {\n self.next_pc = self.instrs.len();\n Ok(result)\n }\n Err(e) => Err(e),\n }\n }\n```"}], "func_name": "compile_expr", "docstring": "Compiles the evaluation of an expression, appends its instructions to the\ncompilation context, and returns the type of the compiled expression.\n\n`allow_varrefs` should be true for top-level expression compilations within\nfunction arguments. In that specific case, we must leave bare variable\nreferences unevaluated because we don't know if the function wants to take\nthe reference or the value.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3ac1f8be7235036ee9b91e7b2abf4f48b3bca75eb2e433ac1d5e96d81b3dde1c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_expr_as_type\n\nDocumentation:\nCompiles the evaluation of an expression with casts to a target type, appends its\ninstructions to the compilation context, and returns the type of the compiled expression.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_expr_as_type(&mut self, expr: Expr, target: ExprType) -> Result<()> {\n compile_expr_as_type(&mut self.instrs, &self.symtable, expr, target)?;\n self.next_pc = self.instrs.len();\n Ok(())\n }\n```"}], "func_name": "compile_expr_as_type", "docstring": "Compiles the evaluation of an expression with casts to a target type, appends its\ninstructions to the compilation context, and returns the type of the compiled expression.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "91cc7bc39e863ba5cb7108e70a5f6f98b0a24323ae4186513d6dd0ce7dc9a2fd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_expr_guard\n\nDocumentation:\nCompiles an expression that guards a conditional statement. Returns an error if the\nexpression is invalid or if it does not evaluate to a boolean.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_expr_guard>(&mut self, guard: Expr, errmsg: S) -> Result<()> {\n let pos = guard.start_pos();\n match self.compile_expr(guard, false)? {\n ExprType::Boolean => Ok(()),\n _ => Err(Error::NotABooleanCondition(pos, errmsg.into())),\n }\n }\n```"}], "func_name": "compile_expr_guard", "docstring": "Compiles an expression that guards a conditional statement. Returns an error if the\nexpression is invalid or if it does not evaluate to a boolean.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e456d0b77afaa6046418a8dd023157683853cbe50266d7ba81232c1d3c230dd7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_one\n\nDocumentation:\nCompiles one statement and appends its bytecode to the current compilation context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_one(&mut self, stmt: Statement) -> Result<()> {\n match stmt {\n Statement::ArrayAssignment(span) => {\n self.compile_array_assignment(span)?;\n }\n\n Statement::Assignment(span) => {\n self.compile_assignment(span.vref, span.vref_pos, span.expr)?;\n }\n\n Statement::Call(span) => {\n let key = SymbolKey::from(&span.vref.name());\n let md = match self.symtable.get(&key) {\n Some(SymbolPrototype::Callable(md)) => {\n if md.is_function() {\n return Err(Error::NotACommand(span.vref_pos, span.vref));\n }\n md.clone()\n }\n\n Some(_) => {\n return Err(Error::NotACommand(span.vref_pos, span.vref));\n }\n\n None => return Err(Error::UndefinedSymbol(span.vref_pos, key)),\n };\n\n let name_pos = span.vref_pos;\n let nargs = compile_command_args(\n &md,\n &mut self.instrs,\n &mut self.symtable,\n name_pos,\n span.args,\n )?;\n self.next_pc = self.instrs.len();\n self.emit(Instruction::BuiltinCall(key, span.vref_pos, nargs));\n }\n\n Statement::Callable(span) => {\n self.compile_callable(span)?;\n }\n\n Statement::Data(mut span) => {\n self.data.append(&mut span.values);\n }\n\n Statement::Dim(span) => {\n self.compile_dim(span)?;\n }\n\n Statement::DimArray(span) => {\n let key = SymbolKey::from(&span.name);\n if self.symtable.contains_key(&key) {\n return Err(Error::RedefinitionError(span.name_pos, key));\n }\n\n let nargs = span.dimensions.len();\n for arg in span.dimensions.into_iter().rev() {\n self.compile_expr_as_type(arg, ExprType::Integer)?;\n }\n self.emit(Instruction::DimArray(DimArrayISpan {\n name: key.clone(),\n name_pos: span.name_pos,\n shared: span.shared,\n dimensions: nargs,\n subtype: span.subtype,\n subtype_pos: span.subtype_pos,\n }));\n\n if span.shared {\n self.symtable.insert_global(key, SymbolPrototype::Array(span.subtype, nargs));\n } else {\n self.symtable.insert(key, SymbolPrototype::Array(span.subtype, nargs));\n }\n }\n\n Statement::Do(span) => {\n self.compile_do(span)?;\n }\n\n Statement::End(span) => match span.code {\n Some(expr) => {\n self.compile_expr_as_type(expr, ExprType::Integer)?;\n self.emit(Instruction::End(true));\n }\n None => {\n self.emit(Instruction::End(false));\n }\n },\n\n Statement::ExitDo(span) => {\n if self.exit_do_level.1 == 0 {\n return Err(Error::MisplacedExitDo(span.pos));\n }\n let exit_do_pc = self.emit(Instruction::Nop);\n self.fixups.insert(\n exit_do_pc,\n Fixup::from_exit_do(Compiler::do_label(self.exit_do_level), span),\n );\n }\n\n Statement::For(span) => {\n self.compile_for(span)?;\n }\n\n Statement::Gosub(span) => {\n let gosub_pc = self.emit(Instruction::Nop);\n self.fixups.insert(gosub_pc, Fixup::from_gosub(span));\n }\n\n Statement::Goto(span) => {\n let goto_pc = self.emit(Instruction::Nop);\n self.fixups.insert(goto_pc, Fixup::from_goto(span));\n }\n\n Statement::If(span) => {\n self.compile_if(span)?;\n }\n\n Statement::Label(span) => {\n if self.labels.insert(span.name.clone(), self.next_pc).is_some() {\n return Err(Error::DuplicateLabel(span.name_pos, span.name));\n }\n }\n\n Statement::OnError(span) => {\n self.compile_on_error(span);\n }\n\n Statement::Return(span) => {\n self.emit(Instruction::Return(span.pos));\n }\n\n Statement::Select(span) => {\n self.compile_select(span)?;\n }\n\n Statement::While(span) => {\n self.compile_while(span)?;\n }\n }\n\n Ok(())\n }\n```"}], "func_name": "compile_one", "docstring": "Compiles one statement and appends its bytecode to the current compilation context.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "61d94b9dbb878665e8afa800b0593ac85d3ad1d2ce1f1958798b7eebb695e410"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_many\n\nDocumentation:\nCompiles a collection of statements and appends their bytecode to the current compilation\ncontext.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_many(&mut self, stmts: Vec) -> Result<()> {\n for stmt in stmts {\n self.compile_one(stmt)?;\n }\n\n Ok(())\n }\n```"}], "func_name": "compile_many", "docstring": "Compiles a collection of statements and appends their bytecode to the current compilation\ncontext.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "55b4eee7716ec7151be55717e5e0d76fa924ff52adb775b8bb8b08f3c9aebd36"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_callables\n\nDocumentation:\nCompiles all callables discovered during the first phase and fixes up all call sites to\npoint to the compiled code.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_callables(&mut self) -> Result<()> {\n let end = self.emit(Instruction::Nop);\n\n let mut functions = HashMap::with_capacity(self.callable_spans.len());\n let mut subs = HashMap::with_capacity(self.callable_spans.len());\n let callable_spans = std::mem::take(&mut self.callable_spans);\n for span in callable_spans {\n let pc = self.next_pc;\n\n let key = SymbolKey::from(span.name.name());\n let return_value = Compiler::return_key(&key);\n match span.name.ref_type() {\n Some(return_type) => {\n self.emit(Instruction::EnterScope);\n self.symtable.enter_scope();\n\n self.emit(Instruction::Dim(DimISpan {\n name: return_value.clone(),\n shared: false,\n vtype: return_type,\n }));\n self.symtable\n .insert(return_value.clone(), SymbolPrototype::Variable(return_type));\n\n for param in span.params {\n let key = SymbolKey::from(param.name());\n let ptype = param.ref_type().unwrap_or(ExprType::Integer);\n self.emit(Instruction::Assign(key.clone()));\n self.symtable.insert(key, SymbolPrototype::Variable(ptype));\n }\n\n self.current_function = Some(key.clone());\n self.compile_many(span.body)?;\n self.current_function = None;\n\n let load_inst = match return_type {\n ExprType::Boolean => Instruction::LoadBoolean,\n ExprType::Double => Instruction::LoadDouble,\n ExprType::Integer => Instruction::LoadInteger,\n ExprType::Text => Instruction::LoadString,\n };\n self.emit(load_inst(return_value.clone(), span.end_pos));\n\n self.emit(Instruction::LeaveScope);\n self.symtable.leave_scope();\n self.emit(Instruction::Return(span.end_pos));\n\n functions.insert(key, pc);\n }\n None => {\n self.emit(Instruction::EnterScope);\n self.symtable.enter_scope();\n\n for param in span.params {\n let key = SymbolKey::from(param.name());\n let ptype = param.ref_type().unwrap_or(ExprType::Integer);\n self.emit(Instruction::Assign(key.clone()));\n self.symtable.insert(key, SymbolPrototype::Variable(ptype));\n }\n\n self.compile_many(span.body)?;\n\n self.emit(Instruction::LeaveScope);\n self.symtable.leave_scope();\n self.emit(Instruction::Return(span.end_pos));\n\n subs.insert(key, pc);\n }\n }\n }\n\n for instr in &mut self.instrs {\n match instr {\n Instruction::BuiltinCall(key, _, _) => {\n if let Some(addr) = subs.get(key) {\n *instr = Instruction::Call(JumpISpan { addr: *addr });\n }\n }\n\n Instruction::FunctionCall(key, _, _, _) => {\n if let Some(addr) = functions.get(key) {\n *instr = Instruction::Call(JumpISpan { addr: *addr });\n }\n }\n\n _ => (),\n }\n }\n\n self.instrs[end] = Instruction::Jump(JumpISpan { addr: self.next_pc });\n\n Ok(())\n }\n```"}], "func_name": "compile_callables", "docstring": "Compiles all callables discovered during the first phase and fixes up all call sites to\npoint to the compiled code.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9530bc84600efe32858d89a8d1db414e95427adb35a843f0a95868bb0155e2a4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_aux\n\nDocumentation:\nCompiles a collection of statements into an image ready for execution.\n\n`symtable` is the symbols table as used by the compiler and should be prepopulated with any\ncallables that the compiled program should recognize.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_aux(input: &mut dyn io::Read, symtable: SymbolsTable) -> Result<(Image, SymbolsTable)> {\n let mut compiler = Compiler { symtable, ..Default::default() };\n for stmt in parser::parse(input) {\n compiler.compile_one(stmt?)?;\n }\n compiler.to_image()\n}\n```"}], "func_name": "compile_aux", "docstring": "Compiles a collection of statements into an image ready for execution.\n\n`symtable` is the symbols table as used by the compiler and should be prepopulated with any\ncallables that the compiled program should recognize.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b377f3e2700f08ec76798d42d6ad1452ced39e8a26780d376726b15400ca1a10"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: define\n\nDocumentation:\nInserts `name` into the symbols table with the type defined by `proto`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn define>(\n mut self,\n name: K,\n proto: SymbolPrototype,\n ) -> Self {\n self.symtable.insert(name.into(), proto);\n self\n }\n```"}], "func_name": "define", "docstring": "Inserts `name` into the symbols table with the type defined by `proto`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "244ae7e996c8e7f2e8067b9731083bc05e7194b9ba6da6da60b7ef8a4d766c37"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: define_callable\n\nDocumentation:\nInserts `name` into the symbols table as a callable.\n\nThis is syntactic sugar over `define` to simplify the definition of callables.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn define_callable(mut self, builder: CallableMetadataBuilder) -> Self {\n let md = builder.test_build();\n let key = SymbolKey::from(md.name());\n self.symtable.insert(key, SymbolPrototype::Callable(md));\n self\n }\n```"}], "func_name": "define_callable", "docstring": "Inserts `name` into the symbols table as a callable.\n\nThis is syntactic sugar over `define` to simplify the definition of callables.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "784d78ef6381f5b8166745cbc9b70aa099bb1db530c1630784da19724389edd5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse\n\nDocumentation:\nParses and appends statements to the list of statements to be compiled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn parse(mut self, input: &str) -> Self {\n self.source.push_str(input);\n self.source.push('\\n');\n self\n }\n```"}], "func_name": "parse", "docstring": "Parses and appends statements to the list of statements to be compiled.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "961e415cfab2233f851ac38f407dd1806964374c7c88baee54d1fee72d1617fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile\n\nDocumentation:\nCompiles the collection of accumulated statements and returns a `Checker` object to\nvalidate expectations about the compilation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn compile(self) -> Checker {\n Checker {\n result: compile_aux(&mut self.source.as_bytes(), self.symtable),\n exp_error: None,\n ignore_instrs: false,\n exp_instrs: vec![],\n exp_data: vec![],\n exp_symtable: HashMap::default(),\n }\n }\n```"}], "func_name": "compile", "docstring": "Compiles the collection of accumulated statements and returns a `Checker` object to\nvalidate expectations about the compilation.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fce4e71505104323e8c40871cfa7b78a93884ecd1c9372555790d7ba94505121"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_instr\n\nDocumentation:\nRecords an instruction to be expected in the compiled output with the given address.\n\nIf the given address is past the last address of the bytecode, the bytecode is extended\nwith \"nops\" until the given address.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn expect_instr(mut self, addr: Address, instr: Instruction) -> Self {\n if addr >= self.exp_instrs.len() {\n self.exp_instrs.resize_with(addr + 1, || Instruction::Nop);\n }\n self.exp_instrs[addr] = instr;\n self\n }\n```"}], "func_name": "expect_instr", "docstring": "Records an instruction to be expected in the compiled output with the given address.\n\nIf the given address is past the last address of the bytecode, the bytecode is extended\nwith \"nops\" until the given address.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "86679d2df6a9d1e103700f01cd44b2d1eb2385b0138b47e31f26993bc1886141"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_symtable\n\nDocumentation:\nRecords an entry to be expected in the symbols table.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn expect_symtable(mut self, key: SymbolKey, proto: SymbolPrototype) -> Self {\n let previous = self.exp_symtable.insert(key, proto);\n assert!(previous.is_none());\n self\n }\n```"}], "func_name": "expect_symtable", "docstring": "Records an entry to be expected in the symbols table.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "58dfd52c43059a94a309aad7939f9801118662070e02a8642e2c4cc4a55f22b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ignore_instrs\n\nDocumentation:\nIndicates that we do not care about the generated instructions in this test.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn ignore_instrs(mut self) -> Self {\n self.ignore_instrs = true;\n self\n }\n```"}], "func_name": "ignore_instrs", "docstring": "Indicates that we do not care about the generated instructions in this test.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f8b0198455de908a0f86e9577b71d0fe559b8d501fe721e6a179f54899ad2ab1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_datum\n\nDocumentation:\nRecords a new datum in the compiled output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn expect_datum(mut self, datum: Option) -> Self {\n self.exp_data.push(datum);\n self\n }\n```"}], "func_name": "expect_datum", "docstring": "Records a new datum in the compiled output.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "112d115c57802ab4c6f44c306c5dd1d79757d3873444a960ed632a470ac38fd3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_err\n\nDocumentation:\nRecords that the compilation should fail with the given `message`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn expect_err>(mut self, message: S) -> Self {\n let message = message.into();\n self.exp_error = Some(message);\n self\n }\n```"}], "func_name": "expect_err", "docstring": "Records that the compilation should fail with the given `message`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "261fc87f99459fec814102f238858499daed59641b169fb83578d71cbeae63f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_compile_case_guard_test\n\nDocumentation:\nTests that parsing one or more `guards` as supplied after `CASE` yields the expected\nexpression in `exp_expr`.\n\n`exp_expr` must assume that its position starts at `(2, 6)`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_compile_case_guard_test(guards: &str, exp_expr_instrs: Vec) {\n let mut t = Tester::default()\n .define_callable(CallableMetadataBuilder::new(\"FOO\"))\n .parse(&format!(\"SELECT CASE 5\\nCASE {}\\nFOO\\nEND SELECT\", guards))\n .compile()\n .expect_instr(0, Instruction::PushInteger(5, lc(1, 13)))\n .expect_instr(1, Instruction::Assign(SymbolKey::from(\"0select1\")));\n let mut n = 2;\n for instr in exp_expr_instrs {\n t = t.expect_instr(n, instr);\n n += 1;\n }\n t.expect_instr(n, Instruction::JumpIfNotTrue(n + 2))\n .expect_instr(n + 1, Instruction::BuiltinCall(SymbolKey::from(\"FOO\"), lc(3, 1), 0))\n .expect_instr(\n n + 2,\n Instruction::Unset(UnsetISpan { name: SymbolKey::from(\"0select1\"), pos: lc(4, 1) }),\n )\n .check();\n }\n```"}], "func_name": "do_compile_case_guard_test", "docstring": "Tests that parsing one or more `guards` as supplied after `CASE` yields the expected\nexpression in `exp_expr`.\n\n`exp_expr` must assume that its position starts at `(2, 6)`.", "repo": "endbasic/endbasic", "path": "core/src/compiler/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/core/src/compiler/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1013490d16ceff7df29b2ba4cf499446c6bdc71a68df9e5bcb33c75863dd5313"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_demo\n\nDocumentation:\nConverts the raw bytes of a demo file into the program string to expose.\n\nThe input `bytes` must be valid UTF-8, which we can guarantee because these bytes come from\nfiles that we own in the source tree.\n\nOn Windows, the output string has all CRLF pairs converted to LF to ensure that the reported\ndemo file sizes are consistent across platforms.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_demo(bytes: &[u8]) -> String {\n let raw_content = str::from_utf8(bytes).expect(\"Malformed demo file\");\n if cfg!(target_os = \"windows\") {\n raw_content.replace(\"\\r\\n\", \"\\n\")\n } else {\n raw_content.to_owned()\n }\n}\n```"}], "func_name": "process_demo", "docstring": "Converts the raw bytes of a demo file into the program string to expose.\n\nThe input `bytes` must be valid UTF-8, which we can guarantee because these bytes come from\nfiles that we own in the source tree.\n\nOn Windows, the output string has all CRLF pairs converted to LF to ensure that the reported\ndemo file sizes are consistent across platforms.", "repo": "endbasic/endbasic", "path": "repl/src/demos.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/demos.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "647955138ed88d5b65ae7a553ae83dcaa3d3c422ac8211e878b9196d2d1a84fc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_indent\n\nDocumentation:\nReturns the indentation of a given string as a new string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn copy_indent(line: &LineBuffer) -> String {\n let mut indent = String::new();\n for ch in line.chars() {\n if !ch.is_whitespace() {\n break;\n }\n indent.push(ch);\n }\n indent\n}\n```"}], "func_name": "copy_indent", "docstring": "Returns the indentation of a given string as a new string.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93c36da0cbe86e98bee44c176ae8fd0f472614aed37854bd4dffa58ff6673ab5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: find_indent_end\n\nDocumentation:\nFinds the first position within the line that is not an indentation character, or returns\nthe line length if no such character is found.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn find_indent_end(line: &LineBuffer) -> usize {\n let mut pos = 0;\n for ch in line.chars() {\n if ch != ' ' {\n break;\n }\n pos += 1;\n }\n debug_assert!(pos <= line.len());\n pos\n}\n```"}], "func_name": "find_indent_end", "docstring": "Finds the first position within the line that is not an indentation character, or returns\nthe line length if no such character is found.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e4e00b1c4d2345a430cd5c7cc00529c397a1945d08c1b9596d68dee495e34e58"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default\n\nDocumentation:\nCreates a new editor without any stored contents.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn default() -> Self {\n Self {\n name: None,\n content: vec![],\n dirty: false,\n viewport_pos: FilePos::default(),\n file_pos: FilePos::default(),\n insert_col: 0,\n }\n }\n```"}], "func_name": "default", "docstring": "Creates a new editor without any stored contents.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7057d9bb44fdddc0d8c4da42d83c7b5fe27b0bc44df50ed64ec9f280b088fb98"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: refresh_status\n\nDocumentation:\nRewrites the status line at the bottom of the `console`, using the previously queried\n`console_size`.\n\nIt is the responsibility of the caller to move the cursor back to the appropriate location\nafter calling this function, and the caller should also hide the cursor before calling this\nfunction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn refresh_status(&self, console: &mut dyn Console, console_size: CharsXY) -> io::Result<()> {\n // Even though we track file positions as 0-indexed, display them as 1-indexed for a better\n // user experience given that this is what all other editor seem to do.\n let dirty_marker = if self.dirty { \"*\" } else { \"\" };\n let long_details = format!(\n \" | {}{} | Ln {}, Col {} \",\n self.name.as_deref().unwrap_or(\"\"),\n dirty_marker,\n self.file_pos.line + 1,\n self.file_pos.col + 1\n );\n\n let width = usize::from(console_size.x);\n let mut status = String::with_capacity(width);\n if KEYS_SUMMARY.len() + long_details.len() >= width {\n let short_details = format!(\" {}:{} \", self.file_pos.line + 1, self.file_pos.col + 1);\n if short_details.len() < width {\n while status.len() < width - short_details.len() {\n status.push(' ');\n }\n }\n status.push_str(&short_details);\n } else {\n status.push_str(KEYS_SUMMARY);\n while status.len() < width - long_details.len() {\n status.push(' ');\n }\n status.push_str(&long_details);\n }\n status.truncate(width);\n\n console.locate(CharsXY::new(0, console_size.y - 1))?;\n console.set_color(STATUS_COLOR.0, STATUS_COLOR.1)?;\n console.write(&status)?;\n Ok(())\n }\n```"}], "func_name": "refresh_status", "docstring": "Rewrites the status line at the bottom of the `console`, using the previously queried\n`console_size`.\n\nIt is the responsibility of the caller to move the cursor back to the appropriate location\nafter calling this function, and the caller should also hide the cursor before calling this\nfunction.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2fd6d26d19088ecdc3ac0212284eb6c3f08a22873c4ebdcdadb4b443448aee15"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: refresh\n\nDocumentation:\nRefreshes the contents of the whole `console`, using the previously queried `console_size`.\n\nIt is the responsibility of the caller to move the cursor back to the appropriate location\nafter calling this function, and the caller should also hide the cursor before calling this\nfunction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn refresh(&self, console: &mut dyn Console, console_size: CharsXY) -> io::Result<()> {\n console.set_color(TEXT_COLOR.0, TEXT_COLOR.1)?;\n console.clear(ClearType::All)?;\n self.refresh_status(console, console_size)?;\n console.set_color(TEXT_COLOR.0, TEXT_COLOR.1)?;\n console.locate(CharsXY::default())?;\n\n let mut row = self.viewport_pos.line;\n let mut printed_rows = 0;\n while row < self.content.len() && printed_rows < console_size.y - 1 {\n let line = &self.content[row];\n let line_len = line.len();\n if line_len > self.viewport_pos.col {\n console.print(&line.range(\n self.viewport_pos.col,\n self.viewport_pos.col + usize::from(console_size.x),\n ))?;\n } else {\n console.print(\"\")?;\n }\n row += 1;\n printed_rows += 1;\n }\n Ok(())\n }\n```"}], "func_name": "refresh", "docstring": "Refreshes the contents of the whole `console`, using the previously queried `console_size`.\n\nIt is the responsibility of the caller to move the cursor back to the appropriate location\nafter calling this function, and the caller should also hide the cursor before calling this\nfunction.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b98d7e3940a529842970f6f44b75118bc8a6874705f8f9a1428e23f1938bf99f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: move_down\n\nDocumentation:\nMoves the cursor down by the given number of lines in `nlines` or to the last line if there\nare insufficient lines to perform the move.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn move_down(&mut self, nlines: usize) {\n if self.file_pos.line + nlines < self.content.len() {\n self.file_pos.line += nlines;\n } else {\n self.file_pos.line = self.content.len() - 1;\n }\n\n let line = &self.content[self.file_pos.line];\n self.file_pos.col = cmp::min(self.insert_col, line.len());\n }\n```"}], "func_name": "move_down", "docstring": "Moves the cursor down by the given number of lines in `nlines` or to the last line if there\nare insufficient lines to perform the move.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ff5b10a36dc149a338aeff51ae50471aa619f8ec8a376122595a38ad24d5f0e8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: move_up\n\nDocumentation:\nMoves the cursor up by the given number of lines in `nlines` or to the first line if there\nare insufficient lines to perform the move.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn move_up(&mut self, nlines: usize) {\n if self.file_pos.line > nlines {\n self.file_pos.line -= nlines;\n } else {\n self.file_pos.line = 0;\n }\n\n let line = &self.content[self.file_pos.line];\n self.file_pos.col = cmp::min(self.insert_col, line.len());\n }\n```"}], "func_name": "move_up", "docstring": "Moves the cursor up by the given number of lines in `nlines` or to the first line if there\nare insufficient lines to perform the move.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0147acffd13b3bf0f6197ed60acf5b8a71a2946d02101b310bd42498ca669c95"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: edit_interactively\n\nDocumentation:\nInternal implementation of the interactive editor, which interacts with the `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn edit_interactively(&mut self, console: &mut dyn Console) -> io::Result<()> {\n let console_size = console.size_chars()?;\n\n if self.content.is_empty() {\n self.content.push(LineBuffer::default());\n }\n\n let mut need_refresh = true;\n loop {\n // The key handling below only deals with moving the insertion position within the file\n // but does not bother to update the viewport. Adjust it now, if necessary.\n let width = usize::from(console_size.x);\n let height = usize::from(console_size.y);\n if self.file_pos.line < self.viewport_pos.line {\n self.viewport_pos.line = self.file_pos.line;\n need_refresh = true;\n } else if self.file_pos.line > self.viewport_pos.line + height - 2 {\n if self.file_pos.line > height - 2 {\n self.viewport_pos.line = self.file_pos.line - (height - 2);\n } else {\n self.viewport_pos.line = 0;\n }\n need_refresh = true;\n }\n\n if self.file_pos.col < self.viewport_pos.col {\n self.viewport_pos.col = self.file_pos.col;\n need_refresh = true;\n } else if self.file_pos.col >= self.viewport_pos.col + width {\n self.viewport_pos.col = self.file_pos.col - width + 1;\n need_refresh = true;\n }\n\n // TODO(jmmv): We must handle the cursor visibility outside of the non-sync block\n // because the current console implementation forces the cursor to be invisible\n // when syncing is disabled. This is suboptimal and should be fixed by decoupling\n // the two properties...\n console.hide_cursor()?;\n if need_refresh {\n self.refresh(console, console_size)?;\n need_refresh = false;\n } else {\n self.refresh_status(console, console_size)?;\n console.set_color(TEXT_COLOR.0, TEXT_COLOR.1)?;\n }\n let cursor_pos = {\n let x = self.file_pos.col - self.viewport_pos.col;\n let y = self.file_pos.line - self.viewport_pos.line;\n if cfg!(debug_assertions) {\n CharsXY::new(\n u16::try_from(x).expect(\"Computed x must have fit on screen\"),\n u16::try_from(y).expect(\"Computed y must have fit on screen\"),\n )\n } else {\n CharsXY::new(x as u16, y as u16)\n }\n };\n console.locate(cursor_pos)?;\n console.show_cursor()?;\n console.sync_now()?;\n\n match console.read_key().await? {\n Key::Escape | Key::Eof | Key::Interrupt => break,\n\n Key::ArrowUp => self.move_up(1),\n\n Key::ArrowDown => self.move_down(1),\n\n Key::ArrowLeft => {\n if self.file_pos.col > 0 {\n self.file_pos.col -= 1;\n self.insert_col = self.file_pos.col;\n }\n }\n\n Key::ArrowRight => {\n if self.file_pos.col < self.content[self.file_pos.line].len() {\n self.file_pos.col += 1;\n self.insert_col = self.file_pos.col;\n }\n }\n\n Key::Backspace => {\n if self.file_pos.col > 0 {\n let line = &mut self.content[self.file_pos.line];\n\n let indent_pos = find_indent_end(line);\n let is_indent = indent_pos >= self.file_pos.col;\n let nremove = if is_indent {\n let new_pos = if self.file_pos.col >= INDENT_WIDTH {\n (self.file_pos.col - 1) / INDENT_WIDTH * INDENT_WIDTH\n } else {\n 0\n };\n self.file_pos.col - new_pos\n } else {\n 1\n };\n\n if self.file_pos.col == line.len() {\n if nremove > 0 {\n console.hide_cursor()?;\n }\n for _ in 0..nremove {\n console.clear(ClearType::PreviousChar)?;\n }\n if nremove > 0 {\n console.show_cursor()?;\n }\n } else {\n // TODO(jmmv): Refresh only the affected line.\n need_refresh = true;\n }\n for _ in 0..nremove {\n line.remove(self.file_pos.col - 1);\n self.file_pos.col -= 1;\n }\n if nremove > 0 {\n self.dirty = true;\n }\n } else if self.file_pos.line > 0 {\n let line = self.content.remove(self.file_pos.line);\n let prev = &mut self.content[self.file_pos.line - 1];\n self.file_pos.col = prev.len();\n prev.push_str(&line);\n self.file_pos.line -= 1;\n need_refresh = true;\n self.dirty = true;\n }\n self.insert_col = self.file_pos.col;\n }\n\n Key::Char(ch) => {\n let mut buf = [0; 4];\n\n let line = &mut self.content[self.file_pos.line];\n if self.file_pos.col < line.len() {\n // TODO(jmmv): Refresh only the affected line.\n need_refresh = true;\n }\n\n line.insert(self.file_pos.col, ch);\n self.file_pos.col += 1;\n self.insert_col = self.file_pos.col;\n\n if cursor_pos.x < console_size.x - 1 && !need_refresh {\n console.write(ch.encode_utf8(&mut buf))?;\n }\n\n self.dirty = true;\n }\n\n Key::End => {\n self.file_pos.col = self.content[self.file_pos.line].len();\n self.insert_col = self.file_pos.col;\n }\n\n Key::Home => {\n let indent_pos = find_indent_end(&self.content[self.file_pos.line]);\n if self.file_pos.col == indent_pos {\n self.file_pos.col = 0;\n } else {\n self.file_pos.col = indent_pos;\n }\n self.insert_col = self.file_pos.col;\n }\n\n Key::NewLine | Key::CarriageReturn => {\n let indent = copy_indent(&self.content[self.file_pos.line]);\n let indent_len = indent.len();\n\n let appending = (self.file_pos.line + 1 == self.content.len())\n && (self.file_pos.col == self.content[self.file_pos.line].len());\n\n let new = self.content[self.file_pos.line].split_off(self.file_pos.col);\n self.content.insert(\n self.file_pos.line + 1,\n LineBuffer::from(indent + &new.into_inner()),\n );\n need_refresh = !appending;\n\n self.file_pos.col = indent_len;\n self.file_pos.line += 1;\n self.insert_col = self.file_pos.col;\n self.dirty = true;\n }\n\n Key::PageDown => self.move_down(usize::from(console_size.y - 2)),\n\n Key::PageUp => self.move_up(usize::from(console_size.y - 2)),\n\n Key::Tab => {\n let line = &mut self.content[self.file_pos.line];\n if self.file_pos.col < line.len() {\n // TODO(jmmv): Refresh only the affected line.\n need_refresh = true;\n }\n\n let new_pos = (self.file_pos.col + INDENT_WIDTH) / INDENT_WIDTH * INDENT_WIDTH;\n let mut new_text = String::with_capacity(new_pos - self.file_pos.col);\n for _ in 0..new_text.capacity() {\n new_text.push(' ');\n }\n line.insert_str(self.file_pos.col, &new_text);\n self.file_pos.col = new_pos;\n self.insert_col = self.file_pos.col;\n if !need_refresh {\n console.write(&new_text)?;\n }\n self.dirty = true;\n }\n\n // TODO(jmmv): Should do something smarter with unknown keys.\n Key::Unknown => (),\n }\n }\n\n Ok(())\n }\n```"}], "func_name": "edit_interactively", "docstring": "Internal implementation of the interactive editor, which interacts with the `console`.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f056321df4c9ec223e82d549223e50ed19933c6c3386c98fdaa6320547ddb969"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: yx\n\nDocumentation:\nSyntactic sugar to easily instantiate a `CharsXY` at `(x,y)`.\n\nNote that the input arguments here are swapped. This is partly because of historical\nreasons, but also because virtually all editors (including this one) display file positions\nwith the line first followed by the column. It's easier to reason about the tests below\nwhen the order of the arguments to `linecol` matches `yx`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn yx(y: u16, x: u16) -> CharsXY {\n CharsXY::new(x, y)\n }\n```"}], "func_name": "yx", "docstring": "Syntactic sugar to easily instantiate a `CharsXY` at `(x,y)`.\n\nNote that the input arguments here are swapped. This is partly because of historical\nreasons, but also because virtually all editors (including this one) display file positions\nwith the line first followed by the column. It's easier to reason about the tests below\nwhen the order of the arguments to `linecol` matches `yx`.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c41c75e01044b73bc75effce1e4cc25657fe360f3627144becefa1f4f2f1fcf8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: linecol\n\nDocumentation:\nSyntactic sugar to easily instantiate a `FilePos` at `(line, col)`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn linecol(line: usize, col: usize) -> FilePos {\n FilePos { line, col }\n }\n```"}], "func_name": "linecol", "docstring": "Syntactic sugar to easily instantiate a `FilePos` at `(line, col)`.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "07635dc7844f28da4b448c1c5da68d74d8d17c2d8a114925c645834939e55008"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConstructs a new output builder with just the command to enter the alternate screen.\n`console_size` holds the size of the mock console, which is used to determine where to\nprint the status bar.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(console_size: CharsXY) -> Self {\n Self {\n console_size,\n output: vec![CapturedOut::EnterAlt, CapturedOut::SetSync(false)],\n dirty: false,\n }\n }\n```"}], "func_name": "new", "docstring": "Constructs a new output builder with just the command to enter the alternate screen.\n`console_size` holds the size of the mock console, which is used to determine where to\nprint the status bar.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93d2a700c38b8f933aaa941f44d32280e02bdfe4a12bf7c79b81e78c0d7fa389"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: refresh_status\n\nDocumentation:\nRecords the console changes needed to update the status line to reflect a new `file_pos`\nposition. Should not be used directly by tests.\n\nNote that, although `file_pos` is 0-indexed (to make it easier to reason about where\nfile changes actually happen in the internal buffers), we display the position as\n1-indexed here as the code under test does.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn refresh_status(mut self, file_pos: FilePos) -> Self {\n let row = file_pos.line + 1;\n let column = file_pos.col + 1;\n\n self.output.push(CapturedOut::Locate(yx(self.console_size.y - 1, 0)));\n self.output.push(CapturedOut::SetColor(STATUS_COLOR.0, STATUS_COLOR.1));\n if self.console_size.x < 30 {\n // Arbitrary number to define \"narrow console\" in tests.\n let details = &format!(\" {}:{} \", row, column);\n let mut status = String::new();\n while status.len() + details.len() < usize::from(self.console_size.x) {\n status.push(' ');\n }\n status += details;\n status.truncate(usize::from(self.console_size.x));\n self.output.push(CapturedOut::Write(status));\n } else {\n let dirty_marker = if self.dirty { \"*\" } else { \"\" };\n let details =\n &format!(\"| {}{} | Ln {}, Col {} \", TEST_FILENAME, dirty_marker, row, column);\n let mut status = String::from(KEYS_SUMMARY);\n while status.len() + details.len() < usize::from(self.console_size.x) {\n status.push(' ');\n }\n status += details;\n self.output.push(CapturedOut::Write(status));\n }\n self\n }\n```"}], "func_name": "refresh_status", "docstring": "Records the console changes needed to update the status line to reflect a new `file_pos`\nposition. Should not be used directly by tests.\n\nNote that, although `file_pos` is 0-indexed (to make it easier to reason about where\nfile changes actually happen in the internal buffers), we display the position as\n1-indexed here as the code under test does.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ae05e44c655be9ff6287a0046843834ba6a9b2eac25def72c6af5d5ac8e26a1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: quick_refresh\n\nDocumentation:\nRecords the console changes needed to incrementally update the editor, without going\nthrough a full refresh, assuming a `file_pos` position.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn quick_refresh(mut self, file_pos: FilePos, cursor: CharsXY) -> Self {\n self.output.push(CapturedOut::HideCursor);\n self = self.refresh_status(file_pos);\n self.output.push(CapturedOut::SetColor(TEXT_COLOR.0, TEXT_COLOR.1));\n self.output.push(CapturedOut::Locate(cursor));\n self.output.push(CapturedOut::ShowCursor);\n self.output.push(CapturedOut::SyncNow);\n self\n }\n```"}], "func_name": "quick_refresh", "docstring": "Records the console changes needed to incrementally update the editor, without going\nthrough a full refresh, assuming a `file_pos` position.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "11d8c59f613a044cd950afca4c5e2fa828a54520152a5e7c310f5471ef7b1c5d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: refresh\n\nDocumentation:\nRecords the console changes needed to refresh the whole console view. The status line\nis updated to reflect `file_pos`; the editor is pre-populated with the lines specified\nin `previous`; and the `cursor` is placed at the given location.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn refresh(mut self, file_pos: FilePos, previous: &[&str], cursor: CharsXY) -> Self {\n self.output.push(CapturedOut::HideCursor);\n self.output.push(CapturedOut::SetColor(TEXT_COLOR.0, TEXT_COLOR.1));\n self.output.push(CapturedOut::Clear(ClearType::All));\n self = self.refresh_status(file_pos);\n self.output.push(CapturedOut::SetColor(TEXT_COLOR.0, TEXT_COLOR.1));\n self.output.push(CapturedOut::Locate(yx(0, 0)));\n for line in previous {\n self.output.push(CapturedOut::Print(line.to_string()));\n }\n self.output.push(CapturedOut::Locate(cursor));\n self.output.push(CapturedOut::ShowCursor);\n self.output.push(CapturedOut::SyncNow);\n self\n }\n```"}], "func_name": "refresh", "docstring": "Records the console changes needed to refresh the whole console view. The status line\nis updated to reflect `file_pos`; the editor is pre-populated with the lines specified\nin `previous`; and the `cursor` is placed at the given location.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e44abcfc2e1b5ecd62673327961e548561e85452e6cdeecf70008cafe4fea401"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add\n\nDocumentation:\nRegisters a new expected side-effect `co` on the console.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add(mut self, co: CapturedOut) -> Self {\n self.output.push(co);\n self\n }\n```"}], "func_name": "add", "docstring": "Registers a new expected side-effect `co` on the console.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "55efdf2469eeb48a6f3ef0b70d3a33cd38ce4e28051a441f8dbe9a8a99fcd6e0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_dirty\n\nDocumentation:\nRegisters that the file has been modified.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_dirty(mut self) -> Self {\n self.dirty = true;\n self\n }\n```"}], "func_name": "set_dirty", "docstring": "Registers that the file has been modified.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ce0f0b9e831b1222c70cf922814982d882d07e5a775ee580b4ec1d941d900bc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nFinalizes the list of expected side-effects on the console.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn build(self) -> Vec {\n let mut output = self.output;\n output.push(CapturedOut::SetSync(true));\n output.push(CapturedOut::LeaveAlt);\n output\n }\n```"}], "func_name": "build", "docstring": "Finalizes the list of expected side-effects on the console.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c1ed847bed81d3b0e736ff9c42d6357588dc2ee67edb482253e69aca37f21516"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_editor\n\nDocumentation:\nRuns the editor and expects that the resulting text matches `exp_text` and that the\nside-effects on the console are those specified in `ob`.\n\nThe editor can be pre-populated with some `previous` contents and the interactions with the\neditor are specified in `cb`. Note that the final Esc key press needed to exit the editor\nis automatically appended to `cb` here.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn run_editor(previous: &str, exp_text: &str, mut console: MockConsole, ob: OutputBuilder) {\n let mut editor = Editor::default();\n editor.load(Some(TEST_FILENAME), previous);\n\n console.add_input_keys(&[Key::Escape]);\n block_on(editor.edit(&mut console)).unwrap();\n assert_eq!(exp_text, editor.text());\n assert_eq!(ob.dirty, editor.is_dirty());\n assert_eq!(ob.build(), console.captured_out());\n }\n```"}], "func_name": "run_editor", "docstring": "Runs the editor and expects that the resulting text matches `exp_text` and that the\nside-effects on the console are those specified in `ob`.\n\nThe editor can be pre-populated with some `previous` contents and the interactions with the\neditor are specified in `cb`. Note that the final Esc key press needed to exit the editor\nis automatically appended to `cb` here.", "repo": "endbasic/endbasic", "path": "repl/src/editor.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/editor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "672f020db897435bca2797c3f2a6b494b98a93098eb09503ece0455da93d05cd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_welcome\n\nDocumentation:\nPrints the EndBASIC welcome message to the given console.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn print_welcome(console: Rc>) -> io::Result<()> {\n let mut console = console.borrow_mut();\n\n if is_narrow(&*console) {\n console.print(&format!(\"EndBASIC {}\", env!(\"CARGO_PKG_VERSION\")))?;\n } else {\n console.print(\"\")?;\n console.print(&format!(\" EndBASIC {}\", env!(\"CARGO_PKG_VERSION\")))?;\n console.print(\" Copyright 2020-2025 Julio Merino\")?;\n console.print(\"\")?;\n console.print(\" Type HELP for interactive usage information.\")?;\n }\n console.print(\"\")?;\n\n Ok(())\n}\n```"}], "func_name": "print_welcome", "docstring": "Prints the EndBASIC welcome message to the given console.", "repo": "endbasic/endbasic", "path": "repl/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "923ca20081f6f3df3430419ff8d5f00d4e50a5296aae969aa580ae55fc9e917b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_load_autoexec\n\nDocumentation:\nLoads the `AUTOEXEC.BAS` file if it exists in the `drive`.\n\nFailures to process the file are logged to the `console` but are ignored. Other failures are\nreturned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn try_load_autoexec(\n machine: &mut Machine,\n console: Rc>,\n storage: Rc>,\n) -> io::Result<()> {\n let code = match storage.borrow().get(\"AUTOEXEC.BAS\").await {\n Ok(code) => code,\n Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),\n Err(e) => {\n return console\n .borrow_mut()\n .print(&format!(\"AUTOEXEC.BAS exists but cannot be read: {}\", e));\n }\n };\n\n match machine.exec(&mut code.as_slice()).await {\n Ok(_) => Ok(()),\n Err(e) => {\n console.borrow_mut().print(&format!(\"AUTOEXEC.BAS failed: {}\", e))?;\n Ok(())\n }\n }\n}\n```"}], "func_name": "try_load_autoexec", "docstring": "Loads the `AUTOEXEC.BAS` file if it exists in the `drive`.\n\nFailures to process the file are logged to the `console` but are ignored. Other failures are\nreturned.", "repo": "endbasic/endbasic", "path": "repl/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "323d754f52220827c180e90a430a78073b406bb97ae0702efcb98392c2ecfd95"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_from_cloud\n\nDocumentation:\nLoads the program given in `username_path` pair (which is of the form `user/path`) from the\ncloud and executes it on the `machine`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_from_cloud(\n machine: &mut Machine,\n console: Rc>,\n storage: Rc>,\n program: Rc>,\n username_path: &str,\n will_run_repl: bool,\n) -> io::Result {\n let (fs_uri, path) = match username_path.split_once('/') {\n Some((username, path)) => (format!(\"cloud://{}\", username), format!(\"AUTORUN:/{}\", path)),\n None => {\n let mut console = console.borrow_mut();\n console.print(&format!(\n \"Invalid program to run '{}'; must be of the form 'username/path'\",\n username_path\n ))?;\n return Ok(1);\n }\n };\n\n console.borrow_mut().print(&format!(\"Mounting {} as AUTORUN...\", fs_uri))?;\n storage.borrow_mut().mount(\"AUTORUN\", &fs_uri)?;\n storage.borrow_mut().cd(\"AUTORUN:/\")?;\n\n console.borrow_mut().print(&format!(\"Loading {}...\", path))?;\n let content = storage.borrow().get(&path).await?;\n let content = match String::from_utf8(content) {\n Ok(text) => text,\n Err(e) => {\n let mut console = console.borrow_mut();\n console.print(&format!(\"Invalid program to run '{}': {}\", path, e))?;\n return Ok(1);\n }\n };\n program.borrow_mut().load(Some(&path), &content);\n\n console.borrow_mut().print(\"Starting...\")?;\n console.borrow_mut().print(\"\")?;\n\n let result = machine.exec(&mut \"RUN\".as_bytes()).await;\n\n let mut console = console.borrow_mut();\n\n console.print(\"\")?;\n let code = match result {\n Ok(r @ StopReason::Eof) => {\n console.print(\"**** Program exited due to EOF ****\")?;\n r.as_exit_code()\n }\n Ok(r @ StopReason::Exited(_)) => {\n let code = r.as_exit_code();\n console.print(&format!(\"**** Program exited with code {} ****\", code))?;\n code\n }\n Ok(r @ StopReason::Break) => {\n console.print(\"**** Program stopped due to BREAK ****\")?;\n r.as_exit_code()\n }\n Err(e) => {\n console.print(&format!(\"**** ERROR: {} ****\", e))?;\n 1\n }\n };\n\n if will_run_repl {\n console.print(\"\")?;\n refill_and_print(\n &mut *console,\n [\n \"You are now being dropped into the EndBASIC interpreter.\",\n \"The program you asked to run is still loaded in memory and you can interact with \\\nit now. Use LIST to view the source code, EDIT to launch an editor on the source code, and RUN to \\\nexecute the program again.\",\n \"Type HELP for interactive usage information.\",\n ],\n \" \",\n )?;\n console.print(\"\")?;\n }\n\n Ok(code)\n}\n```"}], "func_name": "run_from_cloud", "docstring": "Loads the program given in `username_path` pair (which is of the form `user/path`) from the\ncloud and executes it on the `machine`.", "repo": "endbasic/endbasic", "path": "repl/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0fe36d6277dea46941265349a3c180c2f908ed484de01051cb98dd6e2d2931c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_repl_loop\n\nDocumentation:\nEnters the interactive interpreter.\n\nThe `console` provided here is used for the REPL prompt interaction and should match the\nconsole that's in use by the machine (if any). They don't necessarily have to match though.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_repl_loop(\n machine: &mut Machine,\n console: Rc>,\n program: Rc>,\n) -> io::Result {\n let mut stop_reason = StopReason::Eof;\n let mut history = vec![];\n while stop_reason == StopReason::Eof {\n let line = {\n let mut console = console.borrow_mut();\n if console.is_interactive() {\n console.print(\"Ready\")?;\n }\n console::read_line(&mut *console, \"\", \"\", Some(&mut history)).await\n };\n\n // Any signals entered during console input should not impact upcoming execution. Drain\n // them all.\n machine.drain_signals();\n\n match line {\n Ok(line) => match machine.exec(&mut line.as_bytes()).await {\n Ok(reason) => stop_reason = reason,\n Err(e) => {\n let mut console = console.borrow_mut();\n console.print(format!(\"ERROR: {}\", e).as_str())?;\n }\n },\n Err(e) => {\n if e.kind() == io::ErrorKind::Interrupted {\n let mut console = console.borrow_mut();\n console.print(BREAK_MSG)?;\n // Do not exit the interpreter. Other REPLs, such as Python's, do not do so,\n // and it is actually pretty annoying to exit the REPL when one may be furiously\n // pressing CTRL+C to stop a program inside of it.\n } else if e.kind() == io::ErrorKind::UnexpectedEof {\n let mut console = console.borrow_mut();\n console.print(\"End of input by CTRL-D\")?;\n stop_reason = StopReason::Exited(0);\n } else {\n stop_reason = StopReason::Exited(1);\n }\n }\n }\n\n match stop_reason {\n StopReason::Eof => (),\n StopReason::Break => {\n console.borrow_mut().print(\"**** BREAK ****\")?;\n stop_reason = StopReason::Eof;\n }\n StopReason::Exited(_) => {\n if !continue_if_modified(&*program.borrow(), &mut *console.borrow_mut()).await? {\n console.borrow_mut().print(\"Exit aborted; resuming REPL loop.\")?;\n stop_reason = StopReason::Eof;\n }\n }\n }\n }\n Ok(stop_reason.as_exit_code())\n}\n```"}], "func_name": "run_repl_loop", "docstring": "Enters the interactive interpreter.\n\nThe `console` provided here is used for the REPL prompt interaction and should match the\nconsole that's in use by the machine (if any). They don't necessarily have to match though.", "repo": "endbasic/endbasic", "path": "repl/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ebe559146b3f2bcd55d46535a2e3f92ebeafff6e25588849d0f2034532860898"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_is_narrow_welcome\n\nDocumentation:\nRuns `print_welcome` against a console that is `console_width` in height and returns\nwhether the narrow welcome message was printed or not, and the maximum width of all\nprinted messages.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_is_narrow_welcome(console_width: u16) -> (bool, usize) {\n let console = Rc::from(RefCell::from(MockConsole::default()));\n console.borrow_mut().set_size_chars(CharsXY::new(console_width, 1));\n print_welcome(console.clone()).unwrap();\n\n let mut console = console.borrow_mut();\n let mut found = false;\n let mut max_length = 0;\n for output in console.take_captured_out() {\n match output {\n CapturedOut::Print(msg) => {\n if msg.contains(\"Type HELP\") {\n found = true;\n max_length = std::cmp::max(max_length, msg.len());\n }\n }\n _ => panic!(\"Unexpected console operation: {:?}\", output),\n }\n }\n (!found, max_length)\n }\n```"}], "func_name": "check_is_narrow_welcome", "docstring": "Runs `print_welcome` against a console that is `console_width` in height and returns\nwhether the narrow welcome message was printed or not, and the maximum width of all\nprinted messages.", "repo": "endbasic/endbasic", "path": "repl/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/repl/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "67932d97f2818ef62898bb51cb2214130e7868dc58a66c59df6d6febbb9540e3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: gpio_error_to_io_error\n\nDocumentation:\nConverts a `gpio::Error` to an `io::Error`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn gpio_error_to_io_error(e: gpio::Error) -> io::Error {\n match e {\n gpio::Error::Io(e) => e,\n gpio::Error::PermissionDenied(path) => io::Error::new(\n io::ErrorKind::PermissionDenied,\n format!(\"Cannot open {}: permission denied\", path),\n ),\n gpio::Error::PinNotAvailable(pin) => {\n io::Error::new(io::ErrorKind::InvalidInput, format!(\"Unknown pin number {}\", pin))\n }\n e => io::Error::other(e.to_string()),\n }\n}\n```"}], "func_name": "gpio_error_to_io_error", "docstring": "Converts a `gpio::Error` to an `io::Error`.", "repo": "endbasic/endbasic", "path": "rpi/src/gpio.rs", "url": "https://github.com/endbasic/endbasic/blob/master/rpi/src/gpio.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9e24381206549b6a1cff7717b16a80d73741401855a733b1211acea232efc0e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_chip\n\nDocumentation:\nGets access to the default GPIO chip and lazily opens it if not yet open.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_chip(&mut self) -> io::Result<&mut gpio::Gpio> {\n if self.chip.is_none() {\n self.chip = Some(gpio::Gpio::new().map_err(gpio_error_to_io_error)?);\n }\n Ok(self.chip.as_mut().unwrap())\n }\n```"}], "func_name": "get_chip", "docstring": "Gets access to the default GPIO chip and lazily opens it if not yet open.", "repo": "endbasic/endbasic", "path": "rpi/src/gpio.rs", "url": "https://github.com/endbasic/endbasic/blob/master/rpi/src/gpio.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2e267b6ae447c424dc5e71051a932588daf74443ed75c14eac57ea4e318db665"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spi_error_to_io_error\n\nDocumentation:\nConverts an SPI error to an IO error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn spi_error_to_io_error(e: spi::Error) -> io::Error {\n match e {\n spi::Error::Io(e) => e,\n e => io::Error::new(io::ErrorKind::InvalidInput, e.to_string()),\n }\n}\n```"}], "func_name": "spi_error_to_io_error", "docstring": "Converts an SPI error to an IO error.", "repo": "endbasic/endbasic", "path": "rpi/src/spi.rs", "url": "https://github.com/endbasic/endbasic/blob/master/rpi/src/spi.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ea54e8301da6993b44d4c52830ce5e52ec1ae09edc442b4b4a9c8f490e1b941"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: query_spi_bufsiz\n\nDocumentation:\nQueries the maximum SPI transfer size from `path`. If `path` is not provided, defaults to\n`SPIDEV_BUFSIZ_PATH`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn query_spi_bufsiz(path: Option<&Path>) -> io::Result {\n let path = path.unwrap_or(Path::new(SPIDEV_BUFSIZ_PATH));\n\n let content = match fs::read_to_string(path) {\n Ok(content) => content,\n Err(e) => {\n return Err(io::Error::new(\n e.kind(),\n format!(\"Failed to read {}: {}\", path.display(), e),\n ));\n }\n };\n\n let content = content.trim_end();\n\n match content.parse::() {\n Ok(i) => Ok(i),\n Err(e) => Err(io::Error::new(\n io::ErrorKind::InvalidData,\n format!(\"Failed to read {}: invalid content: {}\", path.display(), e),\n )),\n }\n}\n```"}], "func_name": "query_spi_bufsiz", "docstring": "Queries the maximum SPI transfer size from `path`. If `path` is not provided, defaults to\n`SPIDEV_BUFSIZ_PATH`.", "repo": "endbasic/endbasic", "path": "rpi/src/spi.rs", "url": "https://github.com/endbasic/endbasic/blob/master/rpi/src/spi.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27dac62ec954c3a06a964df9b50a2c257045422cc7b2230b8d21596895df0c98"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spi_bus_open\n\nDocumentation:\nFactory function to open an `RppalSpiBus`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn spi_bus_open(bus: u8, slave: u8, clock_hz: u32, mode: SpiMode) -> io::Result {\n let bus = match bus {\n 0 => Bus::Spi0,\n _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, \"Only bus 0 is supported\")),\n };\n\n let slave = match slave {\n 0 => SlaveSelect::Ss0,\n _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, \"Only slave 0 is supported\")),\n };\n\n let mode = match mode {\n SpiMode::Mode0 => spi::Mode::Mode0,\n SpiMode::Mode1 => spi::Mode::Mode1,\n SpiMode::Mode2 => spi::Mode::Mode2,\n SpiMode::Mode3 => spi::Mode::Mode3,\n };\n\n let spi = Spi::new(bus, slave, clock_hz, mode).map_err(spi_error_to_io_error)?;\n\n let bufsiz = query_spi_bufsiz(None)?;\n\n Ok(RppalSpiBus { spi, bufsiz })\n}\n```"}], "func_name": "spi_bus_open", "docstring": "Factory function to open an `RppalSpiBus`.", "repo": "endbasic/endbasic", "path": "rpi/src/spi.rs", "url": "https://github.com/endbasic/endbasic/blob/master/rpi/src/spi.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f38b2eb5462cdd0250c535e54b1a50a8585bfc9517d7006a7e4c3219afb19455"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nInitializes a new SDL console.\n\nThe console is sized to `resolution` pixels and its default colors are set to\n`default_fg_color` and `default_bg_color`. Also loads the desired font from `font_path` at\n`font_size` and uses it to calculate the size of the console in characters.\n\nThere can only be one active `SdlConsole` at any given time given that this initializes and\nowns the SDL context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new(\n resolution: Resolution,\n default_fg_color: Option,\n default_bg_color: Option,\n font_path: PathBuf,\n font_size: u16,\n signals_tx: Sender,\n ) -> io::Result {\n let (request_tx, request_rx) = mpsc::sync_channel(1);\n let (response_tx, response_rx) = mpsc::sync_channel(1);\n let (on_key_tx, on_key_rx) = mpsc::channel();\n let handle = thread::spawn(move || {\n host::run(\n resolution,\n default_fg_color,\n default_bg_color,\n font_path,\n font_size,\n request_rx,\n response_tx,\n on_key_tx,\n signals_tx,\n );\n });\n\n // Wait for the console to be up and running. We must do this for error propagation but\n // also to ensure that the caller can free up the local temporary font resources, if any.\n match response_rx.recv().expect(\"Channel must be alive\") {\n Response::Empty(Ok(())) => Ok(Self {\n handle: Some(handle),\n request_tx,\n response_rx,\n on_key_rx,\n fg_color: None,\n bg_color: None,\n alt_backup: None,\n }),\n Response::Empty(Err(e)) => Err(e),\n r => panic!(\"Unexpected response {:?}\", r),\n }\n }\n```"}], "func_name": "new", "docstring": "Initializes a new SDL console.\n\nThe console is sized to `resolution` pixels and its default colors are set to\n`default_fg_color` and `default_bg_color`. Also loads the desired font from `font_path` at\n`font_size` and uses it to calculate the size of the console in characters.\n\nThere can only be one active `SdlConsole` at any given time given that this initializes and\nowns the SDL context.", "repo": "endbasic/endbasic", "path": "sdl/src/console.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/console.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "df1d36d794c8527324931cb897d2909897db4b7cbcb3c6700d59832e41fa2317"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: call\n\nDocumentation:\nIssues a synchronous call against the console host for a request that returns nothing but\nan error (if any).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn call(&self, request: Request) -> io::Result<()> {\n self.request_tx.send(request).expect(\"Channel must be alive\");\n match self.response_rx.recv().expect(\"Channel must be alive\") {\n Response::Empty(Ok(v)) => Ok(v),\n Response::Empty(Err(e)) => Err(e),\n r => panic!(\"Unexpected response {:?}\", r),\n }\n }\n```"}], "func_name": "call", "docstring": "Issues a synchronous call against the console host for a request that returns nothing but\nan error (if any).", "repo": "endbasic/endbasic", "path": "sdl/src/console.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/console.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8e8384217a27421ca55921e1cdab1ed91c4a71f3d45c09a29952a2335d520e0a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new test context and ensures no other test is running at the same time.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new() -> Self {\n let lock = TEST_LOCK.lock().unwrap();\n let signals_chan = async_channel::unbounded();\n let console = SdlConsole::new(\n Resolution::Windowed((\n NonZeroU32::new(800).unwrap(),\n NonZeroU32::new(600).unwrap(),\n )),\n None,\n None,\n src_path(\"sdl/src/IBMPlexMono-Regular-6.0.0.ttf\"),\n 16,\n signals_chan.0,\n )\n .unwrap();\n Self { _lock: lock, signals_rx: signals_chan.1, console }\n }\n```"}], "func_name": "new", "docstring": "Creates a new test context and ensures no other test is running at the same time.", "repo": "endbasic/endbasic", "path": "sdl/src/console.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/console.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6bfa9af5d8dad70549e158f795685579ed2037ef7582249e56093781951f2b43"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: console\n\nDocumentation:\nObtains access to the SDL console.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn console(&mut self) -> &mut SdlConsole {\n &mut self.console\n }\n```"}], "func_name": "console", "docstring": "Obtains access to the SDL console.", "repo": "endbasic/endbasic", "path": "sdl/src/console.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/console.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f9907550534080c8b51c9a5173933009f1fe2c9f4f45cb59ceb365f5527355ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait_one_signal\n\nDocumentation:\nSynchronously waits for the reception of just one signal.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn wait_one_signal(&self) -> Signal {\n let signal = block_on(self.signals_rx.recv()).unwrap();\n\n match self.signals_rx.try_recv() {\n Ok(signal) => panic!(\"Received duplicate signal {:?}\", signal),\n Err(TryRecvError::Empty) => (),\n Err(TryRecvError::Closed) => panic!(\"Channel must be alive\"),\n }\n\n signal\n }\n```"}], "func_name": "wait_one_signal", "docstring": "Synchronously waits for the reception of just one signal.", "repo": "endbasic/endbasic", "path": "sdl/src/console.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/console.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b08256796600c2c1f6a0778e82c675779f0e0bb78476b6b7f1ed3c828d03b697"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: verify\n\nDocumentation:\nVerifies that the current state of the console matches a golden imagine. `bmp_basename`\nindicates the name of the BMP image to use, without an extension.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn verify(self, bmp_basename: &'static str) {\n let golden_bmp_gz = src_path(\"sdl/src\").join(format!(\"{}.bmp.gz\", bmp_basename));\n let dir = tempfile::tempdir().unwrap();\n let actual_bmp = dir.path().join(format!(\"{}.bmp\", bmp_basename));\n\n self.console.call(Request::SaveBmp(actual_bmp.clone())).unwrap();\n\n if env::var(\"REGEN_BMPS\").as_ref().map(String::as_str) == Ok(\"true\") {\n let mut input = BufReader::new(File::open(actual_bmp).unwrap());\n let output = File::create(golden_bmp_gz).unwrap();\n let mut encoder = GzEncoder::new(output, Compression::default());\n io::copy(&mut input, &mut encoder).unwrap();\n encoder.finish().unwrap();\n\n // We could delete the `actual_bmp` file here, but it's easier to keep it around\n // for manual validation of the new images.\n\n drop(self); // Avoid poisoning the mutex when panicking.\n panic!(\"Golden data regenerated; flip REGEN_BMPS back to false\");\n }\n\n let actual = {\n let mut rwops = RWops::from_file(actual_bmp, \"r\").unwrap();\n Surface::load_bmp_rw(&mut rwops)\n .unwrap()\n .into_canvas()\n .unwrap()\n .read_pixels(None, PixelFormatEnum::BGR888)\n .unwrap()\n };\n\n let golden = {\n let input = BufReader::new(File::open(golden_bmp_gz).unwrap());\n let mut decoder = GzDecoder::new(input);\n let mut buffer = vec![];\n decoder.read_to_end(&mut buffer).unwrap();\n let mut rwops = RWops::from_bytes(buffer.as_slice()).unwrap();\n Surface::load_bmp_rw(&mut rwops)\n .unwrap()\n .into_canvas()\n .unwrap()\n .read_pixels(None, PixelFormatEnum::BGR888)\n .unwrap()\n };\n\n // The test should not fail until this point, or else we poison the mutex and all\n // subsequent tests fail. However, we must do this *after* the `Surface` manipulation\n // above, or else tests misbehave.\n drop(self);\n\n // Compare images for equality. In theory, they should be pixel-perfect across\n // platforms, but in practice, I'm encountering minor color variations (e.g. FreeBSD\n // renders colors that differ by one compared to Windows) that I haven't been able to\n // explain. Cope with those here by tolerating minor differences in the comparison.\n let mut equal = true;\n assert_eq!(golden.len(), actual.len());\n for i in 0..golden.len() {\n let pixel1 = golden[i];\n let pixel2 = actual[i];\n\n let pixel2min = match pixel2 {\n 0 => pixel2,\n 1 => pixel2 - 1,\n _ => pixel2 - 2,\n };\n let pixel2max = match pixel2 {\n 255 => pixel2,\n 254 => pixel2 + 1,\n _ => pixel2 + 2,\n };\n\n if pixel1 < pixel2min || pixel1 > pixel2max {\n eprintln!(\"Diff at pixel {}: {} vs. {}\", i, pixel1, pixel2);\n equal = false;\n }\n }\n assert!(equal, \"Images do not match; see test output\");\n }\n```"}], "func_name": "verify", "docstring": "Verifies that the current state of the console matches a golden imagine. `bmp_basename`\nindicates the name of the BMP image to use, without an extension.", "repo": "endbasic/endbasic", "path": "sdl/src/console.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/console.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cbea6f25f7f9b095713e250bcc78b627c01ef40e3b403a578c0851bc18c0e6ef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: key_down\n\nDocumentation:\nSynthesizes an `Event::KeyDown` event for a single key press.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn key_down(keycode: Keycode, keymod: Mod) -> Event {\n Event::KeyDown {\n keycode: Some(keycode),\n scancode: None,\n keymod,\n timestamp: 0,\n repeat: false,\n window_id: 0,\n }\n }\n```"}], "func_name": "key_down", "docstring": "Synthesizes an `Event::KeyDown` event for a single key press.", "repo": "endbasic/endbasic", "path": "sdl/src/console.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/console.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25918c0f8af3565df2a4208b9b77c3d786cf62cddfbd2643898d7d76756c87ae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: assert_poll_is_none\n\nDocumentation:\nEnsure the console doesn't return a key press for a brief period of time.\n\nGiven that this is based on timing, the console could still report an event long after\nwe finished polling. This is fine: if the console works well, we shouldn't receive\nspurious events here, which means that under normal conditions, this is not flaky.\nHowever, if there is a bug somewhere, this is not guaranteed to catch it reliably.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn assert_poll_is_none(console: &mut SdlConsole) {\n let mut millis = 10;\n while millis > 0 {\n assert_eq!(None, block_on(console.poll_key()).unwrap());\n thread::sleep(Duration::from_millis(1));\n millis -= 1;\n }\n }\n```"}], "func_name": "assert_poll_is_none", "docstring": "Ensure the console doesn't return a key press for a brief period of time.\n\nGiven that this is based on timing, the console could still report an event long after\nwe finished polling. This is fine: if the console works well, we shouldn't receive\nspurious events here, which means that under normal conditions, this is not flaky.\nHowever, if there is a bug somewhere, this is not guaranteed to catch it reliably.", "repo": "endbasic/endbasic", "path": "sdl/src/console.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/console.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "14214570be4c7d24ab2874855be4c4abe823f2640dfbd54f550dae367297dfa6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: assert_poll_is_key\n\nDocumentation:\nWaits for `console.poll_key` to return `exp_key` and fails the test if it returns any\nother key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn assert_poll_is_key(console: &mut SdlConsole, exp_key: Key) {\n loop {\n match block_on(console.poll_key()).unwrap() {\n Some(key) if key == exp_key => break,\n Some(key) => panic!(\"Unexpected key {:?}\", key),\n None => (),\n }\n thread::sleep(Duration::from_millis(1));\n }\n }\n```"}], "func_name": "assert_poll_is_key", "docstring": "Waits for `console.poll_key` to return `exp_key` and fails the test if it returns any\nother key.", "repo": "endbasic/endbasic", "path": "sdl/src/console.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/console.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "06134988f2ecab2ac2db02810f5de25afffc27a6d84885b52586519c73d1499d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init_error_to_io_error\n\nDocumentation:\nConverts an `InitError` to an `io::Error`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn init_error_to_io_error(e: &'static InitError) -> io::Error {\n match e {\n InitError::AlreadyInitializedError => {\n panic!(\"Initialization from once_cell should happen only once\")\n }\n InitError::InitializationError(e) => io::Error::new(e.kind(), format!(\"{}\", e)),\n }\n}\n```"}], "func_name": "init_error_to_io_error", "docstring": "Converts an `InitError` to an `io::Error`.", "repo": "endbasic/endbasic", "path": "sdl/src/font.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/font.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1db4d316543acd895fed60f65d26e9e0e96611cd310e52bb3b73c6e19c33e2db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: font_error_to_io_error\n\nDocumentation:\nConverts a `FontError` to an `io::Error`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn font_error_to_io_error(e: FontError) -> io::Error {\n let kind = match e {\n FontError::InvalidLatin1Text(_) => io::ErrorKind::InvalidInput,\n FontError::SdlError(_) => io::ErrorKind::Other,\n };\n io::Error::new(kind, e)\n}\n```"}], "func_name": "font_error_to_io_error", "docstring": "Converts a `FontError` to an `io::Error`.", "repo": "endbasic/endbasic", "path": "sdl/src/font.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/font.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f7440ba5790077dff4b7823a0a3636d05321f2b5a70571961b6f126068a6dd87"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load\n\nDocumentation:\nLoads the font from the file `path` with `point_size`. If the loaded font is not\nmonospaced, returns an error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn load(path: &Path, point_size: u16) -> io::Result> {\n let ttf_context = TTF_CONTEXT.as_ref().map_err(init_error_to_io_error)?;\n\n let font = ttf_context.load_font(path, point_size).map_err(string_error_to_io_error)?;\n\n if !font.face_is_fixed_width() {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n format!(\"Font {} is not monospaced\", path.display()),\n ));\n }\n\n let glyph_size = {\n let metrics = match font.find_glyph_metrics('A') {\n Some(metrics) => metrics,\n None => {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n \"Font lacks a glyph for 'A'; is it valid?\",\n ))\n }\n };\n\n let width = match u16::try_from(metrics.advance) {\n Ok(0) => {\n return Err(io::Error::new(io::ErrorKind::InvalidInput, \"Invalid font width 0\"))\n }\n Ok(width) => width,\n Err(e) => {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n format!(\"Invalid font width {}: {}\", metrics.advance, e),\n ))\n }\n };\n\n let height = match u16::try_from(font.height()) {\n Ok(0) => {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n \"Invalid font height 0\",\n ))\n }\n Ok(height) => height,\n Err(e) => {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n format!(\"Invalid font height {}: {}\", font.height(), e),\n ))\n }\n };\n\n SizeInPixels::new(width, height)\n };\n\n Ok(MonospacedFont { font, glyph_size })\n }\n```"}], "func_name": "load", "docstring": "Loads the font from the file `path` with `point_size`. If the loaded font is not\nmonospaced, returns an error.", "repo": "endbasic/endbasic", "path": "sdl/src/font.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/font.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c299726b7a663869248c609fc6a62f902d81ae5b30b88a3181fbf6ff54ae1ac"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: chars_in_area\n\nDocumentation:\nComputes the number of characters that fit within the given pixels `area`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn chars_in_area(&self, area: SizeInPixels) -> CharsXY {\n CharsXY::new(\n area.width\n .checked_div(self.glyph_size.width)\n .expect(\"Glyph size tested for non-zero during init\"),\n area.height\n .checked_div(self.glyph_size.height)\n .expect(\"Glyph size tested for non-zero during init\"),\n )\n }\n```"}], "func_name": "chars_in_area", "docstring": "Computes the number of characters that fit within the given pixels `area`.", "repo": "endbasic/endbasic", "path": "sdl/src/font.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/font.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f3d2ad7d4cbf36bbca707e751f677a979d3d9b694f7647c610dff5284e6ac78b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: texture_value_error_to_io_error\n\nDocumentation:\nConverts a `TextureValueError` to an `io::Error`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn texture_value_error_to_io_error(e: TextureValueError) -> io::Error {\n let kind = match e {\n TextureValueError::HeightOverflows(_)\n | TextureValueError::WidthOverflows(_)\n | TextureValueError::WidthMustBeMultipleOfTwoForFormat(_, _) => io::ErrorKind::InvalidInput,\n TextureValueError::SdlError(_) => io::ErrorKind::Other,\n };\n io::Error::new(kind, e)\n}\n```"}], "func_name": "texture_value_error_to_io_error", "docstring": "Converts a `TextureValueError` to an `io::Error`.", "repo": "endbasic/endbasic", "path": "sdl/src/host.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/host.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d92d852f5ea5e646323672bac0749ad85f6df14214e88d84c9b4e20f159ca235"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_texture_error_to_io_error\n\nDocumentation:\nConverts an `UpdateTextureError` to an `io::Error`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn update_texture_error_to_io_error(e: UpdateTextureError) -> io::Error {\n let kind = match e {\n UpdateTextureError::HeightMustBeMultipleOfTwoForFormat(_, _)\n | UpdateTextureError::PitchMustBeMultipleOfTwoForFormat(_, _)\n | UpdateTextureError::PitchOverflows(_)\n | UpdateTextureError::WidthMustBeMultipleOfTwoForFormat(_, _)\n | UpdateTextureError::XMustBeMultipleOfTwoForFormat(_, _)\n | UpdateTextureError::YMustBeMultipleOfTwoForFormat(_, _) => io::ErrorKind::InvalidInput,\n UpdateTextureError::SdlError(_) => io::ErrorKind::Other,\n };\n io::Error::new(kind, e)\n}\n```"}], "func_name": "update_texture_error_to_io_error", "docstring": "Converts an `UpdateTextureError` to an `io::Error`.", "repo": "endbasic/endbasic", "path": "sdl/src/host.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/host.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "707e8861f0d0e689c86e2cefc8f4411b0216ef9d8296a005d6a88d72401a6179"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: window_build_error_to_io_error\n\nDocumentation:\nConverts a `WindowBuildError` to an `io::Error`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn window_build_error_to_io_error(e: WindowBuildError) -> io::Error {\n let kind = match e {\n WindowBuildError::HeightOverflows(_) | WindowBuildError::WidthOverflows(_) => {\n io::ErrorKind::InvalidInput\n }\n WindowBuildError::InvalidTitle(_) => panic!(\"Hardcoded window title is invalid\"),\n WindowBuildError::SdlError(_) => io::ErrorKind::Other,\n };\n io::Error::new(kind, e)\n}\n```"}], "func_name": "window_build_error_to_io_error", "docstring": "Converts a `WindowBuildError` to an `io::Error`.", "repo": "endbasic/endbasic", "path": "sdl/src/host.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/host.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6c901f58c76a68da47e8175cadedc95a71cd54b4ab53aba7242635bd9d4b3471"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: point_xy\n\nDocumentation:\nConstructs an SDL `Point` from a `PixelsXY`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn point_xy(xy: PixelsXY) -> Point {\n Point::new(i32::from(xy.x), i32::from(xy.y))\n}\n```"}], "func_name": "point_xy", "docstring": "Constructs an SDL `Point` from a `PixelsXY`.", "repo": "endbasic/endbasic", "path": "sdl/src/host.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/host.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ec7b487cde707fe9ba8396362e6a1d58e53eb5f7be96ad9c12021863d266199d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rect_origin_size\n\nDocumentation:\nConstructs an SDL `Rect` from a `PixelsXY` `origin` and a `PixelsSize` `size`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn rect_origin_size(origin: PixelsXY, size: SizeInPixels) -> Rect {\n Rect::new(\n i32::from(origin.x),\n i32::from(origin.y),\n u32::from(size.width),\n u32::from(size.height),\n )\n}\n```"}], "func_name": "rect_origin_size", "docstring": "Constructs an SDL `Rect` from a `PixelsXY` `origin` and a `PixelsSize` `size`.", "repo": "endbasic/endbasic", "path": "sdl/src/host.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/host.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "577dd7b0bce7c6f426a0d326e5766362086fb9a7571d09503ae0bf93db7f98e3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rgb_to_color\n\nDocumentation:\nConverts our own `RGB` type to an SDL `Color`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn rgb_to_color(rgb: RGB) -> Color {\n Color::RGB(rgb.0, rgb.1, rgb.2)\n}\n```"}], "func_name": "rgb_to_color", "docstring": "Converts our own `RGB` type to an SDL `Color`.", "repo": "endbasic/endbasic", "path": "sdl/src/host.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/host.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "061d6e9b956076006d5ab3d7152c17808101b036e3704d624b9e01dfc89d3b75"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_event\n\nDocumentation:\nGiven an SDL `event`, converts it to a `Key` event if it is a key press; otherwise, returns\n`None` for unknown events.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_event(event: Event) -> Option {\n match event {\n Event::Quit { .. } => {\n // TODO(jmmv): This isn't really a key so we should be handling it in some other way.\n // For now, we recognize it here so that closing the window causes the interpreter to\n // exit... but that only works when the interpreter is waiting for input (which means\n // that this also confuses INKEY).\n Some(Key::Eof)\n }\n\n Event::KeyDown { keycode: Some(keycode), keymod, .. } => match keycode {\n Keycode::A if (keymod == Mod::LCTRLMOD || keymod == Mod::RCTRLMOD) => Some(Key::Home),\n Keycode::B if (keymod == Mod::LCTRLMOD || keymod == Mod::RCTRLMOD) => {\n Some(Key::ArrowLeft)\n }\n Keycode::C if (keymod == Mod::LCTRLMOD || keymod == Mod::RCTRLMOD) => {\n Some(Key::Interrupt)\n }\n Keycode::D if (keymod == Mod::LCTRLMOD || keymod == Mod::RCTRLMOD) => Some(Key::Eof),\n Keycode::E if (keymod == Mod::LCTRLMOD || keymod == Mod::RCTRLMOD) => Some(Key::End),\n Keycode::F if (keymod == Mod::LCTRLMOD || keymod == Mod::RCTRLMOD) => {\n Some(Key::ArrowRight)\n }\n Keycode::J if (keymod == Mod::LCTRLMOD || keymod == Mod::RCTRLMOD) => {\n Some(Key::NewLine)\n }\n Keycode::M if (keymod == Mod::LCTRLMOD || keymod == Mod::RCTRLMOD) => {\n Some(Key::NewLine)\n }\n Keycode::N if (keymod == Mod::LCTRLMOD || keymod == Mod::RCTRLMOD) => {\n Some(Key::ArrowDown)\n }\n Keycode::P if (keymod == Mod::LCTRLMOD || keymod == Mod::RCTRLMOD) => {\n Some(Key::ArrowUp)\n }\n\n Keycode::Backspace => Some(Key::Backspace),\n Keycode::End => Some(Key::End),\n Keycode::Escape => Some(Key::Escape),\n Keycode::Home => Some(Key::Home),\n Keycode::Return => Some(Key::NewLine),\n Keycode::Tab => Some(Key::Tab),\n\n Keycode::Down => Some(Key::ArrowDown),\n Keycode::Left => Some(Key::ArrowLeft),\n Keycode::Right => Some(Key::ArrowRight),\n Keycode::Up => Some(Key::ArrowUp),\n\n Keycode::PageDown => Some(Key::PageDown),\n Keycode::PageUp => Some(Key::PageUp),\n\n _ => None,\n },\n\n Event::TextInput { text, .. } => {\n let mut chars = text.chars();\n let first =\n chars.next().unwrap_or_else(|| panic!(\"Cannot handle TextInput event: {:?}\", text));\n Some(Key::Char(first))\n }\n\n _ => None,\n }\n}\n```"}], "func_name": "parse_event", "docstring": "Given an SDL `event`, converts it to a `Key` event if it is a key press; otherwise, returns\n`None` for unknown events.", "repo": "endbasic/endbasic", "path": "sdl/src/host.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/host.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "31c7319610a290f7bb6130ceb804cf3078309985a4ecc35d418c503bcc242677"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nInitializes a new SDL console.\n\nThe console is sized to `resolution` pixels. Also loads the desired font from\n`font_path` at `font_size` and uses it to calculate the size of the console in characters.\n\nThere can only be one active `SdlConsole` at any given time given that this initializes and\nowns the SDL context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(resolution: Resolution, font_path: PathBuf, font_size: u16) -> io::Result {\n let font = MonospacedFont::load(&font_path, font_size)?;\n\n let sdl = sdl2::init().map_err(string_error_to_io_error)?;\n let event_pump = sdl.event_pump().map_err(string_error_to_io_error)?;\n let video = sdl.video().map_err(string_error_to_io_error)?;\n\n video.text_input().start();\n\n let mut title = format!(\"EndBASIC {}\", env!(\"CARGO_PKG_VERSION\"));\n let mut window = match resolution {\n Resolution::FullScreenDesktop => {\n let mut window = video.window(&title, 0, 0);\n window.fullscreen_desktop();\n window\n }\n Resolution::FullScreen(size) => {\n let mut window = video.window(&title, size.0.get(), size.1.get());\n window.fullscreen();\n window\n }\n Resolution::Windowed(size) => {\n let mut window = video.window(&title, size.0.get(), size.1.get());\n window.position_centered();\n window\n }\n }\n .opengl()\n .build()\n .map_err(window_build_error_to_io_error)?;\n\n let size_pixels = {\n let (width, height) = window.drawable_size();\n SizeInPixels::new(width.clamped_into(), height.clamped_into())\n };\n let size_chars = font.chars_in_area(size_pixels);\n\n write!(\n &mut title,\n \" - {}x{} pixels, {}x{} chars\",\n size_pixels.width, size_pixels.height, size_chars.x, size_chars.y\n )\n .map_err(fmt_error_to_io_error)?;\n window.set_title(&title).expect(\"There should have been no NULLs in the formatted title\");\n\n let pixel_format = window.window_pixel_format();\n let surface =\n Surface::new(u32::from(size_pixels.width), u32::from(size_pixels.height), pixel_format)\n .map_err(string_error_to_io_error)?;\n let mut canvas = surface.into_canvas().map_err(string_error_to_io_error)?;\n let texture_creator = canvas.texture_creator();\n\n let draw_color = RGB::default();\n canvas.set_draw_color(rgb_to_color(draw_color));\n\n Ok(Self {\n sdl,\n font,\n event_pump,\n window,\n canvas,\n pixel_format,\n texture_creator,\n size_pixels,\n size_chars,\n draw_color,\n })\n }\n```"}], "func_name": "new", "docstring": "Initializes a new SDL console.\n\nThe console is sized to `resolution` pixels. Also loads the desired font from\n`font_path` at `font_size` and uses it to calculate the size of the console in characters.\n\nThere can only be one active `SdlConsole` at any given time given that this initializes and\nowns the SDL context.", "repo": "endbasic/endbasic", "path": "sdl/src/host.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/host.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6373a7ac6ec29343f1e6f9d299bf7d32881fad44786aa4ae7b0a5eb24afc0a54"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_font\n\nDocumentation:\nGets an instance of the default font.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn default_font() -> io::Result {\n let dir = tempfile::tempdir()?;\n let mut file = File::create(dir.path().join(\"font.ttf\"))?;\n file.write_all(DEFAULT_FONT_BYTES)?;\n Ok(Self { dir })\n }\n```"}], "func_name": "default_font", "docstring": "Gets an instance of the default font.", "repo": "endbasic/endbasic", "path": "sdl/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aca6f79a04ab712c71629fe8f1d10aa4587e4ececaa0c76a3bb6dd45d0bb9b5e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: setup\n\nDocumentation:\nCreates the graphical console based on the given `spec`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn setup(\n spec: &mut ConsoleSpec,\n signals_tx: Sender,\n) -> io::Result>> {\n let resolution: Resolution = spec.take_keyed_flag(\"resolution\")?.unwrap_or_else(|| {\n let width = NonZeroU32::new(DEFAULT_RESOLUTION_PIXELS.0).unwrap();\n let height = NonZeroU32::new(DEFAULT_RESOLUTION_PIXELS.1).unwrap();\n Resolution::Windowed((width, height))\n });\n\n let default_fg_color = spec.take_keyed_flag::(\"fg_color\")?;\n let default_bg_color = spec.take_keyed_flag::(\"bg_color\")?;\n\n let font_path = spec.take_keyed_flag::(\"font_path\")?;\n\n let font_size = spec.take_keyed_flag(\"font_size\")?.unwrap_or(DEFAULT_FONT_SIZE);\n\n let console = match font_path {\n None => {\n let default_font = TempFont::default_font()?;\n console::SdlConsole::new(\n resolution,\n default_fg_color,\n default_bg_color,\n default_font.path(),\n font_size,\n signals_tx,\n )?\n // The console has been created at this point, so it should be safe to drop\n // default_font and clean up the on-disk file backing it up.\n }\n Some(font_path) => console::SdlConsole::new(\n resolution,\n default_fg_color,\n default_bg_color,\n font_path.to_owned(),\n font_size,\n signals_tx,\n )?,\n };\n Ok(Rc::from(RefCell::from(console)))\n}\n```"}], "func_name": "setup", "docstring": "Creates the graphical console based on the given `spec`.", "repo": "endbasic/endbasic", "path": "sdl/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/sdl/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5886abd8a774359ea0e272ac9ef33b10f334b8e8612cd00ef233051fc827e304"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConstructs a new input handler that reads button presses through `pins` and multiplexes them\nwith `keyboard`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(pins: Arc>, keyboard: K) -> io::Result {\n let (on_button_tx, on_button_rx) = async_channel::unbounded();\n\n {\n let mut pins = pins.lock().unwrap();\n for (pin, _key) in INPUT_PINS {\n pins.setup(*pin, PinMode::InPullUp)?;\n }\n }\n\n tokio::task::spawn(async move {\n loop {\n let mut keys = vec![];\n {\n let mut pins = pins.lock().unwrap();\n for (pin, key) in INPUT_PINS {\n match pins.read(*pin) {\n Ok(false) => keys.push(*key),\n Ok(true) => (),\n Err(e) => {\n eprintln!(\"Ignoring button {:?} due to error: {}\", key, e);\n continue;\n }\n };\n }\n }\n\n for key in keys {\n if let Err(e) = on_button_tx.send(key).await {\n eprintln!(\"Ignoring button {:?} due to error: {}\", key, e);\n }\n }\n\n tokio::time::sleep(Duration::from_millis(50)).await;\n }\n });\n\n Ok(Self { on_button_rx, keyboard })\n }\n```"}], "func_name": "new", "docstring": "Constructs a new input handler that reads button presses through `pins` and multiplexes them\nwith `keyboard`.", "repo": "endbasic/endbasic", "path": "st7735s/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/st7735s/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3b2bdb2f8e18f05be482fcf00b3a2abcc0ba09a6e980fa9f6430fa3b6ee5422f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lcd_write\n\nDocumentation:\nWrites arbitrary data to the SPI bus.\n\nThe input data is chunked to respect the maximum write size accepted by the SPI bus.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn lcd_write(spi_bus: &mut B, data: &[u8]) -> io::Result<()> {\n // TODO(jmmv): Do we really need to chunk the data ourselves, or can we try to write it\n // all to the bus and then expect the write to return partial results?\n for chunk in data.chunks(spi_bus.max_size()) {\n let mut i = 0;\n loop {\n let n = spi_bus.write(&chunk[i..])?;\n if n == chunk.len() - i {\n break;\n }\n i += n;\n }\n }\n Ok(())\n}\n```"}], "func_name": "lcd_write", "docstring": "Writes arbitrary data to the SPI bus.\n\nThe input data is chunked to respect the maximum write size accepted by the SPI bus.", "repo": "endbasic/endbasic", "path": "st7735s/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/st7735s/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18ca49e179e690d729a4f17db4adba99f46e2e4715adeeb40be2233442189cbe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lcd_write_reg\n\nDocumentation:\nSelects the registers to affect by the next data write.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn lcd_write_reg(pins: &mut P, spi_bus: &mut B, regs: &[u8]) -> io::Result<()> {\n pins.write(OUTPUT_PIN_DC, false)?;\n lcd_write(spi_bus, regs)\n }\n```"}], "func_name": "lcd_write_reg", "docstring": "Selects the registers to affect by the next data write.", "repo": "endbasic/endbasic", "path": "st7735s/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/st7735s/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b63e4d78740c3b55b8c8079bb8710419ce1c2259015a1c475510dfc80bcf0595"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lcd_write_data\n\nDocumentation:\nWrites data to the device. A register should have been selected before.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn lcd_write_data(pins: &mut P, spi_bus: &mut B, data: &[u8]) -> io::Result<()> {\n pins.write(OUTPUT_PIN_DC, true)?;\n lcd_write(spi_bus, data)\n }\n```"}], "func_name": "lcd_write_data", "docstring": "Writes data to the device. A register should have been selected before.", "repo": "endbasic/endbasic", "path": "st7735s/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/st7735s/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8222419505449b56aedd23864277ab733fa04cd2979fdd5bcb0e8c63abb369aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lcd_set_gram_scan_way\n\nDocumentation:\nInitializes the LCD scan direction and pixel color encoding.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn lcd_set_gram_scan_way(pins: &mut P, spi_bus: &mut B) -> io::Result<()> {\n Self::lcd_write_reg(pins, spi_bus, &[0x36])?; // MX, MY, RGB mode.\n let scan_dir = 0x40 | 0x20; // X, Y.\n let rgb_mode = 0x08; // RGB for 1.44in display.\n Self::lcd_write_data(pins, spi_bus, &[scan_dir | rgb_mode])?;\n Ok(())\n }\n```"}], "func_name": "lcd_set_gram_scan_way", "docstring": "Initializes the LCD scan direction and pixel color encoding.", "repo": "endbasic/endbasic", "path": "st7735s/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/st7735s/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8e774c9457c52393dfcbdc18301c6fa5aef7b79935991069d0a006c16e49280b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lcd_set_window\n\nDocumentation:\nConfigures the LCD so that the next write, which carries pixel data, affects the specified\nregion.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn lcd_set_window(pins: &mut P, spi_bus: &mut B, xy: LcdXY, size: LcdSize) -> io::Result<()> {\n let adjust_x = 1;\n let adjust_y = 2;\n\n let x1 = ((xy.x & 0xff) + adjust_x) as u8;\n let x2 = (((xy.x + size.width) + adjust_x - 1) & 0xff) as u8;\n let y1 = ((xy.y & 0xff) + adjust_y) as u8;\n let y2 = (((xy.y + size.height) + adjust_y - 1) & 0xff) as u8;\n\n Self::lcd_write_reg(pins, spi_bus, &[0x2a])?;\n Self::lcd_write_data(pins, spi_bus, &[0x00, x1, 0x00, x2])?;\n\n Self::lcd_write_reg(pins, spi_bus, &[0x2b])?;\n Self::lcd_write_data(pins, spi_bus, &[0x00, y1, 0x00, y2])?;\n\n Self::lcd_write_reg(pins, spi_bus, &[0x2c])?;\n\n Ok(())\n }\n```"}], "func_name": "lcd_set_window", "docstring": "Configures the LCD so that the next write, which carries pixel data, affects the specified\nregion.", "repo": "endbasic/endbasic", "path": "st7735s/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/st7735s/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "33e5b10781e89f085268b01c5dd4ecbcbeae3af3f40c2f9ef380b8f0a5ee9b35"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance of the function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new() -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"LBOUND\")\n .with_return_type(ExprType::Integer)\n .with_syntax(&[\n (\n &[SingularArgSyntax::RequiredRef(\n RequiredRefSyntax {\n name: Cow::Borrowed(\"array\"),\n require_array: true,\n define_undefined: false,\n },\n ArgSepSyntax::End,\n )],\n None,\n ),\n (\n &[\n SingularArgSyntax::RequiredRef(\n RequiredRefSyntax {\n name: Cow::Borrowed(\"array\"),\n require_array: true,\n define_undefined: false,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"dimension\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::End,\n ),\n ],\n None,\n ),\n ])\n .with_category(CATEGORY)\n .with_description(\n \"Returns the lower bound for the given dimension of the array.\nThe lower bound is the smallest available subscript that can be provided to array indexing \\\noperations.\nFor one-dimensional arrays, the dimension% is optional. For multi-dimensional arrays, the \\\ndimension% is a 1-indexed integer.\",\n )\n .build(),\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance of the function.", "repo": "endbasic/endbasic", "path": "std/src/arrays.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/arrays.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18047c7c7029bb33cb43efae3194f34fc422ae2e8badf044c3f49f66e1e06cd8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_all\n\nDocumentation:\nAdds all symbols provided by this module to the given `machine`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_all(machine: &mut Machine) {\n machine.add_callable(LboundFunction::new());\n machine.add_callable(UboundFunction::new());\n}\n```"}], "func_name": "add_all", "docstring": "Adds all symbols provided by this module to the given `machine`.", "repo": "endbasic/endbasic", "path": "std/src/arrays.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/arrays.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "38fbb15ba828564a7a543b983eb2bdfbf6c1bc1f6eac950af8f83db338b44da0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_bound_errors_test\n\nDocumentation:\nValidates error handling of `LBOUND` and `UBOUND` as given in `func`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_bound_errors_test(func: &str) {\n Tester::default()\n .run(format!(\"DIM x(2): result = {}()\", func))\n .expect_compilation_err(format!(\n \"1:20: {} expected | \",\n func\n ))\n .check();\n\n Tester::default()\n .run(format!(\"DIM x(2): result = {}(x, 1, 2)\", func))\n .expect_compilation_err(format!(\n \"1:20: {} expected | \",\n func\n ))\n .check();\n\n Tester::default()\n .run(format!(\"DIM x(2): result = {}(x, -1)\", func))\n .expect_err(\"1:30: Dimension -1 must be positive\")\n .expect_array(\"x\", ExprType::Integer, &[2], vec![])\n .check();\n\n Tester::default()\n .run(format!(\"DIM x(2): result = {}(x, TRUE)\", func))\n .expect_compilation_err(\"1:30: BOOLEAN is not a number\")\n .check();\n\n Tester::default()\n .run(format!(\"i = 0: result = {}(i)\", func))\n .expect_compilation_err(\"1:24: Requires a reference, not a value\")\n .check();\n\n Tester::default()\n .run(format!(\"result = {}(3)\", func))\n .expect_compilation_err(\"1:17: Requires a reference, not a value\")\n .check();\n\n Tester::default()\n .run(format!(\"i = 0: result = {}(i)\", func))\n .expect_compilation_err(\"1:24: Requires a reference, not a value\")\n .check();\n\n Tester::default()\n .run(format!(\"DIM i(3) AS BOOLEAN: result = {}(i$)\", func))\n .expect_compilation_err(\"1:38: Incompatible type annotation in i$ reference\")\n .check();\n\n Tester::default()\n .run(format!(\"result = {}(x)\", func))\n .expect_compilation_err(\"1:17: Undefined symbol X\")\n .check();\n\n Tester::default()\n .run(format!(\"DIM x(2, 3, 4): result = {}(x)\", func))\n .expect_err(\"1:33: Requires a dimension for multidimensional arrays\")\n .expect_array(\"x\", ExprType::Integer, &[2, 3, 4], vec![])\n .check();\n\n Tester::default()\n .run(format!(\"DIM x(2, 3, 4): result = {}(x, 5)\", func))\n .expect_err(\"1:36: Array X has only 3 dimensions but asked for 5\")\n .expect_array(\"x\", ExprType::Integer, &[2, 3, 4], vec![])\n .check();\n }\n```"}], "func_name": "do_bound_errors_test", "docstring": "Validates error handling of `LBOUND` and `UBOUND` as given in `func`.", "repo": "endbasic/endbasic", "path": "std/src/arrays.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/arrays.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "198e484eb9a0afa44ad7bdb3339c33fe26bf7179755c0599345339712a721712"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_all\n\nDocumentation:\nInstantiates all symbols in this module and adds them to the `machine`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_all(machine: &mut Machine) {\n let index = Rc::from(RefCell::from(0));\n machine.add_clearable(Box::from(ClearableIndex(index.clone())));\n machine.add_callable(ReadCommand::new(index.clone()));\n machine.add_callable(RestoreCommand::new(index));\n}\n```"}], "func_name": "add_all", "docstring": "Instantiates all symbols in this module and adds them to the `machine`.", "repo": "endbasic/endbasic", "path": "std/src/data.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "283de925cc5b08ba00cb329077396e4b80819d01554254dd506e0ba7f21be8e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `CLEAR` command that resets the state of the machine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new() -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"CLEAR\")\n .with_syntax(&[(&[], None)])\n .with_category(CATEGORY)\n .with_description(\n \"Restores initial machine state but keeps the stored program.\nThis command resets the machine to a semi-pristine state by clearing all user-defined variables \\\nand restoring the state of shared resources. These resources include: the console, whose color \\\nand video syncing bit are reset; and the GPIO pins, which are set to their default state.\nThe stored program is kept in memory. To clear that too, use NEW (but don't forget to first \\\nSAVE your program!).\nThis command is for interactive use only.\",\n )\n .build(),\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `CLEAR` command that resets the state of the machine.", "repo": "endbasic/endbasic", "path": "std/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ae93dce8b2f4fdc7aa8bad92ac656f92aa62a3464edb5acbfb6601a008747e37"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: system_sleep\n\nDocumentation:\nAn implementation of a `SleepFn` that stops the current thread.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn system_sleep(d: Duration, _pos: LineCol) -> BoxedLocal> {\n async move {\n thread::sleep(d);\n Ok(())\n }\n .boxed_local()\n}\n```"}], "func_name": "system_sleep", "docstring": "An implementation of a `SleepFn` that stops the current thread.", "repo": "endbasic/endbasic", "path": "std/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2cb8e25efe72158f7d0b935d2d61a718724b927e6fe6b5ea3db39249bec863c9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance of the command.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(sleep_fn: SleepFn) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"SLEEP\")\n .with_syntax(&[(\n &[SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"seconds\"),\n vtype: ExprType::Double,\n },\n ArgSepSyntax::End,\n )],\n None,\n )])\n .with_category(CATEGORY)\n .with_description(\n \"Suspends program execution.\nPauses program execution for the given number of seconds, which can be specified either as an \\\ninteger or as a floating point number for finer precision.\",\n )\n .build(),\n sleep_fn,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance of the command.", "repo": "endbasic/endbasic", "path": "std/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "22a161aad118293fa1184d1c8e46115dba684a1da914b8ee55b6b5ccf87b86e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_scripting\n\nDocumentation:\nInstantiates all REPL commands for the scripting machine and adds them to the `machine`.\n\n`sleep_fn` is an async function that implements a pause given a `Duration`. If not provided,\nuses the `std::thread::sleep` function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_scripting(machine: &mut Machine, sleep_fn: Option) {\n machine.add_callable(ErrmsgFunction::new());\n machine.add_callable(SleepCommand::new(sleep_fn.unwrap_or_else(|| Box::from(system_sleep))));\n}\n```"}], "func_name": "add_scripting", "docstring": "Instantiates all REPL commands for the scripting machine and adds them to the `machine`.\n\n`sleep_fn` is an async function that implements a pause given a `Duration`. If not provided,\nuses the `std::thread::sleep` function.", "repo": "endbasic/endbasic", "path": "std/src/exec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ec3dd07deed3ebb3b306f532e6f20d242f401759968edd29ef6a6f3fde06b6e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: header\n\nDocumentation:\nReturns the header for the help summary.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn header() -> Vec {\n vec![\n \"\".to_owned(),\n format!(\" This is EndBASIC {}.\", env!(\"CARGO_PKG_VERSION\")),\n \"\".to_owned(),\n format!(\" Project page at <{}>\", env!(\"CARGO_PKG_HOMEPAGE\")),\n \" License Apache Version 2.0 \".to_owned(),\n ]\n}\n```"}], "func_name": "header", "docstring": "Returns the header for the help summary.", "repo": "endbasic/endbasic", "path": "std/src/help.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/help.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f7a9b768a48a9db755c8fec5cad182ada115fba21b4cebf618307a13a5315f8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: callables_to_index\n\nDocumentation:\nGenerates the index for a collection of `CallableMetadata`s to use in a `CategoryTopic`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn callables_to_index(metadatas: &[CallableMetadata]) -> BTreeMap {\n let category = metadatas.first().expect(\"Must have at least one symbol\").category();\n\n let mut index = BTreeMap::default();\n for metadata in metadatas {\n debug_assert_eq!(\n category,\n metadata.category(),\n \"All commands registered in this category must be equivalent\"\n );\n let name = match metadata.return_type() {\n None => metadata.name().to_owned(),\n Some(return_type) => format!(\"{}{}\", metadata.name(), return_type.annotation()),\n };\n let blurb = metadata.description().next().unwrap();\n let previous = index.insert(name, blurb);\n assert!(previous.is_none(), \"Names should have been unique\");\n }\n index\n}\n```"}], "func_name": "callables_to_index", "docstring": "Generates the index for a collection of `CallableMetadata`s to use in a `CategoryTopic`.", "repo": "endbasic/endbasic", "path": "std/src/help.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/help.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0de62e1284f60aa08b2c96f91de3b820f11d6b0547625918057e654e2837f213"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_lang_reference\n\nDocumentation:\nParses the `lang.md` file and extracts a mapping of language reference topics to their\ndescriptions.\n\nNote that, even if the input looks like Markdown, we do *not* implement a Markdown parser here.\nThe structure of the file is strict and well-known in advance, so this will panic if there are\nproblems in the input data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_lang_reference(lang_md: &'static str) -> Vec<(&'static str, &'static str)> {\n let mut topics = vec![];\n\n // Cope with Windows checkouts. It's tempting to make this a build-time conditional on the OS\n // name, but we don't know how the files are checked out. Assume CRLF delimiters if we see at\n // least one of them.\n let line_end;\n let section_start;\n let body_start;\n if lang_md.contains(\"\\r\\n\") {\n line_end = \"\\r\\n\";\n section_start = \"\\r\\n\\r\\n# \";\n body_start = \"\\r\\n\\r\\n\";\n } else {\n line_end = \"\\n\";\n section_start = \"\\n\\n# \";\n body_start = \"\\n\\n\";\n }\n\n for (start, _match) in lang_md.match_indices(section_start) {\n let section = &lang_md[start + section_start.len()..];\n\n let title_end = section.find(body_start).expect(\"Hardcoded text must be valid\");\n let title = §ion[..title_end];\n let section = §ion[title_end + body_start.len()..];\n\n let end = section.find(section_start).unwrap_or_else(|| {\n if section.ends_with(line_end) {\n section.len() - line_end.len()\n } else {\n section.len()\n }\n });\n let content = §ion[..end];\n topics.push((title, content));\n }\n\n topics\n}\n```"}], "func_name": "parse_lang_reference", "docstring": "Parses the `lang.md` file and extracts a mapping of language reference topics to their\ndescriptions.\n\nNote that, even if the input looks like Markdown, we do *not* implement a Markdown parser here.\nThe structure of the file is strict and well-known in advance, so this will panic if there are\nproblems in the input data.", "repo": "endbasic/endbasic", "path": "std/src/help.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/help.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "df5e97c6642ceee0ffbda692084fca9dc3b67d7079cf2d7b996f46bd5699a1f2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nBuilds an index of the given `symbols` and returns a new collection of help topics.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(symbols: &Symbols) -> Self {\n fn insert(topics: &mut Trie>, topic: Box) {\n let key = topic.name().to_ascii_uppercase();\n topics.insert(key, topic);\n }\n\n let mut topics = Trie::default();\n\n {\n let mut index = BTreeMap::default();\n\n for (title, content) in parse_lang_reference(LANG_MD) {\n let topic = LanguageTopic { name: title, text: content };\n index.insert(topic.name.to_owned(), topic.text.lines().next().unwrap());\n insert(&mut topics, Box::from(topic));\n }\n\n insert(\n &mut topics,\n Box::from(CategoryTopic {\n name: \"Language reference\",\n description: \"General language topics\",\n index,\n }),\n );\n }\n\n let mut categories = HashMap::new();\n for (name, symbol) in symbols.callables().iter() {\n let metadata = symbol.metadata();\n let category_title = metadata.category().lines().next().unwrap();\n categories.entry(category_title).or_insert_with(Vec::default).push(metadata.clone());\n\n let name = match metadata.return_type() {\n None => metadata.name().to_owned(),\n Some(return_type) => format!(\"{}{}\", name, return_type.annotation()),\n };\n\n insert(&mut topics, Box::from(CallableTopic { name, metadata: metadata.clone() }));\n }\n for (name, metadatas) in categories.into_iter() {\n let description = metadatas.first().expect(\"Must have at least one symbol\").category();\n let index = callables_to_index(&metadatas);\n insert(&mut topics, Box::from(CategoryTopic { name, description, index }));\n }\n\n Self(topics)\n }\n```"}], "func_name": "new", "docstring": "Builds an index of the given `symbols` and returns a new collection of help topics.", "repo": "endbasic/endbasic", "path": "std/src/help.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/help.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d819219fc9549daf2c896ebe30e8dc5cb62e835079b34db1ec270e914ced18c3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: find\n\nDocumentation:\nReturns the given topic named `name`, where `name` can be a prefix.\n\nIf `name` is not long enough to uniquely identify a topic or if the topic does not exist,\nreturns an error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn find(&self, name: &str, pos: LineCol) -> Result<&dyn Topic> {\n let key = name.to_ascii_uppercase();\n\n if let Some(topic) = self.0.get(&key) {\n return Ok(topic.as_ref());\n }\n\n match self.0.get_raw_descendant(&key) {\n Some(subtrie) => {\n let children: Vec<(&String, &Box)> = subtrie.iter().collect();\n match children[..] {\n [(_name, topic)] => Ok(topic.as_ref()),\n _ => {\n let completions: Vec =\n children.iter().map(|(name, _topic)| (*name).to_owned()).collect();\n Err(Error::SyntaxError(\n pos,\n format!(\n \"Ambiguous help topic {}; candidates are: {}\",\n name,\n completions.join(\", \")\n ),\n ))\n }\n }\n }\n None => Err(Error::SyntaxError(pos, format!(\"Unknown help topic {}\", name))),\n }\n }\n```"}], "func_name": "find", "docstring": "Returns the given topic named `name`, where `name` can be a prefix.\n\nIf `name` is not long enough to uniquely identify a topic or if the topic does not exist,\nreturns an error.", "repo": "endbasic/endbasic", "path": "std/src/help.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/help.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51a96225e8754489e1b21d6483dc84f00532e3544f69a2c921467f3b9cbfc891"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new command that writes help messages to `output`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"HELP\")\n .with_syntax(&[\n (&[], None),\n (\n &[SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"topic\"),\n vtype: ExprType::Text,\n },\n ArgSepSyntax::End,\n )],\n None,\n ),\n ])\n .with_category(CATEGORY)\n .with_description(\n \"Prints interactive help.\nWithout arguments, shows a summary of all available top-level help topics.\nWith a single argument, which must be a string, shows detailed information about the given help \\\ntopic, command, or function.\nTopic names are case-insensitive and can be specified as prefixes, in which case the topic whose \\\nname starts with the prefix will be shown. For example, the following invocations are all \\\nequivalent: HELP \\\"CON\\\", HELP \\\"console\\\", HELP \\\"Console manipulation\\\".\",\n )\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new command that writes help messages to `output`.", "repo": "endbasic/endbasic", "path": "std/src/help.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/help.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ef41be5b5a3c53b7657c6e91ae70a31827882a3a8486dfac33a23c230985af0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: summary\n\nDocumentation:\nPrints a summary of all available help topics.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn summary(&self, topics: &Topics, pager: &mut Pager<'_>) -> io::Result<()> {\n for line in header() {\n refill_and_page(pager, [&line], \"\").await?;\n }\n\n let previous = pager.color();\n\n pager.print(\"\").await?;\n pager.set_color(Some(TITLE_COLOR), previous.1)?;\n refill_and_page(pager, [\"Top-level help topics\"], \" \").await?;\n pager.set_color(previous.0, previous.1)?;\n pager.print(\"\").await?;\n for topic in topics.values() {\n if topic.show_in_summary() {\n // TODO(jmmv): Should use refill_and_page but continuation lines need special\n // handling to be indented properly.\n pager.write(\" >> \")?;\n pager.set_color(Some(LINK_COLOR), previous.1)?;\n pager.print(topic.title()).await?;\n pager.set_color(previous.0, previous.1)?;\n }\n }\n pager.print(\"\").await?;\n refill_and_page(pager, [\"Type HELP followed by the name of a topic for details.\"], \" \")\n .await?;\n refill_and_page(\n pager,\n [\"Type HELP \\\"HELP\\\" for details on how to specify topic names.\"],\n \" \",\n )\n .await?;\n refill_and_page(pager, [r#\"Type LOAD \"DEMOS:/TOUR.BAS\": RUN for a guided tour.\"#], \" \")\n .await?;\n refill_and_page(pager, [r#\"Type END or press CTRL+D to exit.\"#], \" \").await?;\n pager.print(\"\").await?;\n\n Ok(())\n }\n```"}], "func_name": "summary", "docstring": "Prints a summary of all available help topics.", "repo": "endbasic/endbasic", "path": "std/src/help.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/help.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ecae0d19824c7e85ca0ddb9e3d896201d03206b8cad7267bcc9b7346f725ad00"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_with_name\n\nDocumentation:\nCreates a new instance of the command with a given `name`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_with_name(name: &'static str) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(name)\n .with_syntax(&[(\n &[SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"sample\"),\n vtype: ExprType::Text,\n },\n ArgSepSyntax::End,\n )],\n None,\n )])\n .with_category(\n \"Testing\nThis is a sample category for testing.\",\n )\n .with_description(\n \"This is the blurb.\nFirst paragraph of the extended description.\nSecond paragraph of the extended description.\",\n )\n .build(),\n })\n }\n```"}], "func_name": "new_with_name", "docstring": "Creates a new instance of the command with a given `name`.", "repo": "endbasic/endbasic", "path": "std/src/help.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/help.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94652aa92a94816e15899ef27bc1bef61b87097e5e529f6f0f915b6c806370ee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_with_name\n\nDocumentation:\nCreates a new instance of the function with a given `name`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new_with_name(name: &'static str) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(name)\n .with_return_type(ExprType::Text)\n .with_syntax(&[(\n &[SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"sample\"),\n vtype: ExprType::Text,\n },\n ArgSepSyntax::End,\n )],\n None,\n )])\n .with_category(\n \"Testing\nThis is a sample category for testing.\",\n )\n .with_description(\n \"This is the blurb.\nFirst paragraph of the extended description.\nSecond paragraph of the extended description.\",\n )\n .build(),\n })\n }\n```"}], "func_name": "new_with_name", "docstring": "Creates a new instance of the function with a given `name`.", "repo": "endbasic/endbasic", "path": "std/src/help.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/help.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6de958ec5378528cbc83aaa4778e0ae179adeaebbe16676e867da24a067beedc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_console\n\nDocumentation:\nOverrides the default terminal-based console with the given one.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_console(mut self, console: Rc>) -> Self {\n self.console = Some(console);\n self\n }\n```"}], "func_name": "with_console", "docstring": "Overrides the default terminal-based console with the given one.", "repo": "endbasic/endbasic", "path": "std/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3099f425d641ca13998c64b86251fec4e6d6f6d757ac6c4a2c44eb7b86b0020f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_gpio_pins\n\nDocumentation:\nOverrides the default hardware-based GPIO pins with the given ones.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_gpio_pins(mut self, pins: Rc>) -> Self {\n self.gpio_pins = Some(pins);\n self\n }\n```"}], "func_name": "with_gpio_pins", "docstring": "Overrides the default hardware-based GPIO pins with the given ones.", "repo": "endbasic/endbasic", "path": "std/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "567ac07ead25970ce62b9c5c17caec7e4a3811008fcc09b0c1685d3ade00d222"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_sleep_fn\n\nDocumentation:\nOverrides the default sleep function with the given one.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_sleep_fn(mut self, sleep_fn: exec::SleepFn) -> Self {\n self.sleep_fn = Some(sleep_fn);\n self\n }\n```"}], "func_name": "with_sleep_fn", "docstring": "Overrides the default sleep function with the given one.", "repo": "endbasic/endbasic", "path": "std/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "67a4238bace7bc6f80d32e97f25d615f92033a6f22bf57052f23c87a9ce5915f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_yield_now_fn\n\nDocumentation:\nOverrides the default yielding function with the given one.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_yield_now_fn(mut self, yield_now_fn: YieldNowFn) -> Self {\n self.yield_now_fn = Some(yield_now_fn);\n self\n }\n```"}], "func_name": "with_yield_now_fn", "docstring": "Overrides the default yielding function with the given one.", "repo": "endbasic/endbasic", "path": "std/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b728b6d52d2f398a557fb879590ff0976cbc85519409a3f71e088635900b09e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_signals_chan\n\nDocumentation:\nOverrides the default signals channel with the given one.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_signals_chan(mut self, chan: (Sender, Receiver)) -> Self {\n self.signals_chan = Some(chan);\n self\n }\n```"}], "func_name": "with_signals_chan", "docstring": "Overrides the default signals channel with the given one.", "repo": "endbasic/endbasic", "path": "std/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "29d5a2bb1ff253c1ed1f1695bf5d7e63446aa6cf49c76995a819b66d043d0619"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_console\n\nDocumentation:\nLazily initializes the `console` field with a default value and returns it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_console(&mut self) -> Rc> {\n if self.console.is_none() {\n self.console = Some(Rc::from(RefCell::from(console::TrivialConsole::default())));\n }\n self.console.clone().unwrap()\n }\n```"}], "func_name": "get_console", "docstring": "Lazily initializes the `console` field with a default value and returns it.", "repo": "endbasic/endbasic", "path": "std/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bd6f7ea0971458c1be29e6dd46c75cf5940a513d4e79971df4eb59c5c45d9b2b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_gpio_pins\n\nDocumentation:\nLazily initializes the `gpio_pins` field with a default value and returns it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_gpio_pins(&mut self) -> Rc> {\n if self.gpio_pins.is_none() {\n self.gpio_pins = Some(Rc::from(RefCell::from(gpio::NoopPins::default())))\n }\n self.gpio_pins.as_ref().expect(\"Must have been initialized above\").clone()\n }\n```"}], "func_name": "get_gpio_pins", "docstring": "Lazily initializes the `gpio_pins` field with a default value and returns it.", "repo": "endbasic/endbasic", "path": "std/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fce7e5205b1d4b8050c0900041c74e6c68d3dfe1cdf1891902498eef67090e97"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nConstructs an interactive machine builder from a non-interactive builder.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from(builder: MachineBuilder) -> Self {\n let storage = Rc::from(RefCell::from(storage::Storage::default()));\n InteractiveMachineBuilder { builder, program: None, storage }\n }\n```"}], "func_name": "from", "docstring": "Constructs an interactive machine builder from a non-interactive builder.", "repo": "endbasic/endbasic", "path": "std/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9cfe7da87cbcb474eddf42d58b8813f54f3ab86a904ce6df889ffebe725d5c19"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_program\n\nDocumentation:\nLazily initializes the `program` field with a default value and returns it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_program(&mut self) -> Rc> {\n if self.program.is_none() {\n self.program = Some(Rc::from(RefCell::from(program::ImmutableProgram::default())));\n }\n self.program.clone().unwrap()\n }\n```"}], "func_name": "get_program", "docstring": "Lazily initializes the `program` field with a default value and returns it.", "repo": "endbasic/endbasic", "path": "std/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "caa75c344eaafa9a83b5c99f454ee3e74fdf63825c343e30024484ead366d312"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_program\n\nDocumentation:\nOverrides the default stored program with the given one.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_program(mut self, program: Rc>) -> Self {\n self.program = Some(program);\n self\n }\n```"}], "func_name": "with_program", "docstring": "Overrides the default stored program with the given one.", "repo": "endbasic/endbasic", "path": "std/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ea3cf294e5a807ede0f7a2a27ffc94a3da35bf9632a852e93c2f239b7e08c26"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_angle\n\nDocumentation:\nGets the single argument to a trigonometric function, which is its angle. Applies units\nconversion based on `angle_mode`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn get_angle(scope: &mut Scope<'_>, angle_mode: &AngleMode) -> Result {\n debug_assert_eq!(1, scope.nargs());\n let angle = scope.pop_double();\n\n match angle_mode {\n AngleMode::Degrees => Ok(angle.to_radians()),\n AngleMode::Radians => Ok(angle),\n }\n}\n```"}], "func_name": "get_angle", "docstring": "Gets the single argument to a trigonometric function, which is its angle. Applies units\nconversion based on `angle_mode`.", "repo": "endbasic/endbasic", "path": "std/src/numerics.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/numerics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4453edb0576a58c13ee1dcc211a8701b0e8a2ca2f41b260ae4bb15b1eaa1a3a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_from_entryopy\n\nDocumentation:\nGenerates a new PRNG based on system entropy.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_from_entryopy() -> Self {\n let mut prng = SmallRng::from_entropy();\n let last = prng.next_u32();\n Self { prng, last }\n }\n```"}], "func_name": "new_from_entryopy", "docstring": "Generates a new PRNG based on system entropy.", "repo": "endbasic/endbasic", "path": "std/src/numerics.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/numerics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "260412cbd2b776fd4df90bbb80fc583b8341b4a2aa5ec1a282394f4274c3fede"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_from_seed\n\nDocumentation:\nGenerates a new PRNG based on the given seed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_from_seed(seed: i32) -> Self {\n let mut prng = SmallRng::seed_from_u64(seed as u64);\n let last = prng.next_u32();\n Self { prng, last }\n }\n```"}], "func_name": "new_from_seed", "docstring": "Generates a new PRNG based on the given seed.", "repo": "endbasic/endbasic", "path": "std/src/numerics.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/numerics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3db75e3f5e5b13c6f3fcbe226ec14dba523d962bc6b7cd8b3aad8547fab6da81"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: last\n\nDocumentation:\nReturns the previously returned random number.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn last(&self) -> f64 {\n (self.last as f64) / (u32::MAX as f64)\n }\n```"}], "func_name": "last", "docstring": "Returns the previously returned random number.", "repo": "endbasic/endbasic", "path": "std/src/numerics.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/numerics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "33be19fa978e9eaf84b67c3b32e0f7519a1b636720c3f174f94d1c0a31f0299f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next\n\nDocumentation:\nComputes the next random number and returns it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn next(&mut self) -> f64 {\n self.last = self.prng.next_u32();\n self.last()\n }\n```"}], "func_name": "next", "docstring": "Computes the next random number and returns it.", "repo": "endbasic/endbasic", "path": "std/src/numerics.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/numerics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ccea37a13202181f309426d077f1ab2c06f5643ccc26ede97d82655997545ba9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new command that updates `code` with the exit code once called.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(prng: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"RANDOMIZE\")\n .with_syntax(&[\n (&[], None),\n (\n &[SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"seed\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::End,\n )],\n None,\n ),\n ])\n .with_category(CATEGORY)\n .with_description(\n \"Reinitializes the pseudo-random number generator.\nIf no seed is given, uses system entropy to create a new sequence of random numbers.\nWARNING: These random numbers offer no cryptographic guarantees.\",\n )\n .build(),\n prng,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new command that updates `code` with the exit code once called.", "repo": "endbasic/endbasic", "path": "std/src/numerics.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/numerics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0783b8e36ae5af7b88462c0b82935fe10ef09b0634db2cb0ed12160843ea7a0f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: continue_if_modified\n\nDocumentation:\nIf the `program` is dirty, asks if it's OK to continue on `console` and discard its changes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn continue_if_modified(\n program: &dyn Program,\n console: &mut dyn Console,\n) -> io::Result {\n if !program.is_dirty() {\n return Ok(true);\n }\n\n match program.name() {\n Some(name) => console.print(&format!(\"Current program {} has unsaved changes!\", name))?,\n None => console.print(\"Current program has unsaved changes and has never been saved!\")?,\n }\n let answer = read_line(console, \"Discard and continue (y/N)? \", \"\", None).await?;\n Ok(parse_boolean(&answer).unwrap_or(false))\n}\n```"}], "func_name": "continue_if_modified", "docstring": "If the `program` is dirty, asks if it's OK to continue on `console` and discard its changes.", "repo": "endbasic/endbasic", "path": "std/src/program.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/program.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf68ac670627ecd50a80d0e7486a8998e5b96bb8ab9714c488dfc8e6ea15ae4c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `DISASM` command that dumps the disassembled version of the program.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>, program: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"DISASM\")\n .with_syntax(&[(&[], None)])\n .with_category(CATEGORY)\n .with_description(\n \"Disassembles the stored program.\nThe assembly code printed by this command is provided as a tool to understand how high level code \\\ngets translated to the machine code of a fictitious stack-based machine. Note, however, that the \\\nassembly code cannot be reassembled nor modified at this point.\",\n )\n .build(),\n console,\n program,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `DISASM` command that dumps the disassembled version of the program.", "repo": "endbasic/endbasic", "path": "std/src/program.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/program.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dea735e5e1746a14593d0c32fdfa8fcfad88c04b742c2f4ef3c35d085c167f18"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `EDIT` command that edits the stored `program` in the `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>, program: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"EDIT\")\n .with_syntax(&[(&[], None)])\n .with_category(CATEGORY)\n .with_description(\"Interactively edits the stored program.\")\n .build(),\n console,\n program,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `EDIT` command that edits the stored `program` in the `console`.", "repo": "endbasic/endbasic", "path": "std/src/program.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/program.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca2b3e6d1b5d67f8abc858c1326570e7c2227bc4c6531986b46cf798d511f95c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `LIST` command that dumps the `program` to the `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>, program: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"LIST\")\n .with_syntax(&[(&[], None)])\n .with_category(CATEGORY)\n .with_description(\"Prints the currently-loaded program.\")\n .build(),\n console,\n program,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `LIST` command that dumps the `program` to the `console`.", "repo": "endbasic/endbasic", "path": "std/src/program.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/program.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "366017c5d01a873de8be88d5e703b564ae7514127cfdc8f401a12363b1051232"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `LOAD` command that loads a program from `storage` into `program` and that\nuses `console` to communicate unsaved changes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n console: Rc>,\n storage: Rc>,\n program: Rc>,\n ) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"LOAD\")\n .with_syntax(&[(\n &[SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"filename\"),\n vtype: ExprType::Text,\n },\n ArgSepSyntax::End,\n )],\n None,\n )])\n .with_category(CATEGORY)\n .with_description(\n \"Loads the given program.\nThe filename must be a string and must be a valid EndBASIC path. The .BAS extension is optional \\\nbut, if present, it must be .BAS.\nAny previously stored program is discarded from memory, but LOAD will pause to ask before \\\ndiscarding any unsaved modifications.\nSee the \\\"File system\\\" help topic for information on the path syntax.\",\n )\n .build(),\n console,\n storage,\n program,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `LOAD` command that loads a program from `storage` into `program` and that\nuses `console` to communicate unsaved changes.", "repo": "endbasic/endbasic", "path": "std/src/program.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/program.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44aecd6f560fbdcad753cf1ae225f52082e69f1798b455f11638b9698e37ff17"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `NEW` command that clears the contents of `program` and that uses `console`\nto communicate unsaved changes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>, program: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"NEW\")\n .with_syntax(&[(&[], None)])\n .with_category(CATEGORY)\n .with_description(\n \"Restores initial machine state and creates a new program.\nThis command resets the machine to a pristine state by clearing all user-defined variables \\\nand restoring the state of shared resources. These resources include: the console, whose color \\\nand video syncing bit are reset; and the GPIO pins, which are set to their default state.\nThe stored program is also discarded from memory, but NEW will pause to ask before discarding \\\nany unsaved modifications. To reset resources but avoid clearing the stored program, use CLEAR \\\ninstead.\",\n )\n .build(),\n console,\n program,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `NEW` command that clears the contents of `program` and that uses `console`\nto communicate unsaved changes.", "repo": "endbasic/endbasic", "path": "std/src/program.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/program.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e0d10078c7323dfcbd8709134a287fd1bae0fe0650870c2f8640893d953d866"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `RUN` command that executes the `program`.\n\nReports any non-successful return codes from the program to the console.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>, program: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"RUN\")\n .with_syntax(&[(&[], None)])\n .with_category(CATEGORY)\n .with_description(\n \"Runs the stored program.\nThis issues a CLEAR operation before starting the program to prevent previous leftover state \\\nfrom interfering with the new execution.\",\n )\n .build(),\n console,\n program,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `RUN` command that executes the `program`.\n\nReports any non-successful return codes from the program to the console.", "repo": "endbasic/endbasic", "path": "std/src/program.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/program.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "75cb01a6e3c82007ef9cd586a92d49d01bf149b08ec9cf8a76cf03e03bce797d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `SAVE` command that saves the contents of the `program` into `storage`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n console: Rc>,\n storage: Rc>,\n program: Rc>,\n ) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"SAVE\")\n .with_syntax(&[\n (&[], None),\n (\n &[SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"filename\"),\n vtype: ExprType::Text,\n },\n ArgSepSyntax::End,\n )],\n None,\n ),\n ])\n .with_category(CATEGORY)\n .with_description(\n \"Saves the current program in memory to the given filename.\nThe filename must be a string and must be a valid EndBASIC path. The .BAS extension is optional \\\nbut, if present, it must be .BAS.\nIf no filename is given, SAVE will try to use the filename of the loaded program (if any) and \\\nwill fail if no name has been given yet.\nSee the \\\"File system\\\" help topic for information on the path syntax.\",\n )\n .build(),\n console,\n storage,\n program,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `SAVE` command that saves the contents of the `program` into `storage`.", "repo": "endbasic/endbasic", "path": "std/src/program.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/program.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e24258d6a0c45c614cb4d75479795971b56b86eadb401fa643650c5f98f03127"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_all\n\nDocumentation:\nAdds all program editing commands against the stored `program` to the `machine`, using\n`console` for interactive editing and using `storage` as the on-disk storage for the programs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_all(\n machine: &mut Machine,\n program: Rc>,\n console: Rc>,\n storage: Rc>,\n) {\n machine.add_callable(DisasmCommand::new(console.clone(), program.clone()));\n machine.add_callable(EditCommand::new(console.clone(), program.clone()));\n machine.add_callable(ListCommand::new(console.clone(), program.clone()));\n machine.add_callable(LoadCommand::new(console.clone(), storage.clone(), program.clone()));\n machine.add_callable(NewCommand::new(console.clone(), program.clone()));\n machine.add_callable(RunCommand::new(console.clone(), program.clone()));\n machine.add_callable(SaveCommand::new(console, storage, program));\n}\n```"}], "func_name": "add_all", "docstring": "Adds all program editing commands against the stored `program` to the `machine`, using\n`console` for interactive editing and using `storage` as the on-disk storage for the programs.", "repo": "endbasic/endbasic", "path": "std/src/program.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/program.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7efc9957c8175431072690aadb56b34f2db702449e2502c6af26f09063b18f36"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_load_save_common_errors\n\nDocumentation:\nChecks errors that should be handled the same way by `LOAD` and `SAVE`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_load_save_common_errors(cmd: &str) {\n Tester::default()\n .run(format!(\"{} 3\", cmd))\n .expect_compilation_err(format!(\n \"1:{}: expected STRING but found INTEGER\",\n cmd.len() + 2,\n ))\n .check();\n\n Tester::default()\n .run(format!(r#\"{} \"a/b.bas\"\"#, cmd))\n .expect_err(\"1:1: Too many / separators in path 'a/b.bas'\")\n .check();\n\n Tester::default()\n .run(format!(r#\"{} \"drive:\"\"#, cmd))\n .expect_err(\"1:1: Missing file name in path 'drive:'\")\n .check();\n }\n```"}], "func_name": "check_load_save_common_errors", "docstring": "Checks errors that should be handled the same way by `LOAD` and `SAVE`.", "repo": "endbasic/endbasic", "path": "std/src/program.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/program.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8a9179e713946c79904d207a804ae03f4fdc3125e50d8fbb8cae57528e1bd297"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_input_chars\n\nDocumentation:\nAdds a bunch of characters as golden input keys.\n\nNote that some escape characters within `s` are interpreted and added as their\ncorresponding `Key`s for simplicity.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_input_chars(&mut self, s: &str) {\n for ch in s.chars() {\n match ch {\n '\\n' => self.golden_in.push_back(Key::NewLine),\n '\\r' => self.golden_in.push_back(Key::CarriageReturn),\n ch => self.golden_in.push_back(Key::Char(ch)),\n }\n }\n }\n```"}], "func_name": "add_input_chars", "docstring": "Adds a bunch of characters as golden input keys.\n\nNote that some escape characters within `s` are interpreted and added as their\ncorresponding `Key`s for simplicity.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b12010829d34e48555d8a7cb5cbae25f8a212e9b68d45ed86b00f55e24383a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_size_chars\n\nDocumentation:\nSets the size of the mock text console.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_size_chars(&mut self, size: CharsXY) {\n self.size_chars = size;\n }\n```"}], "func_name": "set_size_chars", "docstring": "Sets the size of the mock text console.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a1e9a24e1abf9a6304df054d55aa7effbc6edcbe2e5376f74c4ae77d8a65616a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_size_pixels\n\nDocumentation:\nSets the size of the mock graphical console.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_size_pixels(&mut self, size: SizeInPixels) {\n self.size_pixels = Some(size);\n }\n```"}], "func_name": "set_size_pixels", "docstring": "Sets the size of the mock graphical console.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "015f8a0b74c8268fb943701da3201f8f2add91fd8f480f066b5fb6177e4ba310"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_interactive\n\nDocumentation:\nSets whether the mock console is interactive or not.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_interactive(&mut self, interactive: bool) {\n self.interactive = interactive;\n }\n```"}], "func_name": "set_interactive", "docstring": "Sets whether the mock console is interactive or not.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "302eec3bda831d5a9bbbf8cff75276de0a61915d4a050cabe1d2fc9fa2374647"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: flatten_output\n\nDocumentation:\nFlattens the captured output into a single string resembling what would be shown in the\nconsole for ease of testing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn flatten_output(captured_out: Vec) -> String {\n let mut flattened = String::new();\n for out in captured_out {\n match out {\n CapturedOut::Write(bs) => flattened.push_str(&bs),\n CapturedOut::Print(s) => flattened.push_str(&s),\n _ => (),\n }\n }\n flattened\n}\n```"}], "func_name": "flatten_output", "docstring": "Flattens the captured output into a single string resembling what would be shown in the\nconsole for ease of testing.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c262df00952fa17815e7733f44b0642851cbaa31a2a124308889069d4c5b06ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default\n\nDocumentation:\nCreates a new tester for a fully-equipped (interactive) machine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn default() -> Self {\n let console = Rc::from(RefCell::from(MockConsole::default()));\n let program = Rc::from(RefCell::from(RecordedProgram::default()));\n\n // Default to the pins set that always returns errors. We could have implemented a set of\n // fake pins here to track GPIO state changes in a nicer way, similar to how we track all\n // other machine state... but the GPIO module already implements its own mocking feature.\n // The mocking feature is necessary for integration testing in any case, so we just use that\n // everywhere instead of having yet another implementation in this module.\n let gpio_pins = Rc::from(RefCell::from(gpio::NoopPins::default()));\n\n let mut builder = crate::MachineBuilder::default()\n .with_console(console.clone())\n .with_gpio_pins(gpio_pins)\n .make_interactive()\n .with_program(program.clone());\n\n // Grab access to the machine's storage subsystem before we lose track of it, as we will\n // need this to check its state.\n let storage = builder.get_storage();\n\n let machine = builder.build().unwrap();\n\n Self { console, storage, program, machine }\n }\n```"}], "func_name": "default", "docstring": "Creates a new tester for a fully-equipped (interactive) machine.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "207aaae5b9f5fe7daf8767e747abdf2bf9a2efefe244392dbbb6c5461fdb0239"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: empty\n\nDocumentation:\nCreates a new tester with an empty `Machine`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn empty() -> Self {\n let console = Rc::from(RefCell::from(MockConsole::default()));\n let storage = Rc::from(RefCell::from(Storage::default()));\n let program = Rc::from(RefCell::from(RecordedProgram::default()));\n\n let machine = Machine::default();\n\n Self { console, storage, program, machine }\n }\n```"}], "func_name": "empty", "docstring": "Creates a new tester with an empty `Machine`.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2d8d2482730e6ca631cd6f422203da4bc866b2c20dd9af868c19415f8fdce32e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_callable\n\nDocumentation:\nRegisters the given builtin command into the machine, which must not yet be registered.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_callable(mut self, callable: Rc) -> Self {\n self.machine.add_callable(callable);\n self\n }\n```"}], "func_name": "add_callable", "docstring": "Registers the given builtin command into the machine, which must not yet be registered.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e58729d2fc1889751527dfe3a700b1bc7ba109931cbf685d84a7c22204a12d11"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_input_chars\n\nDocumentation:\nAdds the `golden_in` characters as console input.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_input_chars(self, golden_in: &str) -> Self {\n self.console.borrow_mut().add_input_chars(golden_in);\n self\n }\n```"}], "func_name": "add_input_chars", "docstring": "Adds the `golden_in` characters as console input.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51ef6a878e18d25ff9d8f76805dd62f8dcbb3797afdbdab14a6b6dd736524e14"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_input_keys\n\nDocumentation:\nAdds a bunch of keys as golden input to the console.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_input_keys(self, keys: &[Key]) -> Self {\n self.console.borrow_mut().add_input_keys(keys);\n self\n }\n```"}], "func_name": "add_input_keys", "docstring": "Adds a bunch of keys as golden input to the console.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "df0ef8002ecafe72073f219d08d54e749b7080afae0e0185c6bdc0fe4696998f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_machine\n\nDocumentation:\nReturns a mutable reference to the machine inside the tester.\n\nThis method should generally not be used, except to run native methods that have\nside-effects on the machine that we'd like to validate later.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_machine(&mut self) -> &mut Machine {\n &mut self.machine\n }\n```"}], "func_name": "get_machine", "docstring": "Returns a mutable reference to the machine inside the tester.\n\nThis method should generally not be used, except to run native methods that have\nside-effects on the machine that we'd like to validate later.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d8c46800fad89066134ad69b8a5ea63667cd9355c52400ac47d7fac55c38dfd2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_var\n\nDocumentation:\nSets a variable to an initial value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_var(mut self, name: &str, value: Value) -> Self {\n self.machine.get_mut_symbols().set_var(&VarRef::new(name, None), value).unwrap();\n self\n }\n```"}], "func_name": "set_var", "docstring": "Sets a variable to an initial value.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bec722dfb9a87a1eacf56696c0284ca7f87b171c679e5db8d0160d131f758c48"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_program\n\nDocumentation:\nSets the initial name of the recorded program to `name` (if any) and its contents to `text`.\nCan only be called once and `text` must not be empty.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_program(self, name: Option<&str>, text: &str) -> Self {\n assert!(!text.is_empty());\n {\n let mut program = self.program.borrow_mut();\n assert!(program.text().is_empty());\n program.load(name, text);\n }\n self\n }\n```"}], "func_name": "set_program", "docstring": "Sets the initial name of the recorded program to `name` (if any) and its contents to `text`.\nCan only be called once and `text` must not be empty.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "481c3434d2d9598016a2674581f05df61c2bd3fa90ed7ddc1c24e6f982d07ae9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_file\n\nDocumentation:\nCreates or overwrites a file in the storage medium.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_file(self, name: &str, content: &str) -> Self {\n block_on(self.storage.borrow_mut().put(name, content.as_bytes())).unwrap();\n self\n }\n```"}], "func_name": "write_file", "docstring": "Creates or overwrites a file in the storage medium.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "387716cbdd6e83f8d7cd2d0560793bc7f90cf0f22db23c9bc9d9171b037094dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRuns `script` in the configured machine and returns a `Checker` object to validate\nexpectations about the execution.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn run>(&mut self, script: S) -> Checker {\n let result = block_on(self.machine.exec(&mut script.into().as_bytes()));\n Checker::new(self, result)\n }\n```"}], "func_name": "run", "docstring": "Runs `script` in the configured machine and returns a `Checker` object to validate\nexpectations about the execution.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82fc80d86fbb6d2ab3f3e63d363047835040fbf5cdc18843eed1a36d926e09e0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_n\n\nDocumentation:\nRuns `scripts` in the configured machine and returns a `Checker` object to validate\nexpectations about the execution.\n\nThe first entry in `scripts` to fail aborts execution and allows checking the result\nof that specific invocation.\n\nThis is useful when compared to `run` because `Machine::exec` compiles the script as one\nunit and thus compilation errors may prevent validating other operations later on.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn run_n(&mut self, scripts: &[&str]) -> Checker {\n let mut result = Ok(StopReason::Eof);\n for script in scripts {\n result = block_on(self.machine.exec(&mut script.as_bytes()));\n if result.is_err() {\n break;\n }\n }\n Checker::new(self, result)\n }\n```"}], "func_name": "run_n", "docstring": "Runs `scripts` in the configured machine and returns a `Checker` object to validate\nexpectations about the execution.\n\nThe first entry in `scripts` to fail aborts execution and allows checking the result\nof that specific invocation.\n\nThis is useful when compared to `run` because `Machine::exec` compiles the script as one\nunit and thus compilation errors may prevent validating other operations later on.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e8a56fa48c8f5d714363cdefcefb352a97f9018056925acd8ed8b08f98d306ce"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new checker with default expectations based on the results of an execution.\n\nThe default expectations are that the execution ran through completion and that it did not\nhave any side-effects.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(tester: &'a Tester, result: exec::Result) -> Self {\n Self {\n tester,\n result,\n exp_result: Ok(StopReason::Eof),\n exp_output: vec![],\n exp_drives: HashMap::default(),\n exp_program_name: None,\n exp_program_text: String::new(),\n exp_arrays: HashMap::default(),\n exp_vars: HashMap::default(),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new checker with default expectations based on the results of an execution.\n\nThe default expectations are that the execution ran through completion and that it did not\nhave any side-effects.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b2e19df27d36d78ae10ff71eb76b6131ff80685a3293cea9be4ee160fc9cc946"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_ok\n\nDocumentation:\nExpects the invocation to have successfully terminated with the given `stop_reason`.\n\nIf not called, defaults to expecting that execution terminated due to EOF. This or\n`expect_err` can only be called once.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_ok(mut self, stop_reason: StopReason) -> Self {\n assert_eq!(Ok(StopReason::Eof), self.exp_result);\n self.exp_result = Ok(stop_reason);\n self\n }\n```"}], "func_name": "expect_ok", "docstring": "Expects the invocation to have successfully terminated with the given `stop_reason`.\n\nIf not called, defaults to expecting that execution terminated due to EOF. This or\n`expect_err` can only be called once.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a2510ea1b9fdde5c5bf25a9252dc25189fece2f344e6951ffa082e300188455d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_compilation_err\n\nDocumentation:\nExpects the invocation to have erroneously terminated with the exact `message` during\ncompilation.\n\nIf not called, defaults to expecting that execution terminated due to EOF. This or\n`expect_err` can only be called once.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_compilation_err>(mut self, message: S) -> Self {\n let message = message.into();\n assert_eq!(Ok(StopReason::Eof), self.exp_result);\n self.exp_result = Err(message.clone());\n self\n }\n```"}], "func_name": "expect_compilation_err", "docstring": "Expects the invocation to have erroneously terminated with the exact `message` during\ncompilation.\n\nIf not called, defaults to expecting that execution terminated due to EOF. This or\n`expect_err` can only be called once.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be4c44a049d350f0bbbc465d6380e8650a7be36ef1dfce871d32b46c2b306445"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_err\n\nDocumentation:\nExpects the invocation to have erroneously terminated with the exact `message`.\n\nIf not called, defaults to expecting that execution terminated due to EOF. This or\n`expect_err` can only be called once.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_err>(mut self, message: S) -> Self {\n let message = message.into();\n assert_eq!(Ok(StopReason::Eof), self.exp_result);\n self.exp_result = Err(message.clone());\n self\n }\n```"}], "func_name": "expect_err", "docstring": "Expects the invocation to have erroneously terminated with the exact `message`.\n\nIf not called, defaults to expecting that execution terminated due to EOF. This or\n`expect_err` can only be called once.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "78c0fc889227abc0cc69b654c4b5704c74bbb0c9044aa0787cdc3501af91edd4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_array\n\nDocumentation:\nAdds the `name` array as an array to expect in the final state of the machine. The array\nwill be tested to have the same `subtype` and `dimensions`, as well as specific `contents`.\nThe contents are provided as a collection of subscripts/value pairs to assign to the\nexpected array.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_array>(\n mut self,\n name: S,\n subtype: ExprType,\n dimensions: &[usize],\n contents: Vec<(&[i32], Value)>,\n ) -> Self {\n let key = SymbolKey::from(name);\n assert!(!self.exp_arrays.contains_key(&key));\n let mut array = Array::new(subtype, dimensions.to_owned());\n for (subscripts, value) in contents.into_iter() {\n array.assign(subscripts, value).unwrap();\n }\n self.exp_arrays.insert(key, array);\n self\n }\n```"}], "func_name": "expect_array", "docstring": "Adds the `name` array as an array to expect in the final state of the machine. The array\nwill be tested to have the same `subtype` and `dimensions`, as well as specific `contents`.\nThe contents are provided as a collection of subscripts/value pairs to assign to the\nexpected array.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e7d5008fc16c46be01c253a6f0d54c8ea4d137225c06260b10f514f78c5c28af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_array_simple\n\nDocumentation:\nAdds the `name` array as an array to expect in the final state of the machine. The array\nwill be tested to have the same `subtype` and only one dimension with `contents`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_array_simple>(\n mut self,\n name: S,\n subtype: ExprType,\n contents: Vec,\n ) -> Self {\n let key = SymbolKey::from(name);\n assert!(!self.exp_arrays.contains_key(&key));\n let mut array = Array::new(subtype, vec![contents.len()]);\n for (i, value) in contents.into_iter().enumerate() {\n array.assign(&[i as i32], value).unwrap();\n }\n self.exp_arrays.insert(key, array);\n self\n }\n```"}], "func_name": "expect_array_simple", "docstring": "Adds the `name` array as an array to expect in the final state of the machine. The array\nwill be tested to have the same `subtype` and only one dimension with `contents`.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "55436b8f0ff0e0eb016f7bfeb62720de1f65971a20c40295a6264427734a338b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_clear\n\nDocumentation:\nAdds tracking for all the side-effects of a clear operation on the machine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_clear(mut self) -> Self {\n self.exp_output.append(&mut vec![\n CapturedOut::LeaveAlt,\n CapturedOut::SetColor(None, None),\n CapturedOut::ShowCursor,\n CapturedOut::SetSync(true),\n ]);\n self\n }\n```"}], "func_name": "expect_clear", "docstring": "Adds tracking for all the side-effects of a clear operation on the machine.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "03862c42dde1763f820df1aefa315e2c3e964fa22ae4311867b1c817378fde40"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_file\n\nDocumentation:\nAdds a file to expect in the drive with a `name` and specific `content`.\n\n`name` must be the absolute path to the file that is expected, including the drive name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_file, C: Into>(mut self, name: N, content: C) -> Self {\n let name = name.into();\n assert!(!self.exp_drives.contains_key(&name));\n self.exp_drives.insert(name, content.into());\n self\n }\n```"}], "func_name": "expect_file", "docstring": "Adds a file to expect in the drive with a `name` and specific `content`.\n\n`name` must be the absolute path to the file that is expected, including the drive name.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d372e2f3207496fb46098dfe188f79b8a6c024ed4d0b8612a7891a9e99b31b04"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_output\n\nDocumentation:\nAdds the `out` sequence of captured outputs to the expected outputs of the execution.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_output>>(mut self, out: V) -> Self {\n self.exp_output.append(&mut out.into());\n self\n }\n```"}], "func_name": "expect_output", "docstring": "Adds the `out` sequence of captured outputs to the expected outputs of the execution.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80ec2b0c0cd9e68b65adefbbee30c681a91b97d8e882fc5f7891c7cec77af8d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_prints\n\nDocumentation:\nAdds the `out` sequence of strings to the expected outputs of the execution.\n\nThis is a convenience function around `expect_output` that wraps all incoming strings in\n`CapturedOut::Print` objects, as these are the most common outputs in tests.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_prints, V: Into>>(mut self, out: V) -> Self {\n let out = out.into();\n self.exp_output\n .append(&mut out.into_iter().map(|x| CapturedOut::Print(x.into())).collect());\n self\n }\n```"}], "func_name": "expect_prints", "docstring": "Adds the `out` sequence of strings to the expected outputs of the execution.\n\nThis is a convenience function around `expect_output` that wraps all incoming strings in\n`CapturedOut::Print` objects, as these are the most common outputs in tests.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "708556ae25c6347fc6a633a131845c6c02310ba6bb93485abcdc6badfa165daa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_program\n\nDocumentation:\nSets the expected name of the stored program to `name` and its contents to `text`. Can only\nbe called once and `text` must not be empty.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_program, S2: Into>(\n mut self,\n name: Option,\n text: S2,\n ) -> Self {\n assert!(self.exp_program_text.is_empty());\n let text = text.into();\n assert!(!text.is_empty());\n self.exp_program_name = name.map(|x| x.into());\n self.exp_program_text = text;\n self\n }\n```"}], "func_name": "expect_program", "docstring": "Sets the expected name of the stored program to `name` and its contents to `text`. Can only\nbe called once and `text` must not be empty.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b5627da46cfc5448dbca19101046c139e5f1d07d37cbb008e729b2e2db8804c6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_var\n\nDocumentation:\nAdds the `name`/`value` pair as a variable to expect in the final state of the machine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect_var, V: Into>(mut self, name: S, value: V) -> Self {\n let key = SymbolKey::from(name);\n assert!(!self.exp_vars.contains_key(&key));\n self.exp_vars.insert(key, value.into());\n self\n }\n```"}], "func_name": "expect_var", "docstring": "Adds the `name`/`value` pair as a variable to expect in the final state of the machine.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b0ac0f703631854194eb640b9995b7b8f4f54a7a6896134a0ef0cec5d48bdb9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_expr_ok\n\nDocumentation:\nExecutes `expr` on a scripting interpreter and ensures that the result is `exp_value`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check_expr_ok>(exp_value: V, expr: &str) {\n Tester::default()\n .run(format!(\"result = {}\", expr))\n .expect_var(\"result\", exp_value.into())\n .check();\n}\n```"}], "func_name": "check_expr_ok", "docstring": "Executes `expr` on a scripting interpreter and ensures that the result is `exp_value`.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a9df0a23dcb9f91740a8e826d927287d2e748afdd3fbfa2d0a71dd57ac915d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_expr_ok_with_vars\n\nDocumentation:\nExecutes `expr` on a scripting interpreter and ensures that the result is `exp_value`.\n\nSets all `vars` before evaluating the expression so that the expression can contain variable\nreferences.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check_expr_ok_with_vars, VS: Into>>(\n exp_value: V,\n expr: &str,\n vars: VS,\n) {\n let vars = vars.into();\n\n let mut t = Tester::default();\n for var in vars.as_slice() {\n t = t.set_var(var.0, var.1.clone());\n }\n\n let mut c = t.run(format!(\"result = {}\", expr));\n c = c.expect_var(\"result\", exp_value.into());\n for var in vars.into_iter() {\n c = c.expect_var(var.0, var.1.clone());\n }\n c.check();\n}\n```"}], "func_name": "check_expr_ok_with_vars", "docstring": "Executes `expr` on a scripting interpreter and ensures that the result is `exp_value`.\n\nSets all `vars` before evaluating the expression so that the expression can contain variable\nreferences.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a4797413b75ba3bfd339021a1e4f71b8fa2d0b9d663a48373e142fcae66c59c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_expr_error\n\nDocumentation:\nExecutes `expr` on a scripting interpreter and ensures that evaluation fails with `exp_error`.\n\nNote that `exp_error` is a literal exact match on the formatted error message returned by the\nmachine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check_expr_error>(exp_error: S, expr: &str) {\n Tester::default().run(format!(\"result = {}\", expr)).expect_err(exp_error).check();\n}\n```"}], "func_name": "check_expr_error", "docstring": "Executes `expr` on a scripting interpreter and ensures that evaluation fails with `exp_error`.\n\nNote that `exp_error` is a literal exact match on the formatted error message returned by the\nmachine.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "668ddd4ac5d0cea4d41e4654e001cbe3ed7d207b71e7c94538f39899aa3877d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_expr_compilation_error\n\nDocumentation:\nExecutes `expr` on a scripting interpreter and ensures that evaluation fails with `exp_error`\nduring compilation.\n\nNote that `exp_error` is a literal exact match on the formatted error message returned by the\nmachine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check_expr_compilation_error>(exp_error: S, expr: &str) {\n Tester::default().run(format!(\"result = {}\", expr)).expect_compilation_err(exp_error).check();\n}\n```"}], "func_name": "check_expr_compilation_error", "docstring": "Executes `expr` on a scripting interpreter and ensures that evaluation fails with `exp_error`\nduring compilation.\n\nNote that `exp_error` is a literal exact match on the formatted error message returned by the\nmachine.", "repo": "endbasic/endbasic", "path": "std/src/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "13eaae96105ed2c976d0e1a6aa89dda8b2f05e656fecaff36a885ee610e62b74"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `CLS` command that clears the `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"CLS\")\n .with_syntax(&[(&[], None)])\n .with_category(CATEGORY)\n .with_description(\"Clears the screen.\")\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `CLS` command that clears the `console`.", "repo": "endbasic/endbasic", "path": "std/src/console/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "578b6c75f8a4cda3bf2d0db68dd8990612606f15784b1342cb4d35beda0a6688"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `COLOR` command that changes the color of the `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"COLOR\")\n .with_syntax(&[\n (&[], None),\n (\n &[SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"fg\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::End,\n )],\n None,\n ),\n (\n &[\n SingularArgSyntax::OptionalValue(\n OptionalValueSyntax {\n name: Cow::Borrowed(\"fg\"),\n vtype: ExprType::Integer,\n missing_value: Self::NO_COLOR,\n present_value: Self::HAS_COLOR,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::OptionalValue(\n OptionalValueSyntax {\n name: Cow::Borrowed(\"bg\"),\n vtype: ExprType::Integer,\n missing_value: Self::NO_COLOR,\n present_value: Self::HAS_COLOR,\n },\n ArgSepSyntax::End,\n ),\n ],\n None,\n ),\n ])\n .with_category(CATEGORY)\n .with_description(\n \"Sets the foreground and background colors.\nColor numbers are given as ANSI numbers and can be between 0 and 255. If a color number is not \\\nspecified, then the color is reset to the console's default. The console default does not \\\nnecessarily match any other color specifiable in the 0 to 255 range, as it might be transparent.\",\n )\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `COLOR` command that changes the color of the `console`.", "repo": "endbasic/endbasic", "path": "std/src/console/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e527355c51aabf19377ebfecf8372b46800f71e90dc2fe047a758dd421374205"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `INKEY` function that waits for a key press.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"INKEY\")\n .with_return_type(ExprType::Text)\n .with_syntax(&[(&[], None)])\n .with_category(CATEGORY)\n .with_description(\n \"Checks for an available key press and returns it.\nIf a key press is available to be read, returns its name. Otherwise, returns the empty string. \\\nThe returned key matches its name, number, or symbol and maintains case. In other words, \\\npressing the X key will return 'x' or 'X' depending on the SHIFT modifier.\nThe following special keys are recognized: arrow keys (UP, DOWN, LEFT, RIGHT), backspace (BS), \\\nend or CTRL+E (END), enter (ENTER), CTRL+D (EOF), escape (ESC), home or CTRL+A (HOME), \\\nCTRL+C (INT), page up (PGUP), page down (PGDOWN), and tab (TAB).\nThis function never blocks. To wait for a key press, you need to explicitly poll the keyboard. \\\nFor example, to wait until the escape key is pressed, you could do:\n k$ = \\\"\\\": WHILE k$ <> \\\"ESC\\\": k = INKEY$: SLEEP 0.01: WEND\nThis non-blocking design lets you to combine the reception of multiple evens, such as from \\\nGPIO_INPUT?, within the same loop.\",\n )\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `INKEY` function that waits for a key press.", "repo": "endbasic/endbasic", "path": "std/src/console/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "76fa9fb1ddfd64a0d8f9a346f06e2354a64879c28acf6cd6d4d756bab0e5e4cc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `INPUT` command that uses `console` to gather user input.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"INPUT\")\n .with_syntax(&[\n (\n &[SingularArgSyntax::RequiredRef(\n RequiredRefSyntax {\n name: Cow::Borrowed(\"vref\"),\n require_array: false,\n define_undefined: true,\n },\n ArgSepSyntax::End,\n )],\n None,\n ),\n (\n &[\n SingularArgSyntax::OptionalValue(\n OptionalValueSyntax {\n name: Cow::Borrowed(\"prompt\"),\n vtype: ExprType::Text,\n missing_value: 0,\n present_value: 1,\n },\n ArgSepSyntax::OneOf(ArgSep::Long, ArgSep::Short),\n ),\n SingularArgSyntax::RequiredRef(\n RequiredRefSyntax {\n name: Cow::Borrowed(\"vref\"),\n require_array: false,\n define_undefined: true,\n },\n ArgSepSyntax::End,\n ),\n ],\n None,\n ),\n ])\n .with_category(CATEGORY)\n .with_description(\n \"Obtains user input from the console.\nThe first expression to this function must be empty or evaluate to a string, and specifies \\\nthe prompt to print. If this first argument is followed by the short `;` separator, the \\\nprompt is extended with a question mark.\nThe second expression to this function must be a bare variable reference and indicates the \\\nvariable to update with the obtained input.\",\n )\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `INPUT` command that uses `console` to gather user input.", "repo": "endbasic/endbasic", "path": "std/src/console/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb89dfdee89afb5f77573f909d186c60298247a1eebd0ee829d38cd9d29fb4b3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `LOCATE` command that moves the cursor of the `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"LOCATE\")\n .with_syntax(&[(\n &[\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"column\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"row\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::End,\n ),\n ],\n None,\n )])\n .with_category(CATEGORY)\n .with_description(\"Moves the cursor to the given position.\")\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `LOCATE` command that moves the cursor of the `console`.", "repo": "endbasic/endbasic", "path": "std/src/console/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1290f95568a9760ec7d0a729077f7fd110a62204c6eb7ad137b9d52e799a55dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `PRINT` command that writes to `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"PRINT\")\n .with_syntax(&[(\n &[],\n Some(&RepeatedSyntax {\n name: Cow::Borrowed(\"expr\"),\n type_syn: RepeatedTypeSyntax::AnyValue,\n sep: ArgSepSyntax::OneOf(ArgSep::Long, ArgSep::Short),\n require_one: false,\n allow_missing: true,\n }),\n )])\n .with_category(CATEGORY)\n .with_description(\n \"Prints one or more values to the console.\nThe expressions given as arguments are all evaluated and converted to strings before they are \\\nprinted. See the documentation of STR$() for the conversion rules.\nUsing a `;` separator between arguments causes the two adjacent values to be displayed together. \\\nFor strings, this means that no space is added between them; for all other types, a space is added \\\nafter the value on the left side.\nUsing a `,` separator between arguments works the same as `;` except that the fields are \\\nleft-aligned to 14-character wide fields on the screen.\nIf the last expression is empty (i.e. if the statement ends in a semicolon or a comma), then \\\nthe cursor position remains on the same line of the message right after what was printed.\",\n )\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `PRINT` command that writes to `console`.", "repo": "endbasic/endbasic", "path": "std/src/console/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "61246a42e76d656e31076d15b408888e1c20be11fb85db6dd36a1b7985b3668f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_all\n\nDocumentation:\nAdds all console-related commands for the given `console` to the `machine`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_all(machine: &mut Machine, console: Rc>) {\n machine.add_clearable(ConsoleClearable::new(console.clone()));\n machine.add_callable(ClsCommand::new(console.clone()));\n machine.add_callable(ColorCommand::new(console.clone()));\n machine.add_callable(InKeyFunction::new(console.clone()));\n machine.add_callable(InputCommand::new(console.clone()));\n machine.add_callable(LocateCommand::new(console.clone()));\n machine.add_callable(PrintCommand::new(console.clone()));\n machine.add_callable(ScrColsFunction::new(console.clone()));\n machine.add_callable(ScrRowsFunction::new(console));\n}\n```"}], "func_name": "add_all", "docstring": "Adds all console-related commands for the given `console` to the `machine`.", "repo": "endbasic/endbasic", "path": "std/src/console/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6d5f70b2704058362eaee06fb5ebf0d7a32c8724f6d369238b63c5b605de8fa5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ansi_color_to_rgb\n\nDocumentation:\nConverts an ANSI color number to an RGB color.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ansi_color_to_rgb(color: u8) -> RGB {\n COLORS[(color as usize) % COLORS.len()]\n}\n```"}], "func_name": "ansi_color_to_rgb", "docstring": "Converts an ANSI color number to an RGB color.", "repo": "endbasic/endbasic", "path": "std/src/console/colors.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/colors.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2164b6d72025f85b31cd274f8fcf04918e6873e5efbca19bf0542e69df7d289e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: draw_line_low\n\nDocumentation:\nAuxiliary function for the `draw_line` algorithm to handle slopes between 0 and -1.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn draw_line_low(rasops: &mut R, x1: i32, y1: i32, x2: i32, y2: i32) -> io::Result<()>\nwhere\n R: RasterOps,\n{\n let dx = x2 - x1;\n let mut dy = y2 - y1;\n\n let mut yi = 1;\n if dy < 0 {\n yi = -1;\n dy = -dy;\n }\n let mut d = (2 * dy) - dx;\n let mut y = y1;\n\n for x in x1..(x2 + 1) {\n if cfg!(debug_assertions) {\n rasops.draw_pixel(PixelsXY {\n x: i16::try_from(x).expect(\"Coordinate must fit after computations\"),\n y: i16::try_from(y).expect(\"Coordinate must fit after computations\"),\n })?;\n } else {\n rasops.draw_pixel(PixelsXY { x: x as i16, y: y as i16 })?;\n }\n if d > 0 {\n y += yi;\n d += 2 * (dy - dx);\n } else {\n d += 2 * dy;\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "draw_line_low", "docstring": "Auxiliary function for the `draw_line` algorithm to handle slopes between 0 and -1.", "repo": "endbasic/endbasic", "path": "std/src/console/drawing.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/drawing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8b258be0732a40950902dd7dedf94343a34bae5c3a1801a8d18a5f1bd5047db8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: draw_line_high\n\nDocumentation:\nAuxiliary function for the `draw_line` algorithm to handle positive or negative slopes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn draw_line_high(rasops: &mut R, x1: i32, y1: i32, x2: i32, y2: i32) -> io::Result<()>\nwhere\n R: RasterOps,\n{\n let mut dx = x2 - x1;\n let dy = y2 - y1;\n\n let mut xi = 1;\n if dx < 0 {\n xi = -1;\n dx = -dx;\n }\n let mut d = (2 * dx) - dy;\n let mut x = x1;\n\n for y in y1..(y2 + 1) {\n if cfg!(debug_assertions) {\n rasops.draw_pixel(PixelsXY {\n x: i16::try_from(x).expect(\"Coordinate must fit after computations\"),\n y: i16::try_from(y).expect(\"Coordinate must fit after computations\"),\n })?;\n } else {\n rasops.draw_pixel(PixelsXY { x: x as i16, y: y as i16 })?;\n }\n if d > 0 {\n x += xi;\n d += 2 * (dx - dy);\n } else {\n d += 2 * dx;\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "draw_line_high", "docstring": "Auxiliary function for the `draw_line` algorithm to handle positive or negative slopes.", "repo": "endbasic/endbasic", "path": "std/src/console/drawing.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/drawing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "71bdfea25a099746e0a81eb946722a9711ed5791bdc00c3ea8687a31f99057b5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: draw_line\n\nDocumentation:\nDraws a line from `x1y1` to `x2y2` via `rasops`.\n\nThis implements the [Bresenham's line\nalgorithm](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn draw_line(rasops: &mut R, x1y1: PixelsXY, x2y2: PixelsXY) -> io::Result<()>\nwhere\n R: RasterOps,\n{\n // Widen coordinates so we don't have to worry about overflows anywhere.\n let x1 = i32::from(x1y1.x);\n let y1 = i32::from(x1y1.y);\n let x2 = i32::from(x2y2.x);\n let y2 = i32::from(x2y2.y);\n\n if (y2 - y1).abs() < (x2 - x1).abs() {\n if x1y1.x > x2y2.x {\n draw_line_low(rasops, x2, y2, x1, y1)\n } else {\n draw_line_low(rasops, x1, y1, x2, y2)\n }\n } else {\n if x1y1.y > x2y2.y {\n draw_line_high(rasops, x2, y2, x1, y1)\n } else {\n draw_line_high(rasops, x1, y1, x2, y2)\n }\n }\n}\n```"}], "func_name": "draw_line", "docstring": "Draws a line from `x1y1` to `x2y2` via `rasops`.\n\nThis implements the [Bresenham's line\nalgorithm](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm).", "repo": "endbasic/endbasic", "path": "std/src/console/drawing.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/drawing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "869f174b21a142ba1b0a5a7266d8e2fdb0bd10d10e528535608382c20b875e50"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: draw_circle\n\nDocumentation:\nDraws a circle via `rasops` with `center` and `radius`.\n\nThis implements the [Midpoint circle\nalgorithm](https://en.wikipedia.org/wiki/Midpoint_circle_algorithm).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn draw_circle(rasops: &mut R, center: PixelsXY, radius: u16) -> io::Result<()>\nwhere\n R: RasterOps,\n{\n fn point(rasops: &mut R, x: i16, y: i16) -> io::Result<()> {\n rasops.draw_pixel(PixelsXY { x, y })\n }\n\n if radius == 0 {\n return Ok(());\n } else if radius == 1 {\n return rasops.draw_pixel(center);\n }\n\n let (diameter, radius): (i16, i16) = match radius.checked_mul(2) {\n Some(d) => match i16::try_from(d) {\n Ok(d) => (d, radius as i16),\n Err(_) => return Err(io::Error::new(io::ErrorKind::InvalidInput, \"Radius is too big\")),\n },\n None => return Err(io::Error::new(io::ErrorKind::InvalidInput, \"Radius is too big\")),\n };\n\n let mut x: i16 = radius - 1;\n let mut y: i16 = 0;\n let mut tx: i16 = 1;\n let mut ty: i16 = 1;\n let mut e: i16 = tx - diameter;\n\n while x >= y {\n point(rasops, center.x + x, center.y - y)?;\n point(rasops, center.x + x, center.y + y)?;\n point(rasops, center.x - x, center.y - y)?;\n point(rasops, center.x - x, center.y + y)?;\n point(rasops, center.x + y, center.y - x)?;\n point(rasops, center.x + y, center.y + x)?;\n point(rasops, center.x - y, center.y - x)?;\n point(rasops, center.x - y, center.y + x)?;\n\n if e <= 0 {\n y += 1;\n e += ty;\n ty += 2;\n }\n\n if e > 0 {\n x -= 1;\n tx += 2;\n e += tx - diameter;\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "draw_circle", "docstring": "Draws a circle via `rasops` with `center` and `radius`.\n\nThis implements the [Midpoint circle\nalgorithm](https://en.wikipedia.org/wiki/Midpoint_circle_algorithm).", "repo": "endbasic/endbasic", "path": "std/src/console/drawing.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/drawing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "254eb27966331e1f4ab851e22d8878e9f1822d3da8135627553ae30c51e71bc9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: draw_rect\n\nDocumentation:\nDraws a rectangle via `rasops` starting at `x1y1` with `size`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn draw_rect(rasops: &mut R, x1y1: PixelsXY, size: SizeInPixels) -> io::Result<()>\nwhere\n R: RasterOps,\n{\n let x2y2 = PixelsXY {\n x: (i32::from(x1y1.x) + i32::from(size.width - 1)).clamped_into(),\n y: (i32::from(x1y1.y) + i32::from(size.height - 1)).clamped_into(),\n };\n rasops.draw_line(PixelsXY { x: x1y1.x, y: x1y1.y }, PixelsXY { x: x2y2.x, y: x1y1.y })?;\n rasops.draw_line(PixelsXY { x: x2y2.x, y: x1y1.y }, PixelsXY { x: x2y2.x, y: x2y2.y })?;\n rasops.draw_line(PixelsXY { x: x2y2.x, y: x2y2.y }, PixelsXY { x: x1y1.x, y: x2y2.y })?;\n rasops.draw_line(PixelsXY { x: x1y1.x, y: x2y2.y }, PixelsXY { x: x1y1.x, y: x1y1.y })?;\n Ok(())\n}\n```"}], "func_name": "draw_rect", "docstring": "Draws a rectangle via `rasops` starting at `x1y1` with `size`.", "repo": "endbasic/endbasic", "path": "std/src/console/drawing.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/drawing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63f8a54b0445a0ff9767d495ef28b76f2126e812934a4a0c2f675d29b9e4062e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: refill\n\nDocumentation:\nRefills a paragraph to fit within a maximum width, returning the formatted lines.\n\nThis does not cut words half-way, which means that it may be impossible to fit certain words in\nthe specified width. If that happens, lines will overflow.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn refill(paragraph: &str, width: usize) -> Vec {\n if paragraph.is_empty() {\n return vec![\"\".to_owned()];\n }\n\n let mut lines = vec![];\n\n let mut line = String::new();\n for word in paragraph.split_whitespace() {\n if !line.is_empty() {\n // Determine how many spaces to inject after a period. We want 2 spaces to separate\n // different sentences and 1 otherwise. The heuristic here isn't great and it'd be\n // better to respect the original spacing of the paragraph.\n let spaces = if line.ends_with('.') {\n let first = word.chars().next().expect(\"Words cannot be empty\");\n if first == first.to_ascii_uppercase() {\n 2\n } else {\n 1\n }\n } else {\n 1\n };\n\n if (line.len() + word.len() + spaces) >= width {\n lines.push(line);\n line = String::new();\n } else {\n for _ in 0..spaces {\n line.push(' ');\n }\n }\n }\n line.push_str(word);\n }\n if !line.is_empty() {\n lines.push(line);\n }\n\n lines\n}\n```"}], "func_name": "refill", "docstring": "Refills a paragraph to fit within a maximum width, returning the formatted lines.\n\nThis does not cut words half-way, which means that it may be impossible to fit certain words in\nthe specified width. If that happens, lines will overflow.", "repo": "endbasic/endbasic", "path": "std/src/console/format.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/format.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d75c6cdedb516c1122485d4f3cb61ba408497d1ac89d5ba883508be0682143bb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: refill_many\n\nDocumentation:\nRefills a collection of paragraphs, prefixing them with an optional `indent`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn refill_many, P: IntoIterator>(\n paragraphs: P,\n indent: &str,\n width: usize,\n) -> Vec {\n let mut formatted = vec![];\n\n let mut first = true;\n for paragraph in paragraphs {\n let paragraph = paragraph.as_ref();\n\n if !first {\n formatted.push(String::new());\n }\n first = false;\n\n let mut extra_indent = String::new();\n for ch in paragraph.chars() {\n // TODO(jmmv): It'd be nice to recognize '*' prefixes so that continuation lines in\n // lists look nicer.\n if ch.is_whitespace() {\n extra_indent.push(' ');\n } else {\n break;\n }\n }\n\n let lines = refill(paragraph, width - 4 - indent.len() - extra_indent.len());\n for line in lines {\n if line.is_empty() {\n formatted.push(String::new());\n } else {\n formatted.push(format!(\"{}{}{}\", indent, extra_indent, line));\n }\n }\n }\n\n formatted\n}\n```"}], "func_name": "refill_many", "docstring": "Refills a collection of paragraphs, prefixing them with an optional `indent`.", "repo": "endbasic/endbasic", "path": "std/src/console/format.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/format.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d0a7def1d5821c1297c8443cb590c3fade3f2883e9e4eac37e87e96e2d1338a2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: refill_and_print\n\nDocumentation:\nSame as `refill` but prints the lines of each paragraph to the console instead of returning\nthem and prefixes them with an optional `indent`.\n\nThe width is automatically determined from the console's size.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn refill_and_print, P: IntoIterator>(\n console: &mut dyn Console,\n paragraphs: P,\n indent: &str,\n) -> io::Result<()> {\n // TODO(jmmv): This queries the size on every print, which is not very efficient. Should\n // reuse this across calls, maybe by having a wrapper over Console and using it throughout.\n let size = console.size_chars()?;\n for line in refill_many(paragraphs, indent, usize::from(size.x)) {\n console.print(&line)?;\n }\n Ok(())\n}\n```"}], "func_name": "refill_and_print", "docstring": "Same as `refill` but prints the lines of each paragraph to the console instead of returning\nthem and prefixes them with an optional `indent`.\n\nThe width is automatically determined from the console's size.", "repo": "endbasic/endbasic", "path": "std/src/console/format.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/format.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "433a1cdb5a697acf7eebdfefcc19aa199e1cf83286545c9f80ae5040887aa1e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: refill_and_page\n\nDocumentation:\nSame as `refill` but prints the lines of each paragraph to a pager instead of returning\nthem and prefixes them with an optional `indent`.\n\nThe width is automatically determined from the console's size.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn refill_and_page, P: IntoIterator>(\n pager: &mut Pager<'_>,\n paragraphs: P,\n indent: &str,\n) -> io::Result<()> {\n for line in refill_many(paragraphs, indent, usize::from(pager.columns())) {\n pager.print(&line).await?;\n }\n Ok(())\n}\n```"}], "func_name": "refill_and_page", "docstring": "Same as `refill` but prints the lines of each paragraph to a pager instead of returning\nthem and prefixes them with an optional `indent`.\n\nThe width is automatically determined from the console's size.", "repo": "endbasic/endbasic", "path": "std/src/console/format.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/format.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1d44c00f563b90d951f15a01f5c5f830738a3717e65cf09d16bea53149cda8c3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rect_points\n\nDocumentation:\nGiven two points, calculates the origin and size of the rectangle they define.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn rect_points(x1y1: PixelsXY, x2y2: PixelsXY) -> Option<(PixelsXY, SizeInPixels)> {\n let (x1, x2) = if x1y1.x < x2y2.x { (x1y1.x, x2y2.x) } else { (x2y2.x, x1y1.x) };\n let (y1, y2) = if x1y1.y < x2y2.y { (x1y1.y, x2y2.y) } else { (x2y2.y, x1y1.y) };\n\n let width = {\n let width = i32::from(x2) - i32::from(x1);\n if cfg!(debug_assertions) {\n u32::try_from(width).expect(\"Width must have been non-negative\")\n } else {\n width as u32\n }\n }\n .clamped_into();\n let height = {\n let height = i32::from(y2) - i32::from(y1);\n if cfg!(debug_assertions) {\n u32::try_from(height).expect(\"Height must have been non-negative\")\n } else {\n height as u32\n }\n }\n .clamped_into();\n\n if width == 0 || height == 0 {\n None\n } else {\n Some((PixelsXY::new(x1, y1), SizeInPixels::new(width, height)))\n }\n}\n```"}], "func_name": "rect_points", "docstring": "Given two points, calculates the origin and size of the rectangle they define.", "repo": "endbasic/endbasic", "path": "std/src/console/graphics.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/graphics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc5b3bcca332c63b08db113a71d0ddb94152155688cd03eb8a3ed2ad7ff71b57"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: present_canvas\n\nDocumentation:\nRenders any buffered changes to the backing surface.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn present_canvas(&mut self) -> io::Result<()> {\n if self.sync_enabled {\n self.raster_ops.present_canvas()\n } else {\n Ok(())\n }\n }\n```"}], "func_name": "present_canvas", "docstring": "Renders any buffered changes to the backing surface.", "repo": "endbasic/endbasic", "path": "std/src/console/graphics.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/graphics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bfeecc5ebd9dfc72b38be2efcc2b9f2993c5968e26d76c2a74e6bf523db78cb3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: draw_cursor\n\nDocumentation:\nDraws the cursor at the current position and saves the previous contents of the screen so\nthat `clear_cursor` can restore them.\n\nDoes not present the canvas.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn draw_cursor(&mut self) -> io::Result<()> {\n if !self.cursor_visible {\n return Ok(());\n }\n\n let x1y1 = self.cursor_pos.clamped_mul(self.glyph_size);\n\n assert!(self.cursor_backup.is_none());\n self.cursor_backup = Some(self.raster_ops.read_pixels(x1y1, self.glyph_size)?);\n\n // TODO(jmmv): It would be nice to draw the cursor with alpha blending so that the letters\n // under it are visible. This was done before in the HTML canvas but was lost when I added\n // the GraphicsConsole abstraction. Maybe all RGB colors should switch to RGBA. Or maybe\n // we should special-case the cursor drawing.\n self.raster_ops.set_draw_color(self.fg_color);\n self.raster_ops.draw_rect_filled(x1y1, self.glyph_size)\n }\n```"}], "func_name": "draw_cursor", "docstring": "Draws the cursor at the current position and saves the previous contents of the screen so\nthat `clear_cursor` can restore them.\n\nDoes not present the canvas.", "repo": "endbasic/endbasic", "path": "std/src/console/graphics.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/graphics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9c72b38cd8f971715856e2778b0f3755650351e889ce6263802a46564555d759"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clear_cursor\n\nDocumentation:\nClears the cursor at the current position by restoring the contents of the screen saved by\nan earlier call to `draw_cursor`.\n\nDoes not present the canvas.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn clear_cursor(&mut self) -> io::Result<()> {\n if !self.cursor_visible || self.cursor_backup.is_none() {\n return Ok(());\n }\n\n let x1y1 = self.cursor_pos.clamped_mul(self.glyph_size);\n\n self.raster_ops.put_pixels(x1y1, self.cursor_backup.as_ref().unwrap())?;\n self.cursor_backup = None;\n Ok(())\n }\n```"}], "func_name": "clear_cursor", "docstring": "Clears the cursor at the current position by restoring the contents of the screen saved by\nan earlier call to `draw_cursor`.\n\nDoes not present the canvas.", "repo": "endbasic/endbasic", "path": "std/src/console/graphics.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/graphics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "172eb09e2312b56bd27070385ad08ef71406360e1894f060206d9dabf46bbf7d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open_line\n\nDocumentation:\nMoves the cursor to beginning of the next line, scrolling the console if necessary.\n\nDoes not clear nor draw the cursor.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn open_line(&mut self) -> io::Result<()> {\n if self.cursor_pos.y < self.size_chars.y - 1 {\n self.cursor_pos.x = 0;\n self.cursor_pos.y += 1;\n return Ok(());\n }\n\n let x1y1 = PixelsXY::new(0, self.glyph_size.height.clamped_into());\n let x2y2 = PixelsXY::new(0, 0);\n let size = SizeInPixels::new(\n self.size_pixels.width,\n self.size_pixels.height - self.glyph_size.height,\n );\n\n self.raster_ops.set_draw_color(self.bg_color);\n self.raster_ops.move_pixels(x1y1, x2y2, size)?;\n\n self.cursor_pos.x = 0;\n Ok(())\n }\n```"}], "func_name": "open_line", "docstring": "Moves the cursor to beginning of the next line, scrolling the console if necessary.\n\nDoes not clear nor draw the cursor.", "repo": "endbasic/endbasic", "path": "std/src/console/graphics.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/graphics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a32a3a089520815f154fd0d6028274aabaafc24265fd3de80c7b868d5b040f75"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: raw_write_wrapped\n\nDocumentation:\nRenders the given text at the current cursor position, with wrapping and\nscrolling if necessary.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn raw_write_wrapped(&mut self, text: String) -> io::Result<()> {\n let mut line_buffer = LineBuffer::from(text);\n\n loop {\n let fit_chars = self.size_chars.x - self.cursor_pos.x;\n\n let remaining = line_buffer.split_off(usize::from(fit_chars));\n let len = match u16::try_from(line_buffer.len()) {\n Ok(len) => len,\n Err(_) => return Err(io::Error::new(io::ErrorKind::InvalidInput, \"Text too long\")),\n };\n\n if len > 0 {\n let xy = self.cursor_pos.clamped_mul(self.glyph_size);\n let size = SizeInPixels::new(\n len.clamped_mul(self.glyph_size.width),\n self.glyph_size.height,\n );\n\n self.raster_ops.set_draw_color(self.bg_color);\n self.raster_ops.draw_rect_filled(xy, size)?;\n\n self.raster_ops.set_draw_color(self.fg_color);\n self.raster_ops.write_text(xy, &line_buffer.into_inner())?;\n self.cursor_pos.x += len;\n }\n\n line_buffer = remaining;\n if line_buffer.is_empty() {\n break;\n } else {\n self.open_line()?;\n }\n }\n\n Ok(())\n }\n```"}], "func_name": "raw_write_wrapped", "docstring": "Renders the given text at the current cursor position, with wrapping and\nscrolling if necessary.", "repo": "endbasic/endbasic", "path": "std/src/console/graphics.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/graphics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6db88d2b6bb809119171e64a53313b7f8efb67986c9af6b1aa21b36e35482f6d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_capacity\n\nDocumentation:\nCreates an empty `LineBuffer` with an allocated `capacity`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_capacity(capacity: usize) -> Self {\n Self { line: String::with_capacity(capacity) }\n }\n```"}], "func_name": "with_capacity", "docstring": "Creates an empty `LineBuffer` with an allocated `capacity`.", "repo": "endbasic/endbasic", "path": "std/src/console/linebuffer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/linebuffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c3f53c7fdd5ce95ebff17fefd78f0463bf8a101c51388daaec983e7e520710cc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: range\n\nDocumentation:\nExtracts a range of characters from this buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn range(&self, start_pos: usize, end_pos: usize) -> String {\n let count = end_pos.saturating_sub(start_pos);\n self.chars().skip(start_pos).take(count).collect()\n }\n```"}], "func_name": "range", "docstring": "Extracts a range of characters from this buffer.", "repo": "endbasic/endbasic", "path": "std/src/console/linebuffer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/linebuffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "802757d09fa6e3f69f7e394320dc9f3f56d8765da83bb34eef92962eb1b9c0e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove\n\nDocumentation:\nRemoves a character from this buffer.\n\nIf the given position if greater than the length of the buffer, this function does nothing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn remove(&mut self, pos: usize) {\n self.line = self.line.chars().take(pos).chain(self.line.chars().skip(pos + 1)).collect();\n }\n```"}], "func_name": "remove", "docstring": "Removes a character from this buffer.\n\nIf the given position if greater than the length of the buffer, this function does nothing.", "repo": "endbasic/endbasic", "path": "std/src/console/linebuffer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/linebuffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "30f84d4eb0889ff51a6a4ea8f2ba9b8dbb77f6c25386c07188f4106ef6417cb8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nInserts a char at the given position.\n\nIf the position is greater than the buffer length, the character will be appended at the\nend ot it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert(&mut self, pos: usize, ch: char) {\n self.line = self\n .line\n .chars()\n .take(pos)\n .chain(iter::once(ch))\n .chain(self.line.chars().skip(pos))\n .collect();\n }\n```"}], "func_name": "insert", "docstring": "Inserts a char at the given position.\n\nIf the position is greater than the buffer length, the character will be appended at the\nend ot it.", "repo": "endbasic/endbasic", "path": "std/src/console/linebuffer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/linebuffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "08151fd985eb08e883dce07c2b6db8af31d71b1cf5050a362441faf37e3f6271"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert_str\n\nDocumentation:\nInserts the given string `s` into the buffer at `pos`.\n\nIf `pos` is greater than the length of the buffer, `s` will be appended at the end of it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert_str(&mut self, pos: usize, s: &str) {\n self.line = self\n .line\n .chars()\n .take(pos)\n .chain(s.chars())\n .chain(self.line.chars().skip(pos))\n .collect();\n }\n```"}], "func_name": "insert_str", "docstring": "Inserts the given string `s` into the buffer at `pos`.\n\nIf `pos` is greater than the length of the buffer, `s` will be appended at the end of it.", "repo": "endbasic/endbasic", "path": "std/src/console/linebuffer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/linebuffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d1cca0bde31fc0d47e05cbc98b7b7bd3ea16fb954bc204c564707d5b7bdf8017"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: split_off\n\nDocumentation:\nSplits the buffer in two parts at the position `at`.\n\nReturns the remaining part of the buffer (same behavior as `String::split_off`).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn split_off(&mut self, at: usize) -> LineBuffer {\n let ret = LineBuffer::from(self.line.chars().skip(at).collect::());\n self.line = self.line.chars().take(at).collect();\n ret\n }\n```"}], "func_name": "split_off", "docstring": "Splits the buffer in two parts at the position `at`.\n\nReturns the remaining part of the buffer (same behavior as `String::split_off`).", "repo": "endbasic/endbasic", "path": "std/src/console/linebuffer.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/linebuffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a0375ae4898c287f8270e4fba780dcf3e184fe4a02b54194f922b83a864b29f8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConstructs a new coordinate at the given `(x, y)` position.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(x: u16, y: u16) -> Self {\n Self { x, y }\n }\n```"}], "func_name": "new", "docstring": "Constructs a new coordinate at the given `(x, y)` position.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "999950c75737b8919d08b9f0e03a26398f0eac464b3d6e94b1e74217c956217a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConstruts a new size in pixels, validating that the quantities are non-zero.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(width: u16, height: u16) -> Self {\n debug_assert!(width > 0, \"Zero widths don't make sense\");\n debug_assert!(height > 0, \"Zero heights don't make sense\");\n Self { width, height }\n }\n```"}], "func_name": "new", "docstring": "Construts a new size in pixels, validating that the quantities are non-zero.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4fb16972e7f8912835946b4b1a4308c5b5a9ea4aa6932e96a91505daa50dba0f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: size_pixels\n\nDocumentation:\nQueries the size of the graphical console.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn size_pixels(&self) -> io::Result {\n Err(io::Error::other(\"No graphics support in this console\"))\n }\n```"}], "func_name": "size_pixels", "docstring": "Queries the size of the graphical console.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "341964fa152f69b78460eceb7a584bf20425636126a4919759446d1ff1e36931"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: draw_circle\n\nDocumentation:\nDraws the outline of a circle at `_center` with `_radius` using the current drawing color.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn draw_circle(&mut self, _center: PixelsXY, _radius: u16) -> io::Result<()> {\n Err(io::Error::other(\"No graphics support in this console\"))\n }\n```"}], "func_name": "draw_circle", "docstring": "Draws the outline of a circle at `_center` with `_radius` using the current drawing color.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "37dae56a7c7ded27b23293cedd1898ad3943bcca5735427a4ea23ca2ae382627"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: draw_circle_filled\n\nDocumentation:\nDraws a filled circle at `_center` with `_radius` using the current drawing color.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn draw_circle_filled(&mut self, _center: PixelsXY, _radius: u16) -> io::Result<()> {\n Err(io::Error::other(\"No graphics support in this console\"))\n }\n```"}], "func_name": "draw_circle_filled", "docstring": "Draws a filled circle at `_center` with `_radius` using the current drawing color.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c4ba622e0a24d0af71aed46885b16e1abb2d17f936c9d55e701625b0f06d230b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: draw_line\n\nDocumentation:\nDraws a line from `_x1y1` to `_x2y2` using the current drawing color.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn draw_line(&mut self, _x1y1: PixelsXY, _x2y2: PixelsXY) -> io::Result<()> {\n Err(io::Error::other(\"No graphics support in this console\"))\n }\n```"}], "func_name": "draw_line", "docstring": "Draws a line from `_x1y1` to `_x2y2` using the current drawing color.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b7d5f2e39ce80d2ae9d5f96ef7d4fcb16202a443bafd50f65150796d7cfb3901"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: draw_pixel\n\nDocumentation:\nDraws a single pixel at `_xy` using the current drawing color.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn draw_pixel(&mut self, _xy: PixelsXY) -> io::Result<()> {\n Err(io::Error::other(\"No graphics support in this console\"))\n }\n```"}], "func_name": "draw_pixel", "docstring": "Draws a single pixel at `_xy` using the current drawing color.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7be23c5c0a3800cf9061a3ed568f561b810c820e1ef59fcdaec4e4156b972047"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: draw_rect\n\nDocumentation:\nDraws the outline of a rectangle from `_x1y1` to `_x2y2` using the current drawing color.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn draw_rect(&mut self, _x1y1: PixelsXY, _x2y2: PixelsXY) -> io::Result<()> {\n Err(io::Error::other(\"No graphics support in this console\"))\n }\n```"}], "func_name": "draw_rect", "docstring": "Draws the outline of a rectangle from `_x1y1` to `_x2y2` using the current drawing color.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f044140d282ee4974dbbe1156d5763cfdc9c77a3b7ad8fbbf9fe93a44d83b191"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: draw_rect_filled\n\nDocumentation:\nDraws a filled rectangle from `_x1y1` to `_x2y2` using the current drawing color.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn draw_rect_filled(&mut self, _x1y1: PixelsXY, _x2y2: PixelsXY) -> io::Result<()> {\n Err(io::Error::other(\"No graphics support in this console\"))\n }\n```"}], "func_name": "draw_rect_filled", "docstring": "Draws a filled rectangle from `_x1y1` to `_x2y2` using the current drawing color.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e38ded66e20e4c2d0eda2d366bf991d03024edebdc8d1275e1bab269b4a8ebab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_control_chars\n\nDocumentation:\nChecks if a given string has control characters.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn has_control_chars(s: &str) -> bool {\n for ch in s.chars() {\n if ch.is_control() {\n return true;\n }\n }\n false\n}\n```"}], "func_name": "has_control_chars", "docstring": "Checks if a given string has control characters.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a4acf0b16ebfdb9e1c8d8acc66f5c786b5a42a5ac44a3aab51872f7cf49ad32e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_control_chars\n\nDocumentation:\nRemoves control characters from a string to make it suitable for printing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn remove_control_chars>(s: S) -> String {\n let s = s.into();\n\n // Handle the expected common case first. We use this function to strip control characters\n // before printing them to the console, and thus we expect such input strings to rarely include\n // control characters.\n if !has_control_chars(&s) {\n return s;\n }\n\n let mut o = String::with_capacity(s.len());\n for ch in s.chars() {\n if ch.is_control() {\n o.push(' ');\n } else {\n o.push(ch);\n }\n }\n o\n}\n```"}], "func_name": "remove_control_chars", "docstring": "Removes control characters from a string to make it suitable for printing.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd552dff2b9a9d14f673f4afc22f0223b2960cd50b92ba35d641309f47f86b85"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_env_var_as_u16\n\nDocumentation:\nGets the value of the environment variable `name` and interprets it as a `u16`. Returns\n`None` if the variable is not set or if its contents are invalid.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_env_var_as_u16(name: &str) -> Option {\n match env::var_os(name) {\n Some(value) => value.as_os_str().to_string_lossy().parse::().map(Some).unwrap_or(None),\n None => None,\n }\n}\n```"}], "func_name": "get_env_var_as_u16", "docstring": "Gets the value of the environment variable `name` and interprets it as a `u16`. Returns\n`None` if the variable is not set or if its contents are invalid.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4b83e54458d586c341d802ebccf7cd591c50d2be1604b22826a028d478571d8d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: line_to_keys\n\nDocumentation:\nConverts a line of text into a collection of keys.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn line_to_keys(s: String) -> VecDeque {\n let mut keys = VecDeque::default();\n for ch in s.chars() {\n if ch == '\\x1b' {\n keys.push_back(Key::Escape);\n } else if ch == '\\n' {\n keys.push_back(Key::NewLine);\n } else if ch == '\\r' {\n // Ignore. When we run under Windows and use golden test input files, we end up\n // seeing two separate characters to terminate a newline (CRLF) and these confuse\n // our tests. I am not sure why this doesn't seem to be a problem for interactive\n // usage though, but it might just be that crossterm hides this from us.\n } else if !ch.is_control() {\n keys.push_back(Key::Char(ch));\n } else {\n keys.push_back(Key::Unknown);\n }\n }\n keys\n}\n```"}], "func_name": "line_to_keys", "docstring": "Converts a line of text into a collection of keys.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e9a982b072bb52c3467c7f797981366afb2c0a1f8fc19a02ac31a2a2c90112b3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_key_from_stdin\n\nDocumentation:\nReads a single key from stdin when not attached to a TTY. Because characters are not\nvisible to us until a newline is received, this reads complete lines and buffers them in\nmemory inside the given `buffer`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_key_from_stdin(buffer: &mut VecDeque) -> io::Result {\n if buffer.is_empty() {\n let mut line = String::new();\n if io::stdin().read_line(&mut line)? == 0 {\n return Ok(Key::Eof);\n }\n *buffer = line_to_keys(line);\n }\n match buffer.pop_front() {\n Some(key) => Ok(key),\n None => Ok(Key::Eof),\n }\n}\n```"}], "func_name": "read_key_from_stdin", "docstring": "Reads a single key from stdin when not attached to a TTY. Because characters are not\nvisible to us until a newline is received, this reads complete lines and buffers them in\nmemory inside the given `buffer`.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "86b15169df45fb9005888ddf467187e4b9708eb4d2fa33177cef6a17a6ec4d48"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_narrow\n\nDocumentation:\nReturns true if the console is too narrow for the standard interface.\n\nA narrow console is defined as one that cannot fit the welcome message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_narrow(console: &dyn Console) -> bool {\n match console.size_chars() {\n Ok(size) => size.x < 50,\n Err(_) => false,\n }\n}\n```"}], "func_name": "is_narrow", "docstring": "Returns true if the console is too narrow for the standard interface.\n\nA narrow console is defined as one that cannot fit the welcome message.", "repo": "endbasic/endbasic", "path": "std/src/console/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7fba9aeed5202f261af16304567ac62c81f84ba91678627a883be39412a655fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nWraps `console` to offer pagination features.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new(console: &'a mut dyn Console) -> io::Result {\n let size = console.size_chars()?;\n let more_message = if is_narrow(console) { MORE_MESSAGE_NARROW } else { MORE_MESSAGE_WIDE };\n Ok(Self { console, size, more_message, cur_columns: 0, cur_lines: 0 })\n }\n```"}], "func_name": "new", "docstring": "Wraps `console` to offer pagination features.", "repo": "endbasic/endbasic", "path": "std/src/console/pager.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/pager.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a07c04518f632d522d3cd6971594cc3be69985aa3f4eca0759eef348f2b2beb3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_color\n\nDocumentation:\nSets the console's foreground and background colors to `fg` and `bg`.\n\nIf any of the colors is `None`, the color is left unchanged.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn set_color(&mut self, fg: Option, bg: Option) -> io::Result<()> {\n self.console.set_color(fg, bg)\n }\n```"}], "func_name": "set_color", "docstring": "Sets the console's foreground and background colors to `fg` and `bg`.\n\nIf any of the colors is `None`, the color is left unchanged.", "repo": "endbasic/endbasic", "path": "std/src/console/pager.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/pager.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "62c3771ba0532171a6f3b3f80c8414542642025dfc499a0e1cce1a823932dfd0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print\n\nDocumentation:\nWrites `text` to the console, followed by a newline or CRLF pair depending on the needs of\nthe console to advance a line.\n\nThe input `text` is not supposed to contain any control characters, such as CR or LF.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn print(&mut self, text: &str) -> io::Result<()> {\n self.console.print(text)?;\n if self.console.is_interactive() {\n self.cur_columns += text.len();\n self.cur_lines += (self.cur_columns / usize::from(self.size.x)) + 1;\n\n if self.cur_lines >= usize::from(self.size.y) - 1 {\n let previous_color = self.console.color();\n if previous_color != (None, None) {\n self.console.set_color(None, None)?;\n }\n self.console.print(self.more_message)?;\n if previous_color != (None, None) {\n self.console.set_color(previous_color.0, previous_color.1)?;\n }\n if matches!(self.console.read_key().await?, Key::Escape | Key::Interrupt) {\n return Err(io::Error::new(io::ErrorKind::Interrupted, \"Interrupted\"));\n }\n\n self.cur_lines = 0;\n }\n\n self.cur_columns = 0;\n }\n Ok(())\n }\n```"}], "func_name": "print", "docstring": "Writes `text` to the console, followed by a newline or CRLF pair depending on the needs of\nthe console to advance a line.\n\nThe input `text` is not supposed to contain any control characters, such as CR or LF.", "repo": "endbasic/endbasic", "path": "std/src/console/pager.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/pager.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "31545a3206ac50122cbb3f3cc4ab9017fdd4f04abddd996b47337ed37882e373"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write\n\nDocumentation:\nWrites the text into the console at the position of the cursor.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn write(&mut self, text: &str) -> io::Result<()> {\n self.console.write(text)?;\n if self.console.is_interactive() {\n self.cur_columns += text.len();\n }\n Ok(())\n }\n```"}], "func_name": "write", "docstring": "Writes the text into the console at the position of the cursor.", "repo": "endbasic/endbasic", "path": "std/src/console/pager.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/pager.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d256307ff2e1ac49a0f7c69c4e2c28516504309cad8a4b9c64c32faebcd05608"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_line\n\nDocumentation:\nRefreshes the current input line to display `line` assuming that the cursor is currently\noffset by `pos` characters from the beginning of the input and that the previous line was\n`clear_len` characters long.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn update_line(\n console: &mut dyn Console,\n pos: usize,\n clear_len: usize,\n line: &LineBuffer,\n) -> io::Result<()> {\n console.hide_cursor()?;\n if pos > 0 {\n console.move_within_line(-(pos as i16))?;\n }\n if !line.is_empty() {\n console.write(&line.to_string())?;\n }\n let line_len = line.len();\n if line_len < clear_len {\n let diff = clear_len - line_len;\n console.write(&\" \".repeat(diff))?;\n console.move_within_line(-(diff as i16))?;\n }\n console.show_cursor()\n}\n```"}], "func_name": "update_line", "docstring": "Refreshes the current input line to display `line` assuming that the cursor is currently\noffset by `pos` characters from the beginning of the input and that the previous line was\n`clear_len` characters long.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6e04fa7b1db83b3399617d3df8d96d8ac5583e6f43eeb55b3107792974290aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_line_interactive\n\nDocumentation:\nReads a line of text interactively from the console, using the given `prompt` and pre-filling\nthe input with `previous`. If `history` is not `None`, then this appends the newly entered line\ninto the history and allows navigating through it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn read_line_interactive(\n console: &mut dyn Console,\n prompt: &str,\n previous: &str,\n mut history: Option<&mut Vec>,\n echo: bool,\n) -> io::Result {\n let console_width = {\n let console_size = console.size_chars()?;\n usize::from(console_size.x)\n };\n\n let mut prompt = Cow::from(prompt);\n let mut prompt_len = prompt.len();\n if prompt_len >= console_width {\n if console_width >= 5 {\n prompt = Cow::from(format!(\"{}...\", &prompt[0..console_width - 5]));\n } else {\n prompt = Cow::from(\"\");\n }\n prompt_len = prompt.len();\n }\n\n let mut line = LineBuffer::from(previous);\n if !prompt.is_empty() || !line.is_empty() {\n if echo {\n console.write(&format!(\"{}{}\", prompt, line))?;\n } else {\n console.write(&format!(\"{}{}\", prompt, \"*\".repeat(line.len())))?;\n }\n console.sync_now()?;\n }\n\n let width = {\n // Assumes that the prompt was printed at column 0. If that was not the case, line length\n // calculation does not work.\n console_width - prompt_len\n };\n\n // Insertion position *within* the line, without accounting for the prompt.\n // TODO(zenria): Handle UTF-8 graphemes.\n let mut pos = line.len();\n\n let mut history_pos = match history.as_mut() {\n Some(history) => {\n history.push(line.to_string());\n history.len() - 1\n }\n None => 0,\n };\n\n loop {\n match console.read_key().await? {\n Key::ArrowUp => {\n if let Some(history) = history.as_mut() {\n if history_pos == 0 {\n continue;\n }\n\n let clear_len = line.len();\n\n history[history_pos] = line.into_inner();\n history_pos -= 1;\n line = LineBuffer::from(&history[history_pos]);\n\n update_line(console, pos, clear_len, &line)?;\n\n pos = line.len();\n }\n }\n\n Key::ArrowDown => {\n if let Some(history) = history.as_mut() {\n if history_pos == history.len() - 1 {\n continue;\n }\n\n let clear_len = line.len();\n\n history[history_pos] = line.to_string();\n history_pos += 1;\n line = LineBuffer::from(&history[history_pos]);\n\n update_line(console, pos, clear_len, &line)?;\n\n pos = line.len();\n }\n }\n\n Key::ArrowLeft => {\n if pos > 0 {\n console.move_within_line(-1)?;\n pos -= 1;\n }\n }\n\n Key::ArrowRight => {\n if pos < line.len() {\n console.move_within_line(1)?;\n pos += 1;\n }\n }\n\n Key::Backspace => {\n if pos > 0 {\n console.hide_cursor()?;\n console.move_within_line(-1)?;\n if echo {\n console.write(&line.end(pos))?;\n } else {\n console.write(&SECURE_CHAR.repeat(line.len() - pos))?;\n }\n console.write(\" \")?;\n console.move_within_line(-((line.len() - pos) as i16 + 1))?;\n console.show_cursor()?;\n line.remove(pos - 1);\n pos -= 1;\n }\n }\n\n Key::CarriageReturn => {\n // TODO(jmmv): This is here because the integration tests may be checked out with\n // CRLF line endings on Windows, which means we'd see two characters to end a line\n // instead of one. Not sure if we should do this or if instead we should ensure\n // the golden data we feed to the tests has single-character line endings.\n if cfg!(not(target_os = \"windows\")) {\n console.print(\"\")?;\n break;\n }\n }\n\n Key::Char(ch) => {\n let line_len = line.len();\n debug_assert!(line_len < width);\n if line_len == width - 1 {\n // TODO(jmmv): Implement support for lines that exceed the width of the input\n // field (the width of the screen).\n continue;\n }\n\n if pos < line_len {\n console.hide_cursor()?;\n if echo {\n let mut buf = [0u8; 4];\n console.write(ch.encode_utf8(&mut buf))?;\n console.write(&line.end(pos))?;\n } else {\n console.write(&SECURE_CHAR.repeat(line_len - pos + 1))?;\n }\n console.move_within_line(-((line_len - pos) as i16))?;\n console.show_cursor()?;\n line.insert(pos, ch);\n } else {\n if echo {\n let mut buf = [0u8; 4];\n console.write(ch.encode_utf8(&mut buf))?;\n } else {\n console.write(SECURE_CHAR)?;\n }\n line.insert(line_len, ch);\n }\n pos += 1;\n }\n\n Key::End => {\n let offset = line.len() - pos;\n if offset > 0 {\n console.move_within_line(offset as i16)?;\n pos += offset;\n }\n }\n\n Key::Eof => return Err(io::Error::new(io::ErrorKind::UnexpectedEof, \"EOF\")),\n\n Key::Escape => {\n // Intentionally ignored.\n }\n\n Key::Home => {\n if pos > 0 {\n console.move_within_line(-(pos as i16))?;\n pos = 0;\n }\n }\n\n Key::Interrupt => return Err(io::Error::new(io::ErrorKind::Interrupted, \"Ctrl+C\")),\n\n Key::NewLine => {\n console.print(\"\")?;\n break;\n }\n\n Key::PageDown | Key::PageUp => {\n // Intentionally ignored.\n }\n\n Key::Tab => {\n // TODO(jmmv): Would be nice to have some form of auto-completion.\n }\n\n // TODO(jmmv): Should do something smarter with unknown keys.\n Key::Unknown => (),\n }\n }\n\n if let Some(history) = history.as_mut() {\n if line.is_empty() {\n history.pop();\n } else {\n let last = history.len() - 1;\n history[last] = line.to_string();\n }\n }\n Ok(line.into_inner())\n}\n```"}], "func_name": "read_line_interactive", "docstring": "Reads a line of text interactively from the console, using the given `prompt` and pre-filling\nthe input with `previous`. If `history` is not `None`, then this appends the newly entered line\ninto the history and allows navigating through it.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9d2e323448b486ba86bb7ecd24e97effd621500fe3a2362561efac3ddfa00adf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_line_raw\n\nDocumentation:\nReads a line of text interactively from the console, which is not expected to be a TTY.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn read_line_raw(console: &mut dyn Console) -> io::Result {\n let mut line = String::new();\n loop {\n match console.read_key().await? {\n Key::ArrowUp | Key::ArrowDown | Key::ArrowLeft | Key::ArrowRight => (),\n Key::Backspace => {\n if !line.is_empty() {\n line.pop();\n }\n }\n Key::CarriageReturn => {\n // TODO(jmmv): This is here because the integration tests may be checked out with\n // CRLF line endings on Windows, which means we'd see two characters to end a line\n // instead of one. Not sure if we should do this or if instead we should ensure\n // the golden data we feed to the tests has single-character line endings.\n if cfg!(not(target_os = \"windows\")) {\n break;\n }\n }\n Key::Char(ch) => line.push(ch),\n Key::End | Key::Home => (),\n Key::Escape => (),\n Key::Eof => return Err(io::Error::new(io::ErrorKind::UnexpectedEof, \"EOF\")),\n Key::Interrupt => return Err(io::Error::new(io::ErrorKind::Interrupted, \"Ctrl+C\")),\n Key::NewLine => break,\n Key::PageDown | Key::PageUp => (),\n Key::Tab => (),\n Key::Unknown => line.push('?'),\n }\n }\n Ok(line)\n}\n```"}], "func_name": "read_line_raw", "docstring": "Reads a line of text interactively from the console, which is not expected to be a TTY.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b42e50b42e9e624d4f2611ece9e324c9cf4f518198473bfc1956de5866fb4007"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_line\n\nDocumentation:\nReads a line from the console. If the console is interactive, this does fancy line editing and\nuses the given `prompt` and pre-fills the input with `previous`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn read_line(\n console: &mut dyn Console,\n prompt: &str,\n previous: &str,\n history: Option<&mut Vec>,\n) -> io::Result {\n if console.is_interactive() {\n read_line_interactive(console, prompt, previous, history, true).await\n } else {\n read_line_raw(console).await\n }\n}\n```"}], "func_name": "read_line", "docstring": "Reads a line from the console. If the console is interactive, this does fancy line editing and\nuses the given `prompt` and pre-fills the input with `previous`.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "43ff29fa90123e4d76422235d38c6aca740b8500e857584f70020b83b6692e02"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_line_secure\n\nDocumentation:\nReads a line from the console without echo using the given `prompt`.\n\nThe console must be interactive for this to work, as otherwise we do not have a mechanism to\nsuppress echo.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn read_line_secure(console: &mut dyn Console, prompt: &str) -> io::Result {\n if !console.is_interactive() {\n return Err(io::Error::other(\"Cannot read secure strings from a raw console\".to_owned()));\n }\n read_line_interactive(console, prompt, \"\", None, false).await\n}\n```"}], "func_name": "read_line_secure", "docstring": "Reads a line from the console without echo using the given `prompt`.\n\nThe console must be interactive for this to work, as otherwise we do not have a mechanism to\nsuppress echo.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ed0c88fdc8157af54fdfae20177dfa434e2f8455ced5e87a5b6036d6d559793"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default\n\nDocumentation:\nConstructs a new test that feeds no input to the function, with no prompt or previous\ntext, and expects an empty return line and no changes to the console.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn default() -> Self {\n Self {\n size_chars: CharsXY::new(15, 5),\n keys: vec![],\n prompt: \"\",\n previous: \"\",\n history: None,\n echo: true,\n exp_line: \"\",\n exp_output: vec![],\n exp_history: None,\n }\n }\n```"}], "func_name": "default", "docstring": "Constructs a new test that feeds no input to the function, with no prompt or previous\ntext, and expects an empty return line and no changes to the console.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b434306a73af834b11d3008a7aa973bc3bcfbcfe83f7aef28024e645afdddbf0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_key\n\nDocumentation:\nAdds `key` to the golden input.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_key(mut self, key: Key) -> Self {\n self.keys.push(key);\n self\n }\n```"}], "func_name": "add_key", "docstring": "Adds `key` to the golden input.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d4a86c2f6dbbf5674da3ea99726f4460fcd21301e5570540ccac32f854db883f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_key_chars\n\nDocumentation:\nAdds a bunch of `chars` as individual key presses to the golden input.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_key_chars(mut self, chars: &'static str) -> Self {\n for ch in chars.chars() {\n self.keys.push(Key::Char(ch));\n }\n self\n }\n```"}], "func_name": "add_key_chars", "docstring": "Adds a bunch of `chars` as individual key presses to the golden input.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bfc9139421dacc3aa489c156d9c37289402e0ccb661ed0138876329fef3a31bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_output\n\nDocumentation:\nAdds a single state change to the expected output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_output(mut self, output: CapturedOut) -> Self {\n self.exp_output.push(output);\n self\n }\n```"}], "func_name": "add_output", "docstring": "Adds a single state change to the expected output.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5bae96bed958ee8f0112541c1bc8898395e6fa80f5e629bea619594263747e2a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_output_bytes\n\nDocumentation:\nAdds a bunch of `bytes` as separate console writes to the expected output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_output_bytes(mut self, bytes: &'static str) -> Self {\n if bytes.is_empty() {\n self.exp_output.push(CapturedOut::Write(\"\".to_string()))\n } else {\n for b in bytes.chars() {\n let mut buf = [0u8; 4];\n self.exp_output.push(CapturedOut::Write(b.encode_utf8(&mut buf).to_string()));\n }\n }\n self\n }\n```"}], "func_name": "add_output_bytes", "docstring": "Adds a bunch of `bytes` as separate console writes to the expected output.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b457ce5c3cb9bcb6fd8008f36d8283535d02fd4207fcd1460378de334f07ffa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_size_chars\n\nDocumentation:\nSets the size of the console.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_size_chars(mut self, size: CharsXY) -> Self {\n self.size_chars = size;\n self\n }\n```"}], "func_name": "set_size_chars", "docstring": "Sets the size of the console.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a2c42eb5aad638a0ba1b4196188943830be02ac575755436e11ffe0836dbc4ae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_line\n\nDocumentation:\nSets the expected resulting line for the test.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_line(mut self, line: &'static str) -> Self {\n self.exp_line = line;\n self\n }\n```"}], "func_name": "set_line", "docstring": "Sets the expected resulting line for the test.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d543b90d085df971b0d0ff0bb98bf57f08953212494882485230016547a4b301"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_prompt\n\nDocumentation:\nSets the prompt to use for the test.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_prompt(mut self, prompt: &'static str) -> Self {\n self.prompt = prompt;\n self\n }\n```"}], "func_name": "set_prompt", "docstring": "Sets the prompt to use for the test.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f018ea0af2f43b7b047b15a4df07206984758f2b373e81fd5766d618d20c4cd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_previous\n\nDocumentation:\nSets the previous text to use for the test.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_previous(mut self, previous: &'static str) -> Self {\n self.previous = previous;\n self\n }\n```"}], "func_name": "set_previous", "docstring": "Sets the previous text to use for the test.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e969190d8afed83ea7060537986537b305ce6a2cae2d9c5f66619f5b23a80b23"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_history\n\nDocumentation:\nEnables history tracking and sets the history to use for the test as `history` and\nexpects that `history` matches `exp_history` upon test completion.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_history(mut self, history: Vec, exp_history: Vec) -> Self {\n self.history = Some(history);\n self.exp_history = Some(exp_history);\n self\n }\n```"}], "func_name": "set_history", "docstring": "Enables history tracking and sets the history to use for the test as `history` and\nexpects that `history` matches `exp_history` upon test completion.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7fce7a436a8dba0b38ca7e57642f967fbb8b04e2403b933f2edc542ca9cd1f27"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_echo\n\nDocumentation:\nSets whether read_line echoes characters or not.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_echo(mut self, echo: bool) -> Self {\n self.echo = echo;\n self\n }\n```"}], "func_name": "set_echo", "docstring": "Sets whether read_line echoes characters or not.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "37ebf727c2f2d6ccf492bc30796cfee687e619aff23c725b3e5aa43f81d8e1e1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accept\n\nDocumentation:\nAdds a final return key to the golden input, a newline to the expected output, and\nexecutes the test.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn accept(mut self) {\n self.keys.push(Key::NewLine);\n self.exp_output.push(CapturedOut::Print(\"\".to_owned()));\n\n let mut console = MockConsole::default();\n console.add_input_keys(&self.keys);\n console.set_size_chars(self.size_chars);\n let line = match self.history.as_mut() {\n Some(history) => block_on(read_line_interactive(\n &mut console,\n self.prompt,\n self.previous,\n Some(history),\n self.echo,\n ))\n .unwrap(),\n None => block_on(read_line_interactive(\n &mut console,\n self.prompt,\n self.previous,\n None,\n self.echo,\n ))\n .unwrap(),\n };\n assert_eq!(self.exp_line, &line);\n assert_eq!(self.exp_output.as_slice(), console.captured_out());\n assert_eq!(self.exp_history, self.history);\n }\n```"}], "func_name": "accept", "docstring": "Adds a final return key to the golden input, a newline to the expected output, and\nexecutes the test.", "repo": "endbasic/endbasic", "path": "std/src/console/readline.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/readline.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "195a3e8357deed4139612f5136e3baeaa56337454df41ececc500325a79c961a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_resolution\n\nDocumentation:\nParses a graphical `resolution` of the form `[WIDTHxHEIGHT][fs]`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_resolution(resolution: &str) -> Result {\n if resolution == \"fs\" {\n return Ok(Resolution::FullScreenDesktop);\n }\n\n let (dimensions, fullscreen) = match resolution.strip_suffix(\"fs\") {\n Some(prefix) => (prefix, true),\n None => (resolution, false),\n };\n\n match dimensions.split_once('x') {\n Some((width, height)) => {\n let width = NonZeroU32::from_str(width).map_err(|e| {\n mkerror!(\"Invalid width {} in resolution {}: {}\", width, resolution, e)\n })?;\n let height = NonZeroU32::from_str(height).map_err(|e| {\n mkerror!(\"Invalid height {} in resolution {}: {}\", height, resolution, e)\n })?;\n\n if fullscreen {\n Ok(Resolution::FullScreen((width, height)))\n } else {\n Ok(Resolution::Windowed((width, height)))\n }\n }\n _ => Err(mkerror!(\n \"Invalid resolution {}: must be of the form [WIDTHxHEIGHT][fs]\",\n resolution\n )),\n }\n}\n```"}], "func_name": "parse_resolution", "docstring": "Parses a graphical `resolution` of the form `[WIDTHxHEIGHT][fs]`.", "repo": "endbasic/endbasic", "path": "std/src/console/spec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/spec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "28a486d5685a54087bfc71987773ac5b3ecb76e138cf63ea5f021a63f7b465de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init\n\nDocumentation:\nInitializes the console specification parser from `s`.\n\n`s` *must* not be empty. The caller must supply, at least, a default console driver name\nif the user did not specify any console flag.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn init(s: &'a str) -> Self {\n assert!(!s.is_empty());\n\n let (driver, rest) = s.split_once(':').unwrap_or((s, \"\"));\n\n let mut flags = HashSet::default();\n let mut keyed_flags = HashMap::default();\n for pair in rest.split(',') {\n if pair.is_empty() {\n continue;\n }\n\n match pair.split_once('=') {\n None => {\n let _exists = flags.insert(pair);\n }\n Some((k, v)) => {\n let _old = keyed_flags.insert(k, v);\n }\n }\n }\n\n Self { driver, flags, keyed_flags }\n }\n```"}], "func_name": "init", "docstring": "Initializes the console specification parser from `s`.\n\n`s` *must* not be empty. The caller must supply, at least, a default console driver name\nif the user did not specify any console flag.", "repo": "endbasic/endbasic", "path": "std/src/console/spec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/spec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4899580283b7c00c183b9ac601cbfc0b45f308b4a06c19e7031347a430c8de38"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: take_keyed_flag\n\nDocumentation:\nQueries the value of the keyed `flag` from the specification, which may or may not be\npresent. The value is parsed according to the type `V`.\n\nThe flag is marked as \"checked\" so that `finish` won't raise it as residual.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn take_keyed_flag(&mut self, key: &str) -> Result>\n where\n V: FromStr,\n V::Err: Display,\n {\n match self.take_keyed_flag_str(key) {\n Some(v) => V::from_str(v)\n .map(|v| Some(v))\n .map_err(|e| mkerror!(\"Invalid console flag {}: {}\", key, e)),\n None => Ok(None),\n }\n }\n```"}], "func_name": "take_keyed_flag", "docstring": "Queries the value of the keyed `flag` from the specification, which may or may not be\npresent. The value is parsed according to the type `V`.\n\nThe flag is marked as \"checked\" so that `finish` won't raise it as residual.", "repo": "endbasic/endbasic", "path": "std/src/console/spec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/spec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5812a6b65d770bbb4200620a8c6aa8286f5770154b0e2729bb0ca5792617d878"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish\n\nDocumentation:\nValidates that all provided flags have been queried by the driver.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn finish(self) -> Result<()> {\n if self.flags.is_empty() && self.keyed_flags.is_empty() {\n Ok(())\n } else {\n let flags_iter = self.flags.into_iter();\n let keyed_iter = self.keyed_flags.into_keys();\n let mut unknown = flags_iter.chain(keyed_iter).collect::>();\n unknown.sort();\n Err(mkerror!(\n \"Console driver {} does not recognize flags: {}\",\n self.driver,\n unknown.join(\", \")\n ))\n }\n }\n```"}], "func_name": "finish", "docstring": "Validates that all provided flags have been queried by the driver.", "repo": "endbasic/endbasic", "path": "std/src/console/spec.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/spec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a42660f1386f933057f0b959a9aa31cdf60283e4435446328a6282197b636f67"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: maybe_flush\n\nDocumentation:\nFlushes the console, which has already been written to via `lock`, if syncing is enabled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn maybe_flush(&self, mut lock: StdoutLock<'_>) -> io::Result<()> {\n if self.sync_enabled {\n lock.flush()\n } else {\n Ok(())\n }\n }\n```"}], "func_name": "maybe_flush", "docstring": "Flushes the console, which has already been written to via `lock`, if syncing is enabled.", "repo": "endbasic/endbasic", "path": "std/src/console/trivial.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/console/trivial.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d29ce8449dcdd7f20715e8f9480b3e22f511fc988d56a1b775f15f29ec3eeb4f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_coordinate\n\nDocumentation:\nParses an expression that represents a single coordinate.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_coordinate(i: i32, pos: LineCol) -> Result {\n match i16::try_from(i) {\n Ok(i) => Ok(i),\n Err(_) => Err(Error::SyntaxError(pos, format!(\"Coordinate {} out of range\", i))),\n }\n}\n```"}], "func_name": "parse_coordinate", "docstring": "Parses an expression that represents a single coordinate.", "repo": "endbasic/endbasic", "path": "std/src/gfx/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc6cde86e31d955a57e0d9aaa93e6152adc7dc4f66d51efcf267f538fb083415"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_coordinates\n\nDocumentation:\nParses a pair of expressions that represent an (x,y) coordinate pair.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_coordinates(xvalue: i32, xpos: LineCol, yvalue: i32, ypos: LineCol) -> Result {\n Ok(PixelsXY { x: parse_coordinate(xvalue, xpos)?, y: parse_coordinate(yvalue, ypos)? })\n}\n```"}], "func_name": "parse_coordinates", "docstring": "Parses a pair of expressions that represent an (x,y) coordinate pair.", "repo": "endbasic/endbasic", "path": "std/src/gfx/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "59ac9a2d9c083c53c81a3ede83b80b456aabb81cc63ed6efbfe7b3a69283eab4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_radius\n\nDocumentation:\nParses an expression that represents a radius.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_radius(i: i32, pos: LineCol) -> Result {\n match u16::try_from(i) {\n Ok(i) => Ok(i),\n Err(_) if i < 0 => Err(Error::SyntaxError(pos, format!(\"Radius {} must be positive\", i))),\n Err(_) => Err(Error::SyntaxError(pos, format!(\"Radius {} out of range\", i))),\n }\n}\n```"}], "func_name": "parse_radius", "docstring": "Parses an expression that represents a radius.", "repo": "endbasic/endbasic", "path": "std/src/gfx/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "59b625cae5916c1e7556ecfcedad4daadb7470c5e6145a04fc6aeb657f46fb80"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `GFX_CIRCLE` command that draws an empty circle on `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"GFX_CIRCLE\")\n .with_syntax(&[(\n &[\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"x\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"y\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"r\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::End,\n ),\n ],\n None,\n )])\n .with_category(CATEGORY)\n .with_description(\n \"Draws a circle of radius r centered at (x,y).\nThe outline of the circle is drawn using the foreground color as selected by COLOR and the \\\narea of the circle is left untouched.\",\n )\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `GFX_CIRCLE` command that draws an empty circle on `console`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "57299695f52623b9eb7bb3aa28d8be13a4a79e7b964e086906f1484c34534c0a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `GFX_CIRCLEF` command that draws a filled circle on `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"GFX_CIRCLEF\")\n .with_syntax(&[(\n &[\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"x\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"y\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"r\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::End,\n ),\n ],\n None,\n )])\n .with_category(CATEGORY)\n .with_description(\n \"Draws a filled circle of radius r centered at (x,y).\nThe outline and area of the circle are drawn using the foreground color as selected by COLOR.\",\n )\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `GFX_CIRCLEF` command that draws a filled circle on `console`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "676d0010e78b9a6dd55acd05fdf353c15b64bf1da316d78ad65c9fce19e64754"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `GFX_LINE` command that draws a line on `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"GFX_LINE\")\n .with_syntax(&[(\n &[\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"x1\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"y1\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"x2\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"y2\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::End,\n ),\n ],\n None,\n )])\n .with_category(CATEGORY)\n .with_description(\n \"Draws a line from (x1,y1) to (x2,y2).\nThe line is drawn using the foreground color as selected by COLOR.\",\n )\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `GFX_LINE` command that draws a line on `console`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a387bfe9abf914a962f94e6124ed950552e1e1569ca02a90659d6bc3457a7de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `GFX_PIXEL` command that draws a single pixel on `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"GFX_PIXEL\")\n .with_syntax(&[(\n &[\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"x\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"y\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::End,\n ),\n ],\n None,\n )])\n .with_category(CATEGORY)\n .with_description(\n \"Draws a pixel at (x,y).\nThe pixel is drawn using the foreground color as selected by COLOR.\",\n )\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `GFX_PIXEL` command that draws a single pixel on `console`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3094e52c6361f980e9423a7ca7b455564b1c492f3b6529363e48b81444b29484"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `GFX_RECT` command that draws an empty rectangle on `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"GFX_RECT\")\n .with_syntax(&[(\n &[\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"x1\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"y1\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"x2\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"y2\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::End,\n ),\n ],\n None,\n )])\n .with_category(CATEGORY)\n .with_description(\n \"Draws a rectangle from (x1,y1) to (x2,y2).\nThe outline of the rectangle is drawn using the foreground color as selected by COLOR and the \\\narea of the rectangle is left untouched.\",\n )\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `GFX_RECT` command that draws an empty rectangle on `console`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8cbcd457294be21ec1f0ac9fc50972cb5feea7772b72278caf9e1a59f82f89f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `GFX_RECTF` command that draws a filled rectangle on `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"GFX_RECTF\")\n .with_syntax(&[(\n &[\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"x1\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"y1\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"x2\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"y2\"),\n vtype: ExprType::Integer,\n },\n ArgSepSyntax::End,\n ),\n ],\n None,\n )])\n .with_category(CATEGORY)\n .with_description(\n \"Draws a filled rectangle from (x1,y1) to (x2,y2).\nThe outline and area of the rectangle are drawn using the foreground color as selected by COLOR.\",\n )\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `GFX_RECTF` command that draws a filled rectangle on `console`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "13844c7e2ded0b9ea340b28745398fda0550471b34c3dd52dd0916e94e21413d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `GFX_SYNC` command that controls video syncing on `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"GFX_SYNC\")\n .with_syntax(&[\n (&[], None),\n (\n &[SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"enabled\"),\n vtype: ExprType::Boolean,\n },\n ArgSepSyntax::End,\n )],\n None,\n ),\n ])\n .with_category(CATEGORY)\n .with_description(\n \"Controls the video syncing flag and/or forces a sync.\nWith no arguments, this command triggers a video sync without updating the video syncing flag. \\\nWhen enabled? is specified, this updates the video syncing flag accordingly and triggers a video \\\nsync if enabled? is TRUE.\nWhen video syncing is enabled, all console commands immediately refresh the console. This is \\\nuseful to see the effects of the commands right away, which is why this is the default mode in the \\\ninterpreter. However, this is a *very* inefficient way of drawing.\nWhen video syncing is disabled, all console updates are buffered until video syncing is enabled \\\nagain. This is perfect to draw complex graphics efficiently. If this is what you want to do, \\\nyou should disable syncing first, render a frame, call GFX_SYNC to flush the frame, repeat until \\\nyou are done, and then enable video syncing again. Note that the textual cursor is not visible \\\nwhen video syncing is disabled.\nWARNING: Be aware that if you disable video syncing in the interactive interpreter, you will not \\\nbe able to see what you are typing any longer until you reenable video syncing.\",\n )\n .build(),\n console,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `GFX_SYNC` command that controls video syncing on `console`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0f31fb790905966e69978370f0f0771c6b9bf8da9afd83b615c9db28c8a49fce"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_errors_two_xy\n\nDocumentation:\nVerifies error conditions for a command named `name` that takes to X/Y pairs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_errors_two_xy(name: &'static str) {\n for args in &[\"1, 2, , 4\", \"1, 2, 3\", \"1, 2, 3, 4, 5\", \"2; 3, 4\"] {\n check_stmt_compilation_err(\n format!(\"1:1: {} expected x1%, y1%, x2%, y2%\", name),\n &format!(\"{} {}\", name, args),\n );\n }\n\n for args in &[\"-40000, 1, 1, 1\", \"1, -40000, 1, 1\", \"1, 1, -40000, 1\", \"1, 1, 1, -40000\"] {\n let pos = name.len() + 1 + args.find('-').unwrap() + 1;\n check_stmt_err(\n format!(\"1:{}: Coordinate -40000 out of range\", pos),\n &format!(\"{} {}\", name, args),\n );\n }\n\n for args in &[\"40000, 1, 1, 1\", \"1, 40000, 1, 1\", \"1, 1, 40000, 1\", \"1, 1, 1, 40000\"] {\n let pos = name.len() + 1 + args.find('4').unwrap() + 1;\n check_stmt_err(\n format!(\"1:{}: Coordinate 40000 out of range\", pos),\n &format!(\"{} {}\", name, args),\n );\n }\n\n for args in &[\"\\\"a\\\", 1, 1, 1\", \"1, \\\"a\\\", 1, 1\", \"1, 1, \\\"a\\\", 1\", \"1, 1, 1, \\\"a\\\"\"] {\n let stmt = &format!(\"{} {}\", name, args);\n let pos = stmt.find('\"').unwrap() + 1;\n check_stmt_compilation_err(format!(\"1:{}: STRING is not a number\", pos), stmt);\n }\n }\n```"}], "func_name": "check_errors_two_xy", "docstring": "Verifies error conditions for a command named `name` that takes to X/Y pairs.", "repo": "endbasic/endbasic", "path": "std/src/gfx/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cfd9cde02d8be73d9af7284c14c591b340d65bdeabebfcadee501201241277be"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_errors_xy_radius\n\nDocumentation:\nVerifies error conditions for a command named `name` that takes an X/Y pair and a radius.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_errors_xy_radius(name: &'static str) {\n for args in &[\"1, , 3\", \"1, 2\", \"1, 2, 3, 4\", \"2; 3, 4\"] {\n check_stmt_compilation_err(\n format!(\"1:1: {} expected x%, y%, r%\", name),\n &format!(\"{} {}\", name, args),\n );\n }\n\n for args in &[\"-40000, 1, 1\", \"1, -40000, 1\"] {\n let pos = name.len() + 1 + args.find('-').unwrap() + 1;\n check_stmt_err(\n format!(\"1:{}: Coordinate -40000 out of range\", pos),\n &format!(\"{} {}\", name, args),\n );\n }\n check_stmt_err(\n format!(\"1:{}: Radius -40000 must be positive\", name.len() + 8),\n &format!(\"{} 1, 1, -40000\", name),\n );\n\n for args in &[\"40000, 1, 1\", \"1, 40000, 1\"] {\n let pos = name.len() + 1 + args.find('4').unwrap() + 1;\n check_stmt_err(\n format!(\"1:{}: Coordinate 40000 out of range\", pos),\n &format!(\"{} {}\", name, args),\n );\n }\n check_stmt_err(\n format!(\"1:{}: Radius 80000 out of range\", name.len() + 8),\n &format!(\"{} 1, 1, 80000\", name),\n );\n\n for args in &[\"\\\"a\\\", 1, 1\", \"1, \\\"a\\\", 1\", \"1, 1, \\\"a\\\"\"] {\n let stmt = &format!(\"{} {}\", name, args);\n let pos = stmt.find('\"').unwrap() + 1;\n check_stmt_compilation_err(format!(\"1:{}: STRING is not a number\", pos), stmt);\n }\n\n check_stmt_err(\n format!(\"1:{}: Radius -1 must be positive\", name.len() + 8),\n &format!(\"{} 1, 1, -1\", name),\n );\n }\n```"}], "func_name": "check_errors_xy_radius", "docstring": "Verifies error conditions for a command named `name` that takes an X/Y pair and a radius.", "repo": "endbasic/endbasic", "path": "std/src/gfx/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b2a3663874e261caf3d6d1e60cc4553f2462aabe4793967df5265d5aae26723e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: between\n\nDocumentation:\nCalculates the size of the window represented by `x1y1` and `x2y2`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn between(x1y1: LcdXY, x2y2: LcdXY) -> Self {\n debug_assert!(x2y2.x >= x1y1.x);\n debug_assert!(x2y2.y >= x1y1.y);\n Self { width: x2y2.x - x1y1.x + 1, height: x2y2.y - x1y1.y + 1 }\n }\n```"}], "func_name": "between", "docstring": "Calculates the size of the window represented by `x1y1` and `x2y2`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17ef4b6e14286849f0c5aec5639764fa5220f6b92263c812f33d79d493d218e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_buffer\n\nDocumentation:\nCreates a new buffer with enough capacity to hold the content of this LCD size for the given\n`stride``. The returned buffer is of zero size.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_buffer(&self, stride: usize) -> Vec {\n Vec::with_capacity(self.width * self.height * stride)\n }\n```"}], "func_name": "new_buffer", "docstring": "Creates a new buffer with enough capacity to hold the content of this LCD size for the given\n`stride``. The returned buffer is of zero size.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ab3dc6b36d0fd4bd2a5e41e7755ef1bda27337d840f50ae3a1b025f529996523"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_xy_size\n\nDocumentation:\nConverts a pair of coordinates to a top-left origin coordinate plus a size.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_xy_size(x1y1: LcdXY, x2y2: LcdXY) -> (LcdXY, LcdSize) {\n let x1 = std::cmp::min(x1y1.x, x2y2.x);\n let y1 = std::cmp::min(x1y1.y, x2y2.y);\n\n let x2 = std::cmp::max(x1y1.x, x2y2.x);\n let y2 = std::cmp::max(x1y1.y, x2y2.y);\n\n (LcdXY { x: x1, y: y1 }, LcdSize { width: x2 + 1 - x1, height: y2 + 1 - y1 })\n}\n```"}], "func_name": "to_xy_size", "docstring": "Converts a pair of coordinates to a top-left origin coordinate plus a size.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e09bb7ed03878a80a511743ea7d691ee630a7879c2dee9b49cb971445ed204ec"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: xy\n\nDocumentation:\nSyntactic sugar to instantiate a coordinate in the LCD space.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn xy(x: usize, y: usize) -> LcdXY {\n LcdXY { x, y }\n }\n```"}], "func_name": "xy", "docstring": "Syntactic sugar to instantiate a coordinate in the LCD space.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4dd9043f4d441f8e16e8af574eadfde88cf6b26a207af251d25190eb01a98604"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: size\n\nDocumentation:\nSyntactic sugar to instantiate a size in the LCD space.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn size(width: usize, height: usize) -> LcdSize {\n LcdSize { width, height }\n }\n```"}], "func_name": "size", "docstring": "Syntactic sugar to instantiate a size in the LCD space.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aa1613b3e96791fa0581588f989b83cc349f244ef81313dfe4bb08794fab0c09"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new buffered LCD backed by `lcd`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(lcd: L, font: &'static Font) -> Self {\n let (size, stride) = lcd.info();\n\n let fb = {\n let pixels = size.width * size.height;\n vec![0; pixels * stride]\n };\n\n let size_chars = CharsXY::new(\n u16::try_from(size.width / font.glyph_size.width).expect(\"Must fit\"),\n u16::try_from(size.height / font.glyph_size.height).expect(\"Must fit\"),\n );\n\n let draw_color = lcd.encode((255, 255, 255));\n let row_buffer = Vec::with_capacity(size.width * stride);\n\n Self {\n lcd,\n font,\n fb,\n stride,\n sync: true,\n damage: None,\n size_pixels: size,\n size_chars,\n draw_color,\n row_buffer,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new buffered LCD backed by `lcd`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c5335f58e7a8c666975117dadfe495843752a0a80399ac5e45d91cd5d49191cd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: without_sync\n\nDocumentation:\nExecutes mutations on the buffered LCD via `ops` while ensuring that syncing is disabled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn without_sync(&mut self, ops: O) -> io::Result<()>\n where\n O: Fn(&mut BufferedLcd) -> io::Result<()>,\n {\n if self.sync {\n let old_sync = self.sync;\n self.sync = false;\n\n let result = ops(self);\n\n self.sync = old_sync;\n if self.sync {\n self.force_present_canvas()?;\n }\n\n result\n } else {\n ops(self)\n }\n }\n```"}], "func_name": "without_sync", "docstring": "Executes mutations on the buffered LCD via `ops` while ensuring that syncing is disabled.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09f870d4b6934b69b3e022cb5709f03eccbab778ee7e1dfb23fc33e4cdd2048c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clip_xy\n\nDocumentation:\nClips the user-supplied `xy` coordinates to the LCD space. Returns `None` if they are out\nof range and the converted value otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn clip_xy(&self, xy: PixelsXY) -> Option {\n fn clamp(value: i16, max: usize) -> Option {\n if value < 0 {\n None\n } else {\n let value = usize::try_from(value).expect(\"Positive value must fit\");\n if value > max {\n None\n } else {\n Some(value)\n }\n }\n }\n\n let x = clamp(xy.x, self.size_pixels.width - 1);\n let y = clamp(xy.y, self.size_pixels.height - 1);\n match (x, y) {\n (Some(x), Some(y)) => Some(LcdXY { x, y }),\n _ => None,\n }\n }\n```"}], "func_name": "clip_xy", "docstring": "Clips the user-supplied `xy` coordinates to the LCD space. Returns `None` if they are out\nof range and the converted value otherwise.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "635e758f67084dbe93c0a29c569b02d1d6c030c97c26797cc6a6ed113693b8e7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clamp_xy\n\nDocumentation:\nClamps the user-supplied `xy` coordinates to the LCD space.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn clamp_xy(&self, xy: PixelsXY) -> LcdXY {\n fn clamp(value: i16, max: usize) -> usize {\n if value < 0 {\n 0\n } else {\n let value = usize::try_from(value).expect(\"Positive value must fit\");\n if value > max {\n max\n } else {\n value\n }\n }\n }\n\n LcdXY {\n x: clamp(xy.x, self.size_pixels.width - 1),\n y: clamp(xy.y, self.size_pixels.height - 1),\n }\n }\n```"}], "func_name": "clamp_xy", "docstring": "Clamps the user-supplied `xy` coordinates to the LCD space.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7d157e83b815d3fc43fe9121179e9145b2fe328cc157f29a2cce02691ddcc61b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clip_x2y2\n\nDocumentation:\nGiven a top-left `xy` coordinate, adds the user-supplied `size` to it and clamps the result\nto the LCD space.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn clip_x2y2(&self, xy: PixelsXY, size: SizeInPixels) -> Option {\n fn clamp(value: i16, delta: u16, max: usize) -> Option {\n let value = i32::from(value);\n let delta = i32::from(delta);\n\n let value = value + delta;\n if value < 0 {\n None\n } else {\n let value = usize::try_from(value).expect(\"Positive value must fit\");\n if value > max {\n Some(max)\n } else {\n Some(value)\n }\n }\n }\n\n let x = clamp(xy.x, size.width - 1, self.size_pixels.width - 1);\n let y = clamp(xy.y, size.height - 1, self.size_pixels.height - 1);\n match (x, y) {\n (Some(x), Some(y)) => Some(LcdXY { x, y }),\n _ => None,\n }\n }\n```"}], "func_name": "clip_x2y2", "docstring": "Given a top-left `xy` coordinate, adds the user-supplied `size` to it and clamps the result\nto the LCD space.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "20db1b7e3469d688ab1ba9d9a9da22a0fe26b589a099b4ad034b390041d9bfdc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: assert_xy_in_range\n\nDocumentation:\nMake sure that the coordinates are within the LCD space.\n\nThis is only used to validate input parameters for those functions that are internal to the\nconsole (such as `move_pixels`). Functions subject to user input (such as `draw_rect`) must\nnot use this.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn assert_xy_in_range(&mut self, xy: PixelsXY) {\n if cfg!(test) {\n let x = usize::try_from(xy.x).expect(\"x must be positive and must fit\");\n let y = usize::try_from(xy.y).expect(\"y must be positive and must fit\");\n debug_assert!(x < self.size_pixels.width, \"x must be within the LCD width\");\n debug_assert!(y < self.size_pixels.height, \"y must be within the LCD height\");\n }\n }\n```"}], "func_name": "assert_xy_in_range", "docstring": "Make sure that the coordinates are within the LCD space.\n\nThis is only used to validate input parameters for those functions that are internal to the\nconsole (such as `move_pixels`). Functions subject to user input (such as `draw_rect`) must\nnot use this.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ade4957ab7af0dff8ce60054b320b0e3fdd5a519b93060e4806a096de8729f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: assert_xy_size_in_range\n\nDocumentation:\nMake sure that the coordinates and size are within the LCD space.\n\nThis is only used to validate input parameters for those functions that are internal to the\nconsole (such as `move_pixels`). Functions subject to user input (such as `draw_rect`) must\nnot use this.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn assert_xy_size_in_range(&mut self, xy: PixelsXY, size: SizeInPixels) {\n if cfg!(test) {\n self.assert_xy_in_range(xy);\n let x = xy.x as usize;\n let y = xy.y as usize;\n\n let width = usize::from(size.width);\n let height = usize::from(size.height);\n\n debug_assert!(\n x + width - 1 < self.size_pixels.width,\n \"x + width must be within the LCD width\"\n );\n debug_assert!(\n y + height - 1 < self.size_pixels.height,\n \"y + height must be within the LCD height\"\n );\n }\n }\n```"}], "func_name": "assert_xy_size_in_range", "docstring": "Make sure that the coordinates and size are within the LCD space.\n\nThis is only used to validate input parameters for those functions that are internal to the\nconsole (such as `move_pixels`). Functions subject to user input (such as `draw_rect`) must\nnot use this.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aff0fa879e02716c34c86a9176a5219323530eb8f5f0b8817054f5e089116b8c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fb_addr\n\nDocumentation:\nGets the start address of the pixel `x`/`y` in the framebuffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fb_addr(&self, x: usize, y: usize) -> usize {\n debug_assert!(x < self.size_pixels.width);\n debug_assert!(y < self.size_pixels.height);\n ((y * self.size_pixels.width) + x) * self.stride\n }\n```"}], "func_name": "fb_addr", "docstring": "Gets the start address of the pixel `x`/`y` in the framebuffer.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "14a3cd993acedabd8177e1db1d6617bbf49b1ae07e6af21275e3d8c7014a75b3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: damage\n\nDocumentation:\nExtends the current damage area to include the area between between `x1y1` and `x2y2`\n(inclusive) as damaged.\n\nThis only makes sense when syncing is disabled, as the damage area represents the contents\nthat need to be flushed to the LCD once syncing is enabled again.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn damage(&mut self, x1y1: LcdXY, x2y2: LcdXY) {\n debug_assert!(!self.sync);\n debug_assert!(x2y2.x >= x1y1.x);\n debug_assert!(x2y2.y >= x1y1.y);\n\n if self.damage.is_none() {\n self.damage = Some((x1y1, x2y2));\n return;\n }\n let mut damage = self.damage.unwrap();\n\n if damage.0.x > x1y1.x {\n damage.0.x = x1y1.x;\n }\n if damage.0.y > x1y1.y {\n damage.0.y = x1y1.y;\n }\n\n if damage.1.x < x2y2.x {\n damage.1.x = x2y2.x;\n }\n if damage.1.y < x2y2.y {\n damage.1.y = x2y2.y;\n }\n\n self.damage = Some(damage);\n }\n```"}], "func_name": "damage", "docstring": "Extends the current damage area to include the area between between `x1y1` and `x2y2`\n(inclusive) as damaged.\n\nThis only makes sense when syncing is disabled, as the damage area represents the contents\nthat need to be flushed to the LCD once syncing is enabled again.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e650d1f71eaa1a751427ee1ae5b774f96af58cb06a1ab441a8937c97c7b37b75"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fill\n\nDocumentation:\nFills the area contained between `x1y1` and `x2y2` (inclusive) with the current drawing\ncolor.\n\nIf syncing is enabled, this writes directly to the LCD. Otherwise, this writes to the\nframebuffer and records the area as damaged.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fill(&mut self, x1y1: LcdXY, x2y2: LcdXY) -> io::Result<()> {\n // Prepare self.row_buffer with the content of every row to be copied to the framebuffer.\n // We do this for efficiency reasons because manipulating individual pixels is costly.\n let rowlen = {\n let xlen = x2y2.x - x1y1.x + 1;\n let rowlen = xlen * self.stride;\n self.row_buffer.clear();\n let color = self.draw_color.as_slice();\n for _ in 0..xlen {\n self.row_buffer.extend_from_slice(color);\n }\n debug_assert_eq!(rowlen, self.row_buffer.len());\n rowlen\n };\n\n if self.sync {\n let mut data = LcdSize::between(x1y1, x2y2).new_buffer(self.stride);\n for y in x1y1.y..(x2y2.y + 1) {\n let offset = self.fb_addr(x1y1.x, y);\n self.fb[offset..offset + rowlen].copy_from_slice(&self.row_buffer);\n data.extend(&self.row_buffer);\n }\n self.lcd.set_data(x1y1, x2y2, &data)?;\n } else {\n for y in x1y1.y..(x2y2.y + 1) {\n let offset = self.fb_addr(x1y1.x, y);\n self.fb[offset..offset + rowlen].copy_from_slice(&self.row_buffer);\n }\n self.damage(x1y1, x2y2);\n }\n\n Ok(())\n }\n```"}], "func_name": "fill", "docstring": "Fills the area contained between `x1y1` and `x2y2` (inclusive) with the current drawing\ncolor.\n\nIf syncing is enabled, this writes directly to the LCD. Otherwise, this writes to the\nframebuffer and records the area as damaged.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8160989a74bdd9012ba7f981d2c3c12aefdca1240d170e8ff4f141129f1a399"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: force_present_canvas\n\nDocumentation:\nFlushes any pending damaged area to the LCD.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn force_present_canvas(&mut self) -> io::Result<()> {\n let (x1y1, x2y2) = match self.damage {\n None => return Ok(()),\n Some(damage) => damage,\n };\n\n let mut data = LcdSize::between(x1y1, x2y2).new_buffer(self.stride);\n for y in x1y1.y..(x2y2.y + 1) {\n for x in x1y1.x..(x2y2.x + 1) {\n let offset = self.fb_addr(x, y);\n data.extend_from_slice(&self.fb[offset..offset + self.stride]);\n }\n }\n debug_assert_eq!(\n {\n let (_xy, size) = to_xy_size(x1y1, x2y2);\n size.width * size.height * self.stride\n },\n data.len()\n );\n\n self.lcd.set_data(x1y1, x2y2, &data)?;\n\n self.damage = None;\n\n Ok(())\n }\n```"}], "func_name": "force_present_canvas", "docstring": "Flushes any pending damaged area to the LCD.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "73710e4b0b2c5c9de2e7e1e02e852158de05bf8e37082abbf72440a06fd201b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_char\n\nDocumentation:\nWrites a single character `ch` at `pos`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_char(&mut self, pos: LcdXY, ch: char) -> io::Result<()> {\n let glyph = self.font.glyph(ch);\n for j in 0..self.font.glyph_size.height {\n for k in 0..self.font.stride {\n let row = glyph[j * self.font.stride + k];\n let mut mask = 0x80;\n for i in 0..self.font.glyph_size.width {\n let bit = row & mask;\n if bit != 0 {\n let x = pos.x + i + k * 8;\n if x >= self.size_pixels.width {\n continue;\n }\n\n let y = pos.y + j;\n if y >= self.size_pixels.height {\n continue;\n }\n\n let xy = LcdXY { x, y };\n // TODO(jmmv): This is very inefficent on a pixel basis.\n self.fill(xy, xy)?;\n }\n mask >>= 1;\n }\n }\n }\n Ok(())\n }\n```"}], "func_name": "write_char", "docstring": "Writes a single character `ch` at `pos`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09b7d1b0454b75c0e3a099ac372885e568ef39f3b5141729c45df33543b7fcc8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a mock LCD of the given `size`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new(size: LcdSize) -> Self {\n Self { size, ops: vec![] }\n }\n```"}], "func_name": "new", "docstring": "Creates a mock LCD of the given `size`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "df21734bce5da92748e87e6b2c5edeb3e83d9b9167a50e741229ef061adf1dab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new tester backed by a mock `LcdRecorder` of the given `size`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn new(size: LcdSize) -> Self {\n Self::with_font(size, &FONT_ZERO)\n }\n```"}], "func_name": "new", "docstring": "Creates a new tester backed by a mock `LcdRecorder` of the given `size`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e48e1435e83990f34a180d93c4e0c584902ba3d77b2cf54977d5f3c5fc862ca8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_font\n\nDocumentation:\nCreates a new tester backed by a mock `LcdRecorder` of the given `size` and using the\nfont in `font`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn with_font(size: LcdSize, font: &'static Font) -> Self {\n let fb_size = size.width * size.height * 3;\n Self {\n size,\n buffered: BufferedLcd::new(LcdRecorder::new(size), font),\n exp_fb: vec![0; fb_size],\n exp_damage: None,\n exp_ops: vec![],\n }\n }\n```"}], "func_name": "with_font", "docstring": "Creates a new tester backed by a mock `LcdRecorder` of the given `size` and using the\nfont in `font`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ae53535e77435d256ca1f2bcd0221cf426eba18c5524a2fbcc55529def375b2f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op\n\nDocumentation:\nExecutes an operation on the backing `LcdRecorder`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn op(mut self, op: F) -> Self\n where\n F: Fn(&mut BufferedLcd),\n {\n op(&mut self.buffered);\n self\n }\n```"}], "func_name": "op", "docstring": "Executes an operation on the backing `LcdRecorder`.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ee6df88e293c3ab4ec1a6f08ac9b5e9d9c5a1353f2cac94d08dc241124397ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_pixel\n\nDocumentation:\nRecords that the pixel `xy` should be `rgb` after all `op`s have been executed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn expect_pixel(mut self, xy: LcdXY, rgb: RGB) -> Self {\n let offset = ((xy.y * self.size.width) + xy.x) * 3;\n self.exp_fb[offset] = rgb.0;\n self.exp_fb[offset + 1] = rgb.1;\n self.exp_fb[offset + 2] = rgb.2;\n self\n }\n```"}], "func_name": "expect_pixel", "docstring": "Records that the pixel `xy` should be `rgb` after all `op`s have been executed.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "12aefe8f02315852dbe9c2a12c189d338b299808592cd34c4e1b8d1b84c1efa0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_damage\n\nDocumentation:\nRecords that the area between `x1y1` and `x2y2` is damaged after all `op`s have been\nexecuted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn expect_damage(mut self, x1y1: LcdXY, x2y2: LcdXY) -> Self {\n assert!(self.exp_damage.is_none());\n self.exp_damage = Some((x1y1, x2y2));\n self\n }\n```"}], "func_name": "expect_damage", "docstring": "Records that the area between `x1y1` and `x2y2` is damaged after all `op`s have been\nexecuted.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be809c67404843c92be4428af615ce9872a857d809930ed49f328814f8fdc352"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_op\n\nDocumentation:\nRecords that the given `op` should have been received by the mock `LcdRecorder` after\nall `op`s have been executed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn expect_op(mut self, op: &str) -> Self {\n self.exp_ops.push(op.into());\n self\n }\n```"}], "func_name": "expect_op", "docstring": "Records that the given `op` should have been received by the mock `LcdRecorder` after\nall `op`s have been executed.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "729d48cca4017fcf8795bbab5c92a524c2a8d5af0be7146a5c32c0bd2af0d5d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ignore_pixels\n\nDocumentation:\nConfigures the test to ignore the content of all pixels. This is for simplicity of\ntests that only one to validate other aspects of the LCD handling.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn ignore_pixels(mut self) -> Self {\n self.exp_fb = self.buffered.fb.clone();\n self\n }\n```"}], "func_name": "ignore_pixels", "docstring": "Configures the test to ignore the content of all pixels. This is for simplicity of\ntests that only one to validate other aspects of the LCD handling.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e802212f9c0809cecf966313b1f35b1c41130edb68ec084d5e945527490123ae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check\n\nDocumentation:\nValidates recorded expectations about the changes made by all executed `op`s.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn check(self) {\n if self.exp_fb != self.buffered.fb {\n for y in 0..self.size.height {\n for x in 0..self.size.width {\n let offset = (y * self.size.width + x) * 3;\n let exp_pixel = &self.exp_fb[offset..offset + 3];\n let pixel = &self.buffered.fb[offset..offset + 3];\n if exp_pixel != pixel {\n // Print the difference as a bunch of expect_pixel lines that can be\n // copy-pasted into the code to re-define golden data.\n eprintln!(\n \".expect_pixel(xy({:3}, {:3}), ({:3}, {:3}, {:3})) // got ({:3}, {:3}, {:3})\",\n x, y,\n pixel[0], pixel[1], pixel[2],\n exp_pixel[0], exp_pixel[1], exp_pixel[2],\n );\n }\n }\n }\n panic!(\"Pixel contents differ; see output above\");\n }\n assert_eq!(self.exp_damage, self.buffered.damage);\n assert_eq!(self.exp_ops, self.buffered.lcd.ops);\n }\n```"}], "func_name": "check", "docstring": "Validates recorded expectations about the changes made by all executed `op`s.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/buffered/testutils.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/buffered/testutils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8a1a6b02997be0ff25db384fbc612ae0cda336c97fa80e0948ffdd2c4c8b485d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: glyph\n\nDocumentation:\nReturns the raw font data for `ch`.\n\nEach entry in the array corresponds to a row of pixels and is a bitmask indicating which\npixels to turn on.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn glyph(&self, mut ch: char) -> &'static [u8] {\n if !(' '..='~').contains(&ch) {\n // TODO(jmmv): Would be nicer to draw an empty box, much like how unknown Unicode\n // characters are typically displayed.\n ch = '?';\n }\n let height = self.glyph_size.height * self.stride;\n let offset = ((ch as usize) - (' ' as usize)) * height;\n debug_assert!(offset < (self.data.len() + height));\n &self.data[offset..offset + height]\n }\n```"}], "func_name": "glyph", "docstring": "Returns the raw font data for `ch`.\n\nEach entry in the array corresponds to a row of pixels and is a bitmask indicating which\npixels to turn on.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/fonts/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/fonts/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f7e8fb907502119941d32b4acd0dfe7465fac2d0d8442e91bb15745bdcf80758"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: all_fonts\n\nDocumentation:\nObtains a mapping of all available fonts.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn all_fonts() -> Fonts {\n let mut fonts = Fonts::default();\n fonts.insert(FONT_5X8.name, &FONT_5X8);\n fonts.insert(FONT_16X16.name, &FONT_16X16);\n fonts\n}\n```"}], "func_name": "all_fonts", "docstring": "Obtains a mapping of all available fonts.", "repo": "endbasic/endbasic", "path": "std/src/gfx/lcd/fonts/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gfx/lcd/fonts/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4b1931dfe1892b0a55ae5c00b293fa1ceec2537dc4db779a87d19b11eab6fcf9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode\n\nDocumentation:\nEncodes a `pin` and `op` pair as a datum for the mock data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn encode(pin: Pin, op: Self) -> i32 {\n assert!(op != Self::ClearAll);\n (pin.0 as i32) * 100 + (op as i32)\n }\n```"}], "func_name": "encode", "docstring": "Encodes a `pin` and `op` pair as a datum for the mock data.", "repo": "endbasic/endbasic", "path": "std/src/gpio/fakes.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gpio/fakes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3aaced141d63e25015c26ea648ef05d2a64575a3b88db8329750b612ae383b98"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decode_read\n\nDocumentation:\nDecodes a datum from the mock data that is to be used for a read operation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn decode_read(pos: i32, datum: i32) -> io::Result<(Pin, bool)> {\n if datum < 0 {\n return Err(io::Error::new(\n io::ErrorKind::InvalidData,\n format!(\"Negative read value at __GPIO_MOCK_DATA({})\", pos),\n ));\n }\n let pin = datum / 100;\n if pin > u8::MAX as i32 {\n return Err(io::Error::new(\n io::ErrorKind::InvalidData,\n format!(\"Pin number too large at __GPIO_MOCK_DATA({})\", pos),\n ));\n }\n let pin = Pin(pin as u8);\n match datum % 100 {\n i if i == (MockOp::ReadLow as i32) => Ok((pin, false)),\n i if i == (MockOp::ReadHigh as i32) => Ok((pin, true)),\n i => Err(io::Error::new(\n io::ErrorKind::InvalidData,\n format!(\"Unknown read operation {} at __GPIO_MOCK_DATA({})\", i, pos),\n )),\n }\n }\n```"}], "func_name": "decode_read", "docstring": "Decodes a datum from the mock data that is to be used for a read operation.", "repo": "endbasic/endbasic", "path": "std/src/gpio/fakes.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gpio/fakes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b09787a1faf477dd39cd263d3be8f55c1d91ad0a504d5437684bf6dc1d0f502"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_new\n\nDocumentation:\nCreates a mock pins instance if `__GPIO_MOCK_DATA` *and* `__GPIO_MOCK_LAST` are set and of\nthe correct types.\n\nNote that, while this object is alive (which is in the context of an individual GPIO call),\nwe know that these symbols are valid so other methods can assume that they are.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn try_new(symbols: &'a mut Symbols) -> Option> {\n if MockPins::get_last(symbols).is_none() || MockPins::get_mut_data(symbols).is_none() {\n None\n } else {\n Some(Self { symbols })\n }\n }\n```"}], "func_name": "try_new", "docstring": "Creates a mock pins instance if `__GPIO_MOCK_DATA` *and* `__GPIO_MOCK_LAST` are set and of\nthe correct types.\n\nNote that, while this object is alive (which is in the context of an individual GPIO call),\nwe know that these symbols are valid so other methods can assume that they are.", "repo": "endbasic/endbasic", "path": "std/src/gpio/fakes.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gpio/fakes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e6d0869443efc3874130c6dc26fefc63851ab101cc23d443569dad5aea4f739"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_last\n\nDocumentation:\nObtains the value of `__GPIO_MOCK_LAST` if present.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_last(symbols: &Symbols) -> Option {\n match symbols.get(&VarRef::new(\"__GPIO_MOCK_LAST\", Some(ExprType::Integer))) {\n Ok(Some(Symbol::Variable(Value::Integer(i)))) => Some(*i),\n _ => None,\n }\n }\n```"}], "func_name": "get_last", "docstring": "Obtains the value of `__GPIO_MOCK_LAST` if present.", "repo": "endbasic/endbasic", "path": "std/src/gpio/fakes.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gpio/fakes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0031c9c631097ef09dfe3155206e17310cef6b6d014ed2d02f7d7a0d12011ca7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_mut_data\n\nDocumentation:\nObtains a mutable reference to `__GPIO_MOCK_DATA` if present.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_mut_data(symbols: &mut Symbols) -> Option<&mut Array> {\n match symbols.get_mut(&VarRef::new(\"__GPIO_MOCK_DATA\", Some(ExprType::Integer))) {\n Ok(Some(Symbol::Array(data))) if data.dimensions().len() == 1 => Some(data),\n _ => None,\n }\n }\n```"}], "func_name": "get_mut_data", "docstring": "Obtains a mutable reference to `__GPIO_MOCK_DATA` if present.", "repo": "endbasic/endbasic", "path": "std/src/gpio/fakes.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gpio/fakes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb8a5d0c3815b17cec7d40fb651944331924a3cae7008bab11cee72415e8d740"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: raw_get\n\nDocumentation:\nReads the current value at `data[last]` with proper validation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn raw_get(last: i32, data: &Array) -> io::Result {\n match data.index(&[last]) {\n Ok(Value::Integer(v)) => Ok(*v),\n Ok(_) => panic!(\"We know it's an integer\"),\n Err(e) => Err(io::Error::new(io::ErrorKind::InvalidData, e.to_string())),\n }\n }\n```"}], "func_name": "raw_get", "docstring": "Reads the current value at `data[last]` with proper validation.", "repo": "endbasic/endbasic", "path": "std/src/gpio/fakes.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gpio/fakes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0a33c1dfda6257103cb10867caa3f6aa1e31960c05be1fd014c38f7524816a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_and_advance\n\nDocumentation:\nReads `__GPIO_MOCK_DATA[__GPIO_MOCK_LAST]` and advances `__GPIO_MOCK_LAST`. Returns the\nposition of the array that was read and the value at that position.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_and_advance(&mut self) -> io::Result<(i32, i32)> {\n let last = MockPins::get_last(self.symbols).expect(\"Validated at construction time\");\n let data = MockPins::get_mut_data(self.symbols).expect(\"Validated at construction time\");\n\n let v = MockPins::raw_get(last, data)?;\n self.increment_last()?;\n Ok((last, v))\n }\n```"}], "func_name": "read_and_advance", "docstring": "Reads `__GPIO_MOCK_DATA[__GPIO_MOCK_LAST]` and advances `__GPIO_MOCK_LAST`. Returns the\nposition of the array that was read and the value at that position.", "repo": "endbasic/endbasic", "path": "std/src/gpio/fakes.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gpio/fakes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ebc64c5eddd561644bbd1079375985881760c9453d5928e63e3f6691de42320"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: append\n\nDocumentation:\nWrites `datum` to `__GPIO_MOCK_DATA[__GPIO_MOCK_LAST]`, which must be zero upfront.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn append(&mut self, datum: i32) -> io::Result<()> {\n let last = MockPins::get_last(self.symbols).expect(\"Validated at construction time\");\n let data = MockPins::get_mut_data(self.symbols).expect(\"Validated at construction time\");\n\n let old_datum = MockPins::raw_get(last, data)?;\n if old_datum != 0 {\n return Err(io::Error::new(\n io::ErrorKind::InvalidData,\n format!(\"Position already occupied at __GPIO_MOCK_READ({})\", last),\n ));\n }\n\n let data = MockPins::get_mut_data(self.symbols).expect(\"Validated at construction time\");\n match data.assign(&[last], Value::Integer(datum)) {\n Ok(()) => (),\n Err(e) => return Err(io::Error::new(io::ErrorKind::InvalidData, e.to_string())),\n };\n self.increment_last()\n }\n```"}], "func_name": "append", "docstring": "Writes `datum` to `__GPIO_MOCK_DATA[__GPIO_MOCK_LAST]`, which must be zero upfront.", "repo": "endbasic/endbasic", "path": "std/src/gpio/fakes.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gpio/fakes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a1a8cdc6d0c374aa91959297551d71c83afbacf12e2c181cb05275f99b138102"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_i32\n\nDocumentation:\nCreates a new pin number from an EndBASIC integer value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_i32(i: i32, pos: LineCol) -> Result {\n if i < 0 {\n return Err(Error::SyntaxError(pos, format!(\"Pin number {} must be positive\", i)));\n }\n if i > u8::MAX as i32 {\n return Err(Error::SyntaxError(pos, format!(\"Pin number {} is too large\", i)));\n }\n Ok(Self(i as u8))\n }\n```"}], "func_name": "from_i32", "docstring": "Creates a new pin number from an EndBASIC integer value.", "repo": "endbasic/endbasic", "path": "std/src/gpio/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gpio/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "adb58c8bcd56e8607b847d07d8ea0a74a704f5aefec04b2aaa4c9a3909f70cf3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_pin_validation\n\nDocumentation:\nCommon checks for pin number validation.\n\nThe given input `fmt` string contains the command to test with a placeholder `_PIN` for\nwhere the pin number goes. The `short_prefix` and `long_prefix` contain possible prefixes\nfor the error messages.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_pin_validation(short_prefix: &str, long_prefix: &str, fmt: &str) {\n check_stmt_compilation_err(\n format!(r#\"{}BOOLEAN is not a number\"#, short_prefix),\n &fmt.replace(\"_PIN_\", \"TRUE\"),\n );\n check_stmt_err(\n format!(r#\"{}Pin number 123456789 is too large\"#, long_prefix),\n &fmt.replace(\"_PIN_\", \"123456789\"),\n );\n check_stmt_err(\n format!(r#\"{}Pin number -1 must be positive\"#, long_prefix),\n &fmt.replace(\"_PIN_\", \"-1\"),\n );\n }\n```"}], "func_name": "check_pin_validation", "docstring": "Common checks for pin number validation.\n\nThe given input `fmt` string contains the command to test with a placeholder `_PIN` for\nwhere the pin number goes. The `short_prefix` and `long_prefix` contain possible prefixes\nfor the error messages.", "repo": "endbasic/endbasic", "path": "std/src/gpio/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gpio/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "623c78cb412dd8552882b4cc19a33f88ebde4c879b3464074d9cb7040f490375"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_mock_test_with_vars\n\nDocumentation:\nDoes a GPIO test using the mocking feature, running the commands in `code` and expecting\nthat the `__GPIO_MOCK_DATA` array contains `trace` after completion.\n\nSets all `vars` before evaluating the expression so that the expression can contain variable\nreferences.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_mock_test_with_vars, VS: Into>>(\n code: S,\n trace: &[i32],\n vars: VS,\n ) {\n let code = code.into();\n let vars = vars.into();\n\n let mut exp_data = vec![Value::Integer(0); 50];\n for (i, d) in trace.iter().enumerate() {\n exp_data[i] = Value::Integer(*d);\n }\n\n let mut t = Tester::default();\n for var in vars.as_slice() {\n t = t.set_var(var.0, var.1.clone());\n }\n\n let mut c = t\n .run(format!(r#\"DIM __GPIO_MOCK_DATA(50) AS INTEGER: __GPIO_MOCK_LAST = 0: {}\"#, code));\n for var in vars.into_iter() {\n c = c.expect_var(var.0, var.1.clone());\n }\n c.expect_var(\"__GPIO_MOCK_LAST\", Value::Integer(trace.len() as i32))\n .expect_array_simple(\"__GPIO_MOCK_DATA\", ExprType::Integer, exp_data)\n .check();\n }\n```"}], "func_name": "do_mock_test_with_vars", "docstring": "Does a GPIO test using the mocking feature, running the commands in `code` and expecting\nthat the `__GPIO_MOCK_DATA` array contains `trace` after completion.\n\nSets all `vars` before evaluating the expression so that the expression can contain variable\nreferences.", "repo": "endbasic/endbasic", "path": "std/src/gpio/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gpio/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c431f0a5367ea9b4a82fa2228bea99f275bd5efdbc1c267316a3c9ba19c1e550"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_mock_test\n\nDocumentation:\nDoes a GPIO test using the mocking feature, running the commands in `code` and expecting\nthat the `__GPIO_MOCK_DATA` array contains `trace` after completion.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_mock_test>(code: S, trace: &[i32]) {\n do_mock_test_with_vars(code, trace, [])\n }\n```"}], "func_name": "do_mock_test", "docstring": "Does a GPIO test using the mocking feature, running the commands in `code` and expecting\nthat the `__GPIO_MOCK_DATA` array contains `trace` after completion.", "repo": "endbasic/endbasic", "path": "std/src/gpio/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/gpio/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "855b8687c16e8f851f1e29d6ea11a64f52702f2e80c9123ed4f4dbd336db676e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: show_dir\n\nDocumentation:\nShows the contents of the given storage location.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn show_dir(storage: &Storage, console: &mut dyn Console, path: &str) -> io::Result<()> {\n let canonical_path = storage.make_canonical(path)?;\n let files = storage.enumerate(path).await?;\n\n let format = format_description::parse(\"[year]-[month]-[day] [hour]:[minute]\")\n .expect(\"Hardcoded format must be valid\");\n let show_narrow = is_narrow(&*console);\n\n let mut pager = Pager::new(console)?;\n pager.print(\"\").await?;\n pager.print(&format!(\" Directory of {}\", canonical_path)).await?;\n pager.print(\"\").await?;\n if show_narrow {\n let mut total_files = 0;\n for name in files.dirents().keys() {\n pager.print(&format!(\" {}\", name,)).await?;\n total_files += 1;\n }\n if total_files > 0 {\n pager.print(\"\").await?;\n }\n pager.print(&format!(\" {} file(s)\", total_files)).await?;\n } else {\n let mut total_files = 0;\n let mut total_bytes = 0;\n pager.print(\" Modified Size Name\").await?;\n for (name, details) in files.dirents() {\n pager\n .print(&format!(\n \" {} {:6} {}\",\n details.date.format(&format).map_err(time_format_error_to_io_error)?,\n details.length,\n name,\n ))\n .await?;\n total_files += 1;\n total_bytes += details.length;\n }\n if total_files > 0 {\n pager.print(\"\").await?;\n }\n pager.print(&format!(\" {} file(s), {} bytes\", total_files, total_bytes)).await?;\n if let (Some(disk_quota), Some(disk_free)) = (files.disk_quota(), files.disk_free()) {\n pager\n .print(&format!(\" {} of {} bytes free\", disk_free.bytes, disk_quota.bytes))\n .await?;\n }\n }\n pager.print(\"\").await?;\n Ok(())\n}\n```"}], "func_name": "show_dir", "docstring": "Shows the contents of the given storage location.", "repo": "endbasic/endbasic", "path": "std/src/storage/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e98f3d955ba28c5472e72ea322a7de01a3f7e27b7470758a4e3032616a68bfdf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `CD` command that changes the current location in `storage`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(storage: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"CD\")\n .with_syntax(&[(\n &[SingularArgSyntax::RequiredValue(\n RequiredValueSyntax { name: Cow::Borrowed(\"path\"), vtype: ExprType::Text },\n ArgSepSyntax::End,\n )],\n None,\n )])\n .with_category(CATEGORY)\n .with_description(\"Changes the current path.\")\n .build(),\n storage,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `CD` command that changes the current location in `storage`.", "repo": "endbasic/endbasic", "path": "std/src/storage/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fb51a3d306d1b3e39ffa51f2964d5292aed05acc685f66c353b01280c3dbf202"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `COPY` command that copies a file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(storage: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"COPY\")\n .with_syntax(&[(\n &[\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"src\"),\n vtype: ExprType::Text,\n },\n ArgSepSyntax::Exactly(ArgSep::Long),\n ),\n SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"dest\"),\n vtype: ExprType::Text,\n },\n ArgSepSyntax::End,\n ),\n ],\n None,\n )])\n .with_category(CATEGORY)\n .with_description(\n \"Copies src to dest.\nIf dest is a path without a name, the target file given in dest will have the same name \\\nas the source file in src.\nSee the \\\"File system\\\" help topic for information on the path syntax.\",\n )\n .build(),\n storage,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `COPY` command that copies a file.", "repo": "endbasic/endbasic", "path": "std/src/storage/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc543f3edaec4d6d2e762f65464b65a16ba634d6ac3c797d760d18cee735335e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `DIR` command that lists `storage` contents on the `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>, storage: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"DIR\")\n .with_syntax(&[\n (&[], None),\n (\n &[SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"path\"),\n vtype: ExprType::Text,\n },\n ArgSepSyntax::End,\n )],\n None,\n ),\n ])\n .with_category(CATEGORY)\n .with_description(\"Displays the list of files on the current or given path.\")\n .build(),\n console,\n storage,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `DIR` command that lists `storage` contents on the `console`.", "repo": "endbasic/endbasic", "path": "std/src/storage/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "29618ce4332f721506bee85a114bce67282f1af5e12b643518ce726a89fe7109"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `KILL` command that deletes a file from `storage`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(storage: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"KILL\")\n .with_syntax(&[(\n &[SingularArgSyntax::RequiredValue(\n RequiredValueSyntax {\n name: Cow::Borrowed(\"filename\"),\n vtype: ExprType::Text,\n },\n ArgSepSyntax::End,\n )],\n None,\n )])\n .with_category(CATEGORY)\n .with_description(\n \"Deletes the given file.\nThe filename must be a string and must be a valid EndBASIC path.\nSee the \\\"File system\\\" help topic for information on the path syntax.\",\n )\n .build(),\n storage,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `KILL` command that deletes a file from `storage`.", "repo": "endbasic/endbasic", "path": "std/src/storage/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a11832d94859221e37185cf1b8c39419b44eca2549c1d93bf8bd6423aaeb010"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `PWD` command that prints the current directory of `storage` to the `console`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(console: Rc>, storage: Rc>) -> Rc {\n Rc::from(Self {\n metadata: CallableMetadataBuilder::new(\"PWD\")\n .with_syntax(&[(&[], None)])\n .with_category(CATEGORY)\n .with_description(\n \"Prints the current working location.\nIf the EndBASIC path representing the current location is backed by a real path that is accessible \\\nby the underlying operating system, displays such path as well.\",\n )\n .build(),\n console,\n storage,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new `PWD` command that prints the current directory of `storage` to the `console`.", "repo": "endbasic/endbasic", "path": "std/src/storage/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c4f3ad17442d03e72f3e5b354076690d3bdfd6d2e88b201231a7ece243404e6b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_all\n\nDocumentation:\nAdds all file system manipulation commands for `storage` to the `machine`, using `console` to\ndisplay information.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_all(\n machine: &mut Machine,\n console: Rc>,\n storage: Rc>,\n) {\n machine.add_callable(CdCommand::new(storage.clone()));\n machine.add_callable(CopyCommand::new(storage.clone()));\n machine.add_callable(DirCommand::new(console.clone(), storage.clone()));\n machine.add_callable(KillCommand::new(storage.clone()));\n machine.add_callable(MountCommand::new(console.clone(), storage.clone()));\n machine.add_callable(PwdCommand::new(console.clone(), storage.clone()));\n machine.add_callable(UnmountCommand::new(storage));\n}\n```"}], "func_name": "add_all", "docstring": "Adds all file system manipulation commands for `storage` to the `machine`, using `console` to\ndisplay information.", "repo": "endbasic/endbasic", "path": "std/src/storage/cmds.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/cmds.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc5479060d7c5e1fadc6a09c42121d263ed8e0be3ee7a73f25ffa295e8e7ed40"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new drive backed by the `dir` directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new>(dir: P) -> io::Result {\n let dir = dir.into();\n\n // Obtain the canonical path to the underlying directory, which we need for system_path to\n // make sense. Unfortunately, we must ensure the directory exists in order to do this.\n let dir = match dir.canonicalize() {\n Ok(dir) => dir,\n Err(e) if e.kind() == io::ErrorKind::NotFound => {\n fs::create_dir_all(&dir)?;\n dir.canonicalize()?\n }\n Err(e) => return Err(e),\n };\n\n Ok(Self { dir })\n }\n```"}], "func_name": "new", "docstring": "Creates a new drive backed by the `dir` directory.", "repo": "endbasic/endbasic", "path": "std/src/storage/fs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9dbb7e30a0cefefa7e6b1b8717cbb3a76970a65346b1cd4fd95cc5928ea23977"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_file\n\nDocumentation:\nReads `path` and checks that its contents match `exp_lines`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_file(path: &Path, exp_lines: &[&str]) {\n let file = File::open(path).unwrap();\n let reader = io::BufReader::new(file);\n let mut lines = vec![];\n for line in reader.lines() {\n lines.push(line.unwrap());\n }\n assert_eq!(exp_lines, lines.as_slice());\n }\n```"}], "func_name": "check_file", "docstring": "Reads `path` and checks that its contents match `exp_lines`.", "repo": "endbasic/endbasic", "path": "std/src/storage/fs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac16f48b0165df0564b6e2db48673214648ae880ec2a21a577ce2829f51c0a27"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_file\n\nDocumentation:\nCreates `path` with the contents in `lines` and with a deterministic modification time.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_file(path: &Path, lines: &[&str]) {\n let mut file = OpenOptions::new()\n .create(true)\n .truncate(false) // Should not be creating the same file more than once.\n .write(true)\n .open(path)\n .unwrap();\n for line in lines {\n file.write_fmt(format_args!(\"{}\\n\", line)).unwrap();\n }\n drop(file);\n\n filetime::set_file_mtime(path, filetime::FileTime::from_unix_time(1_588_757_875, 0))\n .unwrap();\n }\n```"}], "func_name": "write_file", "docstring": "Creates `path` with the contents in `lines` and with a deterministic modification time.", "repo": "endbasic/endbasic", "path": "std/src/storage/fs.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0ae95a270b0e1a517bc73287e9d5944de2316444ff6e62dab8844f77fc79f8f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: readers\n\nDocumentation:\nConvenience function to instantiate a `FileAcls` with the `r` readers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn readers(r: &[&str]) -> FileAcls {\n FileAcls::default().with_readers(r.iter().map(|x| x.to_string()).collect::>())\n }\n```"}], "func_name": "readers", "docstring": "Convenience function to instantiate a `FileAcls` with the `r` readers.", "repo": "endbasic/endbasic", "path": "std/src/storage/mem.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mem.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e76dd12194e5f7ef1c4268997b4b0c08b5ccb898310c6da6847e8ee2a5b3292"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: time_format_error_to_io_error\n\nDocumentation:\nConverts a time formatting error to an I/O error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn time_format_error_to_io_error(e: Format) -> io::Error {\n match e {\n Format::StdIo(e) => e,\n e => io::Error::other(format!(\"{}\", e)),\n }\n}\n```"}], "func_name": "time_format_error_to_io_error", "docstring": "Converts a time formatting error to an I/O error.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3c5cf2d5b44c43b4ec53a1780cafcaef92a7e3358924b5a70000f2e4f76d4e38"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_readers\n\nDocumentation:\nExtends this set of ACLs with the given `readers`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_readers>>(mut self, readers: T) -> Self {\n self.readers.extend(readers.into());\n self\n }\n```"}], "func_name": "with_readers", "docstring": "Extends this set of ACLs with the given `readers`.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80d63c379a1f2e4020bf9d10a974cb45e9a91f8341f6e347bd67e68fa102033d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new representation of disk space.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(bytes: u64, files: u64) -> Self {\n Self { bytes, files }\n }\n```"}], "func_name": "new", "docstring": "Creates a new representation of disk space.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "58ab0dd4b5a880d5c016dc80b90413aaef6ac9525369e845a39678eb49d982b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new collection of files with the given `dirents`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n dirents: BTreeMap,\n disk_quota: Option,\n disk_free: Option,\n ) -> Self {\n Self { dirents, disk_quota, disk_free }\n }\n```"}], "func_name": "new", "docstring": "Creates a new collection of files with the given `dirents`.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc21a044f8bb35674ed6ad5667e80bcb046023aa079e6e5f0a97fe7c84fdb861"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_acls\n\nDocumentation:\nGets the ACLs of the file `_name`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn get_acls(&self, _name: &str) -> io::Result {\n Err(io::Error::other(\"Operation not supported by drive\"))\n }\n```"}], "func_name": "get_acls", "docstring": "Gets the ACLs of the file `_name`.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "42f4d006c6da44b011e117a7f3f5dd7ffd61addf0bdaecd63ae2938da64f585f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_acls\n\nDocumentation:\nUpdates the ACLs of the file `_name` by extending them with the contents of `_add` and\nremoving the existing entries listed in `_remove`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn update_acls(\n &mut self,\n _name: &str,\n _add: &FileAcls,\n _remove: &FileAcls,\n ) -> io::Result<()> {\n Err(io::Error::other(\"Operation not supported by drive\"))\n }\n```"}], "func_name": "update_acls", "docstring": "Updates the ACLs of the file `_name` by extending them with the contents of `_add` and\nremoving the existing entries listed in `_remove`.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "db07aad8f51ca6274cf917aeebe2108016c2b87e3fbee0bd8113b6c3f8103b20"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConstructs a drive from a raw string, validating that the name is valid.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new>(drive: T) -> io::Result {\n let drive = drive.into();\n if !DriveKey::is_valid(&drive) {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n format!(\"Invalid drive name '{}'\", drive),\n ));\n }\n Ok(DriveKey(drive.to_uppercase()))\n }\n```"}], "func_name": "new", "docstring": "Constructs a drive from a raw string, validating that the name is valid.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "10797574a64d87947c3e7e30056230a6781501cc97cd9cfc1a4898bebf60d796"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_valid\n\nDocumentation:\nReturns true if the given drive name is valid.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_valid(s: &str) -> bool {\n !s.is_empty() && !s.chars().any(|c| c == ':' || c == '\\\\' || c == '/' || c == '.')\n }\n```"}], "func_name": "is_valid", "docstring": "Returns true if the given drive name is valid.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "beed344f4e8814d86bf9b30bc40b1fe3214c915577f80bcafa15a5525a71444f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConstructs a new path from the contents of `s` after validating it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(s: &str) -> io::Result {\n let fields = s.split(':').collect::>();\n let (drive, mut path) = match fields.as_slice() {\n [drive, path] => (Some(DriveKey::new(*drive)?), *path),\n [path] => (None, *path),\n _ => {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n format!(\"Too many : separators in path '{}'\", s),\n ))\n }\n };\n\n if path.is_empty() {\n path = \"/\";\n } else {\n if !Location::is_path_valid(path)\n || path == \".\"\n || path == \"..\"\n || path == \"/.\"\n || path == \"/..\"\n {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n format!(\"Invalid path '{}'\", s),\n ));\n }\n let slashes = path.chars().fold(0, |a, c| if c == '/' { a + 1 } else { a });\n if (slashes == 1 && !path.starts_with('/')) || slashes > 1 {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n format!(\"Too many / separators in path '{}'\", s),\n ));\n }\n }\n\n Ok(Self { drive, path: path.to_owned() })\n }\n```"}], "func_name": "new", "docstring": "Constructs a new path from the contents of `s` after validating it.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "23cf4bb6538693d2f2e18f9e3fb5c65ddcd5b75b24c7dbbac6a119aa02e005f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_drive_root\n\nDocumentation:\nConvenience function to create a path to the root of a `drive`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn with_drive_root(drive: DriveKey) -> Self {\n Self { drive: Some(drive), path: \"/\".to_owned() }\n }\n```"}], "func_name": "with_drive_root", "docstring": "Convenience function to create a path to the root of a `drive`.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "77176d7779e97a80009147078a80e0b2102fb7e0cf6f2cc471a31ba9011ed5d2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_path_valid\n\nDocumentation:\nReturns true if the given path is valid.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_path_valid(s: &str) -> bool {\n !s.is_empty() && !s.chars().any(|c| c == ':' || c == '\\\\')\n }\n```"}], "func_name": "is_path_valid", "docstring": "Returns true if the given path is valid.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "319f2c53a5524d321b95a8fa56ad3985f3f412dd502c256ae45160091eab3956"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: leaf_name\n\nDocumentation:\nReturns the last component of this path, or none if there is no referenced file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn leaf_name(&self) -> Option<&str> {\n if self.path == \"/\" {\n None\n } else if self.path.starts_with('/') {\n Some(&self.path[1..])\n } else {\n Some(&self.path)\n }\n }\n```"}], "func_name": "leaf_name", "docstring": "Returns the last component of this path, or none if there is no referenced file.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2750f5ed9243f5fc6b4eee3295abd5867760466e2390bc03b141ecb6d2acf667"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_leaf_name\n\nDocumentation:\nSets the leaf name of this path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_leaf_name(&mut self, name: &str) {\n if self.path.starts_with('/') {\n self.path.clear();\n self.path.push('/');\n self.path.push_str(name);\n } else {\n self.path.clear();\n self.path.push_str(name);\n }\n }\n```"}], "func_name": "set_leaf_name", "docstring": "Sets the leaf name of this path.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a77b40c661195b4260e4e32e364ffa327647483852ed02d7214a746eb8e8cc37"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_extension\n\nDocumentation:\nSets the file name extension as long as this location corresponds to a file and not a\ndirectory and does not already have one.\n\nThe `extension` must be provided in lowercase.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_extension(&mut self, extension: &str) {\n debug_assert_eq!(extension, extension.to_ascii_lowercase());\n\n if let Some(name) = self.leaf_name() {\n if name.is_empty() {\n return;\n }\n\n if name.rfind('.').is_some() {\n return;\n }\n\n // Attempt to determine a sensible extension based on the case of the leaf name,\n // assuming that an all-uppercase basename wants an all-uppercase extension. This is\n // fragile on case-sensitive file systems, but there is not a lot we can do.\n let mut as_uppercase = true;\n for ch in name.chars() {\n if ch.is_ascii_lowercase() {\n as_uppercase = false;\n break;\n }\n }\n\n self.path.push('.');\n if as_uppercase {\n self.path.push_str(&extension.to_ascii_uppercase());\n } else {\n self.path.push_str(extension);\n }\n }\n }\n```"}], "func_name": "set_extension", "docstring": "Sets the file name extension as long as this location corresponds to a file and not a\ndirectory and does not already have one.\n\nThe `extension` must be provided in lowercase.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "339757c51b847a04f6a2ccd8318ec7d19014963fe58d56a4b738552dcc838744"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: split_uri\n\nDocumentation:\nGiven a mount URI, validates it and returns the `(scheme, path)` pair.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn split_uri(uri: &str) -> io::Result<(&str, &str)> {\n match uri.find(\"://\") {\n Some(pos) if pos > 0 => Ok((&uri[0..pos], &uri[pos + 3..])),\n _ => Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n \"Mount URI must be of the form scheme://path\",\n )),\n }\n}\n```"}], "func_name": "split_uri", "docstring": "Given a mount URI, validates it and returns the `(scheme, path)` pair.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5ea6f676e2d41d0429521e64d9f9ea80d78c21fa4deb4fec088121dd069d9388"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default\n\nDocumentation:\nCreates a new storage subsytem backed by an in-memory drive.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn default() -> Self {\n let mut factories: HashMap> = HashMap::default();\n factories.insert(\"memory\".to_owned(), Box::from(InMemoryDriveFactory::default()));\n\n let drive: Box = Box::from(InMemoryDrive::default());\n\n let mut drives = HashMap::new();\n let key = DriveKey::new(\"MEMORY\").expect(\"Hardcoded drive name must be valid\");\n let mounted_drive = MountedDrive { uri: \"memory://\".to_owned(), drive };\n drives.insert(key.clone(), mounted_drive);\n Self { factories, drives, current: key }\n }\n```"}], "func_name": "default", "docstring": "Creates a new storage subsytem backed by an in-memory drive.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0d82601ceb58441b159a46eab77a032632a67d33436f802c3832cbd41edc07c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: register_scheme\n\nDocumentation:\nRegisters a new drive `factory` to handle the `scheme`. Must not have previously been\nregistered and the `scheme` must be in lowercase.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn register_scheme(&mut self, scheme: &str, factory: Box) {\n assert_eq!(scheme.to_lowercase(), scheme);\n let previous = self.factories.insert(scheme.to_owned(), factory);\n assert!(previous.is_none(), \"Tried to register {} twice\", scheme);\n }\n```"}], "func_name": "register_scheme", "docstring": "Registers a new drive `factory` to handle the `scheme`. Must not have previously been\nregistered and the `scheme` must be in lowercase.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "37618171dae2503d0a9f13c69b03646c1e895eb0aae2a9e9b2f58497b359a84a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_canonical\n\nDocumentation:\nConverts a `raw_location`, which needn't exist, to its canonical form.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn make_canonical(&self, raw_location: &str) -> io::Result {\n let mut location = Location::new(raw_location)?;\n if location.drive.is_none() {\n location.drive = Some(self.current.clone());\n }\n Ok(location.to_string())\n }\n```"}], "func_name": "make_canonical", "docstring": "Converts a `raw_location`, which needn't exist, to its canonical form.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1089a86d89f60ed98460fa2f1d53d4a9711032534dfaa1765372d18490186b5d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_canonical_with_extension\n\nDocumentation:\nConverts a `raw_location`, which needn't exist but must represent a file (not a directory),\nto its canonical form.\n\nIf `extension` is not empty, adds it to the location if it didn't not yet have nay.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn make_canonical_with_extension(\n &self,\n raw_location: &str,\n extension: &str,\n ) -> io::Result {\n let mut location = Location::new(raw_location)?;\n if location.drive.is_none() {\n location.drive = Some(self.current.clone());\n }\n if location.leaf_name().is_none() {\n return Err(io::Error::new(\n io::ErrorKind::NotFound,\n format!(\"Missing file name in path '{}'\", raw_location),\n ));\n }\n location.set_extension(extension);\n Ok(location.to_string())\n }\n```"}], "func_name": "make_canonical_with_extension", "docstring": "Converts a `raw_location`, which needn't exist but must represent a file (not a directory),\nto its canonical form.\n\nIf `extension` is not empty, adds it to the location if it didn't not yet have nay.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0fe5caa1280cc2c05cb42035a101a04e1e0108c464b52acbc9d4a5748bcebb49"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: attach\n\nDocumentation:\nAttaches a new `drive` with `name`, which was instantiated with `uri`.\n\nThe `name` must be valid and must not yet have been registered.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn attach(&mut self, name: &str, uri: &str, drive: Box) -> io::Result<()> {\n let key = DriveKey::new(name)?;\n if self.drives.contains_key(&key) {\n return Err(io::Error::new(\n io::ErrorKind::AlreadyExists,\n format!(\"Drive '{}' is already mounted\", name),\n ));\n }\n let mounted_drive = MountedDrive { uri: uri.to_owned(), drive };\n self.drives.insert(DriveKey::new(name)?, mounted_drive);\n Ok(())\n }\n```"}], "func_name": "attach", "docstring": "Attaches a new `drive` with `name`, which was instantiated with `uri`.\n\nThe `name` must be valid and must not yet have been registered.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "42591cdec1da5705666e0e127ace9abe3f514c8ce923d1ec47f822c2bdbe2aff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mount\n\nDocumentation:\nInstantiates and attaches a new `drive` with `name` that points to `uri`.\n\nThe `name` must be valid and must not yet have been registered.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn mount(&mut self, name: &str, uri: &str) -> io::Result<()> {\n let (scheme, path) = split_uri(uri)?;\n let drive = match self.factories.get(&scheme.to_lowercase()) {\n Some(factory) => factory.create(path)?,\n None => {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n format!(\"Unknown mount scheme '{}'\", scheme),\n ))\n }\n };\n self.attach(name, uri, drive)\n }\n```"}], "func_name": "mount", "docstring": "Instantiates and attaches a new `drive` with `name` that points to `uri`.\n\nThe `name` must be valid and must not yet have been registered.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f39ea30b464cf9b82157c0bef4f018cae0aaa4e4afda85e347ca10b3d1b82e3f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unmount\n\nDocumentation:\nDetaches an existing drive named `name`.\n\nThe drive `name` must exist, cannot be the current drive, and cannot be the last mounted\ndrive.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unmount(&mut self, name: &str) -> io::Result<()> {\n let key = DriveKey::new(name)?;\n if !self.drives.contains_key(&key) {\n return Err(io::Error::new(\n io::ErrorKind::NotFound,\n format!(\"Drive '{}' is not mounted\", name),\n ));\n }\n if self.current == key {\n return Err(io::Error::new(\n io::ErrorKind::AlreadyExists,\n format!(\"Cannot unmount the current drive '{}'\", name),\n ));\n }\n assert!(\n self.drives.len() > 1,\n \"There must be more than one drive if the current drive is not the given name\"\n );\n self.drives.remove(&key).expect(\"Drive presence in map checked above\");\n Ok(())\n }\n```"}], "func_name": "unmount", "docstring": "Detaches an existing drive named `name`.\n\nThe drive `name` must exist, cannot be the current drive, and cannot be the last mounted\ndrive.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c24b9ee1be19c38fdc495b40f655d8a82961ab979fe0c8683baf33a23ddde65a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mounted\n\nDocumentation:\nReturns information about the mounted drives as a mapping of drive names to the URIs that\nwere used to mount them.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn mounted(&self) -> BTreeMap<&str, &str> {\n let mut info = BTreeMap::new();\n for (name, mounted_drive) in &self.drives {\n info.insert(name.0.as_str(), mounted_drive.uri.as_str());\n }\n info\n }\n```"}], "func_name": "mounted", "docstring": "Returns information about the mounted drives as a mapping of drive names to the URIs that\nwere used to mount them.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c5f01d4f085e571dc7d1d49dde0516826eebee09d4ad56e687f5099fab5a6fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cd\n\nDocumentation:\nChanges the current location.\n\nGiven that we currently do not support directories, the location can only be of the forms\n`DRIVE:` or `DRIVE:/`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn cd(&mut self, location: &str) -> io::Result<()> {\n let location = Location::new(location)?;\n if location.leaf_name().is_some() {\n return Err(io::Error::new(io::ErrorKind::InvalidInput, \"Cannot cd to a file\"));\n }\n\n match location.drive {\n Some(drive) => {\n if !self.drives.contains_key(&drive) {\n return Err(io::Error::new(\n io::ErrorKind::AlreadyExists,\n format!(\"Drive '{}' is not mounted\", drive),\n ));\n }\n self.current = drive;\n Ok(())\n }\n None => Ok(()),\n }\n }\n```"}], "func_name": "cd", "docstring": "Changes the current location.\n\nGiven that we currently do not support directories, the location can only be of the forms\n`DRIVE:` or `DRIVE:/`.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a93abf772d79f6732e4818ea8e3f1b92c1f26a4c81466029f568f5ffed6aa6bf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_drive\n\nDocumentation:\nReturns the drive referenced by `location`, or an error if it doesn't exist.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_drive(&self, location: &Location) -> io::Result<&dyn Drive> {\n match &location.drive {\n Some(key) => match self.drives.get(key) {\n Some(mounted_drive) => Ok(mounted_drive.drive.as_ref()),\n None => Err(io::Error::new(\n io::ErrorKind::NotFound,\n format!(\"Drive '{}' is not mounted\", key),\n )),\n },\n None => Ok(self\n .drives\n .get(&self.current)\n .expect(\"Current drive out of sync\")\n .drive\n .as_ref()),\n }\n }\n```"}], "func_name": "get_drive", "docstring": "Returns the drive referenced by `location`, or an error if it doesn't exist.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "12f90a76bfd4311ca0431556feb7dccbc9c1bf5e24d597ec0a8020f1d33c119e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: enumerate\n\nDocumentation:\nReturns a sorted list of the entries in `raw_location` and their metadata.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn enumerate(&self, raw_location: &str) -> io::Result {\n let location = Location::new(raw_location)?;\n match location.leaf_name() {\n Some(_) => Err(io::Error::new(\n io::ErrorKind::NotFound,\n format!(\"Location '{}' is not a directory\", raw_location),\n )),\n None => self.get_drive(&location)?.enumerate().await,\n }\n }\n```"}], "func_name": "enumerate", "docstring": "Returns a sorted list of the entries in `raw_location` and their metadata.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d451e051f5f649c9e48e4e45697a3d28d23733d6cb2c15cc9a285479ecc82399"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_location\n\nDocumentation:\nLoads the contents of the program given by `location`. `raw_location` is the\nstring that the user provided and is used for error reporting.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn get_location(&self, raw_location: &str, location: &Location) -> io::Result> {\n match location.leaf_name() {\n Some(name) => self.get_drive(location)?.get(name).await,\n None => Err(io::Error::new(\n io::ErrorKind::NotFound,\n format!(\"Missing file name in path '{}'\", raw_location),\n )),\n }\n }\n```"}], "func_name": "get_location", "docstring": "Loads the contents of the program given by `location`. `raw_location` is the\nstring that the user provided and is used for error reporting.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "680a7642823e78ed4ef5fa4c644fd3b54b438b6ee2c61a940c57f887bba7d3d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nLoads the contents of the program given by `raw_location`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get(&self, raw_location: &str) -> io::Result> {\n let location = Location::new(raw_location)?;\n self.get_location(raw_location, &location).await\n }\n```"}], "func_name": "get", "docstring": "Loads the contents of the program given by `raw_location`.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "890d2a3e6371b8936b4fc46a7782fc4a64327db40ec5fce6d11233d675c399b2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_acls\n\nDocumentation:\nGets the ACLs of the file `raw_location`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_acls(&self, raw_location: &str) -> io::Result {\n let location = Location::new(raw_location)?;\n match location.leaf_name() {\n Some(name) => self.get_drive(&location)?.get_acls(name).await,\n None => Err(io::Error::new(\n io::ErrorKind::NotFound,\n format!(\"Missing file name in path '{}'\", raw_location),\n )),\n }\n }\n```"}], "func_name": "get_acls", "docstring": "Gets the ACLs of the file `raw_location`.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44672e0d90e606b566aa45a17e19a23eca3d7e06347a0b1ac5ed1743a2723f4d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: put_location\n\nDocumentation:\nSaves the in-memory program given by `content` into `location`. `raw_location` is the\nstring that the user provided and is used for error reporting.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn put_location(\n &mut self,\n raw_location: &str,\n location: &Location,\n content: &[u8],\n ) -> io::Result<()> {\n match location.leaf_name() {\n Some(name) => self.get_drive_mut(location)?.put(name, content).await,\n None => Err(io::Error::new(\n io::ErrorKind::NotFound,\n format!(\"Missing file name in path '{}'\", raw_location),\n )),\n }\n }\n```"}], "func_name": "put_location", "docstring": "Saves the in-memory program given by `content` into `location`. `raw_location` is the\nstring that the user provided and is used for error reporting.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6075b3e974152fd8769afd5f8e653c52693ac12661e89b64295833a2658d0e14"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: put\n\nDocumentation:\nSaves the in-memory program given by `content` into `raw_location`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn put(&mut self, raw_location: &str, content: &[u8]) -> io::Result<()> {\n let location = Location::new(raw_location)?;\n self.put_location(raw_location, &location, content).await\n }\n```"}], "func_name": "put", "docstring": "Saves the in-memory program given by `content` into `raw_location`.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8ddc6c7b6666358cf6cb870766c5f8230a846d94b5e8f7f668e4f61ae9a1fa8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_acls\n\nDocumentation:\nUpdates the ACLs of the file `raw_location` by extending them with the contents of `add` and\nremoving the existing entries listed in `remove`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn update_acls(\n &mut self,\n raw_location: &str,\n add: &FileAcls,\n remove: &FileAcls,\n ) -> io::Result<()> {\n let location = Location::new(raw_location)?;\n match location.leaf_name() {\n Some(name) => self.get_drive_mut(&location)?.update_acls(name, add, remove).await,\n None => Err(io::Error::new(\n io::ErrorKind::NotFound,\n format!(\"Missing file name in path '{}'\", raw_location),\n )),\n }\n }\n```"}], "func_name": "update_acls", "docstring": "Updates the ACLs of the file `raw_location` by extending them with the contents of `add` and\nremoving the existing entries listed in `remove`.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "feb68aa36cf4e69f6bbb893363b5164935894880c75b66cc366f38ff939a4da8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: system_path\n\nDocumentation:\nGets the system-addressable path of `raw_location`, if any.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn system_path(&self, raw_location: &str) -> io::Result> {\n let location = Location::new(raw_location)?;\n match location.leaf_name() {\n Some(name) => Ok(self.get_drive(&location)?.system_path(name)),\n None => Ok(self.get_drive(&location)?.system_path(\"\")),\n }\n }\n```"}], "func_name": "system_path", "docstring": "Gets the system-addressable path of `raw_location`, if any.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f641209e5eb2a6b528f986446ba61ff5d1f223be61a29130f51977153230f39"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: drive_names\n\nDocumentation:\nConvenience helper to obtain the sorted list of mounted drive names in canonical form.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn drive_names(storage: &Storage) -> Vec {\n let mut names = storage.drives.keys().map(DriveKey::to_string).collect::>();\n names.sort();\n names\n }\n```"}], "func_name": "drive_names", "docstring": "Convenience helper to obtain the sorted list of mounted drive names in canonical form.", "repo": "endbasic/endbasic", "path": "std/src/storage/mod.rs", "url": "https://github.com/endbasic/endbasic/blob/master/std/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17e0c36bcf26cb606661e8561a6a556505817e297b55f8411c3259e9a721a6fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_stdio\n\nDocumentation:\nCreates a new console based on the properties of stdin/stdout.\n\nThis spawns a background task to handle console input so this must be run in the context of\nan Tokio runtime.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_stdio(signals_tx: Sender) -> io::Result {\n let (terminal, _on_key_tx) = Self::from_stdio_with_injector(signals_tx)?;\n Ok(terminal)\n }\n```"}], "func_name": "from_stdio", "docstring": "Creates a new console based on the properties of stdin/stdout.\n\nThis spawns a background task to handle console input so this must be run in the context of\nan Tokio runtime.", "repo": "endbasic/endbasic", "path": "terminal/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/terminal/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09baae6e553cae42b2dc4d6fae5f656511fc788b5fc81c753770f8c0fe672fdf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_stdio_with_injector\n\nDocumentation:\nCreates a new console based on the properties of stdin/stdout.\n\nThis spawns a background task to handle console input so this must be run in the context of\nan Tokio runtime.\n\nCompared to `from_stdio`, this also returns a key sender to inject extra events into the\nqueue maintained by the terminal.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_stdio_with_injector(signals_tx: Sender) -> io::Result<(Self, Sender)> {\n let (on_key_tx, on_key_rx) = async_channel::unbounded();\n\n let is_tty = io::stdin().is_tty() && io::stdout().is_tty();\n\n if is_tty {\n terminal::enable_raw_mode()?;\n tokio::task::spawn(TerminalConsole::raw_key_handler(on_key_tx.clone(), signals_tx));\n } else {\n tokio::task::spawn(TerminalConsole::stdio_key_handler(on_key_tx.clone()));\n }\n\n Ok((\n Self {\n is_tty,\n fg_color: None,\n bg_color: None,\n cursor_visible: true,\n alt_active: false,\n sync_enabled: true,\n on_key_rx,\n },\n on_key_tx,\n ))\n }\n```"}], "func_name": "from_stdio_with_injector", "docstring": "Creates a new console based on the properties of stdin/stdout.\n\nThis spawns a background task to handle console input so this must be run in the context of\nan Tokio runtime.\n\nCompared to `from_stdio`, this also returns a key sender to inject extra events into the\nqueue maintained by the terminal.", "repo": "endbasic/endbasic", "path": "terminal/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/terminal/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "160d3a281ba205c14f7d2238a8e11a439099606b08f59153d9d11dd591c10a7f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: raw_key_handler\n\nDocumentation:\nAsync task to wait for key events on a raw terminal and translate them into events for the\nconsole or the machine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn raw_key_handler(on_key_tx: Sender, signals_tx: Sender) {\n use event::{KeyCode, KeyModifiers};\n\n let mut done = false;\n while !done {\n let key = match event::read() {\n Ok(event::Event::Key(ev)) => {\n if ev.kind != KeyEventKind::Press {\n continue;\n }\n\n match ev.code {\n KeyCode::Backspace => Key::Backspace,\n KeyCode::End => Key::End,\n KeyCode::Esc => Key::Escape,\n KeyCode::Home => Key::Home,\n KeyCode::Tab => Key::Tab,\n KeyCode::Up => Key::ArrowUp,\n KeyCode::Down => Key::ArrowDown,\n KeyCode::Left => Key::ArrowLeft,\n KeyCode::Right => Key::ArrowRight,\n KeyCode::PageDown => Key::PageDown,\n KeyCode::PageUp => Key::PageUp,\n KeyCode::Char('a') if ev.modifiers == KeyModifiers::CONTROL => Key::Home,\n KeyCode::Char('b') if ev.modifiers == KeyModifiers::CONTROL => {\n Key::ArrowLeft\n }\n KeyCode::Char('c') if ev.modifiers == KeyModifiers::CONTROL => {\n Key::Interrupt\n }\n KeyCode::Char('d') if ev.modifiers == KeyModifiers::CONTROL => Key::Eof,\n KeyCode::Char('e') if ev.modifiers == KeyModifiers::CONTROL => Key::End,\n KeyCode::Char('f') if ev.modifiers == KeyModifiers::CONTROL => {\n Key::ArrowRight\n }\n KeyCode::Char('j') if ev.modifiers == KeyModifiers::CONTROL => Key::NewLine,\n KeyCode::Char('m') if ev.modifiers == KeyModifiers::CONTROL => Key::NewLine,\n KeyCode::Char('n') if ev.modifiers == KeyModifiers::CONTROL => {\n Key::ArrowDown\n }\n KeyCode::Char('p') if ev.modifiers == KeyModifiers::CONTROL => Key::ArrowUp,\n KeyCode::Char(ch) => Key::Char(ch),\n KeyCode::Enter => Key::NewLine,\n _ => Key::Unknown,\n }\n }\n Ok(_) => {\n // Not a key event; ignore and try again.\n continue;\n }\n Err(_) => {\n // There is not much we can do if we get an error from crossterm.\n Key::Unknown\n }\n };\n\n done = key == Key::Eof;\n if key == Key::Interrupt {\n // Handling CTRL+C in this way isn't great because this is not the same as handling\n // SIGINT on Unix builds. First, we are unable to stop long-running operations like\n // sleeps; and second, a real SIGINT will kill the interpreter completely instead of\n // coming this way. We need a real signal handler and we probably should not be\n // running in raw mode all the time.\n signals_tx\n .send(Signal::Break)\n .await\n .expect(\"Send to unbounded channel should not have failed\")\n }\n\n // This should never fail but can if the receiver outruns the console because we\n // don't await for the handler to terminate (which we cannot do safely because\n // `Drop` is not async).\n let _ = on_key_tx.send(key).await;\n }\n\n signals_tx.close();\n on_key_tx.close();\n }\n```"}], "func_name": "raw_key_handler", "docstring": "Async task to wait for key events on a raw terminal and translate them into events for the\nconsole or the machine.", "repo": "endbasic/endbasic", "path": "terminal/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/terminal/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b52c7d7ca94b8d2d9b7f4ce4a47265f8f8cab6e0c52dbe3845020272a6b4884"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stdio_key_handler\n\nDocumentation:\nAsync task to wait for key events on a non-raw terminal and translate them into events for\nthe console or the machine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn stdio_key_handler(on_key_tx: Sender) {\n // TODO(jmmv): We should probably install a signal handler here to capture SIGINT and\n // funnel it to the Machine via signals_rx, as we do in the raw_key_handler. This would\n // help ensure both consoles behave in the same way, but there is strictly no need for this\n // because, when we do not configure the terminal in raw mode, we aren't capturing CTRL+C\n // and the default system handler will work.\n\n let mut buffer = VecDeque::default();\n\n let mut done = false;\n while !done {\n let key = match read_key_from_stdin(&mut buffer) {\n Ok(key) => key,\n Err(_) => {\n // There is not much we can do if we get an error from stdin.\n Key::Unknown\n }\n };\n\n done = key == Key::Eof;\n\n // This should never fail but can if the receiver outruns the console because we don't\n // await for the handler to terminate (which we cannot do safely because `Drop` is not\n // async).\n let _ = on_key_tx.send(key).await;\n }\n\n on_key_tx.close();\n }\n```"}], "func_name": "stdio_key_handler", "docstring": "Async task to wait for key events on a non-raw terminal and translate them into events for\nthe console or the machine.", "repo": "endbasic/endbasic", "path": "terminal/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/terminal/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51698be7da52d18be47a43658f1138ac4c47dd6e7bdf1be66234921171e91656"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: js_value_to_io_error\n\nDocumentation:\nConverts a `JsValue` error to an `io::Error`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn js_value_to_io_error(e: JsValue) -> io::Error {\n if let Some(str) = e.as_string() {\n return io::Error::other(str);\n }\n io::Error::other(\"Unknown error\")\n}\n```"}], "func_name": "js_value_to_io_error", "docstring": "Converts a `JsValue` error to an `io::Error`.", "repo": "endbasic/endbasic", "path": "web/src/canvas.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/canvas.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4bc3dde743747a17625d1ab634ac6446ca3c5641c97354831cb2cb36b21700b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: html_canvas_to_2d_context\n\nDocumentation:\nReturns the 2D rendering context for a given `canvas` element.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn html_canvas_to_2d_context(canvas: HtmlCanvasElement) -> io::Result {\n let attrs = ContextAttributes2d::new();\n\n // We don't use transparency for anything, so disable the alpha channel for performance reasons.\n attrs.set_alpha(false);\n\n // Chrome recommends setting this to true because we read from the canvas to move the cursor\n // and to scroll the console, but these operations needn't be fast. It seems better to keep\n // this disabled to optimize for the rendering path of graphical applications.\n attrs.set_will_read_frequently(false);\n\n let context = match canvas\n .get_context_with_context_options(\"2d\", &attrs)\n .map_err(js_value_to_io_error)?\n {\n Some(context) => context,\n None => {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n \"Failed to get 2D context from canvas\",\n ))\n }\n };\n\n let context = match context.dyn_into::() {\n Ok(context) => context,\n Err(_) => {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n \"Returned 2D context for canvas does not have the correct type\",\n ))\n }\n };\n\n Ok(context)\n}\n```"}], "func_name": "html_canvas_to_2d_context", "docstring": "Returns the 2D rendering context for a given `canvas` element.", "repo": "endbasic/endbasic", "path": "web/src/canvas.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/canvas.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a39a43909140490242c12e3e9d23d6e47fb1d8ab79936cf8c751efd4881a369"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new canvas console backed by the `canvas` HTML element and that receives input\nevents from `input`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new(\n canvas: HtmlCanvasElement,\n yielder: Rc>,\n ) -> io::Result {\n let size_pixels = {\n let width = match u16::try_from(canvas.width()) {\n Ok(v) => v,\n Err(_) => {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n format!(\"Canvas is too wide at {} pixels\", canvas.width()),\n ))\n }\n };\n let height = match u16::try_from(canvas.height()) {\n Ok(v) => v,\n Err(_) => {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n format!(\"Canvas is too tall at {} pixels\", canvas.height()),\n ))\n }\n };\n SizeInPixels::new(width, height)\n };\n\n let context = html_canvas_to_2d_context(canvas)?;\n context.set_font(&format!(\"{}px {}\", DEFAULT_FONT_SIZE, DEFAULT_FONT_FACE));\n context.set_image_smoothing_enabled(false);\n context.set_text_baseline(\"middle\");\n\n let glyph_size = {\n let text_metrics = context.measure_text(\"X\").map_err(js_value_to_io_error)?;\n let width = text_metrics.width().ceil() as u16;\n let height = DEFAULT_FONT_SIZE + 2; // Pad lines a little bit.\n SizeInPixels::new(width, height)\n };\n\n let size_chars = {\n let width = match size_pixels.width.checked_div(glyph_size.width) {\n Some(v) => v,\n None => {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n format!(\"Invalid glyph width {}\", glyph_size.width),\n ))\n }\n };\n let height = match size_pixels.height.checked_div(glyph_size.height) {\n Some(v) => v,\n None => {\n return Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n format!(\"Invalid glyph height {}\", glyph_size.height),\n ))\n }\n };\n CharsXY::new(width, height)\n };\n\n // The actual values are irrelevant but need to be different than the initial values we use\n // below.\n let fill_color = (10, 10, 10);\n let stroke_color = (100, 100, 100);\n\n let mut raster_ops = Self {\n context,\n yielder,\n size_pixels,\n glyph_size,\n size_chars,\n fill_color,\n stroke_color,\n };\n\n raster_ops.set_fill_style_rgb((0, 0, 0));\n raster_ops.set_stroke_style_rgb((255, 255, 255));\n\n Ok(raster_ops)\n }\n```"}], "func_name": "new", "docstring": "Creates a new canvas console backed by the `canvas` HTML element and that receives input\nevents from `input`.", "repo": "endbasic/endbasic", "path": "web/src/canvas.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/canvas.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "74b5ff64f2b1f71f9f7fdc1153a43f1e91e13cd940633f1ec8ac3a5003e231ce"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_fill_style_rgb\n\nDocumentation:\nSets the fill color of the canvas to `rgb`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_fill_style_rgb(&mut self, rgb: RGB) {\n if self.fill_color != rgb {\n self.context.set_fill_style_str(&format!(\"rgb({}, {}, {})\", rgb.0, rgb.1, rgb.2));\n self.fill_color = rgb;\n }\n }\n```"}], "func_name": "set_fill_style_rgb", "docstring": "Sets the fill color of the canvas to `rgb`.", "repo": "endbasic/endbasic", "path": "web/src/canvas.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/canvas.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8d6bdb34f1177aebf3486e0f33d972cccbfe3ff051966aead17fbad298a3331f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_stroke_style_rgb\n\nDocumentation:\nSets the stroke color of the canvas to `rgb`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_stroke_style_rgb(&mut self, rgb: RGB) {\n if self.stroke_color != rgb {\n self.context.set_stroke_style_str(&format!(\"rgb({}, {}, {})\", rgb.0, rgb.1, rgb.2));\n self.stroke_color = rgb;\n }\n }\n```"}], "func_name": "set_stroke_style_rgb", "docstring": "Sets the stroke color of the canvas to `rgb`.", "repo": "endbasic/endbasic", "path": "web/src/canvas.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/canvas.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "613e0590bbcca3884bc1a99bfe72ac97b6bafc6c4ec02d06e2272c0aae39a44a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_input_event_into_key\n\nDocumentation:\nConverts an HTML input event into our own `Key` representation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn on_input_event_into_key(dom_event: InputEvent) -> Key {\n let chars = match dom_event.data() {\n Some(data) => data.chars().collect::>(),\n None => vec![],\n };\n if chars.len() == 1 {\n Key::Char(chars[0])\n } else {\n Key::Unknown\n }\n}\n```"}], "func_name": "on_input_event_into_key", "docstring": "Converts an HTML input event into our own `Key` representation.", "repo": "endbasic/endbasic", "path": "web/src/input.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3eccb85103dd5b3092ede80fd5c026aa71a64ce8c1afaca92ffa9fb8f98fc533"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_key_event_into_key\n\nDocumentation:\nConverts an HTML keyboard event into our own `Key` representation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn on_key_event_into_key(dom_event: KeyboardEvent) -> Key {\n match dom_event.key_code() as u8 {\n 8 => Key::Backspace,\n 9 => Key::Tab,\n 10 => Key::NewLine,\n 13 => Key::CarriageReturn,\n 27 => Key::Escape,\n 33 => Key::PageUp,\n 34 => Key::PageDown,\n 35 => Key::End,\n 36 => Key::Home,\n 37 => Key::ArrowLeft,\n 38 => Key::ArrowUp,\n 39 => Key::ArrowRight,\n 40 => Key::ArrowDown,\n b'A' if dom_event.ctrl_key() => Key::Home,\n b'B' if dom_event.ctrl_key() => Key::ArrowLeft,\n b'C' if dom_event.ctrl_key() => Key::Interrupt,\n b'D' if dom_event.ctrl_key() => Key::Eof,\n b'E' if dom_event.ctrl_key() => Key::End,\n b'F' if dom_event.ctrl_key() => Key::ArrowRight,\n b'J' if dom_event.ctrl_key() => Key::NewLine,\n b'M' if dom_event.ctrl_key() => Key::NewLine,\n b'N' if dom_event.ctrl_key() => Key::ArrowDown,\n b'P' if dom_event.ctrl_key() => Key::ArrowUp,\n _ => {\n let printable = !dom_event.alt_key() && !dom_event.ctrl_key() && !dom_event.meta_key();\n let chars = dom_event.key().chars().collect::>();\n if printable && chars.len() == 1 {\n Key::Char(chars[0])\n } else {\n Key::Unknown\n }\n }\n }\n}\n```"}], "func_name": "on_key_event_into_key", "docstring": "Converts an HTML keyboard event into our own `Key` representation.", "repo": "endbasic/endbasic", "path": "web/src/input.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "011877ceeebc996c1f2c00d40c34455a08363d0ef44664a9cd7e374559ed2eb8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: safe_try_send\n\nDocumentation:\nWrapper around `self.on_key_tx.try_send` that always expects to succeed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn safe_try_send(&self, key: Key) {\n if let Err(e) = self.on_key_tx.try_send(key) {\n log_and_panic!(\"Send to unbounded channel must succeed: {}\", e);\n }\n }\n```"}], "func_name": "safe_try_send", "docstring": "Wrapper around `self.on_key_tx.try_send` that always expects to succeed.", "repo": "endbasic/endbasic", "path": "web/src/input.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "13acf5d55890da336be226eee93fc26ef9fdb7f8b381ed8a5a9c938b5c2c55fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: inject_input_event\n\nDocumentation:\nPushes a new captured `dom_event` input event into the input.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn inject_input_event(&self, dom_event: InputEvent) {\n // TODO(jmmv): Add an on-screen button to send CTRL+C events.\n self.safe_try_send(on_input_event_into_key(dom_event))\n }\n```"}], "func_name": "inject_input_event", "docstring": "Pushes a new captured `dom_event` input event into the input.", "repo": "endbasic/endbasic", "path": "web/src/input.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d5d301e6ec8f8254ae81c558ecfd05fba1f5d650b68088d4b8cb02af66c0d9b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: inject_keyboard_event\n\nDocumentation:\nPushes a new captured `dom_event` keyboard event into the input.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn inject_keyboard_event(&self, dom_event: KeyboardEvent) {\n let key = on_key_event_into_key(dom_event);\n if key == Key::Interrupt {\n if let Err(e) = self.signals_tx.try_send(Signal::Break) {\n log_and_panic!(\"Send to unbounded channel must succeed: {}\", e);\n }\n }\n\n self.safe_try_send(key)\n }\n```"}], "func_name": "inject_keyboard_event", "docstring": "Pushes a new captured `dom_event` keyboard event into the input.", "repo": "endbasic/endbasic", "path": "web/src/input.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cbbcb7fe91240f4401f9a1c4fcd98209c941523dbb5fc2a1378a77e9005ac4fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `WebInput` that can inject events into the interpreter via `signals_tx`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new(signals_tx: Sender, yielder: Rc>) -> Self {\n let (on_key_tx, on_key_rx) = async_channel::unbounded();\n Self { on_key_rx, on_key_tx, signals_tx, yielder }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `WebInput` that can inject events into the interpreter via `signals_tx`.", "repo": "endbasic/endbasic", "path": "web/src/input.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "40527877118fda85952ac2fde6b25ba4a07aa633a972ba926315032835efafd6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_screen_keyboard\n\nDocumentation:\nGenerates a new `OnScreenKeyboard` that can inject key events.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn on_screen_keyboard(&self) -> OnScreenKeyboard {\n OnScreenKeyboard { on_key_tx: self.on_key_tx.clone(), signals_tx: self.signals_tx.clone() }\n }\n```"}], "func_name": "on_screen_keyboard", "docstring": "Generates a new `OnScreenKeyboard` that can inject key events.", "repo": "endbasic/endbasic", "path": "web/src/input.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7bbcca88c83eb001ea250248813a57f67b0972009574d622ce02ff9c60fbcaa3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_recv\n\nDocumentation:\nGets the next key event, if one is available.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn try_recv(&mut self) -> io::Result> {\n match self.on_key_rx.try_recv() {\n Ok(k) => {\n self.yielder.borrow_mut().reset();\n Ok(Some(k))\n }\n Err(TryRecvError::Empty) => Ok(None),\n Err(TryRecvError::Closed) => log_and_panic!(\"Channel unexpectedly closed\"),\n }\n }\n```"}], "func_name": "try_recv", "docstring": "Gets the next key event, if one is available.", "repo": "endbasic/endbasic", "path": "web/src/input.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "595f059d9499868004911f1940869494cd984462e31e691d553fff36636ae758"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: recv\n\nDocumentation:\nGets the next key event, waiting until one is available.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn recv(&mut self) -> io::Result {\n let key = self.on_key_rx.recv().await.unwrap();\n self.yielder.borrow_mut().reset();\n Ok(key)\n }\n```"}], "func_name": "recv", "docstring": "Gets the next key event, waiting until one is available.", "repo": "endbasic/endbasic", "path": "web/src/input.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c225d2ad0522dce0ee00be365c70b99fa28671c46790a5e44dce135da6e7af1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_sleep\n\nDocumentation:\nSleeps for the given period of time in `ms`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_sleep(ms: i32, ret: T) -> Pin>> {\n assert!(ms >= 0, \"Must have been validated by the caller\");\n\n let (timeout_tx, timeout_rx) = async_channel::unbounded();\n let callback = {\n Closure::wrap(Box::new(move || timeout_tx.try_send(true).expect(\"Send must succeed\"))\n as Box)\n };\n\n let window = match web_sys::window() {\n Some(window) => window,\n None => log_and_panic!(\"Failed to get window\"),\n };\n if let Err(e) = window.set_timeout_with_callback_and_timeout_and_arguments(\n callback.as_ref().unchecked_ref(),\n ms,\n &js_sys::Array::new(),\n ) {\n log_and_panic!(\"Failed to set timeout on window: {:?}\", e);\n }\n\n Box::pin(async move {\n let _ = callback; // Must grab ownership so that the closure remains alive until it is used.\n if let Err(e) = timeout_rx.recv().await {\n log_and_panic!(\"Failed to wait for timeout: {}\", e);\n }\n ret\n })\n}\n```"}], "func_name": "do_sleep", "docstring": "Sleeps for the given period of time in `ms`.", "repo": "endbasic/endbasic", "path": "web/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d263698c99ad03a733ae3c92d79a6e42109d361f24265f7759e85682bed9ccff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: yield_now\n\nDocumentation:\nYields execution via a zero timeout if enough instructions have been executed and if enough\ntime has passed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn yield_now(&mut self) -> Pin>> {\n if self.counter > 0 {\n self.counter -= 1;\n\n Box::pin(async move {})\n } else {\n let new_last = OffsetDateTime::now_utc();\n if (new_last - self.last) >= Duration::from_millis(Self::MAX_INTERVAL_MILLIS) {\n debug_assert!(self.counter == 0);\n self.last = new_last;\n\n do_sleep(0, ())\n } else {\n Box::pin(async move {})\n }\n }\n }\n```"}], "func_name": "yield_now", "docstring": "Yields execution via a zero timeout if enough instructions have been executed and if enough\ntime has passed.", "repo": "endbasic/endbasic", "path": "web/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e12fa292e5e75ee43162d34699361fafad147e9bf1f3ded84816bbe1c914461a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset\n\nDocumentation:\nRecords that a yield just happened for some other reason and needn't happen again until the\nnext interval.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reset(&mut self) {\n self.counter = Self::GRACE_ITERATIONS;\n self.last = OffsetDateTime::now_utc();\n }\n```"}], "func_name": "reset", "docstring": "Records that a yield just happened for some other reason and needn't happen again until the\nnext interval.", "repo": "endbasic/endbasic", "path": "web/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6272486fbd07984325a2324391acc7efe8ef5ac42d13cfabf53861c133b16d65"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: schedule\n\nDocumentation:\nSchedules a forced yield on the next round.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn schedule(&mut self) {\n self.counter = 0;\n self.last -= Duration::from_millis(Self::MAX_INTERVAL_MILLIS);\n }\n```"}], "func_name": "schedule", "docstring": "Schedules a forced yield on the next round.", "repo": "endbasic/endbasic", "path": "web/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b40a1c1ba7e1a8ec86e60808e46993d0acff7ac6f898aa6f0ffd1b22e5ccd71a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_yield_now_fn\n\nDocumentation:\nCreates a new `YieldNowFn` that can be passed to the core executor for a given `yielder`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_yield_now_fn(yielder: Rc>) -> YieldNowFn {\n Box::from(move || {\n let yielder = yielder.clone();\n let mut yielder = yielder.borrow_mut();\n yielder.yield_now()\n })\n }\n```"}], "func_name": "new_yield_now_fn", "docstring": "Creates a new `YieldNowFn` that can be passed to the core executor for a given `yielder`.", "repo": "endbasic/endbasic", "path": "web/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ce634d9290d2b8429d6fd586d36457a6f5d795a5bf2f2a5701aa24e43d403a35"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: setup_storage\n\nDocumentation:\nSets up the common storage drives.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn setup_storage(storage: &mut endbasic_std::storage::Storage) {\n storage.register_scheme(\"demos\", Box::from(endbasic_repl::demos::DemoDriveFactory::default()));\n storage.mount(\"demos\", \"demos://\").expect(\"Demos drive shouldn't fail to mount\");\n storage.register_scheme(\"local\", Box::from(WebDriveFactory::default()));\n storage.mount(\"local\", \"local://\").expect(\"Web drive shouldn't fail to mount\");\n storage.cd(\"local:\").expect(\"Local drive was just registered\");\n}\n```"}], "func_name": "setup_storage", "docstring": "Sets up the common storage drives.", "repo": "endbasic/endbasic", "path": "web/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b3222b8359d4d3d2989739c1f8cf822ac6a6b6a484c42f65d367b90520daf601"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: size_description\n\nDocumentation:\nReturns a textual description of the size of the console.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn size_description(&self) -> String {\n let pixels = match self.console.size_pixels() {\n Ok(size) => size,\n Err(e) => panic!(\"Failed to get console size in pixels: {}\", e),\n };\n let chars = match self.console.size_chars() {\n Ok(size) => size,\n Err(e) => panic!(\"Failed to get console size in chars: {}\", e),\n };\n format!(\"{}x{} pixels, {}x{} chars\", pixels.width, pixels.height, chars.x, chars.y)\n }\n```"}], "func_name": "size_description", "docstring": "Returns a textual description of the size of the console.", "repo": "endbasic/endbasic", "path": "web/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "123d7685edf74565b0c2dde0bf60c0f5823b7be3de79a627fbe762a19f3e5848"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: safe_run_repl_loop\n\nDocumentation:\nSafe version of `run_repl_loop` that is able to return errors.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn safe_run_repl_loop(self) -> io::Result<()> {\n let location = match web_sys::window() {\n Some(window) => match window.location().href() {\n Ok(href) => match Url::parse(&href) {\n Ok(url) => url,\n Err(e) => log_and_panic!(\"Failed to parse window's location href: {:?}\", e),\n },\n Err(e) => log_and_panic!(\"Failed to get window's location href: {:?}\", e),\n },\n None => log_and_panic!(\"Failed to get window\"),\n };\n\n let yielder = self.yielder.clone();\n\n let console = Rc::from(RefCell::from(self.console));\n let mut builder = endbasic_std::MachineBuilder::default()\n .with_console(console.clone())\n .with_yield_now_fn(Yielder::new_yield_now_fn(self.yielder))\n .with_signals_chan(self.signals_chan)\n .with_sleep_fn(Box::from(move |d, pos| js_sleep(d, pos, yielder.clone())))\n .make_interactive()\n .with_program(Rc::from(RefCell::from(endbasic_repl::editor::Editor::default())));\n\n let program = builder.get_program();\n\n let storage = builder.get_storage();\n setup_storage(&mut storage.borrow_mut());\n\n let mut machine = match builder.build() {\n Ok(machine) => machine,\n Err(e) => {\n return Err(io::Error::new(\n io::ErrorKind::Other,\n format!(\"Machine initialization failed: {}\", e),\n ))\n }\n };\n\n let service =\n Rc::from(RefCell::from(endbasic_client::CloudService::new(&self.service_url)?));\n endbasic_client::add_all(\n &mut machine,\n service,\n console.clone(),\n storage.clone(),\n format!(\"{}/\", location.origin().unicode_serialization()),\n );\n\n endbasic_repl::print_welcome(console.clone())?;\n\n let mut auto_run = None;\n for (name, value) in location.query_pairs() {\n if name == \"run\" {\n auto_run = Some(value);\n break;\n }\n }\n if let Some(auto_run) = auto_run {\n match endbasic_repl::run_from_cloud(\n &mut machine,\n console.clone(),\n storage.clone(),\n program.clone(),\n &auto_run,\n true,\n )\n .await\n {\n Ok(_code) => (),\n Err(e) => console\n .borrow_mut()\n .print(&format!(\"Failed to execute requested program: {}\", e))?,\n }\n }\n\n endbasic_repl::try_load_autoexec(&mut machine, console.clone(), storage).await?;\n loop {\n let result =\n endbasic_repl::run_repl_loop(&mut machine, console.clone(), program.clone()).await;\n let mut console = console.borrow_mut();\n match result {\n Ok(exit_code) => {\n console.print(&format!(\"Interpreter exited with code {}\", exit_code))\n }\n Err(e) => console.print(&format!(\"FATAL ERROR: {}\", e)),\n }\n .expect(\"Cannot handle terminal printing errors\");\n console.print(\"Resuming execution because the web interpreter cannot be exited\")?;\n console.print(\"\")?;\n }\n }\n```"}], "func_name": "safe_run_repl_loop", "docstring": "Safe version of `run_repl_loop` that is able to return errors.", "repo": "endbasic/endbasic", "path": "web/src/lib.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "908b6f41e5a830e8dfccb6b68ab07fc876dcd8b457399cf997efcbd810b55998"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: for_name\n\nDocumentation:\nCreates a new key for a program name.\n\nThe file name is unconditionally converted to uppercase to facilitate case-insensitive\nmatching.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn for_name(name: &str) -> Self {\n debug_assert!(name.to_ascii_uppercase().ends_with(\".BAS\"));\n Self(format!(\"{}{}\", Key::PREFIX, name.to_ascii_uppercase()))\n }\n```"}], "func_name": "for_name", "docstring": "Creates a new key for a program name.\n\nThe file name is unconditionally converted to uppercase to facilitate case-insensitive\nmatching.", "repo": "endbasic/endbasic", "path": "web/src/store.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad6f8d84afeec93296b713974b5f3c53a546e8dad4adc2a3bbbd794836bd6d9c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: canonical\n\nDocumentation:\nReturns the canonical form of this key.\n\nIn essence, this converts the file name in the key to uppercase. This is necessary to\nmigrate older versions of the drive that were case sensitive.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn canonical(&self) -> Self {\n Self(format!(\"{}{}\", Key::PREFIX, self.name().to_ascii_uppercase()))\n }\n```"}], "func_name": "canonical", "docstring": "Returns the canonical form of this key.\n\nIn essence, this converts the file name in the key to uppercase. This is necessary to\nmigrate older versions of the drive that were case sensitive.", "repo": "endbasic/endbasic", "path": "web/src/store.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "400063adafc0f412bc82a6fd59479933b0bee2bfbfe49ae708644fa04a1b0291"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse\n\nDocumentation:\nConstructs a key from a serialized representation of a key, or none if the `raw` string does\nnot correspond to one of our keys.\n\nNote that this *does* respect the case of the file name provided in the string. This is\nnecessary to migrate older versions of the drive that were case sensitive.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse(raw: &str) -> Option {\n if raw.starts_with(Key::PREFIX) && raw.to_ascii_uppercase().ends_with(\".BAS\") {\n Some(Key(raw.to_owned()))\n } else {\n None\n }\n }\n```"}], "func_name": "parse", "docstring": "Constructs a key from a serialized representation of a key, or none if the `raw` string does\nnot correspond to one of our keys.\n\nNote that this *does* respect the case of the file name provided in the string. This is\nnecessary to migrate older versions of the drive that were case sensitive.", "repo": "endbasic/endbasic", "path": "web/src/store.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0b66c8b8ce931b2ef534b6d706659fcfc0d067067e1b9c17188bc78c97b978f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConstructs a new entry with the given `content` and with a last modification of now.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new>>(content: S, mtime: OffsetDateTime) -> Self {\n Self { version: Entry::VERSION, content: content.into(), mtime }\n }\n```"}], "func_name": "new", "docstring": "Constructs a new entry with the given `content` and with a last modification of now.", "repo": "endbasic/endbasic", "path": "web/src/store.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7dd1a49d4cf41315088674819008d8c9b75630298d6108a836a5c6e7f6d4eaa8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: metadata\n\nDocumentation:\nReturns the generic `Metadata` object for this entry.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn metadata(&self) -> Metadata {\n // I'm sure there is something wrong with this timezone adjustment.\n let tz_offset = match UtcOffset::from_whole_seconds(\n -js_sys::Date::new_0().get_timezone_offset() as i32 * 60,\n ) {\n Ok(tz_offset) => tz_offset,\n Err(_) => UtcOffset::UTC,\n };\n Metadata { date: self.mtime.to_offset(tz_offset), length: self.content.len() as u64 }\n }\n```"}], "func_name": "metadata", "docstring": "Returns the generic `Metadata` object for this entry.", "repo": "endbasic/endbasic", "path": "web/src/store.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2fdb768a898b0741d165ba0ba3bcb8f11e04c45f228730e12cbf3c754a7ca402"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_window\n\nDocumentation:\nCreates a new drive for the current window.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_window() -> Self {\n // TODO(jmmv): Should probably do something fancier here instead of these unwraps...\n let window = web_sys::window().unwrap();\n let storage = window.local_storage().unwrap().unwrap();\n let mut drive = Self { clock: Box::from(JsClock::default()), storage };\n drive.fixup_names().unwrap();\n drive\n }\n```"}], "func_name": "from_window", "docstring": "Creates a new drive for the current window.", "repo": "endbasic/endbasic", "path": "web/src/store.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f435b5b33fbbf9dc138995fd73e66388b627c8714a4ebf08489a95ee59ea54a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fixup_names\n\nDocumentation:\nUpgrades the drive to support case insensitive behavior.\n\nThis scans for all existing files in the drive and, for any that have names that are not in\ncanonical form (all uppercase), renames them to canonical form.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fixup_names(&mut self) -> io::Result<()> {\n let n = match self.storage.length() {\n Ok(n) => n,\n Err(e) => return Err(io::Error::other(format!(\"{:?}\", e))),\n };\n for i in 0..n {\n let key = match self.storage.key(i) {\n Ok(Some(key)) => key,\n Ok(None) => return Err(io::Error::other(\"Entry vanished\")),\n Err(e) => {\n return Err(io::Error::new(\n io::ErrorKind::Other,\n format!(\"Failed to fetch local storage entry with index {}: {:?}\", i, e),\n ))\n }\n };\n\n if let Some(key) = Key::parse(&key) {\n let canonical = key.canonical();\n if key != canonical {\n self.rename(&key, &canonical)?;\n }\n }\n }\n Ok(())\n }\n```"}], "func_name": "fixup_names", "docstring": "Upgrades the drive to support case insensitive behavior.\n\nThis scans for all existing files in the drive and, for any that have names that are not in\ncanonical form (all uppercase), renames them to canonical form.", "repo": "endbasic/endbasic", "path": "web/src/store.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "50478fbfe38f4f12938f2fd20a03f1b9445e61d188ca0bd83f37024616254dd3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rename\n\nDocumentation:\nRenames a file stored with an `old` key to a `new` key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn rename(&self, old: &Key, new: &Key) -> io::Result<()> {\n let old = old.serialized();\n let new = new.serialized();\n\n let raw = match self.storage.get(old) {\n Ok(Some(content)) => content,\n Ok(None) => return Err(io::Error::new(io::ErrorKind::NotFound, \"File not found\")),\n Err(e) => {\n return Err(io::Error::new(\n io::ErrorKind::Other,\n format!(\"Failed to get local storage entry with key {}: {:?}\", old, e),\n ))\n }\n };\n\n if let Err(e) = self.storage.set(new, &raw) {\n return Err(io::Error::new(\n io::ErrorKind::Other,\n format!(\"Failed to put local storage entry with key {}: {:?}\", new, e),\n ));\n };\n\n if let Err(e) = self.storage.delete(old) {\n return Err(io::Error::new(\n io::ErrorKind::Other,\n format!(\"Failed to put remove storage entry with key {}: {:?}\", old, e),\n ));\n };\n\n Ok(())\n }\n```"}], "func_name": "rename", "docstring": "Renames a file stored with an `old` key to a `new` key.", "repo": "endbasic/endbasic", "path": "web/src/store.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0353a82fcc3cc4963ed02713c616eda3ed3eef92a72a509a3be7b62384fd9487"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_entry\n\nDocumentation:\nObtains and parses the entry given by `key`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_entry(&self, key: &Key) -> io::Result {\n let key = key.serialized();\n let raw = match self.storage.get(key) {\n Ok(Some(content)) => content,\n Ok(None) => return Err(io::Error::new(io::ErrorKind::NotFound, \"File not found\")),\n Err(e) => {\n return Err(io::Error::new(\n io::ErrorKind::Other,\n format!(\"Failed to get local storage entry with key {}: {:?}\", key, e),\n ))\n }\n };\n\n match serde_json::from_str(&raw) {\n Ok(entry) => Ok(entry),\n Err(e) => Err(io::Error::new(\n io::ErrorKind::InvalidData,\n format!(\"Failed to parse local storage entry with key {}: {:?}\", key, e),\n )),\n }\n }\n```"}], "func_name": "get_entry", "docstring": "Obtains and parses the entry given by `key`.", "repo": "endbasic/endbasic", "path": "web/src/store.rs", "url": "https://github.com/endbasic/endbasic/blob/master/web/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b86e00f02537cd783d59006b0af3164a6e9f2f1ef1f843b6ada50e7645ba7d8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: register_components\n\nDocumentation:\nRegister all components used by this application.\n\nIf you would like to add additional components to your application\nbeyond the default ones provided by the framework, this is the place\nto do so.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn register_components(&mut self, command: &Self::Cmd) -> Result<(), FrameworkError> {\n let components = self.framework_components(command)?;\n let mut component_registry = self.state.components_mut();\n component_registry.register(components)\n }\n```"}], "func_name": "register_components", "docstring": "Register all components used by this application.\n\nIf you would like to add additional components to your application\nbeyond the default ones provided by the framework, this is the place\nto do so.", "repo": "iqlusioninc/tmkms", "path": "src/application.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/application.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ba7519d59230f629ddf87632bbf2c2ea8ea8ee6475c360d65b249a806e3bd28"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: after_config\n\nDocumentation:\nPost-configuration lifecycle callback.\n\nCalled regardless of whether config is loaded to indicate this is the\ntime in app lifecycle when configuration would be loaded if\npossible.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn after_config(&mut self, config: Self::Cfg) -> Result<(), FrameworkError> {\n let mut component_registry = self.state.components_mut();\n component_registry.after_config(&config)?;\n self.config.set_once(config);\n Ok(())\n }\n```"}], "func_name": "after_config", "docstring": "Post-configuration lifecycle callback.\n\nCalled regardless of whether config is loaded to indicate this is the\ntime in app lifecycle when configuration would be loaded if\npossible.", "repo": "iqlusioninc/tmkms", "path": "src/application.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/application.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef500be2fae53fe49c0ae7def0608a0a3bfe3a78bdf05ffe92b386ad913d86bb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tracing_config\n\nDocumentation:\nGet tracing configuration from command-line options\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn tracing_config(&self, command: &KmsCommand) -> trace::Config {\n if command.verbose() {\n trace::Config::verbose()\n } else {\n trace::Config::default()\n }\n }\n```"}], "func_name": "tracing_config", "docstring": "Get tracing configuration from command-line options", "repo": "iqlusioninc/tmkms", "path": "src/application.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/application.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00f92b5a8259bfe6a295ba8b4f9e5a1a4277130b396c3890810b84354e620042"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_config\n\nDocumentation:\nAttempt to create a `Chain` state from the given configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_config(config: &ChainConfig) -> Result {\n let state_file = match config.state_file {\n Some(ref path) => path.to_owned(),\n None => PathBuf::from(&format!(\"{}_priv_validator_state.json\", config.id)),\n };\n\n let mut state = State::load_state(state_file)?;\n\n if let Some(ref hook) = config.state_hook {\n match state::hook::run(hook) {\n Ok(hook_output) => state.update_from_hook_output(hook_output)?,\n Err(e) => {\n if hook.fail_closed {\n return Err(e);\n } else {\n // fail open: note the error to the log and proceed anyway\n error!(\"error invoking state hook for chain {}: {}\", config.id, e);\n }\n }\n }\n }\n\n Ok(Self {\n id: config.id.clone(),\n sign_extensions: config.sign_extensions,\n keyring: KeyRing::new(config.key_format.clone()),\n state: Mutex::new(state),\n })\n }\n```"}], "func_name": "from_config", "docstring": "Attempt to create a `Chain` state from the given configuration", "repo": "iqlusioninc/tmkms", "path": "src/chain.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/chain.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c8a0351b89dd56a03c844e08a59b5a4cdde70331ddc674a8d052d00fdb37f660"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_config\n\nDocumentation:\nInitialize the chain registry from the configuration file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load_config(config: &KmsConfig) -> Result<(), Error> {\n for config in &config.chain {\n REGISTRY.register(Chain::from_config(config)?)?;\n }\n\n let mut registry = REGISTRY.0.write().unwrap();\n keyring::load_config(&mut registry, &config.providers)\n}\n```"}], "func_name": "load_config", "docstring": "Initialize the chain registry from the configuration file", "repo": "iqlusioninc/tmkms", "path": "src/chain.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/chain.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "21518c5b5137f51f7de9f42aeae9fb21cc97e2edb2d2031b6b1e1ab17d5c9e84"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn\n\nDocumentation:\nSpawn a new client, returning a handle so it can be joined\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn spawn(config: ValidatorConfig) -> Self {\n register_chain(&config.chain_id);\n\n let name = format!(\"{}@{}\", &config.chain_id, &config.addr);\n\n let handle = thread::Builder::new()\n .name(name.clone())\n .spawn(move || main_loop(config))\n .unwrap_or_else(|e| {\n status_err!(\"error spawning thread: {}\", e);\n exit(1);\n });\n\n Self { name, handle }\n }\n```"}], "func_name": "spawn", "docstring": "Spawn a new client, returning a handle so it can be joined", "repo": "iqlusioninc/tmkms", "path": "src/client.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c3b493885878e67b12bc181996cd7ab0cce9d21f4ae2d631ea393f95956026b7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: main_loop\n\nDocumentation:\nMain loop for all clients. Handles reconnecting in the event of an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn main_loop(config: ValidatorConfig) -> Result<(), Error> {\n while let Err(e) = run_client(config.clone()) {\n // `PoisonError` is unrecoverable\n if *e.kind() == ErrorKind::PoisonError {\n error!(\"[{}@{}] FATAL -- {}\", &config.chain_id, &config.addr, e);\n return Err(e);\n } else {\n error!(\"[{}@{}] {}\", &config.chain_id, &config.addr, e);\n }\n\n if config.reconnect {\n // TODO: configurable respawn delay\n thread::sleep(Duration::from_secs(RESPAWN_DELAY));\n } else {\n return Err(e);\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "main_loop", "docstring": "Main loop for all clients. Handles reconnecting in the event of an error", "repo": "iqlusioninc/tmkms", "path": "src/client.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f30357fddcbf16a974bfbe028ab4ade96b1e65d80c1c24af5a985061e1b5086f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: register_chain\n\nDocumentation:\nEnsure chain with given ID is properly registered\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn register_chain(chain_id: &chain::Id) {\n let registry = chain::REGISTRY.get();\n\n debug!(\"registering chain: {}\", chain_id);\n registry.get_chain(chain_id).unwrap_or_else(|| {\n status_err!(\n \"unregistered chain: {} (add it to tmkms.toml's [[chain]] section)\",\n chain_id\n );\n exit(1);\n });\n}\n```"}], "func_name": "register_chain", "docstring": "Ensure chain with given ID is properly registered", "repo": "iqlusioninc/tmkms", "path": "src/client.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb25151c3792ce40f7ad1a8bd5bf0189881d91d9b0f2eeb95f3fabf8fefda3c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_client\n\nDocumentation:\nOpen a new session and run the session loop\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn run_client(config: ValidatorConfig) -> Result<(), Error> {\n panic::catch_unwind(move || Session::open(config)?.request_loop())\n .unwrap_or_else(|e| Err(Error::from_panic(e)))\n}\n```"}], "func_name": "run_client", "docstring": "Open a new session and run the session loop", "repo": "iqlusioninc/tmkms", "path": "src/client.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69fd5fd57aa265fdc26d2d696caf9699d20acb828503288cc06ee15c18bab885"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: verbose\n\nDocumentation:\nAre we configured for verbose logging?\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn verbose(&self) -> bool {\n match self {\n KmsCommand::Start(run) => run.verbose,\n #[cfg(feature = \"yubihsm\")]\n KmsCommand::Yubihsm(yubihsm) => yubihsm.verbose(),\n _ => false,\n }\n }\n```"}], "func_name": "verbose", "docstring": "Are we configured for verbose logging?", "repo": "iqlusioninc/tmkms", "path": "src/commands.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "61efa9a573ef866493ef86413c7c179aa339fe11d1dc2e94f3a70f927adae3c6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: config_path\n\nDocumentation:\nGet the path to the configuration file, either from selected subcommand\nor the default\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn config_path(&self) -> Option {\n let config = match self {\n KmsCommand::Start(start) => start.config.as_ref(),\n #[cfg(feature = \"yubihsm\")]\n KmsCommand::Yubihsm(yubihsm) => yubihsm.config_path(),\n #[cfg(feature = \"ledger\")]\n KmsCommand::Ledger(ledger) => ledger.config_path(),\n _ => return None,\n };\n\n let path = config\n .cloned()\n .or_else(|| env::var(CONFIG_ENV_VAR).ok().map(PathBuf::from))\n .unwrap_or_else(|| PathBuf::from(CONFIG_FILE_NAME));\n\n Some(path)\n }\n```"}], "func_name": "config_path", "docstring": "Get the path to the configuration file, either from selected subcommand\nor the default", "repo": "iqlusioninc/tmkms", "path": "src/commands.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e1a705894eac9d61d4a002d9ea6f84169c7833f34348166827645ebb9eff111"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_ecdsa\n\nDocumentation:\nAdd na ECDSA key to the keyring, returning an error if we already have a\nsigner registered for the given public key\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_ecdsa(&mut self, signer: ecdsa::Signer) -> Result<(), Error> {\n let provider = signer.provider();\n let public_key = signer.public_key();\n let public_key_serialized = self.format.serialize(public_key);\n let key_type = match public_key {\n TendermintKey::AccountKey(_) => \"account\",\n TendermintKey::ConsensusKey(_) => unimplemented!(\n \"ECDSA consensus keys unsupported: {:?}\",\n public_key_serialized\n ),\n };\n\n info!(\n \"[keyring:{}] added {} ECDSA key: {}\",\n provider, key_type, public_key_serialized\n );\n\n if let Some(other) = self.ecdsa_keys.insert(public_key, signer) {\n fail!(\n InvalidKey,\n \"[keyring:{}] duplicate key {} already registered as {}\",\n provider,\n public_key_serialized,\n other.provider(),\n )\n } else {\n Ok(())\n }\n }\n```"}], "func_name": "add_ecdsa", "docstring": "Add na ECDSA key to the keyring, returning an error if we already have a\nsigner registered for the given public key", "repo": "iqlusioninc/tmkms", "path": "src/keyring.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c04d61b1adf35052a16f7f44744407f7e8b300aa881d54796f27d3e1d11074c1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_ed25519\n\nDocumentation:\nAdd a key to the keyring, returning an error if we already have a\nsigner registered for the given public key\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_ed25519(&mut self, signer: ed25519::Signer) -> Result<(), Error> {\n let provider = signer.provider();\n let public_key = signer.public_key();\n let public_key_serialized = self.format.serialize(public_key);\n let key_type = match public_key {\n TendermintKey::AccountKey(_) => unimplemented!(\n \"Ed25519 account keys unsupported: {:?}\",\n public_key_serialized\n ),\n TendermintKey::ConsensusKey(_) => \"consensus\",\n };\n\n info!(\n \"[keyring:{}] added {} Ed25519 key: {}\",\n provider, key_type, public_key_serialized\n );\n\n if let Some(other) = self.ed25519_keys.insert(public_key, signer) {\n fail!(\n InvalidKey,\n \"[keyring:{}] duplicate key {} already registered as {}\",\n provider,\n public_key_serialized,\n other.provider(),\n )\n } else {\n Ok(())\n }\n }\n```"}], "func_name": "add_ed25519", "docstring": "Add a key to the keyring, returning an error if we already have a\nsigner registered for the given public key", "repo": "iqlusioninc/tmkms", "path": "src/keyring.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "975c83e1d093083fd211c30d083afe3aea002a22eb14e247c62431a9f3972aef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_pubkey\n\nDocumentation:\nGet the default Ed25519 (i.e. consensus) public key for this keyring\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn default_pubkey(&self) -> Result {\n if !self.ed25519_keys.is_empty() {\n let mut keys = self.ed25519_keys.keys();\n\n if keys.len() == 1 {\n Ok(*keys.next().unwrap())\n } else {\n fail!(InvalidKey, \"expected only one ed25519 key in keyring\");\n }\n } else if !self.ecdsa_keys.is_empty() {\n let mut keys = self.ecdsa_keys.keys();\n\n if keys.len() == 1 {\n Ok(*keys.next().unwrap())\n } else {\n fail!(InvalidKey, \"expected only one ecdsa key in keyring\");\n }\n } else {\n fail!(InvalidKey, \"keyring is empty\");\n }\n }\n```"}], "func_name": "default_pubkey", "docstring": "Get the default Ed25519 (i.e. consensus) public key for this keyring", "repo": "iqlusioninc/tmkms", "path": "src/keyring.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "32e2d6a202a225141c5090658a8b81cad320fa69201b4c99a0e118efc7c65e42"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_account_pubkey\n\nDocumentation:\nGet ECDSA public key bytes for a given account ID\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_account_pubkey(&self, account_id: account::Id) -> Option {\n for key in self.ecdsa_keys.keys() {\n if let TendermintKey::AccountKey(pk) = key {\n if account_id == account::Id::from(*pk) {\n return Some(*pk);\n }\n }\n }\n\n None\n }\n```"}], "func_name": "get_account_pubkey", "docstring": "Get ECDSA public key bytes for a given account ID", "repo": "iqlusioninc/tmkms", "path": "src/keyring.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b13074660c96c2cb029c4d902f900cdd06a8493b533398f34143acd051123bc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sign\n\nDocumentation:\nSign a message using the secret key associated with the given public key\n(if it is in our keyring)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sign(&self, public_key: Option<&TendermintKey>, msg: &[u8]) -> Result {\n if self.ed25519_keys.len() > 1 || self.ecdsa_keys.len() > 1 {\n fail!(SigningError, \"expected only one key in keyring\");\n }\n\n if !self.ed25519_keys.is_empty() {\n let signer = match public_key {\n Some(public_key) => self.ed25519_keys.get(public_key).ok_or_else(|| {\n format_err!(\n InvalidKey,\n \"not in keyring: {}\",\n match public_key {\n TendermintKey::AccountKey(pk) => pk.to_bech32(\"\"),\n TendermintKey::ConsensusKey(pk) => pk.to_bech32(\"\"),\n }\n )\n }),\n None => self\n .ed25519_keys\n .values()\n .next()\n .ok_or_else(|| format_err!(InvalidKey, \"ed25519 keyring is empty\")),\n }?;\n\n Ok(Signature::Ed25519(signer.sign(msg)?))\n } else if !self.ecdsa_keys.is_empty() {\n let signer = match public_key {\n Some(public_key) => self.ecdsa_keys.get(public_key).ok_or_else(|| {\n format_err!(\n InvalidKey,\n \"not in keyring: {}\",\n match public_key {\n TendermintKey::AccountKey(pk) => pk.to_bech32(\"\"),\n TendermintKey::ConsensusKey(pk) => pk.to_bech32(\"\"),\n }\n )\n }),\n None => self\n .ecdsa_keys\n .values()\n .next()\n .ok_or_else(|| format_err!(InvalidKey, \"ecdsa keyring is empty\")),\n }?;\n\n Ok(Signature::Ecdsa(signer.sign(msg)?))\n } else {\n Err(format_err!(InvalidKey, \"keyring is empty\").into())\n }\n }\n```"}], "func_name": "sign", "docstring": "Sign a message using the secret key associated with the given public key\n(if it is in our keyring)", "repo": "iqlusioninc/tmkms", "path": "src/keyring.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc1ac02d302b68b7d28b94b470f36199b5997a353de4a6c580b0eabe42ef0b06"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_config\n\nDocumentation:\nInitialize the keyring from the configuration file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load_config(registry: &mut chain::Registry, config: &ProviderConfig) -> Result<(), Error> {\n #[cfg(feature = \"softsign\")]\n providers::softsign::init(registry, &config.softsign)?;\n\n #[cfg(feature = \"yubihsm\")]\n providers::yubihsm::init(registry, &config.yubihsm)?;\n\n #[cfg(feature = \"ledger\")]\n providers::ledgertm::init(registry, &config.ledgertm)?;\n\n #[cfg(feature = \"fortanixdsm\")]\n providers::fortanixdsm::init(registry, &config.fortanixdsm)?;\n\n Ok(())\n}\n```"}], "func_name": "load_config", "docstring": "Initialize the keyring from the configuration file", "repo": "iqlusioninc/tmkms", "path": "src/keyring.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3fdd55d954a75b211fa5834ea45e4e0ec5db60e82a6028f6a9dbaa43965181f8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_base64_secret\n\nDocumentation:\nLoad Base64-encoded secret data (i.e. key) from the given path\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load_base64_secret(path: impl AsRef) -> Result>, Error> {\n // TODO(tarcieri): check file permissions are correct\n let base64_data = Zeroizing::new(fs::read_to_string(path.as_ref()).map_err(|e| {\n format_err!(\n IoError,\n \"couldn't read key from {}: {}\",\n path.as_ref().display(),\n e\n )\n })?);\n\n // TODO(tarcieri): constant-time string trimming\n let data = Zeroizing::new(base64::decode(base64_data.trim_end()).map_err(|e| {\n format_err!(\n IoError,\n \"can't decode key from `{}`: {}\",\n path.as_ref().display(),\n e\n )\n })?);\n\n Ok(data)\n}\n```"}], "func_name": "load_base64_secret", "docstring": "Load Base64-encoded secret data (i.e. key) from the given path", "repo": "iqlusioninc/tmkms", "path": "src/key_utils.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/key_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "34a758fe4c72a870daa5ed5f79faaffb6ee943e41b16a4fc7630f35f8029424e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_base64_secret\n\nDocumentation:\nStore Base64-encoded secret data at the given path\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_base64_secret(path: impl AsRef, data: &[u8]) -> Result<(), Error> {\n let base64_data = Zeroizing::new(base64::encode(data));\n\n OpenOptions::new()\n .create(true)\n .write(true)\n .truncate(true)\n .mode(SECRET_FILE_PERMS)\n .open(path.as_ref())\n .and_then(|mut file| file.write_all(&base64_data))\n .map_err(|e| {\n format_err!(\n IoError,\n \"couldn't write `{}`: {}\",\n path.as_ref().display(),\n e\n )\n .into()\n })\n}\n```"}], "func_name": "write_base64_secret", "docstring": "Store Base64-encoded secret data at the given path", "repo": "iqlusioninc/tmkms", "path": "src/key_utils.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/key_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9c4a54eeb29ee0d0ff6dbf5055bfc3a775d7d09ae3191e1484d060f9503c08e0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_key\n\nDocumentation:\nGenerate a Secret Connection key at the given path\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate_key(path: impl AsRef) -> Result<(), Error> {\n let mut secret_key = Zeroizing::new([0u8; ed25519::SigningKey::BYTE_SIZE]);\n OsRng.fill_bytes(&mut *secret_key);\n write_base64_secret(path, &*secret_key)\n}\n```"}], "func_name": "generate_key", "docstring": "Generate a Secret Connection key at the given path", "repo": "iqlusioninc/tmkms", "path": "src/key_utils.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/key_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09bbd46d4bdc04459ec0d6c0070859bc08e5c9cac4804a10646e8a59b0828624"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: canonical_bytes\n\nDocumentation:\nGet the bytes representing a canonically encoded message over which a\nsignature is computed over.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn canonical_bytes(&self, chain_id: chain::Id) -> Result {\n let mut bytes = BytesMut::new();\n\n match self {\n Self::Proposal(proposal) => {\n let canonical = proto::types::CanonicalProposal {\n chain_id: chain_id.to_string(),\n r#type: SignedMsgType::Proposal.into(),\n height: proposal.height.into(),\n block_id: proposal.block_id.map(Into::into),\n pol_round: proposal\n .pol_round\n .map(|round| round.value().into())\n .unwrap_or(-1),\n round: proposal.round.value().into(),\n timestamp: proposal.timestamp.map(Into::into),\n };\n\n canonical.encode_length_delimited(&mut bytes)?;\n }\n Self::Vote(vote) => {\n let canonical = proto::types::CanonicalVote {\n r#type: vote.vote_type.into(),\n height: vote.height.into(),\n round: vote.round.value().into(),\n block_id: vote.block_id.map(Into::into),\n timestamp: vote.timestamp.map(Into::into),\n chain_id: chain_id.to_string(),\n };\n canonical.encode_length_delimited(&mut bytes)?;\n }\n }\n\n Ok(bytes.into())\n }\n```"}], "func_name": "canonical_bytes", "docstring": "Get the bytes representing a canonically encoded message over which a\nsignature is computed over.", "repo": "iqlusioninc/tmkms", "path": "src/privval.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/privval.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "adfd13c6b1adb5d2a04f1675b3c65e5b66190e42943549ca79d97eaa57d76b0d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extension_bytes\n\nDocumentation:\nGet the bytes representing a vote extension if applicable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn extension_bytes(&self, chain_id: chain::Id) -> Result, EncodeError> {\n match self {\n Self::Proposal(_) => Ok(None),\n Self::Vote(v) => {\n match (v.vote_type, v.block_id) {\n // Only sign extension if it's a precommit for a non-nil block.\n // Note that extension can be empty.\n (vote::Type::Precommit, Some(_)) => {\n let canonical = proto::types::CanonicalVoteExtension {\n extension: v.extension.clone(),\n height: v.height.into(),\n round: v.round.value().into(),\n chain_id: chain_id.to_string(),\n };\n\n let mut bytes = BytesMut::new();\n canonical.encode_length_delimited(&mut bytes)?;\n Ok(Some(bytes.into()))\n }\n _ => Ok(None),\n }\n }\n }\n }\n```"}], "func_name": "extension_bytes", "docstring": "Get the bytes representing a vote extension if applicable.", "repo": "iqlusioninc/tmkms", "path": "src/privval.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/privval.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ce612b8a41d6691cd271c755f896b547c041f126379fd1b3f0e13572fc581c36"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: consensus_state\n\nDocumentation:\nParse the consensus state from the request.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn consensus_state(&self) -> consensus::State {\n match self {\n Self::Proposal(p) => consensus::State {\n height: p.height,\n round: p.round,\n step: 0,\n block_id: p.block_id,\n },\n Self::Vote(v) => consensus::State {\n height: v.height,\n round: v.round,\n step: match v.vote_type {\n vote::Type::Prevote => 1,\n vote::Type::Precommit => 2,\n },\n block_id: v.block_id,\n },\n }\n }\n```"}], "func_name": "consensus_state", "docstring": "Parse the consensus state from the request.", "repo": "iqlusioninc/tmkms", "path": "src/privval.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/privval.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fd0db5280a81b3d3218fd54a2c136a1a48d019d0ceceadf6440886387b48d80a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_consensus_signature\n\nDocumentation:\nAdd a consensus signature to this message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_consensus_signature(&mut self, signature: impl Into) {\n match self {\n SignableMsg::Proposal(proposal) => {\n proposal.signature = Some(signature.into());\n }\n SignableMsg::Vote(vote) => {\n vote.signature = Some(signature.into());\n }\n }\n }\n```"}], "func_name": "add_consensus_signature", "docstring": "Add a consensus signature to this message.", "repo": "iqlusioninc/tmkms", "path": "src/privval.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/privval.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48fbf5c5d06e5ff11f8d59e6c5e77ef2bb8a6f2cd59bbd02a9193672f6cb352f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_extension_signature\n\nDocumentation:\nAdd an extension signature to this message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_extension_signature(\n &mut self,\n signature: impl Into,\n ) -> Result<(), Error> {\n match self {\n SignableMsg::Vote(vote) => {\n vote.extension_signature = Some(signature.into());\n Ok(())\n }\n _ => Err(Error::invalid_message_type()),\n }\n }\n```"}], "func_name": "add_extension_signature", "docstring": "Add an extension signature to this message.", "repo": "iqlusioninc/tmkms", "path": "src/privval.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/privval.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4653e2be8573c706c0f10305190215196c0a33da1c1831d09b1fed0e4c1ada1e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: code\n\nDocumentation:\nGet the `i32` code for this message type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn code(self) -> SignedMsgCode {\n self as SignedMsgCode\n }\n```"}], "func_name": "code", "docstring": "Get the `i32` code for this message type.", "repo": "iqlusioninc/tmkms", "path": "src/privval.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/privval.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "46b648a801ea8e192f54a2dc4ebb111f5215475fd47ee90d485e50832653545e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read\n\nDocumentation:\nRead a request from the given readable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read(conn: &mut impl Read, expected_chain_id: &chain::Id) -> Result {\n let mut msg_bytes: Vec = vec![];\n let msg;\n\n // fix for Sei: collect incoming bytes of Protobuf from incoming msg\n loop {\n let mut msg_chunk = read_msg(conn)?;\n let chunk_len = msg_chunk.len();\n msg_bytes.append(&mut msg_chunk);\n\n // if we can decode it, great, break the loop\n match proto::privval::Message::decode_length_delimited(msg_bytes.as_ref()) {\n Ok(m) => {\n msg = m.sum;\n break;\n }\n Err(e) => {\n // if chunk_len < DATA_MAX_SIZE (1024) we assume it was the end of the message and it is malformed\n if chunk_len < DATA_MAX_SIZE {\n return Err(format_err!(\n ErrorKind::ProtocolError,\n \"malformed message packet: {}\",\n e\n )\n .into());\n }\n // otherwise, we go to start of the loop assuming next chunk(s)\n // will fill the message\n }\n }\n }\n\n let (req, chain_id) = match msg {\n Some(proto::privval::message::Sum::SignVoteRequest(\n proto::privval::SignVoteRequest {\n vote: Some(vote),\n chain_id,\n },\n )) => (Request::SignVote(vote.try_into()?), chain_id),\n Some(proto::privval::message::Sum::SignProposalRequest(\n proto::privval::SignProposalRequest {\n proposal: Some(proposal),\n chain_id,\n },\n )) => (Request::SignProposal(proposal.try_into()?), chain_id),\n Some(proto::privval::message::Sum::PubKeyRequest(req)) => {\n (Request::ShowPublicKey, req.chain_id)\n }\n Some(proto::privval::message::Sum::PingRequest(_)) => {\n return Ok(Request::PingRequest);\n }\n _ => fail!(ErrorKind::ProtocolError, \"invalid RPC message: {:?}\", msg),\n };\n\n ensure!(\n expected_chain_id == &chain::Id::try_from(chain_id.as_str())?,\n ErrorKind::ChainIdError,\n \"got unexpected chain ID: {} (expecting: {})\",\n &chain_id,\n expected_chain_id\n );\n\n Ok(req)\n }\n```"}], "func_name": "read", "docstring": "Read a request from the given readable.", "repo": "iqlusioninc/tmkms", "path": "src/rpc.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/rpc.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6abc17e40525de42c6454a663355ea6692d41ee2ccb9e0cbf5b091502f8fb095"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_signable_msg\n\nDocumentation:\nConvert this request into a [`SignableMsg`].\n\nThe expected `chain::Id` is used to validate the request.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_signable_msg(self) -> Result {\n match self {\n Self::SignProposal(proposal) => Ok(proposal.into()),\n Self::SignVote(vote) => Ok(vote.into()),\n _ => fail!(\n ErrorKind::InvalidMessageError,\n \"expected a signable message type: {:?}\",\n self\n ),\n }\n }\n```"}], "func_name": "into_signable_msg", "docstring": "Convert this request into a [`SignableMsg`].\n\nThe expected `chain::Id` is used to validate the request.", "repo": "iqlusioninc/tmkms", "path": "src/rpc.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/rpc.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09991c0a3f979302fe9044daa3b67eb55dedb6ec2a143d1d261b19e10fa5d539"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: error\n\nDocumentation:\nConstruct an error response for a given [`SignableMsg`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn error(msg: SignableMsg, error: proto::privval::RemoteSignerError) -> Response {\n match msg {\n SignableMsg::Proposal(_) => {\n Response::SignedProposal(proto::privval::SignedProposalResponse {\n proposal: None,\n error: Some(error),\n })\n }\n SignableMsg::Vote(_) => Response::SignedVote(proto::privval::SignedVoteResponse {\n vote: None,\n error: Some(error),\n }),\n }\n }\n```"}], "func_name": "error", "docstring": "Construct an error response for a given [`SignableMsg`].", "repo": "iqlusioninc/tmkms", "path": "src/rpc.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/rpc.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "68558fe833bb3b62fd0bb283ae8ae8bad305241b47f3aea5fcd84f7106ec6e1f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open\n\nDocumentation:\nOpen a session using the given validator configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn open(config: ValidatorConfig) -> Result {\n let connection: Box = match &config.addr {\n net::Address::Tcp {\n peer_id,\n host,\n port,\n } => {\n debug!(\n \"[{}@{}] connecting to validator...\",\n &config.chain_id, &config.addr\n );\n\n let conn = tcp::open_secret_connection(\n host,\n *port,\n &config.secret_key,\n peer_id,\n config.timeout,\n config.protocol_version.into(),\n )?;\n\n info!(\n \"[{}@{}] connected to validator successfully\",\n &config.chain_id, &config.addr\n );\n\n if peer_id.is_none() {\n // TODO(tarcieri): make peer verification mandatory\n warn!(\n \"[{}@{}]: unverified validator peer ID! ({})\",\n &config.chain_id,\n &config.addr,\n conn.remote_pubkey().peer_id()\n );\n }\n\n Box::new(conn)\n }\n net::Address::Unix { path } => {\n if let Some(timeout) = config.timeout {\n warn!(\"timeouts not supported with Unix sockets: {}\", timeout);\n }\n\n debug!(\n \"{}: Connecting to socket at {}...\",\n &config.chain_id, &config.addr\n );\n\n let socket = UnixStream::connect(path)?;\n let conn = UnixConnection::new(socket);\n\n info!(\n \"[{}@{}] connected to validator successfully\",\n &config.chain_id, &config.addr\n );\n\n Box::new(conn)\n }\n };\n\n Ok(Self { config, connection })\n }\n```"}], "func_name": "open", "docstring": "Open a session using the given validator configuration", "repo": "iqlusioninc/tmkms", "path": "src/session.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/session.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "42ed67600d8a12c57c538a5686f02a1c577c9832a9b405ce4d7c0831ecdf9515"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_request\n\nDocumentation:\nHandle an incoming request from the validator\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_request(&mut self) -> Result {\n let request = Request::read(&mut self.connection, &self.config.chain_id)?;\n debug!(\n \"[{}@{}] received request: {:?}\",\n &self.config.chain_id, &self.config.addr, &request\n );\n\n let response = match request {\n Request::SignProposal(_) | Request::SignVote(_) => {\n self.sign(request.into_signable_msg()?)?\n }\n // non-signable requests:\n Request::PingRequest => Response::Ping(proto::privval::PingResponse {}),\n Request::ShowPublicKey => self.get_public_key()?,\n };\n\n debug!(\n \"[{}@{}] sending response: {:?}\",\n &self.config.chain_id, &self.config.addr, &response\n );\n\n let response_bytes = response.encode()?;\n self.connection.write_all(&response_bytes)?;\n\n Ok(true)\n }\n```"}], "func_name": "handle_request", "docstring": "Handle an incoming request from the validator", "repo": "iqlusioninc/tmkms", "path": "src/session.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/session.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb42fddf8836cb7fe04a41e047b48ea2b546ec635b828f110ed2d7f98e374cdb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_max_height\n\nDocumentation:\nIf a max block height is configured, ensure the block we're signing\ndoesn't exceed it\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_max_height(&mut self, signable_msg: &SignableMsg) -> Result<(), Error> {\n if let Some(max_height) = self.config.max_height {\n let height = signable_msg.height();\n\n if height > max_height {\n fail!(\n ExceedMaxHeight,\n \"attempted to sign at height {} which is greater than {}\",\n height,\n max_height,\n );\n }\n }\n\n Ok(())\n }\n```"}], "func_name": "check_max_height", "docstring": "If a max block height is configured, ensure the block we're signing\ndoesn't exceed it", "repo": "iqlusioninc/tmkms", "path": "src/session.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/session.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "47f48547d006b1f2783b1807c8366e65f0da94cd3b013f33f1b8a84c51bac3af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_consensus_state\n\nDocumentation:\nUpdate our local knowledge of the chain's consensus state, detecting\nattempted double signing and sending a response in the event it happens\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn update_consensus_state(\n &mut self,\n chain: &Chain,\n signable_msg: &SignableMsg,\n ) -> Result, Error> {\n let msg_type = signable_msg.msg_type();\n let request_state = signable_msg.consensus_state();\n let mut chain_state = chain.state.lock().unwrap();\n\n match chain_state.update_consensus_state(request_state.clone()) {\n Ok(()) => Ok(None),\n Err(e) if e.kind() == StateErrorKind::DoubleSign => {\n // Report double signing error back to the validator\n let original_block_id = chain_state.consensus_state().block_id_prefix();\n\n error!(\n \"[{}@{}] attempted double sign {:?} at h/r/s: {} ({} != {})\",\n &self.config.chain_id,\n &self.config.addr,\n msg_type,\n request_state,\n original_block_id,\n request_state.block_id_prefix()\n );\n\n let remote_err = double_sign(request_state);\n Ok(Some(remote_err))\n }\n Err(e) => Err(e.into()),\n }\n }\n```"}], "func_name": "update_consensus_state", "docstring": "Update our local knowledge of the chain's consensus state, detecting\nattempted double signing and sending a response in the event it happens", "repo": "iqlusioninc/tmkms", "path": "src/session.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/session.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "67a4b46dea5d61719be5355592634db97218d8113e13bfa54cc70161b987833a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_public_key\n\nDocumentation:\nGet the public key for (the only) public key in the keyring\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_public_key(&mut self) -> Result {\n let registry = chain::REGISTRY.get();\n\n let chain = registry\n .get_chain(&self.config.chain_id)\n .unwrap_or_else(|| {\n panic!(\"chain '{}' missing from registry!\", &self.config.chain_id);\n });\n\n let pub_key = match chain.keyring.default_pubkey()? {\n TendermintKey::AccountKey(pk) => pk,\n TendermintKey::ConsensusKey(pk) => pk,\n };\n\n Ok(Response::PublicKey(proto::privval::PubKeyResponse {\n pub_key: Some(pub_key.into()),\n error: None,\n }))\n }\n```"}], "func_name": "get_public_key", "docstring": "Get the public key for (the only) public key in the keyring", "repo": "iqlusioninc/tmkms", "path": "src/session.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/session.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9ace000ebae2884bb95a8aad270219c495bb1631a05879cdadfa9f60ff29d327"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: log_signing_request\n\nDocumentation:\nWrite an INFO logline about a signing request\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn log_signing_request(\n &self,\n signable_msg: &SignableMsg,\n started_at: Instant,\n ) -> Result<(), Error> {\n let msg_type = signable_msg.msg_type();\n let request_state = signable_msg.consensus_state();\n\n info!(\n \"[{}@{}] signed {:?}:{} at h/r/s {} ({} ms)\",\n &self.config.chain_id,\n &self.config.addr,\n msg_type,\n request_state.block_id_prefix(),\n request_state,\n started_at.elapsed().as_millis(),\n );\n\n Ok(())\n }\n```"}], "func_name": "log_signing_request", "docstring": "Write an INFO logline about a signing request", "repo": "iqlusioninc/tmkms", "path": "src/session.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/session.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "04610e6739b871732f1e90c27b5e9b4c1df04284953038cb0be5dddb613c8ca0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mark_cli_command\n\nDocumentation:\nMark that we're in a `tmkms yubihsm` command when initializing the YubiHSM\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn mark_cli_command() {\n CLI_COMMAND.store(true, atomic::Ordering::SeqCst);\n}\n```"}], "func_name": "mark_cli_command", "docstring": "Mark that we're in a `tmkms yubihsm` command when initializing the YubiHSM", "repo": "iqlusioninc/tmkms", "path": "src/yubihsm.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/yubihsm.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8ae21602100f1bf946000a5aa22fc9fd08715a18df3f37a7cdc5c80ec8c2192"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init_client\n\nDocumentation:\nGet a `yubihsm::Client` configured from the global configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn init_client() -> Client {\n let (credentials, reconnect) = client_config();\n\n Client::open(connector().clone(), credentials, reconnect).unwrap_or_else(|e| {\n status_err!(\"error connecting to YubiHSM2: {}\", e);\n process::exit(1);\n })\n}\n```"}], "func_name": "init_client", "docstring": "Get a `yubihsm::Client` configured from the global configuration", "repo": "iqlusioninc/tmkms", "path": "src/yubihsm.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/yubihsm.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5cb9b163b7abccef291fef8aba59c2f928d651f501f1cdf4a94be9ff5d56c983"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_account_key\n\nDocumentation:\nAdd an account key to a keyring for a chain stored in the registry\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_account_key(\n &mut self,\n chain_id: &Id,\n signer: keyring::ecdsa::Signer,\n ) -> Result<(), Error> {\n let chain = self.0.get_mut(chain_id).ok_or_else(|| {\n format_err!(\n InvalidKey,\n \"can't add ECDSA signer {} to unregistered chain: {}\",\n signer.provider(),\n chain_id\n )\n })?;\n\n chain.keyring.add_ecdsa(signer)\n }\n```"}], "func_name": "add_account_key", "docstring": "Add an account key to a keyring for a chain stored in the registry", "repo": "iqlusioninc/tmkms", "path": "src/chain/registry.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/chain/registry.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d2ebd3f0b4e4e0f7fe785b8b7dc84637abb1cd988f69ea47dba10e1d028eb9fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_consensus_key\n\nDocumentation:\nAdd a consensus key to a keyring for a chain stored in the registry\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_consensus_key(\n &mut self,\n chain_id: &Id,\n signer: keyring::ed25519::Signer,\n ) -> Result<(), Error> {\n let chain = self.0.get_mut(chain_id).ok_or_else(|| {\n format_err!(\n InvalidKey,\n \"can't add Ed25519 signer {} to unregistered chain: {}\",\n signer.provider(),\n chain_id\n )\n })?;\n\n chain.keyring.add_ed25519(signer)\n }\n```"}], "func_name": "add_consensus_key", "docstring": "Add a consensus key to a keyring for a chain stored in the registry", "repo": "iqlusioninc/tmkms", "path": "src/chain/registry.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/chain/registry.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "55a45fdb0da25395adf6f8cb5de0fbd96bfd7e15cc695e7d70f829b5d3eec2af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nAcquire a read-only (concurrent) lock to the internal chain registry\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(&self) -> Guard<'_> {\n // TODO(tarcieri): better handle `PoisonError` here?\n self.0.read().unwrap().into()\n }\n```"}], "func_name": "get", "docstring": "Acquire a read-only (concurrent) lock to the internal chain registry", "repo": "iqlusioninc/tmkms", "path": "src/chain/registry.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/chain/registry.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6d009afe0f11ba7cca0774bf0ee34ced724685168cd7129f3dc4fdbd34d35543"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_state\n\nDocumentation:\nLoad the state from the given path\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load_state

(path: P) -> Result\n where\n P: AsRef,\n {\n match fs::read_to_string(path.as_ref()) {\n Ok(state_json) => {\n let consensus_state = serde_json::from_str(&state_json).map_err(|e| {\n format_err!(\n ParseError,\n \"error parsing {}: {}\",\n path.as_ref().display(),\n e\n )\n })?;\n\n Ok(Self {\n consensus_state,\n state_file_path: path.as_ref().to_owned(),\n })\n }\n Err(e) if e.kind() == io::ErrorKind::NotFound => {\n Self::write_initial_state(path.as_ref())\n }\n Err(e) => Err(Error::from(e)),\n }\n }\n```"}], "func_name": "load_state", "docstring": "Load the state from the given path", "repo": "iqlusioninc/tmkms", "path": "src/chain/state.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/chain/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "89af1126506a6a03a387dc1308641057ac96765536956b2179c277fcdb7d7fc6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_from_hook_output\n\nDocumentation:\nUpdate the internal state from the output from a hook command\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn update_from_hook_output(&mut self, output: hook::Output) -> Result<(), StateError> {\n let hook_height = output.latest_block_height.value();\n let last_height = self.consensus_state.height.value();\n\n if hook_height > last_height {\n let delta = hook_height - last_height;\n\n if delta < hook::BLOCK_HEIGHT_SANITY_LIMIT {\n let new_state = consensus::State {\n height: output.latest_block_height,\n ..Default::default()\n };\n self.consensus_state = new_state;\n\n info!(\"updated block height from hook: {}\", hook_height);\n } else {\n warn!(\n \"hook block height more than sanity limit: {} (delta: {}, max: {})\",\n output.latest_block_height,\n delta,\n hook::BLOCK_HEIGHT_SANITY_LIMIT\n );\n }\n } else {\n warn!(\n \"hook block height less than current? current: {}, hook: {}\",\n last_height, hook_height\n );\n }\n\n Ok(())\n }\n```"}], "func_name": "update_from_hook_output", "docstring": "Update the internal state from the output from a hook command", "repo": "iqlusioninc/tmkms", "path": "src/chain/state.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/chain/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "84b30672b456040ea39f9f3653de50e2da7a8abbcd7fa06bfe1415faf98b54d5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_initial_state\n\nDocumentation:\nWrite the initial state to the given path on disk\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_initial_state(path: &Path) -> Result {\n let consensus_state = consensus::State {\n height: 0u32.into(),\n ..Default::default()\n };\n\n let initial_state = Self {\n consensus_state,\n state_file_path: path.to_owned(),\n };\n\n initial_state.sync_to_disk()?;\n\n Ok(initial_state)\n }\n```"}], "func_name": "write_initial_state", "docstring": "Write the initial state to the given path on disk", "repo": "iqlusioninc/tmkms", "path": "src/chain/state.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/chain/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "153bfe2a285c8f531e1d156fabebb3c9ef1cc80bd1cfa206290bafac21fa9319"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sync_to_disk\n\nDocumentation:\nSync the current state to disk\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn sync_to_disk(&self) -> io::Result<()> {\n debug!(\n \"writing new consensus state to {}: {:?}\",\n self.state_file_path.display(),\n &self.consensus_state\n );\n\n let json = serde_json::to_string(&self.consensus_state)?;\n\n let state_file_dir = self.state_file_path.parent().unwrap_or_else(|| {\n panic!(\"state file cannot be root directory\");\n });\n\n let mut state_file = NamedTempFile::new_in(state_file_dir)?;\n state_file.write_all(json.as_bytes())?;\n state_file.persist(&self.state_file_path)?;\n\n debug!(\n \"successfully wrote new consensus state to {}\",\n self.state_file_path.display(),\n );\n\n Ok(())\n }\n```"}], "func_name": "sync_to_disk", "docstring": "Sync the current state to disk", "repo": "iqlusioninc/tmkms", "path": "src/chain/state.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/chain/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ee485807de3e56f8902516b60933cb166368b9c83bfe40c3f107b013f91a9142"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRun the given hook command to obtain the last signing state\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn run(config: &HookConfig) -> Result {\n let mut child = Command::new(&config.cmd[0])\n .args(&config.cmd[1..])\n .spawn()?;\n let timeout = Duration::from_secs(config.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS));\n\n match child.wait_timeout(timeout)? {\n Some(status) => {\n if status.success() {\n if let Some(stdout) = child.stdout {\n Ok(serde_json::from_reader(stdout)?)\n } else {\n fail!(HookError, \"couldn't consume stdout from child\");\n }\n } else {\n fail!(HookError, \"subcommand returned status {:?}\", status.code())\n }\n }\n None => {\n // timeout\n child.kill()?;\n child.wait()?;\n fail!(HookError, \"subcommand timed out after {:?}\", timeout)\n }\n }\n}\n```"}], "func_name": "run", "docstring": "Run the given hook command to obtain the last signing state", "repo": "iqlusioninc/tmkms", "path": "src/chain/state/hook.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/chain/state/hook.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ea63cd3eda730992dddd2345f50fa92e3f6ae4151eaae0884fc29c7fc246a31"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_permissions\n\nDocumentation:\nSet Unix permissions on the given path.\n\nOn error, prints a message and exits the process with status 1 (error)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_permissions(path: impl AsRef, mode: u32) {\n fs::set_permissions(path.as_ref(), fs::Permissions::from_mode(mode)).unwrap_or_else(|e| {\n abort!(\n \"couldn't set permissions on `{}`: {}\",\n path.as_ref().display(),\n e\n );\n });\n}\n```"}], "func_name": "set_permissions", "docstring": "Set Unix permissions on the given path.\n\nOn error, prints a message and exits the process with status 1 (error)", "repo": "iqlusioninc/tmkms", "path": "src/commands/init.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/init.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ae49cda0b1c74d6867fd6759ebe4114b489214482ce01cfb02a5c1e319d3bfa1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn_clients\n\nDocumentation:\nSpawn clients from the app's configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn spawn_clients(&self) -> Vec {\n let config = APP.config();\n\n chain::load_config(&config).unwrap_or_else(|e| {\n status_err!(\"error loading configuration: {}\", e);\n process::exit(1);\n });\n\n // Spawn the validator client threads\n config\n .validator\n .iter()\n .cloned()\n .map(Client::spawn)\n .collect()\n }\n```"}], "func_name": "spawn_clients", "docstring": "Spawn clients from the app's configuration", "repo": "iqlusioninc/tmkms", "path": "src/commands/start.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/start.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2dbc9e17571ae7e7a6ba3827365364a330513756f0c71f9d93a1a1cdd6e4620a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: blocking_wait\n\nDocumentation:\nWait for clients to shut down using synchronous thread joins\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn blocking_wait(validator_clients: Vec) {\n // Wait for all of the validator client threads to exit\n debug!(\"Main thread waiting on clients...\");\n\n let mut success = true;\n\n for client in validator_clients {\n let name = client.name().to_owned();\n\n if let Err(e) = client.join() {\n status_err!(\"client '{}' exited with error: {}\", name, e);\n success = false;\n }\n }\n\n if success {\n info!(\"Shutdown completed successfully\");\n } else {\n warn!(\"Shutdown completed with errors\");\n process::exit(1);\n }\n}\n```"}], "func_name": "blocking_wait", "docstring": "Wait for clients to shut down using synchronous thread joins", "repo": "iqlusioninc/tmkms", "path": "src/commands/start.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/start.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "24c33e9b50d7e13a116ea4f476a84ea8d0461c8e3b5ff9197385130d266657f8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate config builder in the default state\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(kms_home: impl AsRef, networks: &[Network]) -> Self {\n let mut result = Self {\n // We need to template the KMS homedir into a config file so we have\n // to convert it into a string\n kms_home: kms_home.as_ref().display().to_string(),\n networks: networks.to_vec(),\n contents: String::new(),\n };\n\n result.add_str(KMS_CONFIG_HEADER);\n result.add_str(\"\\n\\n\");\n\n result\n }\n```"}], "func_name": "new", "docstring": "Create config builder in the default state", "repo": "iqlusioninc/tmkms", "path": "src/commands/init/config_builder.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/init/config_builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "46c754da9a4b1a00bad5d5109889597b520c9860897742075d6ab4724cffec04"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate\n\nDocumentation:\nGenerate configuration, returning a serialized TOML string\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate(mut self) -> String {\n self.add_chain_config();\n self.add_provider_config();\n self.add_validator_config();\n\n self.contents\n }\n```"}], "func_name": "generate", "docstring": "Generate configuration, returning a serialized TOML string", "repo": "iqlusioninc/tmkms", "path": "src/commands/init/config_builder.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/init/config_builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5fc811bd933cadfb4752b260b4d9c45a70ad35ce5df031d41e4d910fbaffc4f9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_provider_config\n\nDocumentation:\nAdd `[[provider]]` configuration (customized for enabled signing providers)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_provider_config(&mut self) {\n self.add_section_comment(\"Signing Provider Configuration\");\n\n #[cfg(feature = \"yubihsm\")]\n self.add_yubihsm_provider_config();\n\n #[cfg(feature = \"ledger\")]\n self.add_ledgertm_provider_config();\n\n #[cfg(feature = \"softsign\")]\n self.add_softsign_provider_config();\n\n #[cfg(feature = \"fortanixdsm\")]\n self.add_fortanixdsm_provider_config();\n }\n```"}], "func_name": "add_provider_config", "docstring": "Add `[[provider]]` configuration (customized for enabled signing providers)", "repo": "iqlusioninc/tmkms", "path": "src/commands/init/config_builder.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/init/config_builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b5922cb3d79bd5b17ddce28a19fb2e111838eb8ae2fb0125c74c40c9c8d6186a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_template\n\nDocumentation:\nAppend a template to the config file, substituting `$KMS_HOME`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_template(&mut self, template: &str) {\n self.add_str(format_template(\n template,\n &[(\"$KMS_HOME\", self.kms_home.as_ref())],\n ));\n\n self.add_str(\"\\n\\n\");\n }\n```"}], "func_name": "add_template", "docstring": "Append a template to the config file, substituting `$KMS_HOME`", "repo": "iqlusioninc/tmkms", "path": "src/commands/init/config_builder.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/init/config_builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "137955bb2618ced0fb4d8201213f6cd3e8bada590e884bcba95f34157919eb23"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_template_with_chain_id\n\nDocumentation:\nAppend a template to the config file, substituting `$KMS_HOME` and `$CHAIN_ID`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_template_with_chain_id(&mut self, template: &str) {\n for network in self.networks.clone() {\n self.add_str(format_template(\n template,\n &[\n (\"$KMS_HOME\", self.kms_home.as_ref()),\n (\"$CHAIN_ID\", network.chain_id()),\n ],\n ));\n\n self.add_str(\"\\n\\n\");\n }\n }\n```"}], "func_name": "add_template_with_chain_id", "docstring": "Append a template to the config file, substituting `$KMS_HOME` and `$CHAIN_ID`", "repo": "iqlusioninc/tmkms", "path": "src/commands/init/config_builder.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/init/config_builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "75a50f3e005230fee1d2c0c9909bfb6afc9d4927b6bd5aca39d44a8b3d2bf791"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: format_template\n\nDocumentation:\nApply the given set of substitutions and trim newlines\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn format_template(template: &str, substitutions: &[(&str, &str)]) -> String {\n substitutions.iter().fold(\n template.trim_end().to_owned(),\n |string, (name, replacement)| string.replace(name, replacement),\n )\n}\n```"}], "func_name": "format_template", "docstring": "Apply the given set of substitutions and trim newlines", "repo": "iqlusioninc/tmkms", "path": "src/commands/init/config_builder.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/init/config_builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81fdd5483e290eacc3510db457bd1aeeba66ab8702aa20e49fd71adbda9c5dc3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: all\n\nDocumentation:\nGet a slice containing all known networks\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn all() -> &'static [Network] {\n &[\n Network::Columbus,\n Network::CosmosHub,\n Network::IrisHub,\n Network::SentinelHub,\n Network::Osmosis,\n Network::Persistence,\n ]\n }\n```"}], "func_name": "all", "docstring": "Get a slice containing all known networks", "repo": "iqlusioninc/tmkms", "path": "src/commands/init/networks.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/init/networks.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a3bc0ef24483dc53f4b8d2bcdcf6d32fb65d0c9c666d85dc44361fde2ece8ab2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse\n\nDocumentation:\nParse a network name from the chain ID prefix\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse(s: &str) -> Self {\n match s {\n \"columbus\" => Network::Columbus,\n \"cosmoshub\" => Network::CosmosHub,\n \"irishub\" => Network::IrisHub,\n \"sentinelhub\" => Network::SentinelHub,\n \"osmosis\" => Network::Osmosis,\n \"core\" => Network::Persistence,\n other => {\n status_err!(\"unknown Tendermint network: `{}`\", other);\n eprintln!(\"\\nRegistered networks:\");\n\n for network in Self::all() {\n eprintln!(\"- {network}\");\n }\n\n process::exit(1);\n }\n }\n }\n```"}], "func_name": "parse", "docstring": "Parse a network name from the chain ID prefix", "repo": "iqlusioninc/tmkms", "path": "src/commands/init/networks.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/init/networks.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3e33cf315e4ab28b12f08e7a3cb71328cae328143ea5fb6d2769249f1315bd63"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: chain_id\n\nDocumentation:\nGet the current production chain ID for this network\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn chain_id(&self) -> &str {\n match self {\n Network::Columbus => \"columbus-3\",\n Network::CosmosHub => \"cosmoshub-3\",\n Network::IrisHub => \"irishub\",\n Network::SentinelHub => \"sentinelhub-2\",\n Network::Osmosis => \"osmosis-1\",\n Network::Persistence => \"core-1\",\n }\n }\n```"}], "func_name": "chain_id", "docstring": "Get the current production chain ID for this network", "repo": "iqlusioninc/tmkms", "path": "src/commands/init/networks.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/init/networks.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ab1a4207c5fcdf1f012160fa04b45251e49d22d9343c7bbf26d4db1424eaff8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: schema_file\n\nDocumentation:\nGet the schema file for this network\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn schema_file(&self) -> &str {\n match self {\n Network::Columbus => \"terra.toml\",\n Network::CosmosHub => \"cosmos-sdk.toml\",\n Network::IrisHub => \"iris.toml\",\n Network::SentinelHub => \"sentinelhub.toml\",\n Network::Osmosis => \"osmosis.toml\",\n Network::Persistence => \"persistence.toml\",\n }\n }\n```"}], "func_name": "schema_file", "docstring": "Get the schema file for this network", "repo": "iqlusioninc/tmkms", "path": "src/commands/init/networks.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/init/networks.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "406abfe33731f51bb901ad968b6ccfa298d536aeee0399b0a9906db03dc48138"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nGenerate an Ed25519 secret key for use with a software provider (i.e. ed25519-dalek)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn run(&self) {\n if self.output_paths.len() != 1 {\n eprintln!(\"Usage: tmkms softsign keygen [-t account,consensus] PATH\");\n process::exit(1);\n }\n\n let output_path = &self.output_paths[0];\n\n match self\n .key_type\n .as_ref()\n .map(AsRef::as_ref)\n .unwrap_or(DEFAULT_KEY_TYPE)\n {\n \"account\" => generate_secp256k1_key(output_path),\n \"consensus\" => generate_ed25519_key(output_path),\n other => {\n status_err!(\n \"unknown key type: {} (must be 'account' or 'consensus')\",\n other\n );\n process::exit(1);\n }\n }\n }\n```"}], "func_name": "run", "docstring": "Generate an Ed25519 secret key for use with a software provider (i.e. ed25519-dalek)", "repo": "iqlusioninc/tmkms", "path": "src/commands/softsign/keygen.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/softsign/keygen.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f58b49526ccb3f3ecda735b9444921acf2273f7b0a6a912b6fdde17e6dc1917d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_secp256k1_key\n\nDocumentation:\nRandomly generate a Base64-encoded secp256k1 key and store it at the given path\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_secp256k1_key(output_path: &Path) {\n let signing_key = ecdsa::SigningKey::random(&mut OsRng);\n\n key_utils::write_base64_secret(output_path, &signing_key.to_bytes()).unwrap_or_else(|e| {\n status_err!(\"{}\", e);\n process::exit(1);\n });\n\n status_ok!(\n \"Generated\",\n \"account (secp256k1) private key at: {}\",\n output_path.display()\n );\n}\n```"}], "func_name": "generate_secp256k1_key", "docstring": "Randomly generate a Base64-encoded secp256k1 key and store it at the given path", "repo": "iqlusioninc/tmkms", "path": "src/commands/softsign/keygen.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/softsign/keygen.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8dbd6a87f1ad4ee516c2d5b84100e5f9fe09a280cc5a7d8359dd91b42451d967"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_ed25519_key\n\nDocumentation:\nRandomly generate a Base64-encoded Ed25519 key and store it at the given path\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_ed25519_key(output_path: &Path) {\n let mut sk_bytes = [0u8; 32];\n OsRng.fill_bytes(&mut sk_bytes);\n let sk = ed25519::SigningKey::from(sk_bytes);\n\n key_utils::write_base64_secret(output_path, sk.as_bytes()).unwrap_or_else(|e| {\n status_err!(\"{}\", e);\n process::exit(1);\n });\n\n status_ok!(\n \"Generated\",\n \"consensus (Ed25519) private key at: {}\",\n output_path.display()\n );\n}\n```"}], "func_name": "generate_ed25519_key", "docstring": "Randomly generate a Base64-encoded Ed25519 key and store it at the given path", "repo": "iqlusioninc/tmkms", "path": "src/commands/softsign/keygen.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/softsign/keygen.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5480a91b80c1bba15760ebfad20d2517796fe9d2c597e1bbd962b7905e26f80f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nDetect all YubiHSM2 devices connected via USB\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn run(&self) {\n let devices = Devices::detect(Default::default()).unwrap_or_else(|e| {\n status_err!(\"couldn't detect USB devices: {}\", e);\n\n // TODO: handle exits via abscissa\n process::exit(1);\n });\n\n if devices.is_empty() {\n status_err!(\"no YubiHSM2 devices detected!\");\n process::exit(1);\n }\n\n println!(\"Detected YubiHSM2 USB devices:\");\n\n for device in devices.iter() {\n println!(\n \"- Serial #{} (bus {})\",\n device.serial_number,\n device.bus_number(),\n );\n }\n }\n```"}], "func_name": "run", "docstring": "Detect all YubiHSM2 devices connected via USB", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/detect.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/detect.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5ee6a333708c685299ad4a47c85f51fd112c6e73c5b6f9951f1bb357e2a1fc7a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: config_path\n\nDocumentation:\nOptional path to the configuration file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn config_path(&self) -> Option<&PathBuf> {\n match self {\n KeysCommand::Export(export) => export.config.as_ref(),\n KeysCommand::Generate(generate) => generate.config.as_ref(),\n KeysCommand::List(list) => list.config.as_ref(),\n KeysCommand::Import(import) => import.config.as_ref(),\n }\n }\n```"}], "func_name": "config_path", "docstring": "Optional path to the configuration file", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/keys.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/keys.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44d1ff76607b6c7293681025be777409bb3c09f247078947c1a3b3b7066e7c9d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_mnemonic_from_stdin\n\nDocumentation:\nRead the mnemonic phrase from STDIN\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_mnemonic_from_stdin(prompt: &str) -> mnemonic::Phrase {\n print!(\"{prompt}\");\n io::stdout().flush().unwrap();\n\n let mut input_string = String::new();\n io::stdin()\n .read_line(&mut input_string)\n .expect(\"error reading mnemonic from STDIN!\");\n\n let input_words: Vec<_> = input_string.split_whitespace().collect();\n let input_phrase = input_words.join(\" \");\n input_string.zeroize();\n\n let result = mnemonic::Phrase::new(input_phrase, BIP39_LANGUAGE).unwrap_or_else(|_| {\n eprintln!(\"*** ERROR: Couldn't decode mnemonic\");\n exit(1);\n });\n\n println!(\"\\nMnemonic phrase decoded/checksummed successfully!\\n\");\n\n result\n}\n```"}], "func_name": "read_mnemonic_from_stdin", "docstring": "Read the mnemonic phrase from STDIN", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/setup.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/setup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1906e3b8c34f755a516a209f225ab6a740fe42e6dac8a89063563a15fdcfacba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_mnemonic\n\nDocumentation:\nDisplay the mnemonic as two groups of 12 words\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_mnemonic(mnemonic: &mnemonic::Phrase) {\n let words: Vec<&str> = mnemonic.phrase().split(' ').collect();\n let words_len = words.len();\n\n for word_group in &[&words[..(words_len / 2)], &words[(words_len / 2)..]] {\n let mut word_group_joined = word_group.join(\" \");\n println!(\" {word_group_joined}\");\n word_group_joined.zeroize();\n }\n}\n```"}], "func_name": "print_mnemonic", "docstring": "Display the mnemonic as two groups of 12 words", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/setup.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/setup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "935bdc4f5439a9fde5d17d98e2caf01f2f4256c978c66477d1501b9c399e5508"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_hsm_client\n\nDocumentation:\nGet an HSM client from the provided connector\n\nWe need to create our own client here since the global one maintains\na persistent connection, and we need to close this one before we can\nreprovision the HSM\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_hsm_client(hsm_connector: &Connector) -> yubihsm::Client {\n yubihsm::Client::open(\n hsm_connector.clone(),\n crate::yubihsm::config().auth.credentials(),\n false,\n )\n .unwrap_or_else(|e| hsm_error(&e))\n}\n```"}], "func_name": "get_hsm_client", "docstring": "Get an HSM client from the provided connector\n\nWe need to create our own client here since the global one maintains\na persistent connection, and we need to close this one before we can\nreprovision the HSM", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/setup.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/setup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c7e38c6da05773fffc8b4d8f9f2e9a9d38df4d847c5e3f0ec670c2d8a1c9ec95"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_mnemonic_from_hsm_and_os_csprngs\n\nDocumentation:\nGenerate entropy by combining entropy both from the host OS and from the\nYubiHSM2 itself (which includes an internal CSPRNG).\n\nThese are both used as input key material (IKM) for a key derivation\nfunction (HKDF) in order to derive the recovery passphrase, which ideally\nensures that the passphrase will be securely random so long as at least\none of the two inputs is secure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_mnemonic_from_hsm_and_os_csprngs(hsm_connector: &Connector) -> mnemonic::Phrase {\n let hsm_client = get_hsm_client(hsm_connector);\n\n // Obtain half of the IKM from the YubiHSM (256-bits)\n let mut ikm = hsm_client\n .get_pseudo_random(KEY_SIZE)\n .unwrap_or_else(|e| hsm_error(&e));\n\n // Obtain another half of the IKM from the host OS (256-bits)\n // for a total of 512-bits IKM. This ensures we still get 256-bits\n // of good IKM even in the event one of the RNGs fails.\n ikm.extend_from_slice(&[0u8; KEY_SIZE]);\n getrandom(&mut ikm[KEY_SIZE..]).expect(\"RNG failure!\");\n\n let kdf = Hkdf::::new(None, &ikm);\n\n // 32-bytes (256-bits) -> 24 BIP32 words\n let mut okm = [0u8; KEY_SIZE];\n kdf.expand(HKDF_MNEMONIC_INFO, &mut okm).unwrap();\n ikm.zeroize();\n\n let result = mnemonic::Phrase::from_entropy(okm, BIP39_LANGUAGE);\n okm.zeroize();\n\n result\n}\n```"}], "func_name": "generate_mnemonic_from_hsm_and_os_csprngs", "docstring": "Generate entropy by combining entropy both from the host OS and from the\nYubiHSM2 itself (which includes an internal CSPRNG).\n\nThese are both used as input key material (IKM) for a key derivation\nfunction (HKDF) in order to derive the recovery passphrase, which ideally\nensures that the passphrase will be securely random so long as at least\none of the two inputs is secure.", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/setup.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/setup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7355cea3d0e4c89911af5acc599008433cf9e31f13e162118111f37d2a918c7b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: derive_roles_from_mnemonic\n\nDocumentation:\nDerive the default roles form the given BIP39 `mnemonic::Phrase`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn derive_roles_from_mnemonic(mnemonic: &mnemonic::Phrase) -> Vec {\n let admin_role = derive_admin_role_from_mnemonic(mnemonic);\n\n // operator\n let operator_role = derive_role_from_mnemonic(mnemonic, 2, OPERATOR_ROLE_NAME)\n .capabilities(\n Capability::GENERATE_ASYMMETRIC_KEY\n | Capability::PUT_ASYMMETRIC_KEY\n | Capability::GENERATE_HMAC_KEY\n | Capability::PUT_HMAC_KEY\n | Capability::IMPORT_WRAPPED\n | Capability::EXPORT_WRAPPED\n | Capability::GET_OPAQUE\n | Capability::GET_OPTION\n | Capability::GET_LOG_ENTRIES\n | Capability::SIGN_ATTESTATION_CERTIFICATE,\n )\n .delegated_capabilities(Capability::all())\n .domains(Domain::all());\n\n // auditor\n let auditor_role = derive_role_from_mnemonic(mnemonic, 3, AUDITOR_ROLE_NAME)\n .capabilities(\n Capability::GET_LOG_ENTRIES\n | Capability::GET_OPTION\n | Capability::PUT_OPTION\n | Capability::GET_OPAQUE,\n )\n .delegated_capabilities(Capability::empty())\n .domains(Domain::all());\n\n // validator\n let validator_role = derive_role_from_mnemonic(mnemonic, 4, VALIDATOR_ROLE_NAME)\n .capabilities(\n Capability::SIGN_ECDSA\n | Capability::SIGN_EDDSA\n | Capability::SIGN_ATTESTATION_CERTIFICATE\n | Capability::GET_LOG_ENTRIES,\n )\n .delegated_capabilities(Capability::empty())\n .domains(Domain::DOM1);\n\n vec![admin_role, operator_role, auditor_role, validator_role]\n}\n```"}], "func_name": "derive_roles_from_mnemonic", "docstring": "Derive the default roles form the given BIP39 `mnemonic::Phrase`", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/setup.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/setup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ffa4e99c29e1b38806041cb122e1e2230a2fce87b3124762970b68fd9dd9b642"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: derive_admin_role_from_mnemonic\n\nDocumentation:\nDerive the admin role from the given mnemonic.\n\nThe admin role is somewhat different from the others and confers total\nauthority over the HSM device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn derive_admin_role_from_mnemonic(mnemonic: &mnemonic::Phrase) -> Role {\n let admin_credentials = Credentials::new(\n 1,\n authentication::Key::derive_from_password(mnemonic.phrase().as_bytes()),\n );\n\n Role::new(admin_credentials)\n .authentication_key_label(create_object_label(ADMIN_ROLE_NAME))\n .capabilities(Capability::all())\n .delegated_capabilities(Capability::all())\n .domains(Domain::all())\n}\n```"}], "func_name": "derive_admin_role_from_mnemonic", "docstring": "Derive the admin role from the given mnemonic.\n\nThe admin role is somewhat different from the others and confers total\nauthority over the HSM device.", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/setup.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/setup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2c426033c4a10b469670a7a59b2fafc996f2826f11f242ffaa55a75af0eab47f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: derive_role_from_mnemonic\n\nDocumentation:\nDerive the initial settings for a role from the given mnemonic\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn derive_role_from_mnemonic(\n mnemonic: &mnemonic::Phrase,\n key_id: object::Id,\n role_name: &str,\n) -> Role {\n let role_password = RolePassword::derive_from_mnemonic(mnemonic, role_name);\n\n let role_credentials = Credentials::new(\n key_id,\n authentication::Key::derive_from_password(role_password.as_bytes()),\n );\n\n Role::new(role_credentials).authentication_key_label(create_object_label(role_name))\n}\n```"}], "func_name": "derive_role_from_mnemonic", "docstring": "Derive the initial settings for a role from the given mnemonic", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/setup.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/setup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aff9390c3c463a94d59e554968c61f06dcf2f2f08e653859cac93e0f50347dcd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: derive_from_mnemonic\n\nDocumentation:\nDerive a role password from the given BIP39 `mnemonic::Phrase`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn derive_from_mnemonic(mnemonic: &mnemonic::Phrase, role_name: &str) -> Self {\n let mut secret_key =\n derive_secret_from_mnemonic(mnemonic, &[b\"role\", role_name.as_bytes()]);\n\n // YubiHSM authentication keys are 2 x AES-128 keys, derived using\n // PBKDF2. This means we derive no value from more than 128-bits of\n // entropy in the password, whereas shorter passwords are more\n // convenient.\n //\n // For that reason, truncate the derived secret to 16-bytes\n let truncated_secret_key = &secret_key.as_bytes()[..(KEY_SIZE / 2)];\n\n let result = RolePassword(\n Bech32::default().encode(format!(\"kms-{role_name}-password-\"), truncated_secret_key),\n );\n secret_key.zeroize();\n\n result\n }\n```"}], "func_name": "derive_from_mnemonic", "docstring": "Derive a role password from the given BIP39 `mnemonic::Phrase`", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/setup.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/setup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c915ff808ad6774113a33e2e48e5bf5db9ba99aeb338e132c616acd656c82d5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: derive_wrap_key_from_mnemonic\n\nDocumentation:\nDerive a wrap key from the given BIP39 `mnemonic::Phrase`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn derive_wrap_key_from_mnemonic(mnemonic: &mnemonic::Phrase, key_id: object::Id) -> wrap::Key {\n // Capabilities given to the initial wrap key:\n // wrap/unwrap both data and objects\n let wrap_key_capabilities = Capability::EXPORT_WRAPPED\n | Capability::IMPORT_WRAPPED\n | Capability::WRAP_DATA\n | Capability::UNWRAP_DATA;\n\n // Allow the initial wrap key to create new objects with any other\n // capabilities.\n //\n // To prevent escalation of privilege, no roles except administrators\n // will be given the capability to export other objects.\n let wrap_key_delegated_capabilities = Capability::all();\n\n // Make the wrap key accessible from all domains. This allows it to\n // import and export objects from any domain.\n let wrap_key_domains = Domain::all();\n\n // Label to put on the wrap key\n let wrap_key_label = create_object_label(\"primary\");\n\n // Includes the key ID in the derivation path, which allows us to derive\n // other wrap keys from the same seed `mnemonic::Phrase` phrase in the event one\n // has been compromised.\n wrap::Key::from_bytes(\n key_id,\n derive_secret_from_mnemonic(mnemonic, &[b\"wrap\", serialize_key_id(key_id).as_bytes()])\n .as_bytes(),\n )\n .unwrap()\n .label(wrap_key_label)\n .capabilities(wrap_key_capabilities)\n .delegated_capabilities(wrap_key_delegated_capabilities)\n .domains(wrap_key_domains)\n}\n```"}], "func_name": "derive_wrap_key_from_mnemonic", "docstring": "Derive a wrap key from the given BIP39 `mnemonic::Phrase`", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/setup.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/setup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3e6526da9634fb6f23ed1197a1bf8fb03a11496e5541d5970961e8b1504a313f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_object_label\n\nDocumentation:\nCreate a label for a newly generated object which tags it with the date\nit was created\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn create_object_label(label_prefix: &str) -> object::Label {\n // e.g. 2019-02-26T18:03:53Z\n let timestamp = Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true);\n object::Label::from([label_prefix, ×tamp].join(\":\").as_ref())\n}\n```"}], "func_name": "create_object_label", "docstring": "Create a label for a newly generated object which tags it with the date\nit was created", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/setup.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/setup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1df4a03fd602d27d4bddf7517cd8b67357ff23e91d5a73d84143f31f8824e0ed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prompt_for_user_approval\n\nDocumentation:\nPrompt the user to ensure they want to proceed\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn prompt_for_user_approval(prompt: &str) {\n print!(\"\\n*** {prompt} (y/N): \");\n io::stdout().flush().unwrap();\n\n let mut choice_in = String::new();\n io::stdin()\n .read_line(&mut choice_in)\n .expect(\"Failed to read user input\");\n\n let choice = choice_in.trim();\n\n if choice != \"y\" && choice != \"Y\" {\n println!(\"Aborting\");\n exit(1);\n }\n}\n```"}], "func_name": "prompt_for_user_approval", "docstring": "Prompt the user to ensure they want to proceed", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/setup.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/setup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e326f049f35292c6c5bdf693e8a16e3d3dfd64731c985270a4dd507b96342ed5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nPerform a signing test using the current HSM configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn run(&self) {\n if self.key_id == 0 {\n status_err!(\"no key ID given\");\n process::exit(1);\n }\n\n let hsm = crate::yubihsm::client();\n\n loop {\n let started_at = Instant::now();\n\n if let Err(e) = hsm.sign_ed25519(self.key_id, TEST_MESSAGE.as_ref()) {\n status_err!(\"signature operation failed: {}\", e);\n thread::sleep(Duration::from_millis(250));\n } else {\n status_ok!(\n \"Success\",\n \"signed message using key ID #{} in {} ms\",\n self.key_id,\n started_at.elapsed().as_millis()\n );\n }\n }\n }\n```"}], "func_name": "run", "docstring": "Perform a signing test using the current HSM configuration", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/test.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/test.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "34bc75845c18920d7f734fb0827014f338f655fb94254fa85543fe8d09522b12"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_key_id\n\nDocumentation:\nParse the key ID provided in the arguments\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_key_id(&self) -> u16 {\n if self.key_ids.len() != 1 {\n status_err!(\n \"expected exactly 1 key ID to generate, got {}\",\n self.key_ids.len()\n );\n process::exit(1);\n }\n\n let key_id_str = &self.key_ids[0];\n\n if let Some(s) = key_id_str.strip_prefix(\"0x\") {\n u16::from_str_radix(s, 16).ok()\n } else {\n key_id_str.parse().ok()\n }\n .unwrap_or_else(|| {\n status_err!(\"couldn't parse key ID: {}\", key_id_str);\n process::exit(1);\n })\n }\n```"}], "func_name": "parse_key_id", "docstring": "Parse the key ID provided in the arguments", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/keys/generate.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/keys/generate.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3b62455dcd3f6118560acbe8ee94ddbaf983ee41c7058848992abb6c256ac26d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_key_type\n\nDocumentation:\nParse the key type provided in the arguments\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_key_type(&self) -> KeyType {\n match self.key_type.as_ref().map(AsRef::as_ref) {\n Some(\"account\") => KeyType::Account,\n Some(\"consensus\") | None => KeyType::Consensus, // default\n Some(other) => {\n status_err!(\"invalid key type: {}\", other);\n process::exit(1);\n }\n }\n }\n```"}], "func_name": "parse_key_type", "docstring": "Parse the key type provided in the arguments", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/keys/generate.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/keys/generate.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b28e1e8136927f057be273de6009a53b13fd19a3fe210fdfd67c3f2f29be7bff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nGenerate an Ed25519 signing key inside a YubiHSM2 device\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn run(&self) {\n let key_id = self.parse_key_id();\n let key_type = self.parse_key_type();\n\n let hsm = crate::yubihsm::client();\n let mut capabilities = match key_type {\n KeyType::Account => yubihsm::Capability::SIGN_ECDSA,\n KeyType::Consensus => yubihsm::Capability::SIGN_EDDSA,\n };\n\n // If the key isn't explicitly marked as non-exportable, allow it to be exported\n if !self.non_exportable {\n capabilities |= yubihsm::Capability::EXPORTABLE_UNDER_WRAP;\n }\n\n let timestamp = Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true);\n let label = yubihsm::object::Label::from(\n match self.label {\n Some(ref l) => l.to_owned(),\n None => match self.bech32_prefix {\n Some(ref prefix) => format!(\"{prefix}:{timestamp}\"),\n None => format!(\"{key_type}:{timestamp}\"),\n },\n }\n .as_ref(),\n );\n\n let algorithm = match key_type {\n KeyType::Account => yubihsm::asymmetric::Algorithm::EcK256,\n KeyType::Consensus => yubihsm::asymmetric::Algorithm::Ed25519,\n };\n\n if let Err(e) = hsm.generate_asymmetric_key(\n key_id,\n label,\n DEFAULT_DOMAINS, // TODO(tarcieri): customize domains\n capabilities,\n algorithm,\n ) {\n status_err!(\"couldn't generate key #{}: {}\", key_id, e);\n process::exit(1);\n }\n\n match key_type {\n KeyType::Account => {\n // TODO(tarcieri): generate and show account ID (fingerprint)\n status_ok!(\"Generated\", \"account (secp256k1) key 0x{:04x}\", key_id)\n }\n KeyType::Consensus => {\n // TODO(tarcieri): use KeyFormat (when available) to format Bech32\n let public_key = PublicKey::from_raw_ed25519(\n hsm.get_public_key(key_id)\n .unwrap_or_else(|e| {\n status_err!(\"couldn't get public key for key #{}: {}\", key_id, e);\n process::exit(1);\n })\n .as_ref(),\n )\n .unwrap();\n\n let public_key_string = match self.bech32_prefix {\n Some(ref prefix) => public_key.to_bech32(prefix),\n None => public_key.to_hex(),\n };\n\n status_ok!(\n \"Generated\",\n \"consensus (ed25519) key 0x{:04x}: {}\",\n key_id,\n public_key_string\n )\n }\n }\n\n if let Some(ref backup_file) = self.backup_file {\n create_encrypted_backup(\n &hsm,\n key_id,\n backup_file,\n self.wrap_key_id.unwrap_or(DEFAULT_WRAP_KEY),\n );\n }\n }\n```"}], "func_name": "run", "docstring": "Generate an Ed25519 signing key inside a YubiHSM2 device", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/keys/generate.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/keys/generate.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f004f428268578ac5bddce265679fab00ac41252130ad7f786b8e538b0267786"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: import_wrapped\n\nDocumentation:\nImport a wrapped object into the HSM\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn import_wrapped(&self, wrapped_key_base64: &str) {\n if let Some(id) = self.key_id {\n status_warn!(\"ignoring key ID: {} (wrapped keys use original key ID)\", id);\n }\n\n if let Some(ref label) = self.label {\n status_warn!(\n \"ignoring label: {:?} (wrapped keys use original label)\",\n label\n );\n }\n\n let wrap_key_id = self.wrap_key_id.unwrap_or(DEFAULT_WRAP_KEY);\n\n let wrapped_key_ciphertext =\n base64::decode(wrapped_key_base64.as_bytes()).unwrap_or_else(|e| {\n status_err!(\n \"couldn't decode Base64-encoded wrapped key from {}: {}\",\n self.path.display(),\n e\n );\n process::exit(1);\n });\n\n let wrapped_message = yubihsm::wrap::Message::from_vec(wrapped_key_ciphertext)\n .unwrap_or_else(|e| {\n status_err!(\n \"couldn't parse wrapped key from {}: {}\",\n self.path.display(),\n e\n );\n process::exit(1);\n });\n\n let hsm = crate::yubihsm::client();\n\n let obj = hsm\n .import_wrapped(wrap_key_id, wrapped_message)\n .unwrap_or_else(|e| {\n status_err!(\n \"error importing encrypted key from {} (using wrapkey 0x{:04x}): {}\",\n self.path.display(),\n wrap_key_id,\n e\n );\n process::exit(1);\n });\n\n if obj.object_type != object::Type::AsymmetricKey {\n // We mainly care about importing asymmetric keys, but can handle other types.\n // If we encounter a non-asymmetric key type, display basic info.\n status_ok!(\n \"Imported\",\n \"object 0x{:04x} ({:?})\",\n obj.object_id,\n obj.object_type\n );\n process::exit(0);\n }\n\n let public_key = hsm.get_public_key(obj.object_id).unwrap_or_else(|e| {\n status_err!(\n \"couldn't get public key for asymmetric key #{}: {}\",\n obj.object_id,\n e\n );\n process::exit(1);\n });\n\n // TODO: display non hex format when listing/displaying keys\n let key_info = match public_key.algorithm {\n yubihsm::asymmetric::Algorithm::Ed25519 => {\n PublicKey::from_raw_ed25519(public_key.as_ref())\n .unwrap()\n .to_hex()\n }\n alg => format!(\"{:?}: {:?}\", alg, public_key.as_ref()),\n };\n\n status_ok!(\"Imported\", \"key 0x{:04x}: {}\", obj.object_id, key_info);\n }\n```"}], "func_name": "import_wrapped", "docstring": "Import a wrapped object into the HSM", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/keys/import.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/keys/import.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "948c187fa5c7eac171cbd7bb9412d70d35b023b1dd6f82ec50fee0e33546a03c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: import_priv_validator_json\n\nDocumentation:\nImport an existing priv_validator file into the HSM\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn import_priv_validator_json(&self, json_data: &str) {\n if let Some(id) = self.wrap_key_id {\n status_warn!(\n \"ignoring wrapkey ID: {} (not applicable to priv_validator.json files)\",\n id\n );\n }\n\n let key_id = self.key_id.unwrap_or_else(|| {\n status_err!(\n \"no key ID specified (use e.g. tmkms yubihsm keys import -i 1 priv_validator.json)\"\n );\n process::exit(1);\n });\n\n let private_key = PrivValidatorKey::parse_json(json_data)\n .unwrap_or_else(|e| {\n status_err!(\"couldn't parse priv_validator key: {}\", e);\n process::exit(1);\n })\n .priv_key;\n\n let seed = match private_key {\n PrivateKey::Ed25519(pk) => pk,\n _ => unreachable!(),\n };\n\n let label = object::Label::from(self.label.as_ref().map(|l| l.as_ref()).unwrap_or(\"\"));\n\n if let Err(e) = crate::yubihsm::client().put_asymmetric_key(\n key_id,\n label,\n DEFAULT_DOMAINS,\n yubihsm::Capability::SIGN_EDDSA | yubihsm::Capability::EXPORTABLE_UNDER_WRAP,\n yubihsm::asymmetric::Algorithm::Ed25519,\n seed.as_bytes(),\n ) {\n status_err!(\"couldn't import key #{}: {}\", self.key_id.unwrap(), e);\n process::exit(1);\n }\n\n status_ok!(\"Imported\", \"key 0x{:04x}\", key_id);\n }\n```"}], "func_name": "import_priv_validator_json", "docstring": "Import an existing priv_validator file into the HSM", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/keys/import.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/keys/import.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "06f157c782cb7e882c52ef1a8ccba722c0cdde5af408d21c1650ea946c76f554"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: import_base64\n\nDocumentation:\nImport a Base64-encoded private key into the HSM\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn import_base64(&self, base64_data: &str) {\n if let Some(id) = self.wrap_key_id {\n status_warn!(\n \"ignoring wrapkey ID: {} (not applicable to priv_validator.json files)\",\n id\n );\n }\n\n let key_id = self.key_id.unwrap_or_else(|| {\n status_err!(\n \"no key ID specified (use e.g. tmkms yubihsm keys import -i 1 priv_validator.json)\"\n );\n process::exit(1);\n });\n\n // TODO(tarcieri): constant-time string trimming\n let key_bytes =\n Zeroizing::new(base64::decode(base64_data.trim_end()).unwrap_or_else(|e| {\n status_err!(\"can't decode Ed25519 key: {}\", e);\n process::exit(1);\n }));\n\n let secret = ed25519::SigningKey::try_from(key_bytes.as_ref()).unwrap_or_else(|e| {\n status_err!(\"invalid Ed25519 key: {}\", e);\n process::exit(1);\n });\n\n let label = object::Label::from(self.label.as_ref().map(|l| l.as_ref()).unwrap_or(\"\"));\n\n if let Err(e) = crate::yubihsm::client().put_asymmetric_key(\n key_id,\n label,\n DEFAULT_DOMAINS,\n yubihsm::Capability::SIGN_EDDSA | yubihsm::Capability::EXPORTABLE_UNDER_WRAP,\n yubihsm::asymmetric::Algorithm::Ed25519,\n &secret.as_bytes()[..],\n ) {\n status_err!(\"couldn't import key #{}: {}\", self.key_id.unwrap(), e);\n process::exit(1);\n }\n\n status_ok!(\"Imported\", \"key 0x{:04x}\", key_id);\n }\n```"}], "func_name": "import_base64", "docstring": "Import a Base64-encoded private key into the HSM", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/keys/import.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/keys/import.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0db8d12e8c6976e6ab8a93bb7272a6c47a42ef32b9795ece9edec2bf03081de3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nList all suitable Ed25519 keys in the HSM\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn run(&self) {\n let key_formatters = load_key_formatters();\n let hsm = crate::yubihsm::client();\n\n let serial_number = hsm\n .device_info()\n .unwrap_or_else(|e| {\n status_err!(\"couldn't get YubiHSM serial number: {}\", e);\n process::exit(1);\n })\n .serial_number;\n\n let objects = hsm.list_objects(&[]).unwrap_or_else(|e| {\n status_err!(\"couldn't list YubiHSM objects: {}\", e);\n process::exit(1);\n });\n\n let mut keys = objects\n .iter()\n .filter(|o| o.object_type == yubihsm::object::Type::AsymmetricKey)\n .collect::>();\n\n keys.sort_by(|k1, k2| k1.object_id.cmp(&k2.object_id));\n\n if keys.is_empty() {\n status_err!(\"no keys in this YubiHSM (#{})\", serial_number);\n process::exit(0);\n }\n\n println!(\"Listing keys in YubiHSM #{serial_number}:\");\n\n for key in &keys {\n display_key_info(&hsm, key, &key_formatters);\n }\n }\n```"}], "func_name": "run", "docstring": "List all suitable Ed25519 keys in the HSM", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/keys/list.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/keys/list.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea8976a48db70802200285e75ced2cbcbc96e66073001904f49e2d1f3c926a03"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_key_formatters\n\nDocumentation:\nLoad information about configured YubiHSM keys\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn load_key_formatters() -> Map {\n let chain_formatters = load_chain_formatters();\n let cfg = crate::yubihsm::config();\n let mut map = Map::new();\n\n for key_config in &cfg.keys {\n // Only use a preferred formatting if there is one chain per key\n if key_config.chain_ids.len() == 1 {\n if let Some(formatter) = chain_formatters.get(&key_config.chain_ids[0]) {\n if map.insert(key_config.key, formatter.clone()).is_some() {\n status_err!(\"duplicate YubiHSM config for key: 0x{:04x}\", key_config.key);\n process::exit(1);\n }\n }\n }\n }\n\n map\n}\n```"}], "func_name": "load_key_formatters", "docstring": "Load information about configured YubiHSM keys", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/keys/list.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/keys/list.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b3acbef4f5050fb6d1ba5083e2a631649ea460c1f58a4b9c167f8b91e9023763"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_chain_formatters\n\nDocumentation:\nLoad chain-specific key formatters from the configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn load_chain_formatters() -> Map {\n let cfg = APP.config();\n let mut map = Map::new();\n\n for chain in &cfg.chain {\n if map\n .insert(chain.id.clone(), chain.key_format.clone())\n .is_some()\n {\n status_err!(\"duplicate chain config for '{}'\", chain.id);\n process::exit(1);\n }\n }\n\n map\n}\n```"}], "func_name": "load_chain_formatters", "docstring": "Load chain-specific key formatters from the configuration", "repo": "iqlusioninc/tmkms", "path": "src/commands/yubihsm/keys/list.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/commands/yubihsm/keys/list.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7906b99eaf22db1afc92aba34a1c8b9174c756a129734108dea9a2d21109cf4c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: credentials\n\nDocumentation:\nGet the `yubihsm::Credentials` for this `AuthConfig`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn credentials(&self) -> Credentials {\n match self {\n AuthConfig::Path { key, password_file } => {\n let password =\n Zeroizing::new(fs::read_to_string(password_file).unwrap_or_else(|e| {\n status_err!(\"couldn't read key from {}: {}\", password_file.display(), e);\n process::exit(1);\n }));\n\n // TODO(tarcieri): constant-time string trimming\n let password_trimmed = password.trim_end();\n Credentials::from_password(*key, password_trimmed.as_bytes())\n }\n AuthConfig::String { key, password } => {\n Credentials::from_password(*key, password.0.as_bytes())\n }\n }\n }\n```"}], "func_name": "credentials", "docstring": "Get the `yubihsm::Credentials` for this `AuthConfig`", "repo": "iqlusioninc/tmkms", "path": "src/config/provider/yubihsm.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/config/provider/yubihsm.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48bb2c6a40a2e1e1f43ee575a6ad401a0238fd6ec781eb23022318781de8f215"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open_secret_connection\n\nDocumentation:\nOpen a TCP socket connection encrypted with SecretConnection\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn open_secret_connection(\n host: &str,\n port: u16,\n identity_key_path: &Option,\n peer_id: &Option,\n timeout: Option,\n protocol_version: secret_connection::Version,\n) -> Result, Error> {\n let identity_key_path = identity_key_path.as_ref().ok_or_else(|| {\n format_err!(\n ConfigError,\n \"config error: no `secret_key` for validator: {}:{}\",\n host,\n port\n )\n })?;\n\n let identity_key = key_utils::load_base64_ed25519_key(identity_key_path)?;\n info!(\"KMS node ID: {}\", PublicKey::from(&identity_key));\n\n let socket = TcpStream::connect(format!(\"{host}:{port}\"))?;\n let timeout = Duration::from_secs(timeout.unwrap_or(DEFAULT_TIMEOUT).into());\n socket.set_read_timeout(Some(timeout))?;\n socket.set_write_timeout(Some(timeout))?;\n\n let connection = match SecretConnection::new(socket, identity_key.into(), protocol_version) {\n Ok(conn) => conn,\n Err(error) => match error.detail() {\n TmError::Crypto(_) => fail!(CryptoError, format!(\"{error}\")),\n TmError::Protocol(_) => fail!(ProtocolError, format!(\"{error}\")),\n TmError::InvalidKey(_) => fail!(InvalidKey, format!(\"{error}\")),\n _ => fail!(ProtocolError, format!(\"{error}\")),\n },\n };\n let actual_peer_id = connection.remote_pubkey().peer_id();\n\n // TODO(tarcieri): move this into `SecretConnection::new`\n if let Some(expected_peer_id) = peer_id {\n if expected_peer_id.ct_eq(&actual_peer_id).unwrap_u8() == 0 {\n fail!(\n VerificationError,\n \"{}:{}: validator peer ID mismatch! (expected {}, got {})\",\n host,\n port,\n expected_peer_id,\n actual_peer_id\n );\n }\n }\n\n Ok(connection)\n}\n```"}], "func_name": "open_secret_connection", "docstring": "Open a TCP socket connection encrypted with SecretConnection", "repo": "iqlusioninc/tmkms", "path": "src/connection/tcp.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/connection/tcp.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ad20badcc1099a936ccc20265a3e1876d454103f4e8a1f88288cfbe7706249e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new `UnixConnection` for the given socket\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(socket: IoHandler) -> Self {\n Self { socket }\n }\n```"}], "func_name": "new", "docstring": "Create a new `UnixConnection` for the given socket", "repo": "iqlusioninc/tmkms", "path": "src/connection/unix.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/connection/unix.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "206cdcf84986975dbffb26007f05b7dd9435515988262839b50bf6497b7cc054"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sign\n\nDocumentation:\nSign the given message using this signer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sign(&self, msg: &[u8]) -> Result {\n Ok(self\n .signer\n .try_sign(msg)\n .map_err(|e| format_err!(SigningError, \"{}\", e))?)\n }\n```"}], "func_name": "sign", "docstring": "Sign the given message using this signer", "repo": "iqlusioninc/tmkms", "path": "src/keyring/ecdsa.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/ecdsa.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "baff07594ed08a11a79fd4593d917bea7d7500a568f79b7be2baa3a67925c3f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: serialize\n\nDocumentation:\nSerialize a `TendermintKey` according to chain-specific rules\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn serialize(&self, public_key: TendermintKey) -> String {\n match self {\n Format::Bech32 {\n account_key_prefix,\n consensus_key_prefix,\n } => match public_key {\n TendermintKey::AccountKey(pk) => {\n bech32::encode(account_key_prefix, tendermint::account::Id::from(pk))\n }\n TendermintKey::ConsensusKey(pk) => pk.to_bech32(consensus_key_prefix),\n },\n Format::CosmosJson => PublicKey::from(*public_key.public_key()).to_json(),\n Format::Hex => match public_key {\n TendermintKey::AccountKey(pk) => pk.to_hex(),\n TendermintKey::ConsensusKey(pk) => pk.to_hex(),\n },\n }\n }\n```"}], "func_name": "serialize", "docstring": "Serialize a `TendermintKey` according to chain-specific rules", "repo": "iqlusioninc/tmkms", "path": "src/keyring/format.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/format.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a21af4686344d8ef5a276c41cdbe78e63b3352cf4a71cdd6beae384acbdbd5c0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_vec\n\nDocumentation:\nSerialize this signature as a byte vector.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_vec(&self) -> Vec {\n match self {\n Self::Ecdsa(sig) => sig.to_vec(),\n Self::Ed25519(sig) => sig.to_vec(),\n }\n }\n```"}], "func_name": "to_vec", "docstring": "Serialize this signature as a byte vector.", "repo": "iqlusioninc/tmkms", "path": "src/keyring/signature.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/signature.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f4cf3555880588465509fc0b29fcccf671b415166742402fb268f2a38e6d9e23"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init\n\nDocumentation:\nCreate Fortanix DSM backed signer objects from the given configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn init(registry: &mut chain::Registry, configs: &[FortanixDsmConfig]) -> Result<(), Error> {\n if configs.is_empty() {\n return Ok(());\n }\n for config in configs {\n let client = make_sdkms_client(config)?;\n for key in &config.signing_keys {\n add_key(registry, key, client.clone())?;\n }\n }\n Ok(())\n}\n```"}], "func_name": "init", "docstring": "Create Fortanix DSM backed signer objects from the given configuration", "repo": "iqlusioninc/tmkms", "path": "src/keyring/providers/fortanixdsm.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/providers/fortanixdsm.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b563efd8c2314e215aa7256026cdfd82b6460157193aff4889b5e2208eb40153"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init\n\nDocumentation:\nCreate Ledger Tendermint signer object from the given configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn init(\n chain_registry: &mut chain::Registry,\n ledgertm_configs: &[LedgerTendermintConfig],\n) -> Result<(), Error> {\n if ledgertm_configs.is_empty() {\n return Ok(());\n }\n\n if ledgertm_configs.len() != 1 {\n fail!(\n ConfigError,\n \"expected one [providers.ledgertm] in config, found: {}\",\n ledgertm_configs.len()\n );\n }\n\n let provider = Ed25519LedgerTmAppSigner::connect().map_err(|_| Error::from(SigningError))?;\n\n let public_key = PublicKey::from_raw_ed25519(ed25519::VerifyingKey::from(&provider).as_bytes())\n .expect(\"invalid Ed25519 public key\");\n\n let signer = Signer::new(\n SigningProvider::LedgerTm,\n TendermintKey::ConsensusKey(public_key),\n Box::new(provider),\n );\n\n for chain_id in &ledgertm_configs[0].chain_ids {\n chain_registry.add_consensus_key(chain_id, signer.clone())?;\n }\n\n Ok(())\n}\n```"}], "func_name": "init", "docstring": "Create Ledger Tendermint signer object from the given configuration", "repo": "iqlusioninc/tmkms", "path": "src/keyring/providers/ledgertm.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/providers/ledgertm.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dccec47151b651682dbc3a984410a4439e69e7cba18256427ca4714328124979"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init\n\nDocumentation:\nCreate software-backed Ed25519 signer objects from the given configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn init(chain_registry: &mut chain::Registry, configs: &[SoftsignConfig]) -> Result<(), Error> {\n if configs.is_empty() {\n return Ok(());\n }\n\n let mut loaded_consensus_key = false;\n\n for config in configs {\n match config.key_type {\n KeyType::Account => {\n let signer = load_secp256k1_key(config)?;\n let public_key = tendermint::PublicKey::from_raw_secp256k1(\n &signer.verifying_key().to_sec1_bytes(),\n )\n .unwrap();\n\n let account_pubkey = TendermintKey::AccountKey(public_key);\n\n let signer = keyring::ecdsa::Signer::new(\n SigningProvider::SoftSign,\n account_pubkey,\n Box::new(signer),\n );\n\n for chain_id in &config.chain_ids {\n chain_registry.add_account_key(chain_id, signer.clone())?;\n }\n }\n KeyType::Consensus => {\n if loaded_consensus_key {\n fail!(\n ConfigError,\n \"only one [[providers.softsign]] consensus key allowed\"\n );\n }\n\n loaded_consensus_key = true;\n\n let signing_key = load_ed25519_key(config)?;\n let consensus_pubkey =\n TendermintKey::ConsensusKey(signing_key.verifying_key().into());\n\n let signer = ed25519::Signer::new(\n SigningProvider::SoftSign,\n consensus_pubkey,\n Box::new(signing_key),\n );\n\n for chain_id in &config.chain_ids {\n chain_registry.add_consensus_key(chain_id, signer.clone())?;\n }\n }\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "init", "docstring": "Create software-backed Ed25519 signer objects from the given configuration", "repo": "iqlusioninc/tmkms", "path": "src/keyring/providers/softsign.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/providers/softsign.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9903e5035398c264434f1f4f686fe694321c029f41f232cc7173dfde8bc92d71"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_ed25519_key\n\nDocumentation:\nLoad an Ed25519 key according to the provided configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn load_ed25519_key(config: &SoftsignConfig) -> Result {\n let key_format = config.key_format.as_ref().cloned().unwrap_or_default();\n\n match key_format {\n KeyFormat::Base64 => key_utils::load_base64_ed25519_key(&config.path),\n KeyFormat::Json => {\n let private_key = PrivValidatorKey::load_json_file(&config.path)\n .map_err(|e| {\n format_err!(\n ConfigError,\n \"couldn't load `{}`: {}\",\n config.path.as_ref().display(),\n e\n )\n })?\n .priv_key;\n\n if let PrivateKey::Ed25519(pk) = private_key {\n Ok(pk.into())\n } else {\n unreachable!(\"unsupported priv_validator.json algorithm\");\n }\n }\n }\n}\n```"}], "func_name": "load_ed25519_key", "docstring": "Load an Ed25519 key according to the provided configuration", "repo": "iqlusioninc/tmkms", "path": "src/keyring/providers/softsign.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/providers/softsign.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c264a20bdb7c15a1863470638bc861a850236734c2ac5090621130ecd0653cb5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_secp256k1_key\n\nDocumentation:\nLoad a secp256k1 (ECDSA) key according to the provided configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn load_secp256k1_key(config: &SoftsignConfig) -> Result {\n if config.key_format.unwrap_or_default() != KeyFormat::Base64 {\n fail!(\n ConfigError,\n \"[[providers.softsign]] account keys must be `base64` encoded\"\n );\n }\n\n let key_bytes = key_utils::load_base64_secret(&config.path)?;\n\n let secret_key = ecdsa::SigningKey::try_from(key_bytes.as_slice()).map_err(|e| {\n format_err!(\n ConfigError,\n \"can't decode account key base64 from {}: {}\",\n config.path.as_ref().display(),\n e\n )\n })?;\n\n Ok(secret_key)\n}\n```"}], "func_name": "load_secp256k1_key", "docstring": "Load a secp256k1 (ECDSA) key according to the provided configuration", "repo": "iqlusioninc/tmkms", "path": "src/keyring/providers/softsign.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/providers/softsign.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d8cb79e1ecd590f5758c806d3c3e07f53711c98d0287eb1829340faf3ce98a4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init\n\nDocumentation:\nCreate hardware-backed YubiHSM signer objects from the given configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn init(\n chain_registry: &mut chain::Registry,\n yubihsm_configs: &[YubihsmConfig],\n) -> Result<(), Error> {\n if yubihsm_configs.is_empty() {\n return Ok(());\n }\n\n // TODO(tarcieri): support for multiple YubiHSMs per host?\n if yubihsm_configs.len() != 1 {\n fail!(\n ConfigError,\n \"expected one [yubihsm.provider] in config, found: {}\",\n yubihsm_configs.len()\n );\n }\n\n for config in &yubihsm_configs[0].keys {\n match config.key_type {\n KeyType::Account => add_account_key(chain_registry, config)?,\n KeyType::Consensus => add_consensus_key(chain_registry, config)?,\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "init", "docstring": "Create hardware-backed YubiHSM signer objects from the given configuration", "repo": "iqlusioninc/tmkms", "path": "src/keyring/providers/yubihsm.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/providers/yubihsm.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea3117b030833817dc25ed5b47ff187b37edea7e7d75b4e24b65b8e30c5fe7d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_account_key\n\nDocumentation:\nAdd an account key (ECDSA/secp256k1) to the keychain\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_account_key(\n chain_registry: &mut chain::Registry,\n config: &SigningKeyConfig,\n) -> Result<(), Error> {\n let signer = yubihsm::ecdsa::Signer::create(crate::yubihsm::client().clone(), config.key)\n .map_err(|_| {\n format_err!(\n InvalidKey,\n \"YubiHSM key ID 0x{:04x} is not a valid ECDSA signing key\",\n config.key\n )\n })?;\n\n let public_key =\n tendermint::PublicKey::from_raw_secp256k1(signer.public_key().compress().as_bytes())\n .expect(\"invalid secp256k1 key\");\n\n let signer = keyring::ecdsa::Signer::new(\n SigningProvider::Yubihsm,\n TendermintKey::AccountKey(public_key),\n Box::new(signer),\n );\n\n for chain_id in &config.chain_ids {\n chain_registry.add_account_key(chain_id, signer.clone())?;\n }\n\n Ok(())\n}\n```"}], "func_name": "add_account_key", "docstring": "Add an account key (ECDSA/secp256k1) to the keychain", "repo": "iqlusioninc/tmkms", "path": "src/keyring/providers/yubihsm.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/providers/yubihsm.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c6e4b68ab47a736331821b95481472fe3c43a2337d147f5007ea738c905776fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_consensus_key\n\nDocumentation:\nAdd a consensus key (Ed25519) to the keychain\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_consensus_key(\n chain_registry: &mut chain::Registry,\n config: &SigningKeyConfig,\n) -> Result<(), Error> {\n let signer = yubihsm::ed25519::Signer::create(crate::yubihsm::client().clone(), config.key)\n .map_err(|_| {\n format_err!(\n InvalidKey,\n \"YubiHSM key ID 0x{:04x} is not a valid Ed25519 signing key\",\n config.key\n )\n })?;\n\n let public_key = tendermint::PublicKey::from_raw_ed25519(signer.public_key().as_bytes())\n .expect(\"invalid Ed25519 key\");\n\n let signer = keyring::ed25519::Signer::new(\n SigningProvider::Yubihsm,\n TendermintKey::ConsensusKey(public_key),\n Box::new(signer),\n );\n\n for chain_id in &config.chain_ids {\n chain_registry.add_consensus_key(chain_id, signer.clone())?;\n }\n\n Ok(())\n}\n```"}], "func_name": "add_consensus_key", "docstring": "Add a consensus key (Ed25519) to the keychain", "repo": "iqlusioninc/tmkms", "path": "src/keyring/providers/yubihsm.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/providers/yubihsm.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a4ea0f6a5e3e3cdfb163099b9e5105e8e44115303f93f2a7bd7cb03d74bf6ce2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nCreate a new Ed25519 signer based on Ledger Nano S - Tendermint Validator app\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connect() -> Result {\n let validator_app = TendermintValidatorApp::connect().map_err(Error::from_source)?;\n let app = Arc::new(Mutex::new(validator_app));\n Ok(Ed25519LedgerTmAppSigner { app })\n }\n```"}], "func_name": "connect", "docstring": "Create a new Ed25519 signer based on Ledger Nano S - Tendermint Validator app", "repo": "iqlusioninc/tmkms", "path": "src/keyring/providers/ledgertm/signer.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/providers/ledgertm/signer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac9ca954a5087ccbe073708c121159500c602aa9851ada31ddd68123a7a94288"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nReturns the public key that corresponds to the Tendermint Validator app connected to this signer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from(signer: &Ed25519LedgerTmAppSigner) -> VerifyingKey {\n let app = signer.app.lock().unwrap();\n VerifyingKey::try_from(app.public_key().unwrap().as_ref())\n .expect(\"invalid Ed25519 public key\")\n }\n```"}], "func_name": "from", "docstring": "Returns the public key that corresponds to the Tendermint Validator app connected to this signer", "repo": "iqlusioninc/tmkms", "path": "src/keyring/providers/ledgertm/signer.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/providers/ledgertm/signer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4583d267fb2ecde716254848edaf4121651aec3cfca7501bb99fc28979cba123"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_sign\n\nDocumentation:\nc: Compute a compact, fixed-sized signature of the given amino/json vote\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn try_sign(&self, msg: &[u8]) -> Result {\n let app = self.app.lock().unwrap();\n let sig = app.sign(msg).map_err(Error::from_source)?;\n Ok(Signature::from(sig))\n }\n```"}], "func_name": "try_sign", "docstring": "c: Compute a compact, fixed-sized signature of the given amino/json vote", "repo": "iqlusioninc/tmkms", "path": "src/keyring/providers/ledgertm/signer.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/src/keyring/providers/ledgertm/signer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f6be8ee5ee4ae56e6870da6024d146f8dea23fb5dc9cfcc677b35c2fe3589f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_tcp\n\nDocumentation:\nSpawn the KMS process and wait for an incoming TCP connection\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_tcp(key_type: &KeyType) -> Self {\n // Generate a random port and a config file\n let port: u16 = rand::thread_rng().gen_range(60000..=65535);\n let config = KmsProcess::create_tcp_config(port, key_type);\n\n // Listen on a random port\n let listener = TcpListener::bind(format!(\"{}:{}\", \"127.0.0.1\", port)).unwrap();\n\n let args = &[\"start\", \"-c\", config.path().to_str().unwrap()];\n let process = Command::new(KMS_EXE_PATH).args(args).spawn().unwrap();\n\n let (socket, _) = listener.accept().unwrap();\n Self {\n process,\n socket: KmsSocket::TCP(socket),\n }\n }\n```"}], "func_name": "create_tcp", "docstring": "Spawn the KMS process and wait for an incoming TCP connection", "repo": "iqlusioninc/tmkms", "path": "tests/integration.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/tests/integration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e785649eadb3d41d2b5234a247be0a0b24ae0ba5488e5fd1fa265c777c25c2ca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_unix\n\nDocumentation:\nSpawn the KMS process and connect to the Unix listener\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_unix(key_type: &KeyType) -> Self {\n // Create a random socket path and a config file\n let mut rng = rand::thread_rng();\n let letter: char = rng.gen_range(b'a'..=b'z') as char;\n let number: u32 = rng.gen_range(0..=999999);\n let socket_path = format!(\"/tmp/tmkms-{letter}{number:06}.sock\");\n let config = KmsProcess::create_unix_config(&socket_path, key_type);\n\n // Start listening for connections via the Unix socket\n let listener = UnixListener::bind(socket_path).unwrap();\n\n // Fire up the KMS process and allow it to connect to our Unix socket\n let args = &[\"start\", \"-c\", config.path().to_str().unwrap()];\n let process = Command::new(KMS_EXE_PATH).args(args).spawn().unwrap();\n\n let (socket, _) = listener.accept().unwrap();\n Self {\n process,\n socket: KmsSocket::UNIX(socket),\n }\n }\n```"}], "func_name": "create_unix", "docstring": "Spawn the KMS process and connect to the Unix listener", "repo": "iqlusioninc/tmkms", "path": "tests/integration.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/tests/integration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "269b3f27ca5f6996fe079fa27f0cd604f3277efbd53301468a1af5195705db6b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_tcp_config\n\nDocumentation:\nCreate a config file for a TCP KMS and return its path\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn create_tcp_config(port: u16, key_type: &KeyType) -> NamedTempFile {\n let mut config_file = NamedTempFile::new().unwrap();\n let pub_key = test_ed25519_keypair().verifying_key();\n let peer_id = secret_connection::PublicKey::from(pub_key).peer_id();\n\n writeln!(\n config_file,\n r#\"\n [[chain]]\n id = \"test_chain_id\"\n key_format = {{ type = \"bech32\", account_key_prefix = \"cosmospub\", consensus_key_prefix = \"cosmosvalconspub\" }}\n\n [[validator]]\n addr = \"tcp://{}@127.0.0.1:{}\"\n chain_id = \"test_chain_id\"\n max_height = \"500000\"\n reconnect = false\n secret_key = \"tests/support/secret_connection.key\"\n protocol_version = \"v0.34\"\n\n [[providers.softsign]]\n chain_ids = [\"test_chain_id\"]\n key_format = \"base64\"\n path = \"{}\"\n key_type = \"{}\"\n \"#,\n &peer_id.to_string(), port, signing_key_path(key_type), key_type\n )\n .unwrap();\n\n config_file\n }\n```"}], "func_name": "create_tcp_config", "docstring": "Create a config file for a TCP KMS and return its path", "repo": "iqlusioninc/tmkms", "path": "tests/integration.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/tests/integration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "457a59febef863f3598b0930342d64dacfdf6f1a86e3e4be40ed2639e9b17dae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_unix_config\n\nDocumentation:\nCreate a config file for a UNIX KMS and return its path\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn create_unix_config(socket_path: &str, key_type: &KeyType) -> NamedTempFile {\n let mut config_file = NamedTempFile::new().unwrap();\n let key_path = signing_key_path(key_type);\n writeln!(\n config_file,\n r#\"\n [[chain]]\n id = \"test_chain_id\"\n key_format = {{ type = \"bech32\", account_key_prefix = \"cosmospub\", consensus_key_prefix = \"cosmosvalconspub\" }}\n\n [[validator]]\n addr = \"unix://{socket_path}\"\n chain_id = \"test_chain_id\"\n max_height = \"500000\"\n protocol_version = \"v0.34\"\n\n [[providers.softsign]]\n chain_ids = [\"test_chain_id\"]\n key_format = \"base64\"\n path = \"{key_path}\"\n key_type = \"{key_type}\"\n \"#\n )\n .unwrap();\n\n config_file\n }\n```"}], "func_name": "create_unix_config", "docstring": "Create a config file for a UNIX KMS and return its path", "repo": "iqlusioninc/tmkms", "path": "tests/integration.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/tests/integration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8ad022d341711f4a583c6e3a285bb633d5cbe8210a0a6d2321373e28a83bedf8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_actual_len\n\nDocumentation:\nExtract the actual length of an amino message\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn extract_actual_len(buf: &[u8]) -> Result {\n let mut buff = Cursor::new(buf);\n let actual_len = prost::encoding::decode_varint(&mut buff)?;\n if actual_len == 0 {\n return Ok(1);\n }\n Ok(actual_len + (prost::encoding::encoded_len_varint(actual_len) as u64))\n}\n```"}], "func_name": "extract_actual_len", "docstring": "Extract the actual length of an amino message", "repo": "iqlusioninc/tmkms", "path": "tests/integration.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/tests/integration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc0040b5bbf8fb27dd93a74b2a57c4408e94a6ab1d781acee34b7a6cc7219a46"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_buffer_underflow_request\n\nDocumentation:\nOpens a binary file with big proposal (> 1024 bytes, from Sei network)\nand sends via protocol tester\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn send_buffer_underflow_request(pt: &mut ProtocolTester) {\n let mut file = File::open(\"tests/support/buffer-underflow-proposal.bin\").unwrap();\n let mut buf = Vec::::new();\n file.read_to_end(&mut buf).unwrap();\n pt.write_all(&buf).unwrap();\n}\n```"}], "func_name": "send_buffer_underflow_request", "docstring": "Opens a binary file with big proposal (> 1024 bytes, from Sei network)\nand sends via protocol tester", "repo": "iqlusioninc/tmkms", "path": "tests/integration.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/tests/integration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "22e2eec38e49958dec6a9d5bf6a9649df78b9e4e6e76d24ac5200b2d9e7edc77"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_response\n\nDocumentation:\nRead the response as a Protobuf message\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_response(pt: &mut ProtocolTester) -> proto::privval::message::Sum {\n let mut resp_buf = vec![0u8; 4096];\n pt.read(&mut resp_buf).unwrap();\n\n let actual_len = extract_actual_len(&resp_buf).unwrap();\n let mut resp_bytes = vec![0u8; actual_len as usize];\n resp_bytes.copy_from_slice(&resp_buf[..actual_len as usize]);\n\n let message = proto::privval::Message::decode_length_delimited(resp_bytes.as_ref()).unwrap();\n message.sum.expect(\"no sum field in message\")\n}\n```"}], "func_name": "read_response", "docstring": "Read the response as a Protobuf message", "repo": "iqlusioninc/tmkms", "path": "tests/integration.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/tests/integration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "83503975a3805b56aaeb7dbeecf4fd32e52fa19284787dcd05efea2caa41d7fc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRun the `tmkms` CLI command with the given arguments\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn run(args: I) -> Output\nwhere\n I: IntoIterator,\n S: AsRef,\n{\n Command::new(KMS_EXE_PATH).args(args).output().unwrap()\n}\n```"}], "func_name": "run", "docstring": "Run the `tmkms` CLI command with the given arguments", "repo": "iqlusioninc/tmkms", "path": "tests/cli/mod.rs", "url": "https://github.com/iqlusioninc/tmkms/blob/master/tests/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a4b7afdf176dc344dd448da576f496825338e4c1d50f4764b01436ffb61a741c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_tools\n\nDocumentation:\nLoad tools that have a configured version.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn load_tools(&self) -> Result, ProtoLoaderError> {\n self.load_tools_with_options(LoadToolOptions::default())\n .await\n }\n```"}], "func_name": "load_tools", "docstring": "Load tools that have a configured version.", "repo": "moonrepo/proto", "path": "crates/cli/src/session.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/cli/src/session.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9e33f953b1c492f81d0797a0acfe003a90138bccdeeeff5b4eaf9ab03d89579f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_all_tools\n\nDocumentation:\nLoad all tools, even those not configured with a version.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn load_all_tools(&self) -> Result, ProtoLoaderError> {\n self.load_all_tools_with_options(LoadToolOptions::default())\n .await\n }\n```"}], "func_name": "load_all_tools", "docstring": "Load all tools, even those not configured with a version.", "repo": "moonrepo/proto", "path": "crates/cli/src/session.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/cli/src/session.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82f8efcebef3cc98283deb1e8f4d841144c248d508fea3daf3b67552300727d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: path_contains\n\nDocumentation:\nChecks whether the windows path contains the given entry.\nNote this does not guarantee any match isn't just a substring of a longer entry,\ni.e. the entry \"/proto\" will match \"/proto/bin\".\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn path_contains(path: &[u16], entry: &[u16]) -> bool {\n path.windows(entry.len()).any(|path| path == entry)\n}\n```"}], "func_name": "path_contains", "docstring": "Checks whether the windows path contains the given entry.\nNote this does not guarantee any match isn't just a substring of a longer entry,\ni.e. the entry \"/proto\" will match \"/proto/bin\".", "repo": "moonrepo/proto", "path": "crates/cli/src/commands/setup/windows.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/cli/src/commands/setup/windows.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "688387bd19a555b125553ff5d6a829d60d5ea03e5617c2ffc1b5226f92fb2ae7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_winreg_bytes\n\nDocumentation:\nConvert a slice of UCS-2 chars to a null-terminated UCS-2 string in bytes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_winreg_bytes(val: &[u16]) -> Vec {\n let mut v = val.to_owned();\n v.push(0);\n unsafe { std::slice::from_raw_parts(v.as_ptr().cast::(), v.len() * 2).to_vec() }\n }\n```"}], "func_name": "to_winreg_bytes", "docstring": "Convert a slice of UCS-2 chars to a null-terminated UCS-2 string in bytes", "repo": "moonrepo/proto", "path": "crates/cli/src/commands/setup/windows.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/cli/src/commands/setup/windows.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bbd1b01625ab96c24ac289628ac0d7f9d213ad38aab5eeb125b2c1001f1cab14"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_winreg_value\n\nDocumentation:\nThis is used to decode the value of HKCU\\Environment\\PATH. If that key is\nnot REG_SZ | REG_EXPAND_SZ then this returns None. The winreg library itself\ndoes a lossy unicode conversion.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_winreg_value(val: &winreg::RegValue) -> Option> {\n use std::slice;\n\n match val.vtype {\n RegType::REG_SZ | RegType::REG_EXPAND_SZ => {\n // Copied from winreg\n let mut words = unsafe {\n #[allow(clippy::cast_ptr_alignment)]\n slice::from_raw_parts(val.bytes.as_ptr().cast::(), val.bytes.len() / 2)\n .to_owned()\n };\n while words.last() == Some(&0) {\n words.pop();\n }\n Some(words)\n }\n _ => None,\n }\n }\n```"}], "func_name": "from_winreg_value", "docstring": "This is used to decode the value of HKCU\\Environment\\PATH. If that key is\nnot REG_SZ | REG_EXPAND_SZ then this returns None. The winreg library itself\ndoes a lossy unicode conversion.", "repo": "moonrepo/proto", "path": "crates/cli/src/commands/setup/windows.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/cli/src/commands/setup/windows.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27303f4b7257c928c13346db042a5cd42dcb6ebbf71d49ef988ddb46b6d35cbb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_env_var_prefix\n\nDocumentation:\nReturn the prefix for environment variable names.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_env_var_prefix(&self) -> String {\n format!(\"PROTO_{}\", self.id.to_uppercase().replace('-', \"_\"))\n }\n```"}], "func_name": "get_env_var_prefix", "docstring": "Return the prefix for environment variable names.", "repo": "moonrepo/proto", "path": "crates/core/src/tool.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/core/src/tool.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a7a34a9b96dfcf58e4d55a4ff8962390999a67dcfe26be8f5cfd988b61aa861b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_temp_dir\n\nDocumentation:\nReturn an absolute path to a temp directory solely for this tool.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_temp_dir(&self) -> PathBuf {\n self.inventory\n .temp_dir\n .join(self.get_resolved_version().to_string())\n }\n```"}], "func_name": "get_temp_dir", "docstring": "Return an absolute path to a temp directory solely for this tool.", "repo": "moonrepo/proto", "path": "crates/core/src/tool.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/core/src/tool.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "58bf07cfc3d6193fb6c23c30fc02ffc9bdba667031110c64cd81f7c836387958"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_backend_plugin\n\nDocumentation:\nReturn true if this tool instance is a backend plugin.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn is_backend_plugin(&self) -> bool {\n if self.plugin.has_func(\"register_backend\").await {\n Backend::variants()\n .iter()\n .any(|var| var.to_string() == self.id.as_str())\n } else {\n false\n }\n }\n```"}], "func_name": "is_backend_plugin", "docstring": "Return true if this tool instance is a backend plugin.", "repo": "moonrepo/proto", "path": "crates/core/src/tool.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/core/src/tool.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a0e4bb96157def175a29d216fee5e5bee5cfafa017fe24b9bf8b85e061877403"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_version\n\nDocumentation:\nExplicitly set the version to use.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_version(&mut self, version: VersionSpec) {\n self.product = self.inventory.create_product(&version);\n self.version = Some(version);\n }\n```"}], "func_name": "set_version", "docstring": "Explicitly set the version to use.", "repo": "moonrepo/proto", "path": "crates/core/src/tool.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/core/src/tool.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a521a8240e3997c5bccc50af5c2c363f83d5d8b27b16d8e3e907e14f219a298d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_context\n\nDocumentation:\nReturn contextual information to pass to WASM plugin functions.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_context(&self) -> ToolContext {\n ToolContext {\n proto_version: Some(get_proto_version().to_owned()),\n temp_dir: self.to_virtual_path(self.get_temp_dir()),\n tool_dir: self.to_virtual_path(self.get_product_dir()),\n version: self.get_resolved_version(),\n }\n }\n```"}], "func_name": "create_context", "docstring": "Return contextual information to pass to WASM plugin functions.", "repo": "moonrepo/proto", "path": "crates/core/src/tool.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/core/src/tool.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "77bc1a4f56cda605013e0cfbf866bfc7bc494c49854cda33cd92bc87ef189539"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_unresolved_context\n\nDocumentation:\nReturn contextual information to pass to WASM plugin functions,\nrepresenting an unresolved state, which has no version or tool\ndata.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_unresolved_context(&self) -> ToolUnresolvedContext {\n ToolUnresolvedContext {\n proto_version: Some(get_proto_version().to_owned()),\n temp_dir: self.to_virtual_path(&self.inventory.temp_dir),\n // version: self.version.clone(),\n // TODO: temporary until 3rd-party plugins update their PDKs\n tool_dir: self.to_virtual_path(&self.proto.store.inventory_dir),\n version: self\n .version\n .clone()\n .or_else(|| Some(VersionSpec::Alias(\"latest\".into()))),\n }\n }\n```"}], "func_name": "create_unresolved_context", "docstring": "Return contextual information to pass to WASM plugin functions,\nrepresenting an unresolved state, which has no version or tool\ndata.", "repo": "moonrepo/proto", "path": "crates/core/src/tool.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/core/src/tool.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7fa97cb838728c881dd3fbaf3fef2559b71963ea07c30298e8d947048ef8674e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_installed\n\nDocumentation:\nReturn true if the tool has been installed. This is less accurate than `is_setup`,\nas it only checks for the existence of the inventory directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_installed(&self) -> bool {\n let dir = self.get_product_dir();\n\n self.version.as_ref().is_some_and(|v| {\n !v.is_latest() && self.inventory.manifest.installed_versions.contains(v)\n }) && dir.exists()\n && !fs::is_dir_locked(dir)\n }\n```"}], "func_name": "is_installed", "docstring": "Return true if the tool has been installed. This is less accurate than `is_setup`,\nas it only checks for the existence of the inventory directory.", "repo": "moonrepo/proto", "path": "crates/core/src/flow/install.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/core/src/flow/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e173c57c54c30accb0addee9f1d275034b1c70832755cd06cd6bd6d78d820abb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve_primary_exe_location\n\nDocumentation:\nReturn location information for the primary executable within the tool directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn resolve_primary_exe_location(\n &self,\n ) -> Result, ProtoLocateError> {\n let output = self.call_locate_executables().await?;\n\n for (name, config) in output.exes {\n if config.primary {\n if let Some(exe_path) = &config.exe_path {\n return Ok(Some(ExecutableLocation {\n path: self\n .get_product_dir()\n .join(normalize_path_separators(exe_path)),\n name,\n config,\n version: None,\n }));\n }\n }\n }\n\n Ok(None)\n }\n```"}], "func_name": "resolve_primary_exe_location", "docstring": "Return location information for the primary executable within the tool directory.", "repo": "moonrepo/proto", "path": "crates/core/src/flow/locate.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/core/src/flow/locate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f8a1147f6a1100c5ea773a97c3357a955af22ee82ac40410c61b3855261e2088"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve_secondary_exe_locations\n\nDocumentation:\nReturn location information for all secondary executables within the tool directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn resolve_secondary_exe_locations(\n &self,\n ) -> Result, ProtoLocateError> {\n let output = self.call_locate_executables().await?;\n let mut locations = vec![];\n\n for (name, config) in output.exes {\n if config.primary {\n continue;\n }\n\n if let Some(exe_path) = &config.exe_path {\n locations.push(ExecutableLocation {\n path: self\n .get_product_dir()\n .join(normalize_path_separators(exe_path)),\n name,\n config,\n version: None,\n });\n }\n }\n\n Ok(locations)\n }\n```"}], "func_name": "resolve_secondary_exe_locations", "docstring": "Return location information for all secondary executables within the tool directory.", "repo": "moonrepo/proto", "path": "crates/core/src/flow/locate.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/core/src/flow/locate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a797a1be3d1c1cfe8ad61b00ef1be596bcbee8553a01ff4610cf24c417b0c0f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve_bin_locations\n\nDocumentation:\nReturn a list of all binaries that get created in `~/.proto/bin`.\nThe list will contain the executable config, and an absolute path\nto the binaries final location.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn resolve_bin_locations(\n &mut self,\n include_all_versions: bool,\n ) -> Result, ProtoLocateError> {\n self.resolve_bin_locations_with_manager(\n BinManager::from_manifest(&self.inventory.manifest),\n include_all_versions,\n )\n .await\n }\n```"}], "func_name": "resolve_bin_locations", "docstring": "Return a list of all binaries that get created in `~/.proto/bin`.\nThe list will contain the executable config, and an absolute path\nto the binaries final location.", "repo": "moonrepo/proto", "path": "crates/core/src/flow/locate.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/core/src/flow/locate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aae078c6a7f5f05886abe7f8a5c5f5491017cab3999edd1b39b974b3f966285a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve_shim_locations\n\nDocumentation:\nReturn a list of all shims that get created in `~/.proto/shims`.\nThe list will contain the executable config, and an absolute path\nto the shims final location.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn resolve_shim_locations(\n &self,\n ) -> Result, ProtoLocateError> {\n let output = self.call_locate_executables().await?;\n let mut locations = vec![];\n\n let mut add = |name: String, config: ExecutableConfig| {\n if !config.no_shim {\n locations.push(ExecutableLocation {\n path: self.proto.store.shims_dir.join(get_shim_file_name(&name)),\n name,\n config,\n version: None,\n });\n }\n };\n\n if !output.exes.is_empty() {\n for (name, config) in output.exes {\n add(name, config);\n }\n }\n\n Ok(locations)\n }\n```"}], "func_name": "resolve_shim_locations", "docstring": "Return a list of all shims that get created in `~/.proto/shims`.\nThe list will contain the executable config, and an absolute path\nto the shims final location.", "repo": "moonrepo/proto", "path": "crates/core/src/flow/locate.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/core/src/flow/locate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ab1b3c56eb44f1f4fbc10cdc76053a892814d658ce6ae8a28cc8f243a0aa9c23"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_exes_dir\n\nDocumentation:\nReturn an absolute path to the primary executables directory (first in the list),\nafter it has been located.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_exes_dir(&self) -> Option<&Path> {\n self.exes_dirs.first().map(|dir| dir.as_ref())\n }\n```"}], "func_name": "get_exes_dir", "docstring": "Return an absolute path to the primary executables directory (first in the list),\nafter it has been located.", "repo": "moonrepo/proto", "path": "crates/core/src/flow/locate.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/core/src/flow/locate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6f29aead03093ec5e64a60016eac6fcf80b2cf47648d4cb1b0a6b970e8da6ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve_backend\n\nDocumentation:\nGiven a custom backend, resolve and register it to acquire necessary files.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn resolve_backend(\n &mut self,\n backend: Option,\n ) -> Result<(), ProtoResolveError> {\n self.backend = backend;\n self.register_backend().await?;\n\n Ok(())\n }\n```"}], "func_name": "resolve_backend", "docstring": "Given a custom backend, resolve and register it to acquire necessary files.", "repo": "moonrepo/proto", "path": "crates/core/src/flow/resolve.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/core/src/flow/resolve.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18c232a0ffc09e813c6bc6e6955238ee55ca753209ad1ce729c922fa10d959f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_supported_os_and_arch\n\nDocumentation:\nValidate the current host OS and architecture against the\nsupported list of target permutations.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check_supported_os_and_arch(\n tool: &str,\n env: &HostEnvironment,\n permutations: FxHashMap>,\n) -> AnyResult<()> {\n if let Some(archs) = permutations.get(&env.os) {\n if !archs.contains(&env.arch) {\n return Err(PluginError::UnsupportedTarget {\n tool: tool.to_owned(),\n arch: env.arch.to_string(),\n os: env.os.to_string(),\n }\n .into());\n }\n } else {\n return Err(PluginError::UnsupportedOS {\n tool: tool.to_owned(),\n os: env.os.to_string(),\n }\n .into());\n }\n\n Ok(())\n}\n```"}], "func_name": "check_supported_os_and_arch", "docstring": "Validate the current host OS and architecture against the\nsupported list of target permutations.", "repo": "moonrepo/proto", "path": "crates/pdk/src/helpers.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/pdk/src/helpers.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7b7f8830c2c92b7a9e1373ed67637b59971b037a73f120ca0334ad29623f667e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_target_triple\n\nDocumentation:\nReturn a Rust target triple for the current host OS and architecture.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_target_triple(env: &HostEnvironment, name: &str) -> Result {\n match env.os {\n HostOS::Linux => Ok(format!(\n \"{}-unknown-linux-{}\",\n env.arch.to_rust_arch(),\n if matches!(env.libc, HostLibc::Musl) {\n \"musl\"\n } else {\n \"gnu\"\n }\n )),\n HostOS::MacOS => Ok(format!(\"{}-apple-darwin\", env.arch.to_rust_arch())),\n HostOS::Windows => Ok(format!(\"{}-pc-windows-msvc\", env.arch.to_rust_arch())),\n _ => Err(PluginError::UnsupportedTarget {\n tool: name.into(),\n arch: env.arch.to_string(),\n os: env.os.to_string(),\n }),\n }\n}\n```"}], "func_name": "get_target_triple", "docstring": "Return a Rust target triple for the current host OS and architecture.", "repo": "moonrepo/proto", "path": "crates/pdk/src/helpers.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/pdk/src/helpers.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c6a90b769af6d04d8f301e66266dd92f9c054b63fae4ab7066096d6af8857130"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_tool_config\n\nDocumentation:\nGet proto tool configuration that was configured in a `.prototools` file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_tool_config() -> AnyResult {\n let config: T = if let Some(value) = config::get(\"proto_tool_config\")? {\n json::from_str(&value)?\n } else {\n T::default()\n };\n\n Ok(config)\n}\n```"}], "func_name": "get_tool_config", "docstring": "Get proto tool configuration that was configured in a `.prototools` file.", "repo": "moonrepo/proto", "path": "crates/pdk/src/helpers.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/pdk/src/helpers.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f278d75451ff01bcba3bcbab6a5c5b0e9b1f71656cc2d60425871b0267eb78f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new command with the binary and arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new, V: AsRef>(bin: &str, args: I) -> Self {\n Self {\n bin: bin.to_owned(),\n builder: false,\n args: args\n .into_iter()\n .map(|arg| arg.as_ref().to_owned())\n .collect(),\n env: FxHashMap::default(),\n cwd: None,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new command with the binary and arguments.", "repo": "moonrepo/proto", "path": "crates/pdk-api/src/api/build.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/pdk-api/src/api/build.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa84764cffcdc937242e255cfb32f74643f79274269f75a2ba30eedff61a052a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_builder\n\nDocumentation:\nCreate a new command that executes a binary from a builder with the arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_builder, V: AsRef>(id: &str, args: I) -> Self {\n let mut cmd = Self::new(id, args);\n cmd.builder = true;\n cmd\n }\n```"}], "func_name": "with_builder", "docstring": "Create a new command that executes a binary from a builder with the arguments.", "repo": "moonrepo/proto", "path": "crates/pdk-api/src/api/build.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/pdk-api/src/api/build.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "84018013402451196ed16251908a704fcbde8f9e5951a71e6f5efb4c423a55a3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nCreate the output from a list of strings that'll be parsed as versions.\nThe latest version will be the highest version number.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from(values: Vec) -> Result {\n let mut versions = vec![];\n\n for value in values {\n versions.push(VersionSpec::parse(&value)?);\n }\n\n Ok(Self::from_versions(versions))\n }\n```"}], "func_name": "from", "docstring": "Create the output from a list of strings that'll be parsed as versions.\nThe latest version will be the highest version number.", "repo": "moonrepo/proto", "path": "crates/pdk-api/src/api/mod.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/pdk-api/src/api/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "03294d65b352269cdf517ec800b9a9c3b86183de6c6348f59edc1c0443547908"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_versions\n\nDocumentation:\nCreate the output from a list of version specifications.\nThe latest version will be the highest version number.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_versions(versions: Vec) -> Self {\n let mut output = LoadVersionsOutput::default();\n let mut latest = Version::new(0, 0, 0);\n let mut calver = false;\n\n for version in versions {\n if let Some(inner) = version.as_version() {\n if inner.pre.is_empty() && inner.build.is_empty() && inner > &latest {\n inner.clone_into(&mut latest);\n calver = matches!(version, VersionSpec::Calendar(_));\n }\n }\n\n output.versions.push(version);\n }\n\n output.latest = Some(if calver {\n UnresolvedVersionSpec::Calendar(CalVer(latest))\n } else {\n UnresolvedVersionSpec::Semantic(SemVer(latest))\n });\n\n output\n .aliases\n .insert(\"latest\".into(), output.latest.clone().unwrap());\n\n output\n }\n```"}], "func_name": "from_versions", "docstring": "Create the output from a list of version specifications.\nThe latest version will be the highest version number.", "repo": "moonrepo/proto", "path": "crates/pdk-api/src/api/mod.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/pdk-api/src/api/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "60ed55089c3e0628163356d87548ea5596a884fc487892b14b8dce9491a73ec0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_package_names\n\nDocumentation:\nGet a list of package names for the provided OS and package manager.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_package_names(&self, pm: &SystemPackageManager) -> Result, Error> {\n let mut names = self\n .get_package_names_and_versions(pm)?\n .into_keys()\n .collect::>();\n\n names.sort();\n\n Ok(names)\n }\n```"}], "func_name": "get_package_names", "docstring": "Get a list of package names for the provided OS and package manager.", "repo": "moonrepo/proto", "path": "crates/system-env/src/deps.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/deps.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44b782a193b4a608130cd09f41f58d0c0d2bd1486b441ede3d895d17fa780d1e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_package_names_and_versions\n\nDocumentation:\nGet a list of package names and optional versions for the provided OS and package manager.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_package_names_and_versions(\n &self,\n pm: &SystemPackageManager,\n ) -> Result>, Error> {\n let names = match &self.dep {\n DependencyName::Single(name) => vec![name.to_owned()],\n DependencyName::SingleMap(map) => map\n .get(pm)\n .or_else(|| map.get(&SystemPackageManager::All))\n .map(|name| vec![name.to_owned()])\n .ok_or(Error::MissingName)?,\n DependencyName::Multiple(list) => list.clone(),\n DependencyName::MultipleMap(map) => map\n .get(pm)\n .or_else(|| map.get(&SystemPackageManager::All))\n .cloned()\n .ok_or(Error::MissingName)?,\n };\n\n Ok(names\n .into_iter()\n .map(|name| {\n if name.contains('@') {\n name.split_once('@')\n .map(|(a, b)| (a.to_owned(), Some(b.to_owned())))\n .unwrap()\n } else {\n (name, self.version.clone())\n }\n })\n .collect())\n }\n```"}], "func_name": "get_package_names_and_versions", "docstring": "Get a list of package names and optional versions for the provided OS and package manager.", "repo": "moonrepo/proto", "path": "crates/system-env/src/deps.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/deps.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1d9439a2499b273c6a591a80d1462e1c46c7685793fc6788e0510b245002ca05"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_name\n\nDocumentation:\nReturn true if the current config has the provided package name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn has_name(&self, pm: &SystemPackageManager, name: &str) -> bool {\n self.get_package_names(pm)\n .map(|names| names.iter().any(|n| n == name))\n .unwrap_or(false)\n }\n```"}], "func_name": "has_name", "docstring": "Return true if the current config has the provided package name.", "repo": "moonrepo/proto", "path": "crates/system-env/src/deps.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/deps.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4095350f0f5b748b8e16f2a230bfa09c3cfd158273b620a75a5abf46e93a0010"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: for_arch\n\nDocumentation:\nCreate a single dependency by name for the target architecture.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn for_arch(arch: SystemArch, name: impl AsRef) -> SystemDependency {\n SystemDependency::Config(Box::new(DependencyConfig {\n arch: Some(arch),\n dep: DependencyName::Single(name.as_ref().into()),\n ..DependencyConfig::default()\n }))\n }\n```"}], "func_name": "for_arch", "docstring": "Create a single dependency by name for the target architecture.", "repo": "moonrepo/proto", "path": "crates/system-env/src/deps.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/deps.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b6044f0eb9d9a983de261e70d4e2f346d2e6346833367d34a450f80bc3525fd9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: for_os\n\nDocumentation:\nCreate a single dependency by name for the target operating system.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn for_os(os: SystemOS, name: impl AsRef) -> SystemDependency {\n SystemDependency::Config(Box::new(DependencyConfig {\n dep: DependencyName::Single(name.as_ref().into()),\n os: Some(os),\n ..DependencyConfig::default()\n }))\n }\n```"}], "func_name": "for_os", "docstring": "Create a single dependency by name for the target operating system.", "repo": "moonrepo/proto", "path": "crates/system-env/src/deps.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/deps.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0def8810c03a4d9897fdc7bde1e31e057c9a1ed5f45f922afed3fea1c7af774"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: for_os_arch\n\nDocumentation:\nCreate a single dependency by name for the target operating system and architecture.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn for_os_arch(os: SystemOS, arch: SystemArch, name: impl AsRef) -> SystemDependency {\n SystemDependency::Config(Box::new(DependencyConfig {\n arch: Some(arch),\n dep: DependencyName::Single(name.as_ref().into()),\n os: Some(os),\n ..DependencyConfig::default()\n }))\n }\n```"}], "func_name": "for_os_arch", "docstring": "Create a single dependency by name for the target operating system and architecture.", "repo": "moonrepo/proto", "path": "crates/system-env/src/deps.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/deps.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a9a307d7e015616b305feb9fe5d5e44c0947ed308f6a045c456f0ab39337b535"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: for_pm\n\nDocumentation:\nCreate multiple dependencies by name for the target package manager.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn for_pm(pm: SystemPackageManager, names: I) -> SystemDependency\n where\n I: IntoIterator,\n V: AsRef,\n {\n SystemDependency::Config(Box::new(DependencyConfig {\n dep: DependencyName::Multiple(\n names.into_iter().map(|n| n.as_ref().to_owned()).collect(),\n ),\n manager: Some(pm),\n ..DependencyConfig::default()\n }))\n }\n```"}], "func_name": "for_pm", "docstring": "Create multiple dependencies by name for the target package manager.", "repo": "moonrepo/proto", "path": "crates/system-env/src/deps.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/deps.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7d24a259219297e5fccebc8dec355ce8dbbecbe96bb827380c116a120894974d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_config\n\nDocumentation:\nConvert and expand to a dependency configuration.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_config(&self) -> DependencyConfig {\n match self {\n Self::Name(name) => DependencyConfig {\n dep: DependencyName::Single(name.to_owned()),\n ..DependencyConfig::default()\n },\n Self::NameMap(map) => DependencyConfig {\n dep: DependencyName::SingleMap(map.to_owned()),\n ..DependencyConfig::default()\n },\n Self::Names(names) => DependencyConfig {\n dep: DependencyName::Multiple(names.to_owned()),\n ..DependencyConfig::default()\n },\n Self::NamesMap(map) => DependencyConfig {\n dep: DependencyName::MultipleMap(map.to_owned()),\n ..DependencyConfig::default()\n },\n Self::Config(config) => (**config).to_owned(),\n }\n }\n```"}], "func_name": "to_config", "docstring": "Convert and expand to a dependency configuration.", "repo": "moonrepo/proto", "path": "crates/system-env/src/deps.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/deps.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "91686147c12591d28478ca2181872980a97c73b5d97f07d3a2c3f8d2a27077ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_config\n\nDocumentation:\nConvert to the `Config` variant and allow the [`DependencyConfig`]\nto be mutated through a callback function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_config(self, mut op: impl FnMut(&mut DependencyConfig)) -> SystemDependency {\n let mut config = match self {\n Self::Config(config) => *config,\n _ => self.to_config(),\n };\n\n op(&mut config);\n\n Self::Config(Box::new(config))\n }\n```"}], "func_name": "with_config", "docstring": "Convert to the `Config` variant and allow the [`DependencyConfig`]\nto be mutated through a callback function.", "repo": "moonrepo/proto", "path": "crates/system-env/src/deps.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/deps.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e8703f87f8da43a32a4e3c23d13a20dd0e454a1facd84c9a1a679fcbbd9e7de7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_env\n\nDocumentation:\nReturn an instance derived from [`std::env::costs::ARCH`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_env() -> SystemArch {\n serde_json::from_value(Value::String(consts::ARCH.to_owned()))\n .expect(\"Unknown architecture!\")\n }\n```"}], "func_name": "from_env", "docstring": "Return an instance derived from [`std::env::costs::ARCH`].", "repo": "moonrepo/proto", "path": "crates/system-env/src/env.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "19ed16eb8248e9393002722660ced9107e4e5fc1733c77292cbd0560065cfa64"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_rust_arch\n\nDocumentation:\nConvert to a [`std::env::costs::ARCH`] compatible string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_rust_arch(&self) -> String {\n match self {\n Self::X64 => \"x86_64\".into(),\n Self::Arm64 => \"aarch64\".into(),\n Self::LongArm64 => \"loongarch64\".into(),\n _ => self.to_string(),\n }\n }\n```"}], "func_name": "to_rust_arch", "docstring": "Convert to a [`std::env::costs::ARCH`] compatible string.", "repo": "moonrepo/proto", "path": "crates/system-env/src/env.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "67a4e73e6682c5439986629599f776e17f400ec0df1ace190551da42127c2c55"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_env\n\nDocumentation:\nReturn an instance derived from [`std::env::costs::OS`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_env() -> SystemOS {\n serde_json::from_value(Value::String(consts::OS.to_owned()))\n .expect(\"Unknown operating system!\")\n }\n```"}], "func_name": "from_env", "docstring": "Return an instance derived from [`std::env::costs::OS`].", "repo": "moonrepo/proto", "path": "crates/system-env/src/env.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a6a121be7ec4394d8e566887193167488f08c7230b0fa1d2f347cdd9ea6479f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: for_native\n\nDocumentation:\nReturn either a Unix or Windows value based on the current native system.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn for_native<'value, T: AsRef + ?Sized>(\n &self,\n unix: &'value T,\n windows: &'value T,\n ) -> &'value str {\n if self.is_windows() {\n windows.as_ref()\n } else {\n unix.as_ref()\n }\n }\n```"}], "func_name": "for_native", "docstring": "Return either a Unix or Windows value based on the current native system.", "repo": "moonrepo/proto", "path": "crates/system-env/src/env.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80c3f7bfc0a1094d276cb976bc38aaed2049432773fa24a6a09866a82dc92628"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_exe_name\n\nDocumentation:\nReturn the provided name as a system formatted file name for executables.\nOn Windows this will append an \".exe\" extension. On Unix, no extension.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_exe_name(&self, name: impl AsRef) -> String {\n self.get_file_name(name, \"exe\")\n }\n```"}], "func_name": "get_exe_name", "docstring": "Return the provided name as a system formatted file name for executables.\nOn Windows this will append an \".exe\" extension. On Unix, no extension.", "repo": "moonrepo/proto", "path": "crates/system-env/src/env.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b68a61754339c59061c0b0c277a416043b7bcc39eb287070956993c12f10de9e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_file_name\n\nDocumentation:\nReturn the provided file name formatted with the extension (without dot)\nwhen on Windows. On Unix, returns the name as-is.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_file_name(&self, name: impl AsRef, windows_ext: impl AsRef) -> String {\n let name = name.as_ref();\n let ext = windows_ext.as_ref();\n\n if self.is_windows() && !name.ends_with(ext) {\n format!(\"{}.{ext}\", name)\n } else {\n name.to_owned()\n }\n }\n```"}], "func_name": "get_file_name", "docstring": "Return the provided file name formatted with the extension (without dot)\nwhen on Windows. On Unix, returns the name as-is.", "repo": "moonrepo/proto", "path": "crates/system-env/src/env.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f364fe0e6cc975ef29d8ebd8219549d89d856867a6a514af0ee235a48d0cf40"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_unix\n\nDocumentation:\nReturn true if a Unix based OS.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_unix(&self) -> bool {\n self.is_bsd() || matches!(self, Self::Linux | Self::MacOS)\n }\n```"}], "func_name": "is_unix", "docstring": "Return true if a Unix based OS.", "repo": "moonrepo/proto", "path": "crates/system-env/src/env.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "39a0c024f6df14fe2ee343174e341cb8530d0815bc9d6b7ceb4d307469e17078"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: detect\n\nDocumentation:\nDetect the libc type from the current system environment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn detect(os: SystemOS) -> Self {\n match os {\n SystemOS::IOS | SystemOS::MacOS => Self::Gnu,\n SystemOS::Windows => Self::Unknown,\n _ => {\n if Self::is_musl() {\n Self::Musl\n } else {\n Self::Gnu\n }\n }\n }\n }\n```"}], "func_name": "detect", "docstring": "Detect the libc type from the current system environment.", "repo": "moonrepo/proto", "path": "crates/system-env/src/env.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6d78796e89a30a4a7a19e0528f0ad2d0f1f6cdf8e8a1e78adb0091eb5340497c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_musl\n\nDocumentation:\nCheck if musl is available on the current machine, by running the\n`ldd --version` command, or the `uname` command. This will return false\non systems that have neither of those commands.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_musl() -> bool {\n let mut command = if let Some(ldd_path) = find_command_on_path(\"ldd\") {\n let mut cmd = Command::new(ldd_path);\n cmd.arg(\"--version\");\n cmd\n } else if let Some(uname_path) = find_command_on_path(\"uname\") {\n Command::new(uname_path)\n } else {\n return false;\n };\n\n if let Ok(result) = command.output() {\n let output = if result.status.success() {\n String::from_utf8_lossy(&result.stdout).to_lowercase()\n } else {\n // ldd on apline returns stderr with a 1 exit code\n String::from_utf8_lossy(&result.stderr).to_lowercase()\n };\n\n return output.contains(\"musl\") || output.contains(\"alpine\");\n }\n\n false\n }\n```"}], "func_name": "is_musl", "docstring": "Check if musl is available on the current machine, by running the\n`ldd --version` command, or the `uname` command. This will return false\non systems that have neither of those commands.", "repo": "moonrepo/proto", "path": "crates/system-env/src/env.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9f45d64fadb48a4565ccc63cac83b9fc4d7e79076d9ff10e3e73ed16b35f079"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_process_command\n\nDocumentation:\nCreate a new process [`Command`] and append the provided arguments. If the provided binary\nname is not an absolute path, we'll attempt to find it on `PATH` using [`find_command_on_path`].\n\nFurthermore, if the binary path is a Windows script (`.ps1`, `.cmd`, `.bat`), we'll wrap\nthe binary in a PowerShell command, and pass the original command via `-Command`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_process_command, I: IntoIterator, A: AsRef>(\n bin: T,\n args: I,\n) -> Command {\n let bin = bin.as_ref();\n\n // If an absolute path, use as-is, otherwise find the command\n let bin_path = if bin\n .as_encoded_bytes()\n .iter()\n .any(|b| b.eq_ignore_ascii_case(&b'/') || b.eq_ignore_ascii_case(&b'\\\\'))\n {\n PathBuf::from(bin)\n } else {\n find_command_on_path(bin).unwrap_or_else(|| bin.into())\n };\n\n // If a Windows script, we must execute the command through powershell\n match bin_path.extension().and_then(|ext| ext.to_str()) {\n Some(\"ps1\" | \"cmd\" | \"bat\") => {\n // This conversion is unfortunate...\n let args = args\n .into_iter()\n .map(|a| String::from_utf8_lossy(a.as_ref().as_encoded_bytes()).to_string())\n .collect::>();\n\n let mut cmd =\n Command::new(find_command_on_path(\"pwsh\").unwrap_or_else(|| \"powershell\".into()));\n cmd.arg(\"-Command\");\n cmd.arg(format!(\"{} {}\", bin_path.display(), shell_words::join(args)).trim());\n cmd\n }\n _ => {\n let mut cmd = Command::new(bin_path);\n cmd.args(args);\n cmd\n }\n }\n}\n```"}], "func_name": "create_process_command", "docstring": "Create a new process [`Command`] and append the provided arguments. If the provided binary\nname is not an absolute path, we'll attempt to find it on `PATH` using [`find_command_on_path`].\n\nFurthermore, if the binary path is a Windows script (`.ps1`, `.cmd`, `.bat`), we'll wrap\nthe binary in a PowerShell command, and pass the original command via `-Command`.", "repo": "moonrepo/proto", "path": "crates/system-env/src/helpers.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/helpers.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b2b807795bb87ab74394c112b57de23587036e10c07b0f528b42036f8d567482"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_config\n\nDocumentation:\nReturn vendor configuration for the current package manager.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_config(&self) -> PackageManagerConfig {\n match self {\n Self::Apk => apk(),\n Self::Apt => apt(),\n Self::Dnf => dnf(),\n Self::Pacman => pacman(),\n Self::Pkg => pkg(),\n Self::Pkgin => pkgin(),\n Self::Yum => yum(),\n Self::Brew => brew(),\n Self::Choco => choco(),\n Self::Scoop => scoop(),\n Self::All => unreachable!(),\n }\n }\n```"}], "func_name": "get_config", "docstring": "Return vendor configuration for the current package manager.", "repo": "moonrepo/proto", "path": "crates/system-env/src/pm.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/pm.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "991f0ace3799762e945c884d43fc9c4b641aa94347d88c9a98f3d29372894671"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_elevated_command\n\nDocumentation:\nReturn the command to use for elevated access. On Unix, this will use\n\"doas\" or \"sudo\", and on Windows or WASM this does nothing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_elevated_command(&self) -> Option<&str> {\n // Does not support sudo!\n if matches!(self, Self::Brew | Self::All) {\n return None;\n }\n\n #[cfg(unix)]\n {\n use crate::is_command_on_path;\n\n if is_command_on_path(\"doas\") {\n Some(\"doas\")\n } else if is_command_on_path(\"sudo\") {\n Some(\"sudo\")\n } else {\n None\n }\n }\n\n #[cfg(any(windows, target_arch = \"wasm32\"))]\n None\n }\n```"}], "func_name": "get_elevated_command", "docstring": "Return the command to use for elevated access. On Unix, this will use\n\"doas\" or \"sudo\", and on Windows or WASM this does nothing.", "repo": "moonrepo/proto", "path": "crates/system-env/src/pm.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/pm.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8f2afcdece2445de7a1668bb48f5b901267bcd7dbc1a530475d197e9390fec13"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_manager\n\nDocumentation:\nCreate a new instance with the provided package manager.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_manager(manager: SystemPackageManager) -> Self {\n Self {\n arch: SystemArch::from_env(),\n manager: Some(manager),\n os: SystemOS::from_env(),\n }\n }\n```"}], "func_name": "with_manager", "docstring": "Create a new instance with the provided package manager.", "repo": "moonrepo/proto", "path": "crates/system-env/src/system.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/system.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a670fd77d0fcf44c62c120dca66ed43c96493c16288e03f7fdf69a8cb4c0b528"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_install_package_command\n\nDocumentation:\nReturn the command and arguments to \"install a package\" for the\ncurrent package manager. Will replace `$` in an argument with the\ndependency name, derived from [`DependencyName`].\n\nThe [`DependencyConfig`] must be filtered for the current operating\nsystem and package manager beforehad.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_install_package_command(\n &self,\n dep_config: &DependencyConfig,\n interactive: bool,\n ) -> Result>, Error> {\n let Some(base_args) = self.extract_command(CommandType::InstallPackage, interactive)?\n else {\n return Ok(None);\n };\n\n let mut args = vec![];\n let pm = self.manager.as_ref().unwrap();\n let pm_config = pm.get_config();\n\n for arg in base_args {\n if arg == \"$\" {\n args.extend(self.extract_package_args(dep_config, &pm_config, pm)?);\n } else {\n args.push(arg);\n }\n }\n\n Ok(Some(args))\n }\n```"}], "func_name": "get_install_package_command", "docstring": "Return the command and arguments to \"install a package\" for the\ncurrent package manager. Will replace `$` in an argument with the\ndependency name, derived from [`DependencyName`].\n\nThe [`DependencyConfig`] must be filtered for the current operating\nsystem and package manager beforehad.", "repo": "moonrepo/proto", "path": "crates/system-env/src/system.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/system.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69dbbd447370ccc07ccee878c4fdafcad99a4c25cde7452500b58f64fd8f0dd4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_install_packages_command\n\nDocumentation:\nReturn the command and arguments to \"install many packages\" for the\ncurrent package manager. Will replace `$` in an argument with the\ndependency name, derived from [`DependencyName`].\n\nThe [`DependencyConfig`]s must be filtered for the current operating\nsystem and package manager beforehad.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_install_packages_command(\n &self,\n dep_configs: &[DependencyConfig],\n interactive: bool,\n ) -> Result>, Error> {\n let Some(base_args) = self.extract_command(CommandType::InstallPackage, interactive)?\n else {\n return Ok(None);\n };\n\n let mut args = vec![];\n let pm = self.manager.as_ref().unwrap();\n let pm_config = pm.get_config();\n\n for arg in base_args {\n if arg == \"$\" {\n for dep_config in dep_configs {\n args.extend(self.extract_package_args(dep_config, &pm_config, pm)?);\n }\n } else {\n args.push(arg);\n }\n }\n\n Ok(Some(args))\n }\n```"}], "func_name": "get_install_packages_command", "docstring": "Return the command and arguments to \"install many packages\" for the\ncurrent package manager. Will replace `$` in an argument with the\ndependency name, derived from [`DependencyName`].\n\nThe [`DependencyConfig`]s must be filtered for the current operating\nsystem and package manager beforehad.", "repo": "moonrepo/proto", "path": "crates/system-env/src/system.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/system.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e59625ba0d4b2f180a0990d63e794ce283a184264e0a3c80c35c1372adb2df32"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_list_packages_command\n\nDocumentation:\nReturn the command and arguments to \"list installed packages\"\nfor the current package manager.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_list_packages_command(\n &self,\n interactive: bool,\n ) -> Result>, Error> {\n self.extract_command(CommandType::ListPackages, interactive)\n }\n```"}], "func_name": "get_list_packages_command", "docstring": "Return the command and arguments to \"list installed packages\"\nfor the current package manager.", "repo": "moonrepo/proto", "path": "crates/system-env/src/system.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/system.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3d0364f6dc625ece9c8bf00f124865140b5359238467a0ed98b4ca8bda4bc929"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_update_index_command\n\nDocumentation:\nReturn the command and arguments to \"update the registry index\"\nfor the current package manager.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_update_index_command(\n &self,\n interactive: bool,\n ) -> Result>, Error> {\n self.extract_command(CommandType::UpdateIndex, interactive)\n }\n```"}], "func_name": "get_update_index_command", "docstring": "Return the command and arguments to \"update the registry index\"\nfor the current package manager.", "repo": "moonrepo/proto", "path": "crates/system-env/src/system.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/system.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb6d68563eceece2193e23507c7b09bb0f8cb4ce6386fb329aa092797f3257ac"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve_dependencies\n\nDocumentation:\nResolve and reduce the dependencies to a list that's applicable\nto the current system.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn resolve_dependencies(&self, deps: &[SystemDependency]) -> Vec {\n let mut configs = vec![];\n\n for dep in deps {\n let config = dep.to_config();\n\n if config.os.as_ref().is_some_and(|o| o != &self.os) {\n continue;\n }\n\n if config.arch.as_ref().is_some_and(|a| a != &self.arch) {\n continue;\n }\n\n if let Some(pm) = &self.manager {\n if config.manager.as_ref().is_some_and(|m| m != pm) {\n continue;\n }\n } else if config.manager.is_some() {\n continue;\n }\n\n configs.push(config);\n }\n\n configs\n }\n```"}], "func_name": "resolve_dependencies", "docstring": "Resolve and reduce the dependencies to a list that's applicable\nto the current system.", "repo": "moonrepo/proto", "path": "crates/system-env/src/system.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/system-env/src/system.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e5150ad0b72f756d27371718e76b0aad3f5811977798eb2dba9146c04adae779"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_alias_name\n\nDocumentation:\nReturns true if the provided value is an alias. An alias is a word that\nmaps to version, for example, \"latest\" -> \"1.2.3\".\n\nIs considered an alias if the string is alpha-numeric, starts with a\ncharacter, and supports `-`, `_`, `/`, `.`, and `*` characters.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_alias_name>(value: T) -> bool {\n let value = value.as_ref();\n\n value.chars().enumerate().all(|(i, c)| {\n if i == 0 {\n char::is_ascii_alphabetic(&c)\n } else {\n char::is_ascii_alphanumeric(&c)\n || c == '-'\n || c == '_'\n || c == '/'\n || c == '.'\n || c == '*'\n }\n })\n}\n```"}], "func_name": "is_alias_name", "docstring": "Returns true if the provided value is an alias. An alias is a word that\nmaps to version, for example, \"latest\" -> \"1.2.3\".\n\nIs considered an alias if the string is alpha-numeric, starts with a\ncharacter, and supports `-`, `_`, `/`, `.`, and `*` characters.", "repo": "moonrepo/proto", "path": "crates/version-spec/src/lib.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/version-spec/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b7351466019044ea954a003a8e76e960be3aa60f16ea102dbf1b335b1bd946d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clean_version_string\n\nDocumentation:\nCleans a potential version string by removing a leading `v` or `V`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clean_version_string>(value: T) -> String {\n let mut version = value.as_ref().trim();\n\n // Remove a leading \"v\" or \"V\" from a version string\n #[allow(clippy::assigning_clones)]\n if (version.starts_with('v') || version.starts_with('V'))\n && version.as_bytes()[1].is_ascii_digit()\n {\n version = &version[1..];\n }\n\n version.to_owned()\n}\n```"}], "func_name": "clean_version_string", "docstring": "Cleans a potential version string by removing a leading `v` or `V`.", "repo": "moonrepo/proto", "path": "crates/version-spec/src/lib.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/version-spec/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d86d0b1a2a4bdfcea415ad5523e1982d09b612ac5eb39395984690346feecc2e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clean_version_req_string\n\nDocumentation:\nCleans a version requirement string by removing * version parts,\nand correcting AND operators.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clean_version_req_string>(value: T) -> String {\n value\n .as_ref()\n .trim()\n .replace(\".*\", \"\")\n .replace(\".x\", \"\")\n .replace(\".X\", \"\")\n .replace(\"-*\", \"\")\n .replace(\"&&\", \",\")\n}\n```"}], "func_name": "clean_version_req_string", "docstring": "Cleans a version requirement string by removing * version parts,\nand correcting AND operators.", "repo": "moonrepo/proto", "path": "crates/version-spec/src/lib.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/version-spec/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "248ef25e334f40e911d6179cf961b626803f433d8b98ac0e2f69f9ae1303410c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_calver_regex\n\nDocumentation:\nGet a regex pattern that matches calendar versions (calver).\nFor example: 2024-02-26, 2024-12, 2024-01-alpha, etc.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_calver_regex() -> &'static Regex {\n CALVER_REGEX.get_or_init(|| {\n Regex::new(r\"^(?[0-9]{1,4})-(?((0?[1-9]{1})|10|11|12))(-(?(0?[1-9]{1}|[1-3]{1}[0-9]{1})))?((_|\\.)(?[0-9]+))?(?

-[a-zA-Z]{1}[-0-9a-zA-Z.]+)?$\").unwrap()\n    })\n}\n```"}], "func_name": "get_calver_regex", "docstring": "Get a regex pattern that matches calendar versions (calver).\nFor example: 2024-02-26, 2024-12, 2024-01-alpha, etc.", "repo": "moonrepo/proto", "path": "crates/version-spec/src/lib.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/version-spec/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f6117b2db1ea8f2adff6267f4f694e62647d74101a126a3cd9e8a19ccf381ca"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_semver_regex\n\nDocumentation:\nGet a regex pattern that matches semantic versions (semver).\nFor example: 1.2.3, 6.5.4, 7.8.9-alpha, etc.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_semver_regex() -> &'static Regex {\n    // https://semver.org/#backusnaur-form-grammar-for-valid-semver-versions\n    SEMVER_REGEX.get_or_init(|| {\n        Regex::new(r\"^(?[0-9]+).(?[0-9]+).(?[0-9]+)(?
-[-0-9a-zA-Z.]+)?(?\\+[-0-9a-zA-Z.]+)?$\")\n        .unwrap()\n    })\n}\n```"}], "func_name": "get_semver_regex", "docstring": "Get a regex pattern that matches semantic versions (semver).\nFor example: 1.2.3, 6.5.4, 7.8.9-alpha, etc.", "repo": "moonrepo/proto", "path": "crates/version-spec/src/lib.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/version-spec/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7b41c5856f79a235174351341e408646da5fa5172bbd770274058b18aa7e1e7c"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_version\n\nDocumentation:\nReturn the specification as a resolved [`Version`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_version(&self) -> Option<&Version> {\n        match self {\n            Self::Calendar(inner) => Some(&inner.0),\n            Self::Semantic(inner) => Some(&inner.0),\n            _ => None,\n        }\n    }\n```"}], "func_name": "as_version", "docstring": "Return the specification as a resolved [`Version`].", "repo": "moonrepo/proto", "path": "crates/version-spec/src/resolved_spec.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/version-spec/src/resolved_spec.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "085f5014a88cf6d29859e8a912f6ae53e8e6a0561f8c733d3e45ffd29dd65218"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_alias\n\nDocumentation:\nReturn true if the provided alias matches the current specification.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_alias>(&self, name: A) -> bool {\n        match self {\n            Self::Alias(alias) => alias == name.as_ref(),\n            _ => false,\n        }\n    }\n```"}], "func_name": "is_alias", "docstring": "Return true if the provided alias matches the current specification.", "repo": "moonrepo/proto", "path": "crates/version-spec/src/resolved_spec.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/version-spec/src/resolved_spec.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "372d55bbb147cf4a7380aada7e0250b20c83549d03e5f79d01ef71b3dda848c0"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_canary\n\nDocumentation:\nReturn true if the current specification is canary.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_canary(&self) -> bool {\n        match self {\n            Self::Canary => true,\n            Self::Alias(alias) => alias == \"canary\",\n            _ => false,\n        }\n    }\n```"}], "func_name": "is_canary", "docstring": "Return true if the current specification is canary.", "repo": "moonrepo/proto", "path": "crates/version-spec/src/resolved_spec.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/version-spec/src/resolved_spec.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "afd60a9c77eeb5eb16b5c12f24a2434f723bc7e47b5222aa4930b6b93a00e8c4"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_latest\n\nDocumentation:\nReturn true if the current specification is the \"latest\" alias.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_latest(&self) -> bool {\n        match self {\n            Self::Alias(alias) => alias == \"latest\",\n            _ => false,\n        }\n    }\n```"}], "func_name": "is_latest", "docstring": "Return true if the current specification is the \"latest\" alias.", "repo": "moonrepo/proto", "path": "crates/version-spec/src/resolved_spec.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/version-spec/src/resolved_spec.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a8535e50ace99b5a52b43f160391d5ba3add22ba0193d74d1bb0e5f41e06bc0"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_unresolved_spec\n\nDocumentation:\nConvert the current resolved specification to an unresolved specification.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_unresolved_spec(&self) -> UnresolvedVersionSpec {\n        match self {\n            Self::Canary => UnresolvedVersionSpec::Canary,\n            Self::Alias(alias) => UnresolvedVersionSpec::Alias(alias.to_owned()),\n            Self::Calendar(version) => UnresolvedVersionSpec::Calendar(version.to_owned()),\n            Self::Semantic(version) => UnresolvedVersionSpec::Semantic(version.to_owned()),\n        }\n    }\n```"}], "func_name": "to_unresolved_spec", "docstring": "Convert the current resolved specification to an unresolved specification.", "repo": "moonrepo/proto", "path": "crates/version-spec/src/resolved_spec.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/version-spec/src/resolved_spec.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "10aa4a1a84ee3b62572c57d0690457ae7e0be44e7543c3c5542847da6447f351"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_multi\n\nDocumentation:\nParse the provided string as a list of version requirements,\nas separated by `||`. Each requirement will be parsed\nindividually with [`parse`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_multi(input: impl AsRef) -> Result, SpecError> {\n    let input = input.as_ref();\n    let mut results = vec![];\n\n    if input.contains(\"||\") {\n        let mut parts = input.split(\"||\").map(|p| p.trim()).collect::>();\n\n        // Try and sort from highest to lowest range\n        parts.sort_by(|a, d| compare(d, a));\n\n        for part in parts {\n            results.push(parse(part)?.0);\n        }\n    } else {\n        results.push(parse(input)?.0);\n    }\n\n    Ok(results)\n}\n```"}], "func_name": "parse_multi", "docstring": "Parse the provided string as a list of version requirements,\nas separated by `||`. Each requirement will be parsed\nindividually with [`parse`].", "repo": "moonrepo/proto", "path": "crates/version-spec/src/unresolved_parser.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/version-spec/src/unresolved_parser.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ec8a849f6fcdf2d32dd0506530cd1298f4117751fa6fee524e5c699a0198b524"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_resolved_spec\n\nDocumentation:\nConvert the current unresolved specification to a resolved specification.\nNote that this *does not* actually resolve or validate against a manifest,\nand instead simply constructs the [`VersionSpec`].\n\nFurthermore, the `Req` and `ReqAny` variants will return a \"latest\" alias,\nas they are not resolved or valid versions.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_resolved_spec(&self) -> VersionSpec {\n        match self {\n            Self::Canary => VersionSpec::Canary,\n            Self::Alias(alias) => VersionSpec::Alias(CompactString::new(alias)),\n            Self::Calendar(version) => VersionSpec::Calendar(version.to_owned()),\n            Self::Semantic(version) => VersionSpec::Semantic(version.to_owned()),\n            _ => VersionSpec::default(),\n        }\n    }\n```"}], "func_name": "to_resolved_spec", "docstring": "Convert the current unresolved specification to a resolved specification.\nNote that this *does not* actually resolve or validate against a manifest,\nand instead simply constructs the [`VersionSpec`].\n\nFurthermore, the `Req` and `ReqAny` variants will return a \"latest\" alias,\nas they are not resolved or valid versions.", "repo": "moonrepo/proto", "path": "crates/version-spec/src/unresolved_spec.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/version-spec/src/unresolved_spec.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "db2accfd2b9916684c0b1f396d1235e11692f48ae168e1c467c90cd242493b36"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse\n\nDocumentation:\nIf the provided value is a calver-like version string,\nparse and convert it to a semver compatible version string,\nso that we can utilize the [`semver::Version`] type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse(value: &str) -> Result {\n        let Some(caps) = get_calver_regex().captures(value) else {\n            return Err(SpecError::InvalidCalverFormat);\n        };\n\n        // Short years (less than 4 characters) are relative\n        // from the year 2000, so let's enforce it. Is this correct?\n        // https://calver.org/#scheme\n        let year = caps\n            .name(\"year\")\n            .map(|cap| cap.as_str().trim_start_matches('0'))\n            .unwrap_or(\"0\");\n        let mut year_no: usize = year.parse().unwrap();\n\n        if year.len() < 4 {\n            year_no += 2000;\n        }\n\n        // Strip leading zeros from months and days. If the value is\n        // not provided, fallback to a zero, as calver is 1-index based\n        // and we can use this 0 for comparison.\n        let month = caps\n            .name(\"month\")\n            .map(|cap| cap.as_str().trim_start_matches('0'))\n            .unwrap_or(\"0\");\n\n        let day = caps\n            .name(\"day\")\n            .map(|cap| cap.as_str().trim_start_matches('0'))\n            .unwrap_or(\"0\");\n\n        let mut version = format!(\"{year_no}.{month}.{day}\");\n\n        if let Some(pre) = caps.name(\"pre\") {\n            version.push_str(pre.as_str());\n        }\n\n        if let Some(micro) = caps.name(\"micro\") {\n            version.push('+');\n            version.push_str(micro.as_str());\n        }\n\n        Ok(Self(Version::parse(&version)?))\n    }\n```"}], "func_name": "parse", "docstring": "If the provided value is a calver-like version string,\nparse and convert it to a semver compatible version string,\nso that we can utilize the [`semver::Version`] type.", "repo": "moonrepo/proto", "path": "crates/version-spec/src/version_types.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/version-spec/src/version_types.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba5b32798d2a96af0c94426edb8b4c0206c968d8fa29997ad276ec6e428139cf"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_http_client_with_options\n\nDocumentation:\nCreate an HTTP(S) client with the provided options, that'll be\nused for downloading files.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_http_client_with_options(\n    options: &HttpOptions,\n) -> Result {\n    debug!(\"Creating HTTP client\");\n\n    let mut client_builder = reqwest::Client::builder()\n        .user_agent(format!(\"warpgate@{}\", env!(\"CARGO_PKG_VERSION\")))\n        .use_rustls_tls();\n\n    if options.allow_invalid_certs {\n        trace!(\"Allowing invalid certificates (I hope you know what you're doing!)\");\n\n        client_builder = client_builder.danger_accept_invalid_certs(true);\n    }\n\n    if let Some(root_cert) = &options.root_cert {\n        trace!(root_cert = ?root_cert, \"Adding user provided root certificate\");\n\n        match root_cert.extension().and_then(|ext| ext.to_str()) {\n            Some(\"der\") => {\n                client_builder = client_builder.add_root_certificate(\n                    reqwest::Certificate::from_der(&fs::read_file_bytes(root_cert)?).map_err(\n                        |error| WarpgateClientError::InvalidCert {\n                            path: root_cert.to_path_buf(),\n                            error: Box::new(error),\n                        },\n                    )?,\n                )\n            }\n            Some(\"pem\") => {\n                client_builder = client_builder.add_root_certificate(\n                    reqwest::Certificate::from_pem(&fs::read_file_bytes(root_cert)?).map_err(\n                        |error| WarpgateClientError::InvalidCert {\n                            path: root_cert.to_path_buf(),\n                            error: Box::new(error),\n                        },\n                    )?,\n                )\n            }\n            _ => {\n                warn!(\n                    root_cert = ?root_cert,\n                    \"Invalid root certificate type, must be a DER or PEM file\",\n                );\n            }\n        };\n    }\n\n    let mut insecure_proxies = vec![];\n    let mut secure_proxies = options.secure_proxies.iter().collect::>();\n\n    for proxy in &options.proxies {\n        if proxy.starts_with(\"https:\") || (proxy.starts_with(\"http:\") && proxy.contains(\":443\")) {\n            secure_proxies.push(proxy);\n        } else if proxy.starts_with(\"http:\") {\n            insecure_proxies.push(proxy);\n        } else {\n            warn!(proxy, \"Invalid proxy, only http or https URLs allowed\");\n        };\n    }\n\n    if !insecure_proxies.is_empty() {\n        trace!(proxies = ?insecure_proxies, \"Adding insecure proxies to client\");\n\n        for proxy in insecure_proxies {\n            client_builder =\n                client_builder.proxy(reqwest::Proxy::http(proxy).map_err(|error| {\n                    WarpgateClientError::InvalidProxy {\n                        url: proxy.to_owned(),\n                        error: Box::new(error),\n                    }\n                })?);\n        }\n    }\n\n    if !secure_proxies.is_empty() {\n        trace!(proxies = ?secure_proxies, \"Adding secure proxies to client\");\n\n        for proxy in secure_proxies {\n            client_builder =\n                client_builder.proxy(reqwest::Proxy::https(proxy).map_err(|error| {\n                    WarpgateClientError::InvalidProxy {\n                        url: proxy.to_owned(),\n                        error: Box::new(error),\n                    }\n                })?);\n        }\n    }\n\n    let client = client_builder\n        .build()\n        .map_err(|error| WarpgateClientError::Client {\n            error: Box::new(error),\n        })?;\n\n    trace!(\"Applying middleware to client\");\n\n    let mut middleware_builder = ClientBuilder::new(client.clone());\n\n    if let Ok(netrc) = NetrcMiddleware::new() {\n        trace!(\"Adding .netrc support\");\n\n        middleware_builder = middleware_builder.with_init(netrc);\n    }\n\n    if let Some(cache_dir) = &options.cache_dir {\n        if !is_docker() {\n            use http_cache_reqwest::{\n                CACacheManager, Cache, CacheMode, CacheOptions, HttpCache, HttpCacheOptions,\n            };\n\n            trace!(\"Adding GET and HEAD request caching\");\n\n            middleware_builder = middleware_builder.with(Cache(HttpCache {\n                manager: CACacheManager {\n                    path: cache_dir.to_owned(),\n                },\n                mode: CacheMode::Default,\n                options: HttpCacheOptions {\n                    // https://github.com/kornelski/rusty-http-cache-semantics\n                    cache_options: Some(CacheOptions {\n                        cache_heuristic: 0.025,\n                        ..Default::default()\n                    }),\n                    ..Default::default()\n                },\n            }));\n        }\n    }\n\n    let middleware = middleware_builder.build();\n\n    debug!(\"Created HTTP client\");\n\n    Ok(HttpClient { client, middleware })\n}\n```"}], "func_name": "create_http_client_with_options", "docstring": "Create an HTTP(S) client with the provided options, that'll be\nused for downloading files.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/client.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/client.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aaa49c7d8c1fba9189367b451f80cfb9e71279faffef2220483642bd301c60b9"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_cache_key\n\nDocumentation:\nCreate a SHA256 hash key based on the provided URL and seed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_cache_key(url: &str, seed: Option<&str>) -> String {\n    let mut sha = Sha256::new();\n    sha.update(url);\n\n    if let Some(seed) = seed {\n        sha.update(seed);\n    }\n\n    format!(\"{:x}\", sha.finalize())\n}\n```"}], "func_name": "create_cache_key", "docstring": "Create a SHA256 hash key based on the provided URL and seed.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/helpers.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/helpers.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "59941f21654085e487457f52f35102617bd409d6df8c777fdaab5e41bdd402a5"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: determine_cache_extension\n\nDocumentation:\nDetermine the extension to use for a cache file, based on our\nlist of supported extensions.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn determine_cache_extension(value: &str) -> Option<&str> {\n    [\".toml\", \".json\", \".jsonc\", \".yaml\", \".yml\", \".wasm\", \".txt\"]\n        .into_iter()\n        .find(|ext| value.ends_with(ext))\n}\n```"}], "func_name": "determine_cache_extension", "docstring": "Determine the extension to use for a cache file, based on our\nlist of supported extensions.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/helpers.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/helpers.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f1caa8ea0cc857ae2c9bc89b4f47b52cb650d736a504d3d0f9b0f839e7dd0f28"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sort_virtual_paths\n\nDocumentation:\nSort virtual paths from longest to shortest host path,\nso that prefix replacing is deterministic and accurate.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn sort_virtual_paths(map: &BTreeMap) -> Vec<(&PathBuf, &PathBuf)> {\n    let mut list = map.iter().collect::>();\n    list.sort_by(|a, d| d.0.cmp(a.0));\n    list\n}\n```"}], "func_name": "sort_virtual_paths", "docstring": "Sort virtual paths from longest to shortest host path,\nso that prefix replacing is deterministic and accurate.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/helpers.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/helpers.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "14d9d1ea53c5f0a52280d2aed0aca3113149aa2e68a76b3d7f8421af03370101"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_host_functions\n\nDocumentation:\nCreate a list of our built-in host functions.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_host_functions(data: HostData) -> Vec {\n    vec![\n        Function::new(\n            \"exec_command\",\n            [ValType::I64],\n            [ValType::I64],\n            UserData::new(data.clone()),\n            exec_command,\n        ),\n        Function::new(\n            \"from_virtual_path\",\n            [ValType::I64],\n            [ValType::I64],\n            UserData::new(data.clone()),\n            from_virtual_path,\n        ),\n        Function::new(\n            \"get_env_var\",\n            [ValType::I64],\n            [ValType::I64],\n            UserData::new(()),\n            get_env_var,\n        ),\n        Function::new(\"host_log\", [ValType::I64], [], UserData::new(()), host_log),\n        Function::new(\n            \"send_request\",\n            [ValType::I64],\n            [ValType::I64],\n            UserData::new(data.clone()),\n            send_request,\n        ),\n        Function::new(\n            \"set_env_var\",\n            [ValType::I64, ValType::I64],\n            [],\n            UserData::new(data.clone()),\n            set_env_var,\n        ),\n        Function::new(\n            \"to_virtual_path\",\n            [ValType::I64],\n            [ValType::I64],\n            UserData::new(data.clone()),\n            to_virtual_path,\n        ),\n    ]\n}\n```"}], "func_name": "create_host_functions", "docstring": "Create a list of our built-in host functions.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/host.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/host.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "22424e1510cf99633c25da9d86a2c21f86a62562f6b782495b6c8a7f521a58d8"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new loader that stores plugins and downloads in the provided directories.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new, T: AsRef>(plugins_dir: P, temp_dir: T) -> Self {\n        let plugins_dir = plugins_dir.as_ref();\n\n        trace!(cache_dir = ?plugins_dir, \"Creating plugin loader\");\n\n        Self {\n            http_client: OnceCell::new(),\n            http_options: HttpOptions::default(),\n            offline_checker: None,\n            plugins_dir: plugins_dir.to_owned(),\n            temp_dir: temp_dir.as_ref().to_owned(),\n            seed: None,\n        }\n    }\n```"}], "func_name": "new", "docstring": "Create a new loader that stores plugins and downloads in the provided directories.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/loader.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/loader.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c7ae26e6b3a07bd6baa12731a5a53fd14bbe978d9361da8e64ccdd12c7228c6c"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_client\n\nDocumentation:\nReturn the HTTP client, or create it if it does not exist.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_client(&self) -> Result<&Arc, WarpgateClientError> {\n        self.http_client\n            .get_or_try_init(|| create_http_client_with_options(&self.http_options).map(Arc::new))\n    }\n```"}], "func_name": "get_client", "docstring": "Return the HTTP client, or create it if it does not exist.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/loader.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/loader.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a5ba6f476901ed5b35c84f8e562fab52b7fb5e6f498e7d29cede256989e4dde"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_cache_path\n\nDocumentation:\nCreate an absolute path to the plugin's destination file, located in the plugins directory.\nHash the source URL to ensure uniqueness of each plugin + version combination.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_cache_path(&self, id: &Id, url: &str, is_latest: bool) -> PathBuf {\n        self.plugins_dir.join(format!(\n            \"{}{}{}{}\",\n            // Remove unwanted or unsafe file name characters\n            id.as_str().replace(['/', '@', '.', ' '], \"\"),\n            if is_latest { \"-latest-\" } else { \"-\" },\n            create_cache_key(url, self.seed.as_deref()),\n            determine_cache_extension(url).unwrap_or(\".wasm\"),\n        ))\n    }\n```"}], "func_name": "create_cache_path", "docstring": "Create an absolute path to the plugin's destination file, located in the plugins directory.\nHash the source URL to ensure uniqueness of each plugin + version combination.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/loader.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/loader.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "920ccf3da025b3d4cf02036ae984c93ab6a7470ee8b3efb2836eb9fcc8f88c69"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_client_options\n\nDocumentation:\nSet the options to pass to the HTTP client.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_client_options(&mut self, options: &HttpOptions) {\n        options.clone_into(&mut self.http_options);\n    }\n```"}], "func_name": "set_client_options", "docstring": "Set the options to pass to the HTTP client.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/loader.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/loader.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "39642a6d460025d8bba7043b64120f8dff7fe58001526f56b9408d643198740e"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_offline_checker\n\nDocumentation:\nSet the function that checks for offline state.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_offline_checker(&mut self, op: fn() -> bool) {\n        self.offline_checker = Some(Arc::new(op));\n    }\n```"}], "func_name": "set_offline_checker", "docstring": "Set the function that checks for offline state.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/loader.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/loader.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e0e4ac1a8fbc4add5aa929aaeed54531e1135e4901e6eaa6fe3f837237b663df"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_seed\n\nDocumentation:\nSet the provided value as a seed for generating hashes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_seed(&mut self, value: &str) {\n        self.seed = Some(value.to_owned());\n    }\n```"}], "func_name": "set_seed", "docstring": "Set the provided value as a seed for generating hashes.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/loader.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/loader.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6d18881c096de0c56d3eb107fe14f5ec6b24a95b17248e5b70069ab5f8d6ad74"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_without_functions\n\nDocumentation:\nCreate a new container with the provided manifest.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_without_functions(\n        id: Id,\n        manifest: Manifest,\n    ) -> Result {\n        Self::new(id, manifest, [])\n    }\n```"}], "func_name": "new_without_functions", "docstring": "Create a new container with the provided manifest.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/plugin.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/plugin.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7fdfbfd349e07d81371ad8e1b48e2a5841f22ac795e65c5bb425cb254299e7f5"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_on_call\n\nDocumentation:\nSet a callback handler to be executed when calling a plugin function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_on_call(&self, func: OnCallFn) {\n        let _ = self.on_call_func.set(func);\n    }\n```"}], "func_name": "set_on_call", "docstring": "Set a callback handler to be executed when calling a plugin function.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/plugin.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/plugin.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fcd316a34128181ffa1b42703788afebe90dbbfae705bb921c7f0cb195d1db35"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cache_func\n\nDocumentation:\nCall a function on the plugin with no input and cache the output before returning it.\nSubsequent calls will read from the cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn cache_func(&self, func: &str) -> Result\n    where\n        O: Debug + DeserializeOwned,\n    {\n        self.cache_func_with(func, Empty::default()).await\n    }\n```"}], "func_name": "cache_func", "docstring": "Call a function on the plugin with no input and cache the output before returning it.\nSubsequent calls will read from the cache.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/plugin.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/plugin.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "546abbc3fad9405f18d513ba23bb5c11fa55896c3eb8096d6bef6e384cf1f8e1"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: call_func\n\nDocumentation:\nCall a function on the plugin with no input and return the output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn call_func(&self, func: &str) -> Result\n    where\n        O: Debug + DeserializeOwned,\n    {\n        self.call_func_with(func, Empty::default()).await\n    }\n```"}], "func_name": "call_func", "docstring": "Call a function on the plugin with no input and return the output.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/plugin.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/plugin.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b69de7dc38c72d78ad680167e5902da84093605ced70c0058b92cf7cd862095c"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_virtual_path\n\nDocumentation:\nConvert the provided virtual guest path to an absolute host path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_virtual_path(&self, path: impl AsRef + Debug) -> PathBuf {\n        let Some(virtual_paths) = self.manifest.allowed_paths.as_ref() else {\n            return path.as_ref().to_path_buf();\n        };\n\n        let paths = map_virtual_paths(virtual_paths);\n\n        from_virtual_path(&paths, path)\n    }\n```"}], "func_name": "from_virtual_path", "docstring": "Convert the provided virtual guest path to an absolute host path.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/plugin.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/plugin.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b99aeee635baf28879e94a4c980322f62693f808c9cd193154e9eeda7449547"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_virtual_path\n\nDocumentation:\nConvert the provided absolute host path to a virtual guest path suitable\nfor WASI sandboxed runtimes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_virtual_path(&self, path: impl AsRef + Debug) -> VirtualPath {\n        let Some(virtual_paths) = self.manifest.allowed_paths.as_ref() else {\n            return VirtualPath::Real(path.as_ref().to_path_buf());\n        };\n\n        let paths = map_virtual_paths(virtual_paths);\n\n        to_virtual_path(&paths, path)\n    }\n```"}], "func_name": "to_virtual_path", "docstring": "Convert the provided absolute host path to a virtual guest path suitable\nfor WASI sandboxed runtimes.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/plugin.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/plugin.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6fb6446d7e10e1ccfe0b6707e528c6b490ca4fe6acac0267b84320de14ca69a2"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: call\n\nDocumentation:\nCall a function on the plugin with the given raw input and return the raw output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn call(\n        &self,\n        func: &str,\n        input: impl AsRef<[u8]>,\n    ) -> Result, WarpgatePluginError> {\n        let mut instance = self.plugin.write().await;\n        let input = input.as_ref();\n        let input_string = String::from_utf8_lossy(input);\n        let uuid = instance.id.to_string(); // Copy\n        let instant = Instant::now();\n\n        trace!(\n            id = self.id.as_str(),\n            plugin = &uuid,\n            input = %(if input_string.len() > 5000 && !self.debug_call {\n                \"(truncated)\"\n            } else {\n                &input_string\n            }),\n            \"Calling guest function {}\",\n            color::property(func),\n        );\n\n        if let Some(callback) = self.on_call_func.get() {\n            callback(func, Some(&input_string), None);\n        }\n\n        let output = block_in_place(|| instance.call(func, input)).map_err(|error| {\n            if is_incompatible_runtime(&error) {\n                return WarpgatePluginError::IncompatibleRuntime {\n                    id: self.id.clone(),\n                };\n            }\n\n            let message = apply_style_tags(\n                error\n                    .source()\n                    .map(|src| src.to_string())\n                    .unwrap_or_else(|| error.to_string())\n                    .replace(\"\\\\\\\\n\", \"\\n\")\n                    .replace(\"\\\\n\", \"\\n\")\n                    .trim(),\n            );\n\n            // When in debug mode, include more information around errors.\n            #[cfg(debug_assertions)]\n            {\n                WarpgatePluginError::FailedPluginCall {\n                    id: self.id.clone(),\n                    func: func.to_owned(),\n                    error: message,\n                }\n            }\n\n            // When in release mode, errors don't render properly with the\n            // previous variant, so this is a special variant that renders as-is.\n            #[cfg(not(debug_assertions))]\n            {\n                WarpgatePluginError::FailedPluginCallRelease { error: message }\n            }\n        })?;\n\n        let output_string = String::from_utf8_lossy(output);\n\n        trace!(\n            id = self.id.as_str(),\n            plugin = &uuid,\n            output = %(if output_string.len() > 5000 && !self.debug_call {\n                \"(truncated)\"\n            } else {\n                &output_string\n            }),\n            elapsed = ?instant.elapsed(),\n            \"Called guest function {}\",\n            color::property(func),\n        );\n\n        if let Some(callback) = self.on_call_func.get() {\n            callback(func, None, Some(&output_string));\n        }\n\n        Ok(output.to_vec())\n    }\n```"}], "func_name": "call", "docstring": "Call a function on the plugin with the given raw input and return the raw output.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/plugin.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/plugin.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f9f1d4e4d8369ca4697c45f038e526b7b09be6eb7534bd87e3e8168d1a41ee4"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: find_target_dir\n\nDocumentation:\nFind the WASM compiled target directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn find_target_dir>(search_dir: T) -> Option {\n    traverse_target_dir(search_dir, \"\")\n}\n```"}], "func_name": "find_target_dir", "docstring": "Find the WASM compiled target directory.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/test_utils.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/test_utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e0f07cbfadbceccaa77fea6ff6408200bda04f6269fa4994435161c365297ea8"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: find_wasm_file\n\nDocumentation:\nFind an applicable WASM file to run tests with. Will attempt to find\nthe file based on the Cargo package name and target directories.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn find_wasm_file() -> PathBuf {\n    let wasm_file = format!(\n        \"{}.wasm\",\n        env::var(\"CARGO_PKG_NAME\").expect(\"Missing CARGO_PKG_NAME!\")\n    );\n\n    for env_var in [\"CARGO_MANIFEST_DIR\", \"CARGO_TARGET_DIR\"] {\n        if let Some(env_path) = path_var(env_var) {\n            if let Some(wasm_path) = traverse_target_dir(env_path, &wasm_file) {\n                return wasm_path;\n            }\n        }\n    }\n\n    panic!(\n        \"WASM file `{}` does not exist. Please build it with `cargo build --target wasm32-wasip1` before running tests!\",\n        wasm_file\n    );\n}\n```"}], "func_name": "find_wasm_file", "docstring": "Find an applicable WASM file to run tests with. Will attempt to find\nthe file based on the Cargo package name and target directories.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/test_utils.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/test_utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "328825eda8d94643da3f7f96c976091f8b49e864aec672d00c6d9f4d14a524cd"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: enable_wasm_logging\n\nDocumentation:\nEnable logging for the provided WASM file by extracting any `tracing` logs\nfired from within WASM and writing them to a local file in the current directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn enable_wasm_logging(wasm_file: &Path) {\n    use std::io::Write;\n\n    let log_file = std::env::current_dir().unwrap().join(\n        wasm_file\n            .file_name()\n            .and_then(|name| name.to_str())\n            .unwrap_or_default()\n            .replace(\".wasm\", \".log\"),\n    );\n\n    // Remove the file otherwise it keeps growing\n    if log_file.exists() {\n        let _ = fs::remove_file(&log_file);\n    }\n\n    let _ = extism::set_log_callback(\n        move |line| {\n            let mut file = std::fs::OpenOptions::new()\n                .create(true)\n                .append(true)\n                .open(&log_file)\n                .unwrap();\n\n            file.write_all(line.as_bytes()).unwrap();\n        },\n        \"trace\",\n    );\n}\n```"}], "func_name": "enable_wasm_logging", "docstring": "Enable logging for the provided WASM file by extracting any `tracing` logs\nfired from within WASM and writing them to a local file in the current directory.", "repo": "moonrepo/proto", "path": "crates/warpgate/src/test_utils.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate/src/test_utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "74853d1c048e3192424ace222eb321a89cadf3c4f63a386ba737a171a86e6b39"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new host log with the provided message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(message: impl AsRef) -> Self {\n        Self {\n            message: message.as_ref().to_owned(),\n            ..Default::default()\n        }\n    }\n```"}], "func_name": "new", "docstring": "Create a new host log with the provided message.", "repo": "moonrepo/proto", "path": "crates/warpgate-api/src/host_funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-api/src/host_funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82c798dc482429d7cbde40b9b747565d48548df23e25dfdf6bad99f0a236a819"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new command that inherits and streams the output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(command: C, args: I) -> ExecCommandInput\n    where\n        C: AsRef,\n        I: IntoIterator,\n        V: AsRef,\n    {\n        let mut input = Self::pipe(command, args);\n        input.stream = true;\n        input\n    }\n```"}], "func_name": "new", "docstring": "Create a new command that inherits and streams the output.", "repo": "moonrepo/proto", "path": "crates/warpgate-api/src/host_funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-api/src/host_funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6de4e7c48216b9164f218364508190960ced7895f797997338caf56565d224f8"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pipe\n\nDocumentation:\nCreate a new command that pipes and captures the output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pipe(command: C, args: I) -> ExecCommandInput\n    where\n        C: AsRef,\n        I: IntoIterator,\n        V: AsRef,\n    {\n        ExecCommandInput {\n            command: command.as_ref().to_string(),\n            args: args.into_iter().map(|a| a.as_ref().to_owned()).collect(),\n            ..ExecCommandInput::default()\n        }\n    }\n```"}], "func_name": "pipe", "docstring": "Create a new command that pipes and captures the output.", "repo": "moonrepo/proto", "path": "crates/warpgate-api/src/host_funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-api/src/host_funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf75749f1078cd9a77b9ce564e3da0cccc4b957e4b61e078e6bc930f35e2261d"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new send request with the provided url.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(url: impl AsRef) -> Self {\n        Self {\n            url: url.as_ref().to_owned(),\n            ..Default::default()\n        }\n    }\n```"}], "func_name": "new", "docstring": "Create a new send request with the provided url.", "repo": "moonrepo/proto", "path": "crates/warpgate-api/src/host_funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-api/src/host_funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fe9a4e177d2550ee7f744cb05a56ce799c4f2f59b8a5cc40e40b905728257811"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: join\n\nDocumentation:\nAppend the path part and return a new [`VirtualPath`] instance.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn join>(&self, path: P) -> VirtualPath {\n        match self {\n            Self::Real(base) => Self::Real(base.join(path.as_ref())),\n            Self::Virtual {\n                path: base,\n                virtual_prefix,\n                real_prefix,\n            } => Self::Virtual {\n                path: base.join(path.as_ref()),\n                virtual_prefix: virtual_prefix.clone(),\n                real_prefix: real_prefix.clone(),\n            },\n        }\n    }\n```"}], "func_name": "join", "docstring": "Append the path part and return a new [`VirtualPath`] instance.", "repo": "moonrepo/proto", "path": "crates/warpgate-api/src/virtual_path.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-api/src/virtual_path.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3ee65fa1b9bbf485453083c144f64e24a16a1971901759adddc4ef9a1ff1fd91"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parent\n\nDocumentation:\nReturn the parent directory as a new [`VirtualPath`] instance.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parent(&self) -> Option {\n        // If at the root (`/`), then we have gone outside the allowed\n        // virtual paths, so there's no parent to use!\n        fn is_root(path: &Path) -> bool {\n            path.to_str()\n                .is_some_and(|comp| comp.is_empty() || comp == \"/\")\n        }\n\n        match self {\n            Self::Real(base) => base.parent().and_then(|parent| {\n                if is_root(parent) {\n                    None\n                } else {\n                    Some(Self::Real(parent.to_owned()))\n                }\n            }),\n            Self::Virtual {\n                path: base,\n                virtual_prefix,\n                real_prefix,\n            } => base.parent().and_then(|parent| {\n                if is_root(parent) {\n                    None\n                } else {\n                    Some(Self::Virtual {\n                        path: parent.to_owned(),\n                        virtual_prefix: virtual_prefix.clone(),\n                        real_prefix: real_prefix.clone(),\n                    })\n                }\n            }),\n        }\n    }\n```"}], "func_name": "parent", "docstring": "Return the parent directory as a new [`VirtualPath`] instance.", "repo": "moonrepo/proto", "path": "crates/warpgate-api/src/virtual_path.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-api/src/virtual_path.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "45be27fb625877b04b23887887719e923057ddbc72c298b0f8b7a8f049a411ac"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: any_path\n\nDocumentation:\nReturn any path available, either virtual or real, regardless of any\nconditions. This is primarily used for debugging.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn any_path(&self) -> &PathBuf {\n        match self {\n            Self::Real(path) => path,\n            Self::Virtual { path, .. } => path,\n        }\n    }\n```"}], "func_name": "any_path", "docstring": "Return any path available, either virtual or real, regardless of any\nconditions. This is primarily used for debugging.", "repo": "moonrepo/proto", "path": "crates/warpgate-api/src/virtual_path.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-api/src/virtual_path.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a483ad854f97cd16582d21c1c621893bf92b8e1931fa150654a18e7ddbb71e65"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: real_path\n\nDocumentation:\nReturn the original real path. If we don't have access to prefixes,\nor removing prefix fails, returns `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn real_path(&self) -> Option {\n        match self {\n            Self::Real(path) => Some(path.to_path_buf()),\n            Self::Virtual { real_prefix, .. } => {\n                self.without_prefix().map(|path| real_prefix.join(path))\n            }\n        }\n    }\n```"}], "func_name": "real_path", "docstring": "Return the original real path. If we don't have access to prefixes,\nor removing prefix fails, returns `None`.", "repo": "moonrepo/proto", "path": "crates/warpgate-api/src/virtual_path.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-api/src/virtual_path.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0f8a6b81410b96835960c17dbc9de631019fe8ec5ab376b9717d28a6810759e"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: real_path_string\n\nDocumentation:\nReturn the original real path as a string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn real_path_string(&self) -> Option {\n        self.real_path()\n            .and_then(|path| path.to_str().map(|path| path.to_owned()))\n    }\n```"}], "func_name": "real_path_string", "docstring": "Return the original real path as a string.", "repo": "moonrepo/proto", "path": "crates/warpgate-api/src/virtual_path.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-api/src/virtual_path.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "720a341ed7899d23f7e7a60468481176ae2e78eaa4a2256788b4d0f3edb291ee"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: virtual_path\n\nDocumentation:\nReturn the virtual path. If a real path only, returns `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn virtual_path(&self) -> Option {\n        match self {\n            Self::Real(_) => None,\n            Self::Virtual { path, .. } => Some(path.to_owned()),\n        }\n    }\n```"}], "func_name": "virtual_path", "docstring": "Return the virtual path. If a real path only, returns `None`.", "repo": "moonrepo/proto", "path": "crates/warpgate-api/src/virtual_path.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-api/src/virtual_path.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "16f21734792717326b13593aa4e85f45c9aa9943532c96d940e26b943486f0fe"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: virtual_path_string\n\nDocumentation:\nReturn the virtual path as a string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn virtual_path_string(&self) -> Option {\n        self.virtual_path()\n            .and_then(|path| path.to_str().map(|path| path.to_owned()))\n    }\n```"}], "func_name": "virtual_path_string", "docstring": "Return the virtual path as a string.", "repo": "moonrepo/proto", "path": "crates/warpgate-api/src/virtual_path.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-api/src/virtual_path.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a514247df55f83622d8ce7e41b95388d822bb1b123cff12566845dce043c448"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: without_prefix\n\nDocumentation:\nReturn the current path without a virtual prefix.\nIf we don't have access to prefixes, returns `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn without_prefix(&self) -> Option<&Path> {\n        match self {\n            Self::Real(_) => None,\n            Self::Virtual {\n                path,\n                virtual_prefix,\n                ..\n            } => path.strip_prefix(virtual_prefix).ok(),\n        }\n    }\n```"}], "func_name": "without_prefix", "docstring": "Return the current path without a virtual prefix.\nIf we don't have access to prefixes, returns `None`.", "repo": "moonrepo/proto", "path": "crates/warpgate-api/src/virtual_path.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-api/src/virtual_path.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8a65c0828ad51d3e90f30faeeeaca4a9d4983eeca430b0bd33360fd42351e2a2"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fetch\n\nDocumentation:\nFetch the requested input and return a response.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fetch(input: SendRequestInput) -> AnyResult {\n    let url = input.url.clone();\n    let response = send_request!(input, input);\n    let status = response.status;\n\n    if status != 200 {\n        let body = response.text()?;\n\n        debug!(\n            \"Response body for {}: {}\",\n            url, body\n        );\n\n        return Err(anyhow!(\n            \"Failed to request {url} ({})\",\n            status\n        ));\n    }\n\n    if response.body.is_empty() {\n        return Err(anyhow!(\"Invalid response from {url}, no body\"));\n    }\n\n    Ok(response)\n}\n```"}], "func_name": "fetch", "docstring": "Fetch the requested input and return a response.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0bb263c5b7e9d8c8a2550300bb78a83e5fdc91ae72b255c716beb2f14ee18cd8"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fetch_bytes\n\nDocumentation:\nFetch the provided URL and return the response as bytes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fetch_bytes(url: U) -> AnyResult>\nwhere\n    U: AsRef,\n{\n    Ok(fetch(SendRequestInput::new(url))?.body)\n}\n```"}], "func_name": "fetch_bytes", "docstring": "Fetch the provided URL and return the response as bytes.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc467ddfd1663c936b99c046ec5b52b77bbf6e4113a753bc9cb1f0ca1cdbdb3b"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fetch_json\n\nDocumentation:\nFetch the provided URL and deserialize the response as JSON.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fetch_json(url: U) -> AnyResult\nwhere\n    U: AsRef,\n    R: DeserializeOwned,\n{\n    fetch(SendRequestInput::new(url))?.json()\n}\n```"}], "func_name": "fetch_json", "docstring": "Fetch the provided URL and deserialize the response as JSON.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac1925b9cd941cfc27ae8b040e6269355c36f0bc722ada55d2299914e555fb63"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fetch_text\n\nDocumentation:\nFetch the provided URL and return the response as text.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fetch_text(url: U) -> AnyResult\nwhere\n    U: AsRef,\n{\n    fetch(SendRequestInput::new(url))?.text()\n}\n```"}], "func_name": "fetch_text", "docstring": "Fetch the provided URL and return the response as text.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63b94ea6e12e8027febcac3c11eac571824eb5cd44fb52b48f03d1fb80155f35"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec\n\nDocumentation:\nExecute a command on the host with the provided input.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exec(input: ExecCommandInput) -> AnyResult {\n    Ok(exec_command!(input, input))\n}\n```"}], "func_name": "exec", "docstring": "Execute a command on the host with the provided input.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3b8a47658547f7c6aee8d2cdcd77b9ddfa4e1f79f30f3ac8bd1b4024908245c5"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_captured\n\nDocumentation:\nExecute a command on the host and capture its output (pipe).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exec_captured(command: C, args: I) -> AnyResult\nwhere\n    C: AsRef,\n    I: IntoIterator,\n    A: AsRef,\n{\n    exec(ExecCommandInput::pipe(command, args))\n}\n```"}], "func_name": "exec_captured", "docstring": "Execute a command on the host and capture its output (pipe).", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "19c48ffa0c6f29b7425c5f5b93cee723171b4ab3a692880905fd0e9f89254c53"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exec_streamed\n\nDocumentation:\nExecute a command on the host and stream its output to the console (inherit).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exec_streamed(command: C, args: I) -> AnyResult\nwhere\n    C: AsRef,\n    I: IntoIterator,\n    A: AsRef,\n{\n    exec(ExecCommandInput::inherit(command, args))\n}\n```"}], "func_name": "exec_streamed", "docstring": "Execute a command on the host and stream its output to the console (inherit).", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d360078fa8f93b8bfa27bf37b9c0ef13482e40ae53511a84f5e20d7bda55bf9c"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_git_tags\n\nDocumentation:\nLoad all Git tags from the provided remote URL.\nThe `git` binary must exist on the host machine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load_git_tags(url: U) -> AnyResult>\nwhere\n    U: AsRef,\n{\n    let url = url.as_ref();\n\n    debug!(\"Loading Git tags from remote {}\", url);\n\n    let mut tags: Vec = vec![];\n    let output = exec_captured(\n        \"git\",\n        [\"ls-remote\", \"--tags\", \"--sort\", \"version:refname\", url],\n    )?;\n\n    if output.exit_code != 0 {\n        debug!(\"Failed to load Git tags\");\n\n        return Ok(tags);\n    }\n\n    for line in output.stdout.split('\\n') {\n        // https://superuser.com/questions/1445823/what-does-mean-in-the-tags\n        if line.ends_with(\"^{}\") {\n            continue;\n        }\n\n        let parts = line.split('\\t').collect::>();\n\n        if parts.len() < 2 {\n            continue;\n        }\n\n        if let Some(tag) = parts[1].strip_prefix(\"refs/tags/\") {\n            tags.push(tag.to_owned());\n        }\n    }\n\n    debug!(\"Loaded {} Git tags\", tags.len());\n\n    Ok(tags)\n}\n```"}], "func_name": "load_git_tags", "docstring": "Load all Git tags from the provided remote URL.\nThe `git` binary must exist on the host machine.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc2585c681be09314dabca216d9f9652e4be0f12bd653b8985029ba29fefbb54"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: command_exists\n\nDocumentation:\nCheck whether a command exists or not on the host machine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn command_exists(env: &HostEnvironment, command: &str) -> bool {\n    debug!(\n        \"Checking if command {} exists on the host\",\n        command\n    );\n\n    let result = if env.os == HostOS::Windows {\n        exec_captured(\n            \"powershell\",\n            [\"-Command\", format!(\"Get-Command {command}\").as_str()],\n        )\n    } else {\n        exec_captured(\"which\", [command])\n    };\n\n    if result.is_ok_and(|res| res.exit_code == 0) {\n        debug!(\"Command does exist\");\n\n        return true;\n    }\n\n    debug!(\"Command does NOT exist\");\n\n    false\n}\n```"}], "func_name": "command_exists", "docstring": "Check whether a command exists or not on the host machine.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "277420d3e0533a2881b509e73050705453269cb3ce27e7a6f34379a7f6eae02e"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_host_env_var\n\nDocumentation:\nReturn the value of an environment variable on the host machine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_host_env_var(key: K) -> AnyResult>\nwhere\n    K: AsRef,\n{\n    let inner = unsafe { get_env_var(key.as_ref().into())? };\n\n    Ok(if inner.is_empty() { None } else { Some(inner) })\n}\n```"}], "func_name": "get_host_env_var", "docstring": "Return the value of an environment variable on the host machine.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ceeaf842270a34f97898efd3e2b7e363b9aad85efdb17283b2b4b2fee3af3bb5"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_host_env_var\n\nDocumentation:\nSet the value of an environment variable on the host machine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_host_env_var(key: K, value: V) -> AnyResult<()>\nwhere\n    K: AsRef,\n    V: AsRef,\n{\n    unsafe { set_env_var(key.as_ref().into(), value.as_ref().into())? };\n\n    Ok(())\n}\n```"}], "func_name": "set_host_env_var", "docstring": "Set the value of an environment variable on the host machine.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "97f9d8fa8dc4530a0bd740f0848a0d62100e8b05c55fb328c72c8361367160c3"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_host_paths\n\nDocumentation:\nAppend paths to the `PATH` environment variable on the host machine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_host_paths(paths: I) -> AnyResult<()>\nwhere\n    I: IntoIterator,\n    P: AsRef,\n{\n    let paths = paths\n        .into_iter()\n        .map(|p| p.as_ref().to_owned())\n        .collect::>();\n\n    set_host_env_var(\"PATH\", paths.join(\":\"))\n}\n```"}], "func_name": "add_host_paths", "docstring": "Append paths to the `PATH` environment variable on the host machine.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8991760c3d0c69b9c32d5392bb9fdb370a28e37d42ca521868042c948d3f1c99"}
{"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_real_path\n\nDocumentation:\nConvert the provided path into a [`PathBuf`] instance,\nwith the prefix resolved absolutely to the host.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_real_path

(path: P) -> AnyResult\nwhere\n P: AsRef,\n{\n Ok(PathBuf::from(unsafe {\n from_virtual_path(path.as_ref().to_string_lossy().into())?\n }))\n}\n```"}], "func_name": "into_real_path", "docstring": "Convert the provided path into a [`PathBuf`] instance,\nwith the prefix resolved absolutely to the host.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "73579ff989c5f932ae5f282701c6fe99700c05222d7326f6e0a9cbdd847c6694"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_virtual_path\n\nDocumentation:\nConvert the provided path into a [`VirtualPath`] instance,\nwith the prefix resolved to the WASM virtual whitelist.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_virtual_path

(path: P) -> AnyResult\nwhere\n P: AsRef,\n{\n let data = unsafe { to_virtual_path(path.as_ref().to_string_lossy().into())? };\n\n Ok(data.0)\n}\n```"}], "func_name": "into_virtual_path", "docstring": "Convert the provided path into a [`VirtualPath`] instance,\nwith the prefix resolved to the WASM virtual whitelist.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9ef836a4162b7be0546cacabfed537d097048d5178966776c157a987c3fa94dd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_plugin_id\n\nDocumentation:\nReturn the ID for the current plugin.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_plugin_id() -> AnyResult {\n Ok(config::get(\"plugin_id\")?.expect(\"Missing plugin ID!\"))\n}\n```"}], "func_name": "get_plugin_id", "docstring": "Return the ID for the current plugin.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "373903e09be821e3b3ea44bcd4f600cbc5d8d2acafcd2077b9db3e1c9e3184c2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_host_environment\n\nDocumentation:\nReturn information about the host environment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_host_environment() -> AnyResult {\n let config = config::get(\"host_environment\")?.expect(\"Missing host environment!\");\n let config: HostEnvironment = json::from_str(&config)?;\n\n Ok(config)\n}\n```"}], "func_name": "get_host_environment", "docstring": "Return information about the host environment.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "46de5625ae75aeb45f27b6bc41dbc1e0cb460013aacf166707d7bdaf885f231e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_test_environment\n\nDocumentation:\nReturn information about the testing environment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_test_environment() -> AnyResult> {\n if let Some(config) = config::get(\"test_environment\")? {\n return Ok(json::from_str(&config)?);\n }\n\n Ok(None)\n}\n```"}], "func_name": "get_test_environment", "docstring": "Return information about the testing environment.", "repo": "moonrepo/proto", "path": "crates/warpgate-pdk/src/funcs.rs", "url": "https://github.com/moonrepo/proto/blob/master/crates/warpgate-pdk/src/funcs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5e19ddeb6c4c1fcf1c9ab0db15ae1b15a4c03d9300adfb84ecdbe502e3867c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build_query_tree\n\nDocumentation:\nTranslate a parsed and validated input source (specified by `source` and `cursor`) into a `QueryTree`.\nWhen `is_cpp` is set, C++ specific features are enabled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build_query_tree(\n source: &str,\n cursor: &mut TreeCursor,\n is_cpp: bool,\n regex_constraints: Option,\n) -> Result {\n _build_query_tree(source, cursor, 0, is_cpp, false, false, regex_constraints)\n}\n```"}], "func_name": "build_query_tree", "docstring": "Translate a parsed and validated input source (specified by `source` and `cursor`) into a `QueryTree`.\nWhen `is_cpp` is set, C++ specific features are enabled.", "repo": "weggli-rs/weggli", "path": "src/builder.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5774d3e606ff26802a5fa69efd1112cc1bbd1f1dee006ed7f229fc8f634abe38"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_captures\n\nDocumentation:\nIterates through `captures` starting at `offset` and returns the necessary query predicates as a string.\nIn addition, all captured variables are added to the `variables` set.\n\nFor constant captures (such as function or variable names), `process_captures` creates a equality predicate\n(#eq @0 \"memcpy\"). For variables, we enforce equality between two occurences of the same variable (#eq @0 @1)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_captures(\n captures: &[Capture],\n offset: usize,\n variables: &mut HashSet,\n) -> String {\n // HashMap to store the capture indexes of each variable.\n let mut vars: HashMap> = HashMap::new();\n // tree-sitter query predicates\n let mut sexp = String::new();\n\n // Note that we need offset to assign the right names to our\n // capture predicates. So simply passing captures[offset..] to\n // the function would not work.\n for (i, c) in captures.iter().skip(offset).enumerate() {\n match c {\n Capture::Display => (),\n Capture::Check(s) => {\n sexp += &format!(r#\"(#eq? @{} \"{}\")\"#, (i + offset), s);\n }\n Capture::Variable(var, _) => {\n vars.entry(var.clone())\n .or_insert_with(Vec::new)\n .push(i + offset);\n\n // Add var to our result set\n variables.insert(var.clone());\n }\n _ => (),\n }\n }\n\n // Create equality predicates for all captures pointing at the same variable\n for (_, vec) in vars.iter() {\n if vec.len() > 1 {\n let a = vec[0].to_string();\n for capture in vec.iter().skip(1) {\n let b = capture.to_string();\n sexp += &format!(r#\"(#eq? @{} @{})\"#, a, b);\n }\n }\n }\n\n sexp\n}\n```"}], "func_name": "process_captures", "docstring": "Iterates through `captures` starting at `offset` and returns the necessary query predicates as a string.\nIn addition, all captured variables are added to the `variables` set.\n\nFor constant captures (such as function or variable names), `process_captures` creates a equality predicate\n(#eq @0 \"memcpy\"). For variables, we enforce equality between two occurences of the same variable (#eq @0 @1)", "repo": "weggli-rs/weggli", "path": "src/builder.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "afd72e9bdd41f964eab450385178263832ade55aa9ea7d83655fb464c6597ffb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nTranslate the tree below `c` into a tree-sitter query string.\nThis function is responsible for the weggli's greediness by turning\nthe fixed input AST into a tree-sitter query that can match on different but related\nAST's in the queried source code. Besides returning the query string, `build` will\nalso add captures and negations to the active QueryBuilder.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn build(\n &mut self,\n c: &mut TreeCursor,\n depth: usize,\n strict_mode: bool,\n parent: &'static str,\n ) -> Result {\n // This function works by recursively processing every node in the tree,\n // creating new sub queries, captures or negative queries when needed\n // and slowly constructing the final tree-sitter query (note that query predicates are only\n // added in build_query_tree after this function returns)\n // Query building isn't performance critical as it's only done once at program startup, so\n // we don't have to worry much about optimizing this code.\n\n // Anonymous nodes are string constants like \"+\" or \"+=\".\n // We can simply copy them into the query.\n if !c.node().is_named() {\n return Ok(format!(r#\"\"{}\"\"#, c.node().kind()));\n }\n\n let kind = c.node().kind();\n\n // First handle special cases. Note the implicit fallthroughs to the\n // default case after this match statement.\n match kind {\n \"binary_expression\" if self.is_transformable_binary_exp(c.node()) => {\n assert!(c.goto_first_child());\n let left = self.build(c, depth + 1, strict_mode, kind)?;\n\n // operator\n assert!(c.goto_next_sibling());\n let op = c.node().kind();\n\n let alt_op = match op {\n \">\" => \"<\",\n \"<\" => \">\",\n \"<=\" => \">=\",\n \">=\" => \"<=\",\n // handle +, *, &, |, == and !=\n _ => op,\n };\n\n assert!(c.goto_next_sibling());\n let right = self.build(c, depth + 1, strict_mode, kind)?;\n\n c.goto_parent();\n return Ok(\n format! {\"[(binary_expression left: {0} operator: \\\"{1}\\\" right: {2})\n (binary_expression left: {2} operator: \\\"{3}\\\" right: {0})]\", left, op, right, alt_op},\n );\n }\n // Handle not: xyz;\n \"labeled_statement\" => {\n let label = c.node().child(0).unwrap();\n if self.get_text(&label).to_uppercase() == \"NOT\" {\n self.build_negative_query(c)?;\n // negative sub queries are special in that they do not add anything\n // to the main query. We just return an empty string, which will get\n // filtered out by _build_query_tree\n return Ok(\"\".to_string());\n } else if self.get_text(&label).to_uppercase() == \"STRICT\" {\n if let Some(child) = c.node().named_child(1) {\n return self.build(&mut child.walk(), depth, true, kind);\n } else {\n return Ok(\"\".to_string());\n }\n }\n }\n // Build a multi-pattern tree for {.., .., ..}\n \"compound_statement\" if c.node().named_child_count() > 0 => {\n self.id += 1;\n let mut c = c.node().walk();\n let capture = Capture::Subquery(Box::new(_build_query_tree(\n &self.query_source,\n &mut c,\n self.id,\n self.cpp,\n true,\n false, // limit strictness to current depth for now\n Some(self.regex_constraints.clone()),\n )?));\n return Ok(\"(compound_statement) @\".to_string()\n + &add_capture(&mut self.captures, capture));\n }\n // Greedy matching of all type of identifiers + variable support\n \"identifier\"\n | \"type_identifier\"\n | \"field_identifier\"\n | \"sized_type_specifier\"\n | \"primitive_type\"\n | \"namespace_identifier\" => return self.build_identifier(c, parent),\n \"assignment_expression\" => return self.build_assignment(c, depth, strict_mode),\n // Function calls (including wildcards)\n \"call_expression\" => {\n if let Some(s) = self.build_call_expr(c, depth, strict_mode, kind)? {\n return Ok(s);\n }\n }\n // When the query contains an expression statement (e.g \"func(x,y);\")\n // we insert a sub query for the expression instead. This ensures that\n // we also match on x=func(x,y); or if (func(x,y))\n // We can't unwrap the expression statements in all cases so make sure\n // the parent node is either a compound statement, a TU or one of our\n // two \"magic\" labels.\n \"expression_statement\" => {\n if let Some(child) = c.node().named_child(0) {\n if let Some(p) = c.node().parent() {\n if [\n \"compound_statement\",\n \"labeled_statement\",\n \"translation_unit\",\n ]\n .contains(&p.kind())\n {\n let mut unwrap = !strict_mode || self.is_subexpr_wildcard(child);\n if p.kind() == \"labeled_statement\" {\n let l = p.child(0).unwrap();\n let label = self.get_text(&l).to_uppercase();\n if label != \"NOT\" && label != \"STRICT\" {\n unwrap = false;\n }\n }\n if self.get_text(&child) == \"_\" {\n unwrap = false\n }\n\n if unwrap {\n c.goto_first_child();\n return self.build(c, depth, strict_mode, kind);\n }\n }\n }\n }\n }\n \"number_literal\" => {\n let pattern = self.get_text(&c.node());\n\n let capture = if let Some(num) = parse_number_literal(pattern) {\n Capture::Number(num)\n } else {\n warn! {\"Could not parse {} as a number. Forcing string matching\", pattern}\n Capture::Check(pattern.to_string())\n };\n\n return Ok(\n format! {\"(number_literal) @{}\", &add_capture(&mut self.captures, capture)},\n );\n }\n \"string_literal\" => {\n let pattern = self.get_text(&c.node());\n let unquoted = &pattern[1..pattern.len() - 1];\n\n if unquoted.starts_with('$') {\n let c = Capture::Variable(\n unquoted.to_string(),\n self.regex_constraints.get(unquoted),\n );\n return Ok(\n format! {\"(string_literal) @{}\", &add_capture(&mut self.captures, c)},\n );\n }\n }\n _ => (),\n }\n\n // Default case. Handle everything else\n\n // Enforce ordering of arguments by anchoring them to each other if the user specified\n // more than one arg.\n let anchoring = kind == \"argument_list\" && c.node().named_child_count() > 1;\n\n let is_funcdef = kind == \"function_definition\";\n\n let mut result = format!(\"({}\", c.node().kind());\n if !c.goto_first_child() {\n if !c.node().is_named() {\n return Ok(format!(r#\"\"{}\"\"#, c.node().kind()));\n }\n return Ok(result + \")\");\n }\n\n // Iterate through all fields\n loop {\n let name = c.field_name();\n\n // Named fields (for example \"condition\" and \"consequence\" for an if statement)\n if let Some(n) = name {\n result += &format!(\" {}:\", n);\n\n // Recursively build the query for the child node.\n let t = self.build(c, depth + 1, strict_mode, n)?;\n\n if n == \"declarator\" && is_funcdef {\n // hacky way to make \"_ func()\" match on \"bar * func()\".\n // The problem is that the pointer isn't part of the return\n // type but is a pointer_declaration wrapper\n // around the function_definition. We add a single level wildcard\n // to still match, but of course that still fails for bar** func() :/\n // TODO: Think about better ways to implement this, maybe we should just add another sub expression\n result += &format!(\"([(_ {}) ({})])\", t, t);\n } else {\n result += &t\n }\n // Argument Lists for function calls\n } else if c.node().is_named() {\n if anchoring {\n result += \" .\";\n }\n result += \" \";\n result += &self.build(c, depth + 1, strict_mode, kind)?;\n // Unnamed syntax nodes like {, ; or keywords.\n } else {\n let sexp = self.build(c, depth + 1, strict_mode, kind)?;\n // We want to highlight keywords in our search results so we add Display captures\n if sexp.chars().all(|c| char::is_alphanumeric(c) || c == '\"') && sexp != \"\\\"\\\"\\\"\" {\n result += &format!(\n \" {} @{}\",\n sexp,\n &add_capture(&mut self.captures, Capture::Display)\n );\n }\n }\n\n if !c.goto_next_sibling() {\n break;\n }\n }\n c.goto_parent();\n\n debug!(\"generated query: {}\", result);\n Ok(result + \")\")\n }\n```"}], "func_name": "build", "docstring": "Translate the tree below `c` into a tree-sitter query string.\nThis function is responsible for the weggli's greediness by turning\nthe fixed input AST into a tree-sitter query that can match on different but related\nAST's in the queried source code. Besides returning the query string, `build` will\nalso add captures and negations to the active QueryBuilder.", "repo": "weggli-rs/weggli", "path": "src/builder.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c2dd1532fba5f83c32b9897551f49e71a01312d1317d241e26beef930882d66"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_arguments\n\nDocumentation:\nParse command arguments and return them inside the Args structure.\nThe clap crate handles program exit and error messages for invalid arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_arguments() -> Args {\n let matches = App::new(\"weggli\")\n .version(\"0.2.4\")\n .author(\"Felix Wilhelm \")\n .about(help::ABOUT)\n .setting(clap::AppSettings::ArgRequiredElseHelp)\n .setting(clap::AppSettings::UnifiedHelpMessage)\n .template(help::TEMPLATE)\n .help_message(\"Prints help information.\")\n .version_message(\"Prints version information.\")\n .arg(\n Arg::with_name(\"PATTERN\")\n .help(\"Search pattern.\")\n .long_help(help::PATTERN)\n .required(true)\n .index(1),\n )\n .arg(\n Arg::with_name(\"p\")\n .long(\"pattern\")\n .short(\"p\")\n .help(\"Specify additional search patterns.\")\n .takes_value(true)\n .multiple(true)\n .number_of_values(1),\n )\n .arg(\n Arg::with_name(\"PATH\")\n .help(\"A file or directory to search.\")\n .long_help(help::PATH)\n .required(true)\n .index(2),\n )\n .arg(\n Arg::with_name(\"v\")\n .long(\"verbose\")\n .short(\"v\")\n .multiple(true)\n .help(\"Sets the level of verbosity.\"),\n )\n .arg(\n Arg::with_name(\"extensions\")\n .long(\"extensions\")\n .short(\"e\")\n .takes_value(true)\n .multiple(true)\n .help(\"File extensions to include in the search.\"),\n )\n .arg(\n Arg::with_name(\"before\")\n .long(\"before\")\n .short(\"B\")\n .takes_value(true)\n .help(\"Lines to print before a match. Default = 5.\"),\n )\n .arg(\n Arg::with_name(\"after\")\n .long(\"after\")\n .short(\"A\")\n .takes_value(true)\n .help(\"Lines to print after a match. Default = 5.\"),\n )\n .arg(\n Arg::with_name(\"limit\")\n .long(\"limit\")\n .short(\"l\")\n .takes_value(false)\n .help(\"Only show the first match in each function.\"),\n )\n .arg(\n Arg::with_name(\"regex\")\n .long(\"regex\")\n .short(\"R\")\n .takes_value(true)\n .multiple(true)\n .number_of_values(1)\n .help(\"Enforce that a variable has to (not) match a regex.\")\n .long_help(help::REGEX),\n )\n .arg(\n Arg::with_name(\"cpp\")\n .short(\"X\")\n .long(\"cpp\")\n .takes_value(false)\n .help(\"Enable C++ mode.\"),\n )\n .arg(\n Arg::with_name(\"color\")\n .short(\"C)\")\n .long(\"color\")\n .takes_value(false)\n .help(\"Force enable color output.\"),\n )\n .arg(\n Arg::with_name(\"force\")\n .long(\"force\")\n .short(\"f\")\n .takes_value(false)\n .help(\"Force a search even if the queries contains syntax errors.\"),\n )\n .arg(\n Arg::with_name(\"unique\")\n .long(\"unique\")\n .short(\"u\")\n .takes_value(false)\n .help(\"Enforce uniqueness of variable matches.\")\n .long_help(help::UNIQUE),\n )\n .arg(\n Arg::with_name(\"exclude\")\n .long(\"exclude\")\n .takes_value(true)\n .multiple(true)\n .help(\"Exclude files that match the given regex.\"),\n )\n .arg(\n Arg::with_name(\"include\")\n .long(\"include\")\n .takes_value(true)\n .multiple(true)\n .help(\"Only search files that match the given regex.\"),\n )\n .arg(\n Arg::with_name(\"line-numbers\")\n .long(\"line-numbers\")\n .short(\"n\")\n .takes_value(false)\n .help(\"Enable line numbers\"),\n )\n .get_matches();\n\n let helper = |option_name| -> Vec {\n if let Some(v) = matches.values_of(option_name) {\n v.map(|v| v.to_string()).collect()\n } else {\n vec![]\n }\n };\n\n let level = match matches.occurrences_of(\"v\") {\n 0 => LevelFilter::Warn,\n 1 => log::LevelFilter::Info,\n _ => log::LevelFilter::Debug,\n };\n\n let _ = SimpleLogger::init(level, Config::default());\n\n let directory = Path::new(matches.value_of(\"PATH\").unwrap_or(\".\"));\n\n let mut pattern = vec![matches.value_of(\"PATTERN\").unwrap().to_string()];\n if let Some(p) = matches.values_of(\"p\") {\n pattern.extend(p.map(|v| v.to_string()))\n }\n\n let regexes = helper(\"regex\");\n\n let path = if directory.is_absolute() || directory.to_string_lossy() == \"-\" {\n directory.to_path_buf()\n } else {\n std::env::current_dir().unwrap().join(directory)\n };\n\n let before = match matches.value_of(\"before\") {\n Some(v) => v.parse().unwrap_or(5),\n None => 5,\n };\n\n let after = match matches.value_of(\"after\") {\n Some(v) => v.parse().unwrap_or(5),\n None => 5,\n };\n\n let limit = matches.occurrences_of(\"limit\") > 0;\n\n let unique = matches.occurrences_of(\"unique\") > 0;\n\n let cpp = matches.occurrences_of(\"cpp\") > 0;\n let force_color = matches.occurrences_of(\"color\") > 0;\n\n let extensions = {\n let e = helper(\"extensions\");\n if e.is_empty() {\n if !cpp {\n vec![\"c\".to_string(), \"h\".into()]\n } else {\n vec![\n \"cc\".to_string(),\n \"cpp\".into(),\n \"h\".into(),\n \"cxx\".into(),\n \"hpp\".into(),\n ]\n }\n } else {\n e\n }\n };\n\n let exclude = helper(\"exclude\");\n let include = helper(\"include\");\n\n let force_query = matches.occurrences_of(\"force\") > 0;\n\n let enable_line_numbers = matches.occurrences_of(\"line-numbers\") > 0;\n\n Args {\n path,\n pattern,\n before,\n after,\n extensions,\n regexes,\n limit,\n cpp,\n unique,\n force_color,\n force_query,\n include,\n exclude,\n enable_line_numbers,\n }\n}\n```"}], "func_name": "parse_arguments", "docstring": "Parse command arguments and return them inside the Args structure.\nThe clap crate handles program exit and error messages for invalid arguments.", "repo": "weggli-rs/weggli", "path": "src/cli.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/cli.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f89025055036cb44ee759a41150db3b17cc3e9666ad2a7af72c2f42d6a3f8244"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse\n\nDocumentation:\nHelper function to parse an input string\ninto a tree-sitter tree, using our own slightly modified\nC grammar. This function won't fail but the returned\nTree might be invalid and contain errors.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse(source: &str, cpp: bool) -> Tree {\n let mut parser = get_parser(cpp);\n parser.parse(source, None).unwrap()\n}\n```"}], "func_name": "parse", "docstring": "Helper function to parse an input string\ninto a tree-sitter tree, using our own slightly modified\nC grammar. This function won't fail but the returned\nTree might be invalid and contain errors.", "repo": "weggli-rs/weggli", "path": "src/lib.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7de01ea1671f120ab1652b530131e96226fcf628b71960ee296d691eed4b98a7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_search_pattern\n\nDocumentation:\nTranslate the search pattern in `pattern` into a weggli QueryTree.\n`is_cpp` enables C++ mode. `force_query` can be used to allow queries with syntax errors.\nWe support some basic normalization (adding { } around queries) and store the normalized form\nin `normalized_patterns` to avoid lifetime issues.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_search_pattern(\n pattern: &str,\n is_cpp: bool,\n force_query: bool,\n regex_constraints: Option,\n) -> Result {\n let mut tree = parse(pattern, is_cpp);\n let mut p = pattern;\n\n let temp_pattern;\n\n // Try to fix missing ';' at the end of a query.\n // weggli 'memcpy(a,b,size)' should work.\n if tree.root_node().has_error() && !pattern.ends_with(';') {\n temp_pattern = format!(\"{};\", &p);\n let fixed_tree = parse(&temp_pattern, is_cpp);\n if !fixed_tree.root_node().has_error() {\n info!(\"normalizing query: add missing ;\");\n tree = fixed_tree;\n p = &temp_pattern;\n }\n }\n\n let temp_pattern2;\n\n // Try to do query normalization to support missing { }\n // 'memcpy(_);' -> {memcpy(_);}\n if !tree.root_node().has_error() {\n let c = tree.root_node().child(0);\n if let Some(n) = c {\n if !VALID_NODE_KINDS.contains(&n.kind()) {\n temp_pattern2 = format!(\"{{{}}}\", &p);\n let fixed_tree = parse(&temp_pattern2, is_cpp);\n if !fixed_tree.root_node().has_error() {\n info!(\"normalizing query: add {}\", \"{}\");\n tree = fixed_tree;\n p = &temp_pattern2;\n }\n }\n }\n }\n\n let mut c = validate_query(&tree, p, force_query)?;\n\n builder::build_query_tree(p, &mut c, is_cpp, regex_constraints)\n}\n```"}], "func_name": "parse_search_pattern", "docstring": "Translate the search pattern in `pattern` into a weggli QueryTree.\n`is_cpp` enables C++ mode. `force_query` can be used to allow queries with syntax errors.\nWe support some basic normalization (adding { } around queries) and store the normalized form\nin `normalized_patterns` to avoid lifetime issues.", "repo": "weggli-rs/weggli", "path": "src/lib.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "71a9b5df8d2d5da39f24cc10832ac175f7e05bfcfa8dd37479aacab4d573824f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: validate_query\n\nDocumentation:\nValidates the user supplied search query and quits with an error message in case\nit contains syntax errors or isn't rooted in one of `VALID_NODE_KINDS`\nIf `force` is true, syntax errors are ignored. Returns a cursor to the\nroot node.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn validate_query<'a>(\n tree: &'a tree_sitter::Tree,\n query: &str,\n force: bool,\n) -> Result, QueryError> {\n if tree.root_node().has_error() && !force {\n let mut errmsg = format!(\"{}\", \"Error! Query parsing failed:\".red().bold());\n let mut cursor = tree.root_node().walk();\n\n let mut first_error = None;\n loop {\n let node = cursor.node();\n if node.has_error() {\n if node.is_error() || node.is_missing() {\n first_error = Some(node);\n break;\n } else if !cursor.goto_first_child() {\n break;\n }\n } else if !cursor.goto_next_sibling() {\n break;\n }\n }\n\n if let Some(node) = first_error {\n errmsg.push_str(&format!(\" {}\", &query[0..node.start_byte()].italic()));\n if node.is_missing() {\n errmsg.push_str(&format!(\n \"{}{}{}\",\n \" [MISSING \".red(),\n node.kind().red().bold(),\n \" ] \".red()\n ));\n }\n errmsg.push_str(&format!(\n \"{}{}\",\n &query[node.start_byte()..node.end_byte()]\n .red()\n .italic()\n .bold(),\n &query[node.end_byte()..].italic()\n ));\n }\n\n return Err(QueryError { message: errmsg });\n }\n\n info!(\"query sexp: {}\", tree.root_node().to_sexp());\n\n let mut c = tree.walk();\n\n if c.node().named_child_count() > 1 {\n return Err(QueryError {\n message: format!(\n \"{}'{}' query contains multiple root nodes\",\n \"Error: \".red(),\n query\n ),\n });\n }\n\n c.goto_first_child();\n\n if !VALID_NODE_KINDS.contains(&c.node().kind()) {\n return Err(QueryError {\n message: format!(\n \"{}'{}' is not a supported query root node.\",\n \"Error: \".red(),\n query\n ),\n });\n }\n\n Ok(c)\n}\n```"}], "func_name": "validate_query", "docstring": "Validates the user supplied search query and quits with an error message in case\nit contains syntax errors or isn't rooted in one of `VALID_NODE_KINDS`\nIf `force` is true, syntax errors are ignored. Returns a cursor to the\nroot node.", "repo": "weggli-rs/weggli", "path": "src/lib.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "068b5a8a718fd025e842ce8177a03b610bac28407796cd88b72fbaf18e567226"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_regexes\n\nDocumentation:\nValidate all passed regexes and compile them.\nReturns an error if an invalid regex is supplied otherwise return a RegexMap\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_regexes(regexes: &[String]) -> Result {\n let mut result = HashMap::new();\n\n for r in regexes {\n let mut s = r.splitn(2, '=');\n let var = s.next().ok_or_else(|| RegexError::InvalidArg(r.clone()))?;\n let raw_regex = s.next().ok_or_else(|| RegexError::InvalidArg(r.clone()))?;\n\n let mut normalized_var = if var.starts_with('$') {\n var.to_string()\n } else {\n \"$\".to_string() + var\n };\n let negative = normalized_var.ends_with('!');\n\n if negative {\n normalized_var.pop(); // remove !\n }\n\n let regex = Regex::new(raw_regex)?;\n result.insert(normalized_var, (negative, regex));\n }\n Ok(RegexMap::new(result))\n}\n```"}], "func_name": "process_regexes", "docstring": "Validate all passed regexes and compile them.\nReturns an error if an invalid regex is supplied otherwise return a RegexMap", "repo": "weggli-rs/weggli", "path": "src/main.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c7b93a71c4b8c4a41204cce9834d427da9a1b559258500e19c724b3b5ee1e97"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: iter_files\n\nDocumentation:\nRecursively iterate through all files under `path` that match an ending listed in `extensions`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn iter_files(path: &Path, extensions: Vec) -> impl Iterator {\n let is_hidden = |entry: &walkdir::DirEntry| {\n entry\n .file_name()\n .to_str()\n .map(|s| s.starts_with('.'))\n .unwrap_or(false)\n };\n\n WalkDir::new(path)\n .into_iter()\n .filter_entry(move |e| !is_hidden(e))\n .filter_map(|e| e.ok())\n .filter(move |entry| {\n if entry.file_type().is_dir() {\n return false;\n }\n\n let path = entry.path();\n\n match path.extension() {\n None => return false,\n Some(ext) => {\n let s = ext.to_str().unwrap_or_default();\n if !extensions.contains(&s.to_string()) {\n return false;\n }\n }\n }\n true\n })\n}\n```"}], "func_name": "iter_files", "docstring": "Recursively iterate through all files under `path` that match an ending listed in `extensions`", "repo": "weggli-rs/weggli", "path": "src/main.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "591550b2a097273c9d952cd6233735643891e8e20ed3462ee7b6470ebe06ddb7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_files_worker\n\nDocumentation:\nIterate over all paths in `files`, parse files that might contain a match for any of the queries\nin `work` and send them to the next worker using `sender`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_files_worker(\n files: Vec,\n sender: Sender<(Arc, Tree, String)>,\n work: &[WorkItem],\n is_cpp: bool,\n) {\n let tl = ThreadLocal::new();\n\n files\n .into_par_iter()\n .for_each_with(sender, move |sender, path| {\n let maybe_parse = |path| {\n let c = match fs::read(path) {\n Ok(content) => content,\n Err(_) => return None,\n };\n\n let source = String::from_utf8_lossy(&c);\n\n let potential_match = work.iter().any(|WorkItem { qt: _, identifiers }| {\n identifiers.iter().all(|i| source.find(i).is_some())\n });\n\n if !potential_match {\n None\n } else {\n let mut parser = tl\n .get_or(|| RefCell::new(weggli::get_parser(is_cpp)))\n .borrow_mut();\n let tree = parser.parse(&source.as_bytes(), None).unwrap();\n Some((tree, source.to_string()))\n }\n };\n if let Some((source_tree, source)) = maybe_parse(&path) {\n sender\n .send((\n std::sync::Arc::new(source),\n source_tree,\n path.display().to_string(),\n ))\n .unwrap();\n }\n });\n}\n```"}], "func_name": "parse_files_worker", "docstring": "Iterate over all paths in `files`, parse files that might contain a match for any of the queries\nin `work` and send them to the next worker using `sender`.", "repo": "weggli-rs/weggli", "path": "src/main.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d972f59f953af1601919ba23bc91ea13b02b38fffd5c805033564695654d633e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: multi_query_worker\n\nDocumentation:\nFor multi query runs, we collect all independent results first and filter\nthem to make sure that variable assignments are valid for all queries.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn multi_query_worker(\n results_rx: Receiver,\n num_queries: usize,\n before: usize,\n after: usize,\n enable_line_numbers: bool\n) {\n let mut query_results = Vec::with_capacity(num_queries);\n for _ in 0..num_queries {\n query_results.push(Vec::new());\n }\n\n // collect all results\n for ctx in results_rx {\n query_results[ctx.query_index].push(ctx);\n }\n\n // filter results.\n // We now have a list of results for each query in query_results, but we still need to ensure\n // that we only show results for query A that can be combined with at least one result in query B\n // (and C and D).\n // TODO: The runtime of this approach is pretty terrible, think about improving it.\n let filter = |x: &mut Vec, y: &mut Vec| {\n x.retain(|r| {\n y.iter()\n .any(|f| r.result.chainable(&r.source, &f.result, &f.source))\n })\n };\n\n for i in 0..query_results.len() {\n let (part1, part2) = query_results.split_at_mut(i + 1);\n let a = part1.last_mut().unwrap();\n for b in part2 {\n filter(a, b);\n filter(b, a);\n }\n }\n\n // Print remaining results\n query_results.into_iter().for_each(|rv| {\n rv.into_iter().for_each(|r| {\n let line = r.source[..r.result.start_offset()].matches('\\n').count() + 1;\n println!(\n \"{}:{}\\n{}\",\n r.path.bold(),\n line,\n r.result.display(&r.source, before, after, enable_line_numbers)\n );\n })\n });\n}\n```"}], "func_name": "multi_query_worker", "docstring": "For multi query runs, we collect all independent results first and filter\nthem to make sure that variable assignments are valid for all queries.", "repo": "weggli-rs/weggli", "path": "src/main.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ccbda175181113e79141b38f89918f7ef8a4bc486fdb08a4b48ec5673659971"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: variables\n\nDocumentation:\nReturn all query variables used in a query.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn variables(&self) -> HashSet {\n let mut result = HashSet::new();\n for c in &self.captures {\n match c {\n Capture::Variable(s, _) => {\n result.insert(s.to_string());\n }\n Capture::Subquery(t) => {\n let sub_vars = t.variables();\n result.extend(sub_vars);\n }\n _ => (),\n }\n }\n\n for neg in &self.negations {\n result.extend(neg.qt.variables())\n }\n\n result\n }\n```"}], "func_name": "variables", "docstring": "Return all query variables used in a query.", "repo": "weggli-rs/weggli", "path": "src/query.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/query.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "393ebee182f3c8e3f08c303531148e2dfddd4c1c02fb580542d0f55765e467a7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: identifiers\n\nDocumentation:\nReturn all identifiers (function, variable and types) used in a query.\nThis can be used to filter inputs without doing a full parse.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn identifiers(&self) -> Vec {\n let mut result = Vec::new();\n for c in &self.captures {\n match c {\n Capture::Check(s) => result.push(s.to_string()),\n Capture::Subquery(t) => {\n let mut sub_identifiers = t.identifiers();\n result.append(&mut sub_identifiers);\n }\n _ => (),\n }\n }\n\n result\n }\n```"}], "func_name": "identifiers", "docstring": "Return all identifiers (function, variable and types) used in a query.\nThis can be used to filter inputs without doing a full parse.", "repo": "weggli-rs/weggli", "path": "src/query.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/query.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6db884f42a4aa04ce076d1bd3ba6ba906eeb1007859becfe1295a126e9edafa0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: display\n\nDocumentation:\nReturns a colored String representation of the result with `before` + `after`\ncontext lines around each captured node.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn display(\n &self,\n source: &'b str,\n before: usize,\n after: usize,\n enable_line_numbers: bool,\n ) -> String {\n let mut d = DisplayHelper::new(source);\n\n // add header\n d.add(self.function.start..self.function.start + 1);\n\n let mut sorted = self.captures.clone();\n sorted.sort_by(|a, b| a.range.start.cmp(&b.range.start));\n\n // Before printing out the different nodes, we first filter out overlapping nodes.\n // If we matched on `(a + b)` and also captured `b` clean_ranges will not contain\n // the range for `b`.\n let mut clean_ranges: Vec> = Vec::with_capacity(self.captures.len());\n for r in sorted.into_iter().skip(1).map(|c| c.range) {\n if !clean_ranges.is_empty() && clean_ranges.last().unwrap().contains(&r.start) {\n continue;\n }\n clean_ranges.push(r.clone());\n }\n\n // Add highlighted elements\n for r in clean_ranges.into_iter() {\n d.highlight(r);\n }\n\n // add function ending\n d.add(self.function.end - 1..self.function.end);\n\n d.display(before, after, enable_line_numbers)\n }\n```"}], "func_name": "display", "docstring": "Returns a colored String representation of the result with `before` + `after`\ncontext lines around each captured node.", "repo": "weggli-rs/weggli", "path": "src/result.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/result.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "60508da9e4acde015a7ab0aad6ab22ca98e61764476042fcc091d1d86531f6cc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: value\n\nDocumentation:\nReturn the captured value for a variable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn value(&self, var: &str, source: &'b str) -> Option<&'b str> {\n match self.vars.get(var) {\n None => None,\n Some(i) => Some(&source[self.captures[*i].range.clone()]),\n }\n }\n```"}], "func_name": "value", "docstring": "Return the captured value for a variable.", "repo": "weggli-rs/weggli", "path": "src/result.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/result.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5e618a8390ce39cb4c39a00d2705f0ecab30e2510913089eb21a91d76b1c3353"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: merge\n\nDocumentation:\nTry to merge two QueryResults from the same source file.\nThe function returns None if the variable assignments for the two results differ.\nIf `enforce_order` is set this can fail because the new ranges\nare not strictly after the current ranges.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn merge(\n &self,\n other: &QueryResult,\n source: &str,\n enforce_order: bool,\n ) -> Option {\n let mut vars = self.vars.clone();\n\n let mut captures = self.captures.clone();\n\n if enforce_order\n && other\n .captures\n .iter()\n .any(|r| self.captures.iter().any(|r2| r.range.start <= r2.range.end))\n {\n return None;\n }\n\n captures.extend(other.captures.clone());\n\n for (k, v) in other.vars.iter() {\n match self.value(k, source) {\n None => {\n vars.insert(k.clone(), v + self.captures.len());\n }\n Some(s) => {\n if s != other.value(k, source).unwrap() {\n return None;\n }\n }\n }\n }\n\n Some(QueryResult::new(captures, vars, self.function.clone()))\n }\n```"}], "func_name": "merge", "docstring": "Try to merge two QueryResults from the same source file.\nThe function returns None if the variable assignments for the two results differ.\nIf `enforce_order` is set this can fail because the new ranges\nare not strictly after the current ranges.", "repo": "weggli-rs/weggli", "path": "src/result.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/result.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e76600789f6425127e8f105bc910af35aaa6f6da71ee9c01d6321cb71b793fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: chainable\n\nDocumentation:\nChecks if two QueryResults from different source files have compatible variable assignments\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn chainable(&self, source: &str, other: &QueryResult, other_source: &str) -> bool {\n !other.vars.iter().any(|(k, _)| {\n if let Some(value) = self.value(k, source) {\n value != other.value(k, other_source).unwrap()\n } else {\n false\n }\n })\n }\n```"}], "func_name": "chainable", "docstring": "Checks if two QueryResults from different source files have compatible variable assignments", "repo": "weggli-rs/weggli", "path": "src/result.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/result.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18144bbcb44da90ffffb0666352116441cd6449bb6f58962a73a4f385353df6d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_capture_result\n\nDocumentation:\nTry to find the result for the capture `capture_idx` in query `query_id`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_capture_result(&self, query_id: usize, capture_idx: u32) -> Option<&CaptureResult> {\n self.captures\n .iter()\n .find(|c| c.capture_idx == capture_idx && c.query_id == query_id)\n }\n```"}], "func_name": "get_capture_result", "docstring": "Try to find the result for the capture `capture_idx` in query `query_id`", "repo": "weggli-rs/weggli", "path": "src/result.rs", "url": "https://github.com/weggli-rs/weggli/blob/master/src/result.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "99c4134dd7888f3611935e2eb53da45bb694c7db2dcda4f81d04b9d1e00f56bf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compare_result\n\nDocumentation:\nCompare results from two different implementations of a command.\n\n# Arguments\n* `test_type` - The command.\n* `input` - The input provided to the command.\n* `rust_result` - The result of running the command with the Rust implementation.\n* `gnu_result` - The result of running the command with the GNU implementation.\n* `fail_on_stderr_diff` - Whether to fail the test if there is a difference in stderr output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compare_result(\n test_type: &str,\n input: &str,\n pipe_input: Option<&str>,\n rust_result: &CommandResult,\n gnu_result: &CommandResult,\n fail_on_stderr_diff: bool,\n) {\n print_section(format!(\"Compare result for: {test_type} {input}\"));\n\n if let Some(pipe) = pipe_input {\n println!(\"Pipe: {pipe}\");\n }\n\n let mut discrepancies = Vec::new();\n let mut should_panic = false;\n\n if rust_result.stdout.trim() != gnu_result.stdout.trim() {\n discrepancies.push(\"stdout differs\");\n println!(\"Rust stdout:\");\n print_or_empty(rust_result.stdout.as_str());\n println!(\"GNU stdout:\");\n print_or_empty(gnu_result.stdout.as_ref());\n print_diff(&rust_result.stdout, &gnu_result.stdout);\n should_panic = true;\n }\n\n if rust_result.stderr.trim() != gnu_result.stderr.trim() {\n discrepancies.push(\"stderr differs\");\n println!(\"Rust stderr:\");\n print_or_empty(rust_result.stderr.as_str());\n println!(\"GNU stderr:\");\n print_or_empty(gnu_result.stderr.as_str());\n print_diff(&rust_result.stderr, &gnu_result.stderr);\n if fail_on_stderr_diff {\n should_panic = true;\n }\n }\n\n if rust_result.exit_code != gnu_result.exit_code {\n discrepancies.push(\"exit code differs\");\n println!(\n \"Different exit code: (Rust: {}, GNU: {})\",\n rust_result.exit_code, gnu_result.exit_code\n );\n should_panic = true;\n }\n\n if discrepancies.is_empty() {\n print_end_with_status(\"Same behavior\", true);\n } else {\n print_with_style(\n format!(\"Discrepancies detected: {}\", discrepancies.join(\", \")),\n Style::new().red(),\n );\n if should_panic {\n print_end_with_status(\n format!(\"Test failed and will panic for: {test_type} {input}\"),\n false,\n );\n panic!(\"Test failed for: {test_type} {input}\");\n } else {\n print_end_with_status(\n format!(\"Test completed with discrepancies for: {test_type} {input}\"),\n false,\n );\n }\n }\n println!();\n}\n```"}], "func_name": "compare_result", "docstring": "Compare results from two different implementations of a command.\n\n# Arguments\n* `test_type` - The command.\n* `input` - The input provided to the command.\n* `rust_result` - The result of running the command with the Rust implementation.\n* `gnu_result` - The result of running the command with the GNU implementation.\n* `fail_on_stderr_diff` - Whether to fail the test if there is a difference in stderr output.", "repo": "uutils/coreutils", "path": "fuzz/uufuzz/src/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/fuzz/uufuzz/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d1ea39097175c4e7654ac9ccddbe41db52ef601f46fd80864132d596211059e7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: binary_path\n\nDocumentation:\n# Panics\nPanics if the binary path cannot be determined\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn binary_path(args: &mut impl Iterator) -> PathBuf {\n match args.next() {\n Some(ref s) if !s.is_empty() => PathBuf::from(s),\n _ => std::env::current_exe().unwrap(),\n }\n}\n```"}], "func_name": "binary_path", "docstring": "# Panics\nPanics if the binary path cannot be determined", "repo": "uutils/coreutils", "path": "src/bin/coreutils.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/bin/coreutils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ce2718f76e7783b4b26ebc62e1857be9b6c8e07623bca41fe3484c8b90c67809"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: gen_completions\n\nDocumentation:\nPrints completions for the utility in the first parameter for the shell in the second parameter to stdout\n# Panics\nPanics if the utility map is empty\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn gen_completions(\n args: impl Iterator,\n util_map: &UtilityMap,\n) -> ! {\n let all_utilities: Vec<_> = std::iter::once(\"coreutils\")\n .chain(util_map.keys().copied())\n .collect();\n\n let matches = Command::new(\"completion\")\n .about(\"Prints completions to stdout\")\n .arg(\n Arg::new(\"utility\")\n .value_parser(clap::builder::PossibleValuesParser::new(all_utilities))\n .required(true),\n )\n .arg(\n Arg::new(\"shell\")\n .value_parser(clap::builder::EnumValueParser::::new())\n .required(true),\n )\n .get_matches_from(std::iter::once(OsString::from(\"completion\")).chain(args));\n\n let utility = matches.get_one::(\"utility\").unwrap();\n let shell = *matches.get_one::(\"shell\").unwrap();\n\n let mut command = if utility == \"coreutils\" {\n gen_coreutils_app(util_map)\n } else {\n util_map.get(utility).unwrap().1()\n };\n let bin_name = std::env::var(\"PROG_PREFIX\").unwrap_or_default() + utility;\n\n clap_complete::generate(shell, &mut command, bin_name, &mut io::stdout());\n io::stdout().flush().unwrap();\n process::exit(0);\n}\n```"}], "func_name": "gen_completions", "docstring": "Prints completions for the utility in the first parameter for the shell in the second parameter to stdout\n# Panics\nPanics if the utility map is empty", "repo": "uutils/coreutils", "path": "src/bin/coreutils.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/bin/coreutils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c2d10054652bc77e3255e24e846178e1712f9456fcd633a40c77290317559eba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: gen_manpage\n\nDocumentation:\nGenerate the manpage for the utility in the first parameter\n# Panics\nPanics if the utility map is empty\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn gen_manpage(\n args: impl Iterator,\n util_map: &UtilityMap,\n) -> ! {\n let all_utilities: Vec<_> = std::iter::once(\"coreutils\")\n .chain(util_map.keys().copied())\n .collect();\n\n let matches = Command::new(\"manpage\")\n .about(\"Prints manpage to stdout\")\n .arg(\n Arg::new(\"utility\")\n .value_parser(clap::builder::PossibleValuesParser::new(all_utilities))\n .required(true),\n )\n .get_matches_from(std::iter::once(OsString::from(\"manpage\")).chain(args));\n\n let utility = matches.get_one::(\"utility\").unwrap();\n\n let command = if utility == \"coreutils\" {\n gen_coreutils_app(util_map)\n } else {\n setup_localization_or_exit(utility);\n util_map.get(utility).unwrap().1()\n };\n\n let man = clap_mangen::Man::new(command);\n man.render(&mut io::stdout())\n .expect(\"Man page generation failed\");\n io::stdout().flush().unwrap();\n process::exit(0);\n}\n```"}], "func_name": "gen_manpage", "docstring": "Generate the manpage for the utility in the first parameter\n# Panics\nPanics if the utility map is empty", "repo": "uutils/coreutils", "path": "src/bin/coreutils.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/bin/coreutils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "98d4c110e92824bff48490b07cfa584899ef242c4e6d27e8d471ee9f0824a8b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: gen_coreutils_app\n\nDocumentation:\n# Panics\nPanics if the utility map is empty\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn gen_coreutils_app(util_map: &UtilityMap) -> Command {\n let mut command = Command::new(\"coreutils\");\n for (name, (_, sub_app)) in util_map {\n // Recreate a small subcommand with only the relevant info\n // (name & short description)\n let about = sub_app()\n .get_about()\n .expect(\"Could not get the 'about'\")\n .to_string();\n let sub_app = Command::new(name).about(about);\n command = command.subcommand(sub_app);\n }\n command\n}\n```"}], "func_name": "gen_coreutils_app", "docstring": "# Panics\nPanics if the utility map is empty", "repo": "uutils/coreutils", "path": "src/bin/coreutils.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/bin/coreutils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7759fa6b907bf83b5ccad14917dfa4838a9d3edcaf8c217982a576ebb6099f21"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_padding\n\nDocumentation:\nDetermines if the input buffer ends with padding ('=') after trimming trailing whitespace.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn has_padding(input: &mut R) -> UResult {\n let mut buf = Vec::new();\n input\n .read_to_end(&mut buf)\n .map_err(|err| USimpleError::new(1, format_read_error(err.kind())))?;\n\n // Reverse iterator and skip trailing whitespace without extra collections\n let has_padding = buf\n .iter()\n .rfind(|&&byte| !byte.is_ascii_whitespace())\n .is_some_and(|&byte| byte == b'=');\n\n input.seek(SeekFrom::Start(0))?;\n Ok(has_padding)\n}\n```"}], "func_name": "has_padding", "docstring": "Determines if the input buffer ends with padding ('=') after trimming trailing whitespace.", "repo": "uutils/coreutils", "path": "src/uu/base32/src/base_common.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/base32/src/base_common.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0277a11456955756cfe27f83ab59b5df78cf4f272d4d0a1dedc683cc300dcab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: can_write_fast\n\nDocumentation:\nWe can write fast if we can simply copy the contents of the file to\nstdout, without augmenting the output with e.g. line numbers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn can_write_fast(&self) -> bool {\n !(self.show_tabs\n || self.show_nonprint\n || self.show_ends\n || self.squeeze_blank\n || self.number != NumberingMode::None)\n }\n```"}], "func_name": "can_write_fast", "docstring": "We can write fast if we can simply copy the contents of the file to\nstdout, without augmenting the output with e.g. line numbers.", "repo": "uutils/coreutils", "path": "src/uu/cat/src/cat.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cat/src/cat.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0b1e828f2772dd8d060ffd87ae9583dd597c0687b8bf4d8a9fa2bb372933942"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_exact\n\nDocumentation:\nMove exactly `num_bytes` bytes from `read_fd` to `write_fd`.\n\nPanics if not enough bytes can be read.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn copy_exact(read_fd: &impl AsFd, write_fd: &impl AsFd, num_bytes: usize) -> nix::Result<()> {\n let mut left = num_bytes;\n let mut buf = [0; BUF_SIZE];\n while left > 0 {\n let read = unistd::read(read_fd, &mut buf)?;\n assert_ne!(read, 0, \"unexpected end of pipe\");\n let mut written = 0;\n while written < read {\n match unistd::write(write_fd, &buf[written..read])? {\n 0 => panic!(),\n n => written += n,\n }\n }\n left -= read;\n }\n Ok(())\n}\n```"}], "func_name": "copy_exact", "docstring": "Move exactly `num_bytes` bytes from `read_fd` to `write_fd`.\n\nPanics if not enough bytes can be read.", "repo": "uutils/coreutils", "path": "src/uu/cat/src/splice.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cat/src/splice.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d4ceb304238abaa234dcd98e6ca8e57cb2ce281686817585c2dc0279c3695a5e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_unsafe_overwrite\n\nDocumentation:\nAn unsafe overwrite occurs when the same nonempty file is used as both stdin and stdout,\nand the file offset of stdin is positioned earlier than that of stdout.\nIn this scenario, bytes read from stdin are written to a later part of the file\nvia stdout, which can then be read again by stdin and written again by stdout,\ncausing an infinite loop and potential file corruption.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_unsafe_overwrite(input: &I, output: &O) -> bool {\n // `FileInformation::from_file` returns an error if the file descriptor is closed, invalid,\n // or refers to a non-regular file (e.g., socket, pipe, or special device).\n let Ok(input_info) = FileInformation::from_file(input) else {\n return false;\n };\n let Ok(output_info) = FileInformation::from_file(output) else {\n return false;\n };\n if input_info != output_info || output_info.file_size() == 0 {\n return false;\n }\n if is_appending(output) {\n return true;\n }\n // `lseek` returns an error if the file descriptor is closed or it refers to\n // a non-seekable resource (e.g., pipe, socket, or some devices).\n let Ok(input_pos) = lseek(input.as_fd(), 0, Whence::SeekCur) else {\n return false;\n };\n let Ok(output_pos) = lseek(output.as_fd(), 0, Whence::SeekCur) else {\n return false;\n };\n input_pos < output_pos\n}\n```"}], "func_name": "is_unsafe_overwrite", "docstring": "An unsafe overwrite occurs when the same nonempty file is used as both stdin and stdout,\nand the file offset of stdin is positioned earlier than that of stdout.\nIn this scenario, bytes read from stdin are written to a later part of the file\nvia stdout, which can then be read again by stdin and written again by stdout,\ncausing an infinite loop and potential file corruption.", "repo": "uutils/coreutils", "path": "src/uu/cat/src/platform/unix.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cat/src/platform/unix.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "89780bbbea82bc3cbcc94660dcd719c67684feb3a1b17c794841fe86dea828e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_appending\n\nDocumentation:\nWhether the file is opened with the `O_APPEND` flag\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_appending(file: &F) -> bool {\n let flags_raw = fcntl(file.as_fd(), FcntlArg::F_GETFL).unwrap_or_default();\n let flags = OFlag::from_bits_truncate(flags_raw);\n flags.contains(OFlag::O_APPEND)\n}\n```"}], "func_name": "is_appending", "docstring": "Whether the file is opened with the `O_APPEND` flag", "repo": "uutils/coreutils", "path": "src/uu/cat/src/platform/unix.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cat/src/platform/unix.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "64e37edad8a62403cfad158ff62899a3b8c90b090d90a8ef617832ac928b1912"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_unsafe_overwrite\n\nDocumentation:\nAn unsafe overwrite occurs when the same file is used as both stdin and stdout\nand the stdout file is not empty.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_unsafe_overwrite(input: &I, output: &O) -> bool {\n if !is_same_file_by_path(input, output) {\n return false;\n }\n\n // Check if the output file is empty\n FileInformation::from_file(output)\n .map(|info| info.file_size() > 0)\n .unwrap_or(false)\n}\n```"}], "func_name": "is_unsafe_overwrite", "docstring": "An unsafe overwrite occurs when the same file is used as both stdin and stdout\nand the stdout file is not empty.", "repo": "uutils/coreutils", "path": "src/uu/cat/src/platform/windows.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cat/src/platform/windows.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8d23ce1425325c25773c8f556dfa423da3129848d4c3d580fa52056bc0f95589"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_file_path_from_handle\n\nDocumentation:\nGet the file path for a file handle\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_file_path_from_handle(file: &F) -> Option {\n let handle = file.as_raw();\n let mut path_buf = vec![0u16; 4096];\n\n // SAFETY: We should check how many bytes was written to `path_buf`\n // and only read that many bytes from it.\n let len = unsafe {\n GetFinalPathNameByHandleW(\n handle,\n path_buf.as_mut_ptr(),\n path_buf.len() as u32,\n FILE_NAME_NORMALIZED | VOLUME_NAME_NT,\n )\n };\n if len == 0 {\n return None;\n }\n let path = OsString::from_wide(&path_buf[..len as usize]);\n Some(PathBuf::from(path))\n}\n```"}], "func_name": "get_file_path_from_handle", "docstring": "Get the file path for a file handle", "repo": "uutils/coreutils", "path": "src/uu/cat/src/platform/windows.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cat/src/platform/windows.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "34d62a1a281589738b5961d62099ceea5f2f3e06a9de8079c778858dc4291164"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_same_file_by_path\n\nDocumentation:\nCompare two file handles if they correspond to the same file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_same_file_by_path(a: &A, b: &B) -> bool {\n match (get_file_path_from_handle(a), get_file_path_from_handle(b)) {\n (Some(path1), Some(path2)) => path1 == path2,\n _ => false,\n }\n}\n```"}], "func_name": "is_same_file_by_path", "docstring": "Compare two file handles if they correspond to the same file", "repo": "uutils/coreutils", "path": "src/uu/cat/src/platform/windows.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cat/src/platform/windows.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd4a3f1a0e3bafd3ef30909ad1db4ccd41225b20a43cf98e10c817246e655969"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_negative_modes\n\nDocumentation:\nExtract negative modes (starting with '-') from the rest of the arguments.\n\nThis is mainly required for GNU compatibility, where \"non-positional negative\" modes are used\nas the actual positional MODE. Some examples of these cases are:\n* \"chmod -w -r file\", which is the same as \"chmod -w,-r file\"\n* \"chmod -w file -r\", which is the same as \"chmod -w,-r file\"\n\nThese can currently not be handled by clap.\nTherefore it might be possible that a pseudo MODE is inserted to pass clap parsing.\nThe pseudo MODE is later replaced by the extracted (and joined) negative modes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extract_negative_modes(mut args: impl uucore::Args) -> (Option, Vec) {\n // we look up the args until \"--\" is found\n // \"-mode\" will be extracted into parsed_cmode_vec\n let (parsed_cmode_vec, pre_double_hyphen_args): (Vec, Vec) =\n args.by_ref().take_while(|a| a != \"--\").partition(|arg| {\n let arg = if let Some(arg) = arg.to_str() {\n arg.to_string()\n } else {\n return false;\n };\n arg.len() >= 2\n && arg.starts_with('-')\n && matches!(\n arg.chars().nth(1).unwrap(),\n 'r' | 'w' | 'x' | 'X' | 's' | 't' | 'u' | 'g' | 'o' | '0'..='7'\n )\n });\n\n let mut clean_args = Vec::new();\n if !parsed_cmode_vec.is_empty() {\n // we need a pseudo cmode for clap, which won't be used later.\n // this is required because clap needs the default \"chmod MODE FILE\" scheme.\n clean_args.push(\"w\".into());\n }\n clean_args.extend(pre_double_hyphen_args);\n\n if let Some(arg) = args.next() {\n // as there is still something left in the iterator, we previously consumed the \"--\"\n // -> add it to the args again\n clean_args.push(\"--\".into());\n clean_args.push(arg);\n }\n clean_args.extend(args);\n\n let parsed_cmode = Some(\n parsed_cmode_vec\n .iter()\n .map(|s| s.to_str().unwrap())\n .collect::>()\n .join(\",\"),\n )\n .filter(|s| !s.is_empty());\n (parsed_cmode, clean_args)\n}\n```"}], "func_name": "extract_negative_modes", "docstring": "Extract negative modes (starting with '-') from the rest of the arguments.\n\nThis is mainly required for GNU compatibility, where \"non-positional negative\" modes are used\nas the actual positional MODE. Some examples of these cases are:\n* \"chmod -w -r file\", which is the same as \"chmod -w,-r file\"\n* \"chmod -w file -r\", which is the same as \"chmod -w,-r file\"\n\nThese can currently not be handled by clap.\nTherefore it might be possible that a pseudo MODE is inserted to pass clap parsing.\nThe pseudo MODE is later replaced by the extracted (and joined) negative modes.", "repo": "uutils/coreutils", "path": "src/uu/chmod/src/chmod.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chmod/src/chmod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "97554a9671c92c5f2579dacb3f44461991c5ac61a57c5b40d885fdbda4ee139a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_uid\n\nDocumentation:\nParses the user string to extract the UID.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_uid(user: &str, spec: &str, sep: char) -> UResult> {\n if user.is_empty() {\n return Ok(None);\n }\n match Passwd::locate(user) {\n Ok(u) => Ok(Some(u.uid)), // We have been able to get the uid\n Err(_) => {\n // we have NOT been able to find the uid\n // but we could be in the case where we have user.group\n if spec.contains('.') && !spec.contains(':') && sep == ':' {\n // but the input contains a '.' but not a ':'\n // we might have something like username.groupname\n // So, try to parse it this way\n parse_spec(spec, '.').map(|(uid, _)| uid)\n } else {\n // It's possible that the `user` string contains a\n // numeric user ID, in which case, we respect that.\n match user.parse() {\n Ok(uid) => Ok(Some(uid)),\n Err(_) => Err(USimpleError::new(\n 1,\n format!(\"invalid user: {}\", spec.quote()),\n )),\n }\n }\n }\n }\n}\n```"}], "func_name": "parse_uid", "docstring": "Parses the user string to extract the UID.", "repo": "uutils/coreutils", "path": "src/uu/chown/src/chown.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chown/src/chown.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "623cc9f607d8b8aa510dceb1e43edac29df6260a900af0b0c264179a1e1323c8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_gid\n\nDocumentation:\nParses the group string to extract the GID.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_gid(group: &str, spec: &str) -> UResult> {\n if group.is_empty() {\n return Ok(None);\n }\n match Group::locate(group) {\n Ok(g) => Ok(Some(g.gid)),\n Err(_) => match group.parse() {\n Ok(gid) => Ok(Some(gid)),\n Err(_) => Err(USimpleError::new(\n 1,\n format!(\"invalid group: {}\", spec.quote()),\n )),\n },\n }\n}\n```"}], "func_name": "parse_gid", "docstring": "Parses the group string to extract the GID.", "repo": "uutils/coreutils", "path": "src/uu/chown/src/chown.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chown/src/chown.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "19aecf697263040ca812fbb2dfa3fa0537d9092ee644fd46a02d49799bb2d40c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_spec\n\nDocumentation:\nParse the owner/group specifier string into a user ID and a group ID.\n\nThe `spec` can be of the form:\n\n* `\"owner:group\"`,\n* `\"owner\"`,\n* `\":group\"`,\n\nand the owner or group can be specified either as an ID or a\nname. The `sep` argument specifies which character to use as a\nseparator between the owner and group; calling code should set\nthis to `':'`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_spec(spec: &str, sep: char) -> UResult<(Option, Option)> {\n assert!(['.', ':'].contains(&sep));\n let mut args = spec.splitn(2, sep);\n let user = args.next().unwrap_or(\"\");\n let group = args.next().unwrap_or(\"\");\n\n let uid = parse_uid(user, spec, sep)?;\n let gid = parse_gid(group, spec)?;\n\n if user.chars().next().map(char::is_numeric).unwrap_or(false)\n && group.is_empty()\n && spec != user\n {\n // if the arg starts with an id numeric value, the group isn't set but the separator is provided,\n // we should fail with an error\n return Err(USimpleError::new(\n 1,\n format!(\"invalid spec: {}\", spec.quote()),\n ));\n }\n\n Ok((uid, gid))\n}\n```"}], "func_name": "parse_spec", "docstring": "Parse the owner/group specifier string into a user ID and a group ID.\n\nThe `spec` can be of the form:\n\n* `\"owner:group\"`,\n* `\"owner\"`,\n* `\":group\"`,\n\nand the owner or group can be specified either as an ID or a\nname. The `sep` argument specifies which character to use as a\nseparator between the owner and group; calling code should set\nthis to `':'`.", "repo": "uutils/coreutils", "path": "src/uu/chown/src/chown.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chown/src/chown.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a0180ff57c225e89f3fee74b7024f5f6ae4042cac87329e3449efc78c5e6be86"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_userspec\n\nDocumentation:\nParse a user and group from the argument to `--userspec`.\n\nThe `spec` must be of the form `[USER][:[GROUP]]`, otherwise an\nerror is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_userspec(spec: &str) -> UserSpec {\n match spec.split_once(':') {\n // \"\"\n None if spec.is_empty() => UserSpec::NeitherGroupNorUser,\n // \"usr\"\n None => UserSpec::UserOnly(spec.to_string()),\n // \":\"\n Some((\"\", \"\")) => UserSpec::NeitherGroupNorUser,\n // \":grp\"\n Some((\"\", grp)) => UserSpec::GroupOnly(grp.to_string()),\n // \"usr:\"\n Some((usr, \"\")) => UserSpec::UserOnly(usr.to_string()),\n // \"usr:grp\"\n Some((usr, grp)) => UserSpec::UserAndGroup(usr.to_string(), grp.to_string()),\n }\n}\n```"}], "func_name": "parse_userspec", "docstring": "Parse a user and group from the argument to `--userspec`.\n\nThe `spec` must be of the form `[USER][:[GROUP]]`, otherwise an\nerror is returned.", "repo": "uutils/coreutils", "path": "src/uu/chroot/src/chroot.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chroot/src/chroot.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "57a53bc9f1bdc3faccd10e547f66cce72467b009b4623ef84c929c345f9567ed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nParse parameters from the command-line arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from(matches: &clap::ArgMatches) -> UResult {\n let newroot = match matches.get_one::(options::NEWROOT) {\n Some(v) => Path::new(v).to_path_buf(),\n None => return Err(ChrootError::MissingNewRoot.into()),\n };\n let groups = match matches.get_one::(options::GROUPS) {\n None => None,\n Some(s) => {\n if s.is_empty() {\n Some(vec![])\n } else {\n Some(parse_group_list(s)?)\n }\n }\n };\n let skip_chdir = matches.get_flag(options::SKIP_CHDIR);\n let userspec = matches\n .get_one::(options::USERSPEC)\n .map(|s| parse_userspec(s));\n Ok(Self {\n newroot,\n skip_chdir,\n groups,\n userspec,\n })\n }\n```"}], "func_name": "from", "docstring": "Parse parameters from the command-line arguments.", "repo": "uutils/coreutils", "path": "src/uu/chroot/src/chroot.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chroot/src/chroot.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "83875f29dd7b7cb5f3898ee5979e4b77bc438991577246002a2bdf2cb819d320"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: name_to_uid\n\nDocumentation:\nGet the UID for the given username, falling back to numeric parsing.\n\nAccording to the documentation of GNU `chroot`, \"POSIX requires that\nthese commands first attempt to resolve the specified string as a\nname, and only once that fails, then try to interpret it as an ID.\"\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn name_to_uid(name: &str) -> Result {\n match usr2uid(name) {\n Ok(uid) => Ok(uid),\n Err(_) => name\n .parse::()\n .map_err(|_| ChrootError::NoSuchUser),\n }\n}\n```"}], "func_name": "name_to_uid", "docstring": "Get the UID for the given username, falling back to numeric parsing.\n\nAccording to the documentation of GNU `chroot`, \"POSIX requires that\nthese commands first attempt to resolve the specified string as a\nname, and only once that fails, then try to interpret it as an ID.\"", "repo": "uutils/coreutils", "path": "src/uu/chroot/src/chroot.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chroot/src/chroot.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "215dac2f1329f5201c7a2b8219114681982f983002d3c747ccdcce8e5dda7c16"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: name_to_gid\n\nDocumentation:\nGet the GID for the given group name, falling back to numeric parsing.\n\nAccording to the documentation of GNU `chroot`, \"POSIX requires that\nthese commands first attempt to resolve the specified string as a\nname, and only once that fails, then try to interpret it as an ID.\"\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn name_to_gid(name: &str) -> Result {\n match grp2gid(name) {\n Ok(gid) => Ok(gid),\n Err(_) => name\n .parse::()\n .map_err(|_| ChrootError::NoSuchGroup),\n }\n}\n```"}], "func_name": "name_to_gid", "docstring": "Get the GID for the given group name, falling back to numeric parsing.\n\nAccording to the documentation of GNU `chroot`, \"POSIX requires that\nthese commands first attempt to resolve the specified string as a\nname, and only once that fails, then try to interpret it as an ID.\"", "repo": "uutils/coreutils", "path": "src/uu/chroot/src/chroot.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chroot/src/chroot.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bcb7d9159caea2097050022859cf4a2cfc8dd365985425875426573e7ad4a69d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: supplemental_gids\n\nDocumentation:\nGet the list of group IDs for the given user.\n\nAccording to the GNU documentation, \"the supplementary groups are\nset according to the system defined list for that user\". This\nfunction gets that list.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn supplemental_gids(uid: libc::uid_t) -> Vec {\n match Passwd::locate(uid) {\n Err(_) => vec![],\n Ok(passwd) => passwd.belongs_to(),\n }\n}\n```"}], "func_name": "supplemental_gids", "docstring": "Get the list of group IDs for the given user.\n\nAccording to the GNU documentation, \"the supplementary groups are\nset according to the system defined list for that user\". This\nfunction gets that list.", "repo": "uutils/coreutils", "path": "src/uu/chroot/src/chroot.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chroot/src/chroot.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf93c1c2241895a9447e11086de5bd3c5daa4d9714a5519a52a492ee4dda387f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_supplemental_gids\n\nDocumentation:\nSet the supplemental group IDs for this process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_supplemental_gids(gids: &[libc::gid_t]) -> std::io::Result<()> {\n #[cfg(any(target_vendor = \"apple\", target_os = \"freebsd\", target_os = \"openbsd\"))]\n let n = gids.len() as libc::c_int;\n #[cfg(any(target_os = \"linux\", target_os = \"android\"))]\n let n = gids.len() as libc::size_t;\n let err = unsafe { setgroups(n, gids.as_ptr()) };\n if err == 0 {\n Ok(())\n } else {\n Err(Error::last_os_error())\n }\n}\n```"}], "func_name": "set_supplemental_gids", "docstring": "Set the supplemental group IDs for this process.", "repo": "uutils/coreutils", "path": "src/uu/chroot/src/chroot.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chroot/src/chroot.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c075754ab185759f9a2733d4076a8ea418df8a24111dce8eaea240e8cd4ecda"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_gid\n\nDocumentation:\nSet the group ID of this process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_gid(gid: libc::gid_t) -> std::io::Result<()> {\n let err = unsafe { setgid(gid) };\n if err == 0 {\n Ok(())\n } else {\n Err(Error::last_os_error())\n }\n}\n```"}], "func_name": "set_gid", "docstring": "Set the group ID of this process.", "repo": "uutils/coreutils", "path": "src/uu/chroot/src/chroot.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chroot/src/chroot.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ecf5815d7b3b6a868b499cecadce27f0340fc01d10b78e8441a5cb34ca83710"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_uid\n\nDocumentation:\nSet the user ID of this process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_uid(uid: libc::uid_t) -> std::io::Result<()> {\n let err = unsafe { setuid(uid) };\n if err == 0 {\n Ok(())\n } else {\n Err(Error::last_os_error())\n }\n}\n```"}], "func_name": "set_uid", "docstring": "Set the user ID of this process.", "repo": "uutils/coreutils", "path": "src/uu/chroot/src/chroot.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chroot/src/chroot.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "450d8f0a40833b07ae2190c4ba835b319d036cc68464b00626195a61bb3fb574"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_missing_groups\n\nDocumentation:\nSet supplemental groups when the `--groups` argument is not specified.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_missing_groups(strategy: Strategy) -> Result<(), ChrootError> {\n match strategy {\n Strategy::Nothing => Ok(()),\n Strategy::FromUID(uid, false) => {\n let gids = supplemental_gids(uid);\n if gids.is_empty() {\n Err(ChrootError::NoGroupSpecified(uid))\n } else {\n set_supplemental_gids(&gids).map_err(ChrootError::SetGroupsFailed)\n }\n }\n Strategy::FromUID(uid, true) => {\n let gids = supplemental_gids(uid);\n set_supplemental_gids(&gids).map_err(ChrootError::SetGroupsFailed)\n }\n }\n}\n```"}], "func_name": "handle_missing_groups", "docstring": "Set supplemental groups when the `--groups` argument is not specified.", "repo": "uutils/coreutils", "path": "src/uu/chroot/src/chroot.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chroot/src/chroot.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c6464ac450c55e36a25c8d66de032eca9e926d8754e025f09b5074a6cbcc021"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_supplemental_gids_with_strategy\n\nDocumentation:\nSet supplemental groups for this process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_supplemental_gids_with_strategy(\n strategy: Strategy,\n groups: Option<&Vec>,\n) -> Result<(), ChrootError> {\n match groups {\n None => handle_missing_groups(strategy),\n Some(groups) => {\n let mut gids = vec![];\n for group in groups {\n gids.push(name_to_gid(group)?);\n }\n set_supplemental_gids(&gids).map_err(ChrootError::SetGroupsFailed)\n }\n }\n}\n```"}], "func_name": "set_supplemental_gids_with_strategy", "docstring": "Set supplemental groups for this process.", "repo": "uutils/coreutils", "path": "src/uu/chroot/src/chroot.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chroot/src/chroot.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5ea84c62000a6b7a6cda12c403c945c27fcd3b53efb72007720c78110ea70292"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_context\n\nDocumentation:\nChange the root, set the user ID, and set the group IDs for this process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_context(options: &Options) -> UResult<()> {\n enter_chroot(&options.newroot, options.skip_chdir)?;\n match &options.userspec {\n None | Some(UserSpec::NeitherGroupNorUser) => {\n let strategy = Strategy::Nothing;\n set_supplemental_gids_with_strategy(strategy, options.groups.as_ref())?;\n }\n Some(UserSpec::UserOnly(user)) => {\n let uid = name_to_uid(user)?;\n let gid = uid as libc::gid_t;\n let strategy = Strategy::FromUID(uid, false);\n set_supplemental_gids_with_strategy(strategy, options.groups.as_ref())?;\n set_gid(gid).map_err(|e| ChrootError::SetGidFailed(user.to_string(), e))?;\n set_uid(uid).map_err(|e| ChrootError::SetUserFailed(user.to_string(), e))?;\n }\n Some(UserSpec::GroupOnly(group)) => {\n let gid = name_to_gid(group)?;\n let strategy = Strategy::Nothing;\n set_supplemental_gids_with_strategy(strategy, options.groups.as_ref())?;\n set_gid(gid).map_err(|e| ChrootError::SetGidFailed(group.to_string(), e))?;\n }\n Some(UserSpec::UserAndGroup(user, group)) => {\n let uid = name_to_uid(user)?;\n let gid = name_to_gid(group)?;\n let strategy = Strategy::FromUID(uid, true);\n set_supplemental_gids_with_strategy(strategy, options.groups.as_ref())?;\n set_gid(gid).map_err(|e| ChrootError::SetGidFailed(group.to_string(), e))?;\n set_uid(uid).map_err(|e| ChrootError::SetUserFailed(user.to_string(), e))?;\n }\n }\n Ok(())\n}\n```"}], "func_name": "set_context", "docstring": "Change the root, set the user ID, and set the group IDs for this process.", "repo": "uutils/coreutils", "path": "src/uu/chroot/src/chroot.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/chroot/src/chroot.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6672dc2d43a6baa3dec38db001d76820563f669cb2a62cf5b11fe8fbc1d1e60a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_local_to_root_parent\n\nDocumentation:\nGet a descendant path relative to the given parent directory.\n\nIf `root_parent` is `None`, then this just returns the `path`\nitself. Otherwise, this function strips the parent prefix from the\ngiven `path`, leaving only the portion of the path relative to the\nparent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_local_to_root_parent(\n path: &Path,\n root_parent: Option<&Path>,\n) -> Result {\n match root_parent {\n Some(parent) => {\n // On Windows, some paths are starting with \\\\?\n // but not always, so, make sure that we are consistent for strip_prefix\n // See https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file for more info\n #[cfg(windows)]\n let (path, parent) = (\n adjust_canonicalization(path),\n adjust_canonicalization(parent),\n );\n let path = path.strip_prefix(parent)?;\n Ok(path.to_path_buf())\n }\n None => Ok(path.to_path_buf()),\n }\n}\n```"}], "func_name": "get_local_to_root_parent", "docstring": "Get a descendant path relative to the given parent directory.\n\nIf `root_parent` is `None`, then this just returns the `path`\nitself. Otherwise, this function strips the parent prefix from the\ngiven `path`, leaving only the portion of the path relative to the\nparent.", "repo": "uutils/coreutils", "path": "src/uu/cp/src/copydir.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/copydir.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "88a4ac5832cad58c0d0bc1c8ab7ce0766b3963e164aa274cb422207a9172cd20"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: skip_last\n\nDocumentation:\nGiven an iterator, return all its items except the last.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn skip_last(mut iter: impl Iterator) -> impl Iterator {\n let last = iter.next();\n iter.scan(last, |state, item| state.replace(item))\n}\n```"}], "func_name": "skip_last", "docstring": "Given an iterator, return all its items except the last.", "repo": "uutils/coreutils", "path": "src/uu/cp/src/copydir.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/copydir.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00b47feba8d53c2d5eb9e6423aae86aa045d82b4d9c46a753e05382fdb426893"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_direntry\n\nDocumentation:\nCopy a single entry during a directory traversal.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn copy_direntry(\n progress_bar: Option<&ProgressBar>,\n entry: Entry,\n options: &Options,\n symlinked_files: &mut HashSet,\n preserve_hard_links: bool,\n copied_destinations: &HashSet,\n copied_files: &mut HashMap,\n) -> CopyResult<()> {\n let Entry {\n source_absolute,\n source_relative,\n local_to_target,\n target_is_file,\n } = entry;\n\n // If the source is a symbolic link and the options tell us not to\n // dereference the link, then copy the link object itself.\n if source_absolute.is_symlink() && !options.dereference {\n return copy_link(&source_absolute, &local_to_target, symlinked_files);\n }\n\n // If the source is a directory and the destination does not\n // exist, ...\n if source_absolute.is_dir() && !local_to_target.exists() {\n return if target_is_file {\n Err(\"cannot overwrite non-directory with directory\".into())\n } else {\n build_dir(&local_to_target, false, options, Some(&source_absolute))?;\n if options.verbose {\n println!(\"{}\", context_for(&source_relative, &local_to_target));\n }\n Ok(())\n };\n }\n\n // If the source is not a directory, then we need to copy the file.\n if !source_absolute.is_dir() {\n if let Err(err) = copy_file(\n progress_bar,\n &source_absolute,\n local_to_target.as_path(),\n options,\n symlinked_files,\n copied_destinations,\n copied_files,\n false,\n ) {\n if preserve_hard_links {\n if !source_absolute.is_symlink() {\n return Err(err);\n }\n // silent the error with a symlink\n // In case we do --archive, we might copy the symlink\n // before the file itself\n } else {\n // At this point, `path` is just a plain old file.\n // Terminate this function immediately if there is any\n // kind of error *except* a \"permission denied\" error.\n //\n // TODO What other kinds of errors, if any, should\n // cause us to continue walking the directory?\n match err {\n CpError::IoErrContext(e, _) if e.kind() == io::ErrorKind::PermissionDenied => {\n show!(uio_error!(\n e,\n \"cannot open {} for reading\",\n source_relative.quote(),\n ));\n }\n e => return Err(e),\n }\n }\n }\n }\n\n // In any other case, there is nothing to do, so we just return to\n // continue the traversal.\n Ok(())\n}\n```"}], "func_name": "copy_direntry", "docstring": "Copy a single entry during a directory traversal.", "repo": "uutils/coreutils", "path": "src/uu/cp/src/copydir.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/copydir.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7b8228c4ea763e71f6dbeb8f843963c850ff4d9da9743cea6739e15592163af8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: path_has_prefix\n\nDocumentation:\nDecide whether the second path is a prefix of the first.\n\nThis function canonicalizes the paths via\n[`uucore::fs::canonicalize`] before comparing.\n\n# Errors\n\nIf there is an error determining the canonical, absolute form of\neither path.\n\n# Examples\n\n```rust,ignore\nassert!(path_has_prefix(Path::new(\"/usr/bin\"), Path::new(\"/usr\")))\nassert!(!path_has_prefix(Path::new(\"/usr\"), Path::new(\"/usr/bin\")))\nassert!(!path_has_prefix(Path::new(\"/usr/bin\"), Path::new(\"/var/log\")))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn path_has_prefix(p1: &Path, p2: &Path) -> io::Result {\n let pathbuf1 = canonicalize(p1, MissingHandling::Normal, ResolveMode::Logical)?;\n let pathbuf2 = canonicalize(p2, MissingHandling::Normal, ResolveMode::Logical)?;\n\n Ok(pathbuf1.starts_with(pathbuf2))\n}\n```"}], "func_name": "path_has_prefix", "docstring": "Decide whether the second path is a prefix of the first.\n\nThis function canonicalizes the paths via\n[`uucore::fs::canonicalize`] before comparing.\n\n# Errors\n\nIf there is an error determining the canonical, absolute form of\neither path.\n\n# Examples\n\n```rust,ignore\nassert!(path_has_prefix(Path::new(\"/usr/bin\"), Path::new(\"/usr\")))\nassert!(!path_has_prefix(Path::new(\"/usr\"), Path::new(\"/usr/bin\")))\nassert!(!path_has_prefix(Path::new(\"/usr/bin\"), Path::new(\"/var/log\")))\n```", "repo": "uutils/coreutils", "path": "src/uu/cp/src/copydir.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/copydir.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "28d1ae217e052c71ca8b77a27f13a816d955e9c435908ec0e1fe58ce290b593d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: show_debug\n\nDocumentation:\nThis function prints the debug information of a file copy operation if\nno hard link or symbolic link is required, and data copy is required.\nIt prints the debug information of the offload, reflink, and sparse detection actions.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn show_debug(copy_debug: &CopyDebug) {\n println!(\n \"copy offload: {}, reflink: {}, sparse detection: {}\",\n copy_debug.offload.to_string(),\n copy_debug.reflink.to_string(),\n copy_debug.sparse_detection.to_string(),\n );\n}\n```"}], "func_name": "show_debug", "docstring": "This function prints the debug information of a file copy operation if\nno hard link or symbolic link is required, and data copy is required.\nIt prints the debug information of the offload, reflink, and sparse detection actions.", "repo": "uutils/coreutils", "path": "src/uu/cp/src/cp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/cp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba49ea911e4828fcb66a3427ab47786b672794289f5d4a2fdf51db6c3093e496"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: diff\n\nDocumentation:\nSet the field to Preserve::NO { explicit: true } if the corresponding field\nin other is set to Preserve::Yes { .. }.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn diff(self, other: &Self) -> Self {\n fn update_preserve_field(current: Preserve, other: Preserve) -> Preserve {\n if matches!(other, Preserve::Yes { .. }) {\n Preserve::No { explicit: true }\n } else {\n current\n }\n }\n Self {\n #[cfg(unix)]\n ownership: update_preserve_field(self.ownership, other.ownership),\n mode: update_preserve_field(self.mode, other.mode),\n timestamps: update_preserve_field(self.timestamps, other.timestamps),\n context: update_preserve_field(self.context, other.context),\n links: update_preserve_field(self.links, other.links),\n xattr: update_preserve_field(self.xattr, other.xattr),\n }\n }\n```"}], "func_name": "diff", "docstring": "Set the field to Preserve::NO { explicit: true } if the corresponding field\nin other is set to Preserve::Yes { .. }.", "repo": "uutils/coreutils", "path": "src/uu/cp/src/cp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/cp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "060446790efe4af54dcc6c29c8493b92e4899d7bb44935b022a4f8f52294fab4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_single_string\n\nDocumentation:\nTries to match string containing a parameter to preserve with the corresponding entry in the\nAttributes struct.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_single_string(value: &str) -> CopyResult {\n let value = value.to_lowercase();\n\n if value == \"all\" {\n return Ok(Self::ALL);\n }\n\n let mut new = Self::NONE;\n let attribute = match value.as_ref() {\n \"mode\" => &mut new.mode,\n #[cfg(unix)]\n \"ownership\" => &mut new.ownership,\n \"timestamps\" => &mut new.timestamps,\n \"context\" => &mut new.context,\n \"link\" | \"links\" => &mut new.links,\n \"xattr\" => &mut new.xattr,\n _ => {\n return Err(CpError::InvalidArgument(format!(\n \"invalid attribute {}\",\n value.quote()\n )));\n }\n };\n\n *attribute = Preserve::Yes { required: true };\n\n Ok(new)\n }\n```"}], "func_name": "parse_single_string", "docstring": "Tries to match string containing a parameter to preserve with the corresponding entry in the\nAttributes struct.", "repo": "uutils/coreutils", "path": "src/uu/cp/src/cp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/cp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6e90744c9a37a690a156da6743dbe4349511bad76420d38658cac19fee785fd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: force\n\nDocumentation:\nWhether to force overwriting the destination file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn force(&self) -> bool {\n matches!(self.overwrite, OverwriteMode::Clobber(ClobberMode::Force))\n }\n```"}], "func_name": "force", "docstring": "Whether to force overwriting the destination file.", "repo": "uutils/coreutils", "path": "src/uu/cp/src/cp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/cp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a520a0e884921c282f26dfb3076df5d7ecc6683453dad7e384ddc2b6083ecf0f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: determine\n\nDocumentation:\nReturn TargetType required for `target`.\n\nTreat target as a dir if we have multiple sources or the target\nexists and already is a directory\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn determine(sources: &[PathBuf], target: &Path) -> Self {\n if sources.len() > 1 || target.is_dir() {\n Self::Directory\n } else {\n Self::File\n }\n }\n```"}], "func_name": "determine", "docstring": "Return TargetType required for `target`.\n\nTreat target as a dir if we have multiple sources or the target\nexists and already is a directory", "repo": "uutils/coreutils", "path": "src/uu/cp/src/cp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/cp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ff0dfe2273786bf5857f6630f2d44e2f522d19ab02f87a630a696984df0a26dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_path_args\n\nDocumentation:\nReturns tuple of (Source paths, Target)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_path_args(\n mut paths: Vec,\n options: &Options,\n) -> CopyResult<(Vec, PathBuf)> {\n if paths.is_empty() {\n // No files specified\n return Err(\"missing file operand\".into());\n } else if paths.len() == 1 && options.target_dir.is_none() {\n // Only one file specified\n return Err(format!(\n \"missing destination file operand after {}\",\n paths[0].display().to_string().quote()\n )\n .into());\n }\n\n // Return an error if the user requested to copy more than one\n // file source to a file target\n if options.no_target_dir && options.target_dir.is_none() && paths.len() > 2 {\n return Err(format!(\"extra operand {:}\", paths[2].display().to_string().quote()).into());\n }\n\n let target = match options.target_dir {\n Some(ref target) => {\n // All path args are sources, and the target dir was\n // specified separately\n target.clone()\n }\n None => {\n // If there was no explicit target-dir, then use the last\n // path_arg\n paths.pop().unwrap()\n }\n };\n\n if options.strip_trailing_slashes {\n // clippy::assigning_clones added with Rust 1.78\n // Rust version = 1.76 on OpenBSD stable/7.5\n #[cfg_attr(not(target_os = \"openbsd\"), allow(clippy::assigning_clones))]\n for source in &mut paths {\n *source = source.components().as_path().to_owned();\n }\n }\n\n Ok((paths, target))\n}\n```"}], "func_name": "parse_path_args", "docstring": "Returns tuple of (Source paths, Target)", "repo": "uutils/coreutils", "path": "src/uu/cp/src/cp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/cp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48c67801c341edf5af29a57bb4dc1a450a54e0c5a0bb225443310a43a8daf3ed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: show_error_if_needed\n\nDocumentation:\nWhen handling errors, we don't always want to show them to the user. This function handles that.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn show_error_if_needed(error: &CpError) {\n match error {\n // When using --no-clobber, we don't want to show\n // an error message\n CpError::NotAllFilesCopied => {\n // Need to return an error code\n }\n CpError::Skipped(_) => {\n // touch a b && echo \"n\"|cp -i a b && echo $?\n // should return an error from GNU 9.2\n }\n _ => {\n show_error!(\"{error}\");\n }\n }\n}\n```"}], "func_name": "show_error_if_needed", "docstring": "When handling errors, we don't always want to show them to the user. This function handles that.", "repo": "uutils/coreutils", "path": "src/uu/cp/src/cp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/cp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6cfe3802abbd9de7fcf6b9c05338f208c3b176aae1a379a3ef47267580a6c3b8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy\n\nDocumentation:\nCopy all `sources` to `target`.\n\nReturns an `Err(Error::NotAllFilesCopied)` if at least one non-fatal error\nwas encountered.\n\nBehavior is determined by the `options` parameter, see [`Options`] for details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn copy(sources: &[PathBuf], target: &Path, options: &Options) -> CopyResult<()> {\n let target_type = TargetType::determine(sources, target);\n verify_target_type(target, &target_type)?;\n\n let mut non_fatal_errors = false;\n let mut seen_sources = HashSet::with_capacity(sources.len());\n let mut symlinked_files = HashSet::new();\n\n // to remember the copied files for further usage.\n // the FileInformation implemented the Hash trait by using\n // 1. inode number\n // 2. device number\n // the combination of a file's inode number and device number is unique throughout all the file systems.\n //\n // key is the source file's information and the value is the destination filepath.\n let mut copied_files: HashMap = HashMap::with_capacity(sources.len());\n // remember the copied destinations for further usage.\n // we can't use copied_files as it is because the key is the source file's information.\n let mut copied_destinations: HashSet = HashSet::with_capacity(sources.len());\n\n let progress_bar = if options.progress_bar {\n let pb = ProgressBar::new(disk_usage(sources, options.recursive)?)\n .with_style(\n ProgressStyle::with_template(\n \"{msg}: [{elapsed_precise}] {wide_bar} {bytes:>7}/{total_bytes:7}\",\n )\n .unwrap(),\n )\n .with_message(uucore::util_name());\n pb.tick();\n Some(pb)\n } else {\n None\n };\n\n for source in sources {\n let normalized_source = normalize_path(source);\n if options.backup == BackupMode::None && seen_sources.contains(&normalized_source) {\n let file_type = if source.symlink_metadata()?.file_type().is_dir() {\n \"directory\"\n } else {\n \"file\"\n };\n show_warning!(\n \"source {file_type} {} specified more than once\",\n source.quote()\n );\n } else {\n let dest = construct_dest_path(source, target, target_type, options)\n .unwrap_or_else(|_| target.to_path_buf());\n\n if fs::metadata(&dest).is_ok()\n && !fs::symlink_metadata(&dest)?.file_type().is_symlink()\n // if both `source` and `dest` are symlinks, it should be considered as an overwrite.\n || fs::metadata(source).is_ok()\n && fs::symlink_metadata(source)?.file_type().is_symlink()\n || matches!(options.copy_mode, CopyMode::SymLink)\n {\n // There is already a file and it isn't a symlink (managed in a different place)\n if copied_destinations.contains(&dest) && options.backup != BackupMode::Numbered {\n // If the target file was already created in this cp call, do not overwrite\n return Err(CpError::Error(format!(\n \"will not overwrite just-created '{}' with '{}'\",\n dest.display(),\n source.display()\n )));\n }\n }\n\n if let Err(error) = copy_source(\n progress_bar.as_ref(),\n source,\n target,\n target_type,\n options,\n &mut symlinked_files,\n &copied_destinations,\n &mut copied_files,\n ) {\n show_error_if_needed(&error);\n if !matches!(error, CpError::Skipped(false)) {\n non_fatal_errors = true;\n }\n } else {\n copied_destinations.insert(dest.clone());\n }\n }\n seen_sources.insert(normalized_source);\n }\n\n if let Some(pb) = progress_bar {\n pb.finish();\n }\n\n if non_fatal_errors {\n Err(CpError::NotAllFilesCopied)\n } else {\n Ok(())\n }\n}\n```"}], "func_name": "copy", "docstring": "Copy all `sources` to `target`.\n\nReturns an `Err(Error::NotAllFilesCopied)` if at least one non-fatal error\nwas encountered.\n\nBehavior is determined by the `options` parameter, see [`Options`] for details.", "repo": "uutils/coreutils", "path": "src/uu/cp/src/cp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/cp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dee5a717f619f8e163af51c212e8912a304c3835609b612c0ce76cd090592078"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_preserve\n\nDocumentation:\nHandles errors for attributes preservation. If the attribute is not required, and\nerrored, tries to show error (see `show_error_if_needed` for additional behavior details).\nIf it's required, then the error is thrown.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_preserve CopyResult<()>>(p: &Preserve, f: F) -> CopyResult<()> {\n match p {\n Preserve::No { .. } => {}\n Preserve::Yes { required } => {\n let result = f();\n if *required {\n result?;\n } else if let Err(error) = result {\n show_error_if_needed(&error);\n }\n }\n };\n Ok(())\n}\n```"}], "func_name": "handle_preserve", "docstring": "Handles errors for attributes preservation. If the attribute is not required, and\nerrored, tries to show error (see `show_error_if_needed` for additional behavior details).\nIf it's required, then the error is thrown.", "repo": "uutils/coreutils", "path": "src/uu/cp/src/cp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/cp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0030e15a7db271ab936910d5d5a815ec62b03bd1c3e9425c6a5e75efa831ed7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_sparse_detection\n\nDocumentation:\nChecks whether a file is sparse i.e. it contains holes, uses the crude heuristic blocks < size / 512\nReference:``\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_sparse_detection(source: &Path) -> Result {\n let src_file = File::open(source)?;\n let metadata = src_file.metadata()?;\n let size = metadata.size();\n let blocks = metadata.blocks();\n\n if blocks < size / 512 {\n return Ok(true);\n }\n Ok(false)\n}\n```"}], "func_name": "check_sparse_detection", "docstring": "Checks whether a file is sparse i.e. it contains holes, uses the crude heuristic blocks < size / 512\nReference:``", "repo": "uutils/coreutils", "path": "src/uu/cp/src/platform/linux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/platform/linux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "887a5e393df6064e54ba45b69d5dc301840ba69dd812b89f6011f9f8380507e7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_dest_is_fifo\n\nDocumentation:\nChecks whether an existing destination is a fifo\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_dest_is_fifo(dest: &Path) -> bool {\n // If our destination file exists and its a fifo , we do a standard copy .\n let file_type = std::fs::metadata(dest);\n match file_type {\n Ok(f) => f.file_type().is_fifo(),\n\n _ => false,\n }\n}\n```"}], "func_name": "check_dest_is_fifo", "docstring": "Checks whether an existing destination is a fifo", "repo": "uutils/coreutils", "path": "src/uu/cp/src/platform/linux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/platform/linux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81ef50c31ea68fa5b20d9c48d4274b26156cb2e8022f6a0ffc34e36c24b6572a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_stream\n\nDocumentation:\nCopy the contents of a stream from `source` to `dest`. The `if_fifo` argument is used to\ndetermine if we need to modify the file's attributes before and after copying.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn copy_stream

(source: P, dest: P, is_fifo: bool) -> std::io::Result\nwhere\n P: AsRef,\n{\n // For some reason,\n //\n // cp --preserve=ownership --copy-contents fifo fifo2\n //\n // causes `fifo2` to be created with limited permissions (mode 622\n // or maybe 600 it seems), and then after `fifo` is closed, the\n // permissions get updated to match those of `fifo`. This doesn't\n // make much sense to me but the behavior appears in\n // `tests/cp/file-perm-race.sh`.\n //\n // So it seems that if `--preserve=ownership` is true then what we\n // need to do is create the destination file with limited\n // permissions, copy the contents, then update the permissions. If\n // `--preserve=ownership` is not true, however, then we can just\n // match the mode of the source file.\n //\n // TODO Update the code below to respect the case where\n // `--preserve=ownership` is not true.\n let mut src_file = File::open(&source)?;\n let mode = 0o622 & !get_umask();\n let mut dst_file = OpenOptions::new()\n .create(true)\n .write(true)\n .mode(mode)\n .open(&dest)?;\n\n let num_bytes_copied = buf_copy::copy_stream(&mut src_file, &mut dst_file)\n .map_err(|_| std::io::Error::from(std::io::ErrorKind::Other))?;\n\n if is_fifo {\n dst_file.set_permissions(src_file.metadata()?.permissions())?;\n }\n\n Ok(num_bytes_copied)\n}\n```"}], "func_name": "copy_stream", "docstring": "Copy the contents of a stream from `source` to `dest`. The `if_fifo` argument is used to\ndetermine if we need to modify the file's attributes before and after copying.", "repo": "uutils/coreutils", "path": "src/uu/cp/src/platform/linux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/platform/linux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6873339f923acba628eb5e6b398605a2de4640ffa5031fb9950f82d46bc5b5ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_on_write\n\nDocumentation:\nCopies `source` to `dest` using copy-on-write if possible.\n\nThe `source_is_fifo` flag must be set to `true` if and only if\n`source` is a FIFO (also known as a named pipe). In this case,\ncopy-on-write is not possible, so we copy the contents using\n[`std::io::copy`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn copy_on_write(\n source: &Path,\n dest: &Path,\n reflink_mode: ReflinkMode,\n sparse_mode: SparseMode,\n context: &str,\n source_is_fifo: bool,\n source_is_stream: bool,\n) -> CopyResult {\n let mut copy_debug = CopyDebug {\n offload: OffloadReflinkDebug::Unknown,\n reflink: OffloadReflinkDebug::Unsupported,\n sparse_detection: SparseDebug::No,\n };\n let result = match (reflink_mode, sparse_mode) {\n (ReflinkMode::Never, SparseMode::Always) => {\n copy_debug.sparse_detection = SparseDebug::Zeros;\n // Default SparseDebug val for SparseMode::Always\n copy_debug.reflink = OffloadReflinkDebug::No;\n if source_is_stream {\n copy_debug.offload = OffloadReflinkDebug::Avoided;\n copy_stream(source, dest, source_is_fifo).map(|_| ())\n } else {\n let mut copy_method = CopyMethod::Default;\n let result = handle_reflink_never_sparse_always(source, dest);\n if let Ok((debug, method)) = result {\n copy_debug = debug;\n copy_method = method;\n }\n\n match copy_method {\n CopyMethod::FSCopy => std::fs::copy(source, dest).map(|_| ()),\n _ => sparse_copy(source, dest),\n }\n }\n }\n (ReflinkMode::Never, SparseMode::Never) => {\n copy_debug.reflink = OffloadReflinkDebug::No;\n\n if source_is_stream {\n copy_debug.offload = OffloadReflinkDebug::Avoided;\n copy_stream(source, dest, source_is_fifo).map(|_| ())\n } else {\n let result = handle_reflink_never_sparse_never(source);\n if let Ok(debug) = result {\n copy_debug = debug;\n }\n std::fs::copy(source, dest).map(|_| ())\n }\n }\n (ReflinkMode::Never, SparseMode::Auto) => {\n copy_debug.reflink = OffloadReflinkDebug::No;\n\n if source_is_stream {\n copy_debug.offload = OffloadReflinkDebug::Avoided;\n copy_stream(source, dest, source_is_fifo).map(|_| ())\n } else {\n let mut copy_method = CopyMethod::Default;\n let result = handle_reflink_never_sparse_auto(source, dest);\n if let Ok((debug, method)) = result {\n copy_debug = debug;\n copy_method = method;\n }\n\n match copy_method {\n CopyMethod::SparseCopyWithoutHole => sparse_copy_without_hole(source, dest),\n _ => std::fs::copy(source, dest).map(|_| ()),\n }\n }\n }\n (ReflinkMode::Auto, SparseMode::Always) => {\n copy_debug.sparse_detection = SparseDebug::Zeros; // Default SparseDebug val for\n // SparseMode::Always\n if source_is_stream {\n copy_debug.offload = OffloadReflinkDebug::Avoided;\n copy_stream(source, dest, source_is_fifo).map(|_| ())\n } else {\n let mut copy_method = CopyMethod::Default;\n let result = handle_reflink_auto_sparse_always(source, dest);\n if let Ok((debug, method)) = result {\n copy_debug = debug;\n copy_method = method;\n }\n\n match copy_method {\n CopyMethod::FSCopy => clone(source, dest, CloneFallback::FSCopy),\n _ => clone(source, dest, CloneFallback::SparseCopy),\n }\n }\n }\n\n (ReflinkMode::Auto, SparseMode::Never) => {\n copy_debug.reflink = OffloadReflinkDebug::No;\n if source_is_stream {\n copy_debug.offload = OffloadReflinkDebug::Avoided;\n copy_stream(source, dest, source_is_fifo).map(|_| ())\n } else {\n let result = handle_reflink_auto_sparse_never(source);\n if let Ok(debug) = result {\n copy_debug = debug;\n }\n\n clone(source, dest, CloneFallback::FSCopy)\n }\n }\n (ReflinkMode::Auto, SparseMode::Auto) => {\n if source_is_stream {\n copy_debug.offload = OffloadReflinkDebug::Unsupported;\n copy_stream(source, dest, source_is_fifo).map(|_| ())\n } else {\n let mut copy_method = CopyMethod::Default;\n let result = handle_reflink_auto_sparse_auto(source, dest);\n if let Ok((debug, method)) = result {\n copy_debug = debug;\n copy_method = method;\n }\n\n match copy_method {\n CopyMethod::SparseCopyWithoutHole => {\n clone(source, dest, CloneFallback::SparseCopyWithoutHole)\n }\n _ => clone(source, dest, CloneFallback::FSCopy),\n }\n }\n }\n\n (ReflinkMode::Always, SparseMode::Auto) => {\n copy_debug.sparse_detection = SparseDebug::No;\n copy_debug.reflink = OffloadReflinkDebug::Yes;\n\n clone(source, dest, CloneFallback::Error)\n }\n (ReflinkMode::Always, _) => {\n return Err(\"`--reflink=always` can be used only with --sparse=auto\".into());\n }\n };\n result.map_err(|e| CpError::IoErrContext(e, context.to_owned()))?;\n Ok(copy_debug)\n}\n```"}], "func_name": "copy_on_write", "docstring": "Copies `source` to `dest` using copy-on-write if possible.\n\nThe `source_is_fifo` flag must be set to `true` if and only if\n`source` is a FIFO (also known as a named pipe). In this case,\ncopy-on-write is not possible, so we copy the contents using\n[`std::io::copy`].", "repo": "uutils/coreutils", "path": "src/uu/cp/src/platform/linux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/platform/linux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6460e7161604971fa7364a8a50f9611b7480f4c68cb13b8a5389b39ce62d6dd9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_reflink_auto_sparse_always\n\nDocumentation:\nHandles debug results when flags are \"--reflink=auto\" and \"--sparse=always\" and specifies what\ntype of copy should be used\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_reflink_auto_sparse_always(\n source: &Path,\n dest: &Path,\n) -> Result<(CopyDebug, CopyMethod), std::io::Error> {\n let mut copy_debug = CopyDebug {\n offload: OffloadReflinkDebug::Unknown,\n reflink: OffloadReflinkDebug::Unsupported,\n sparse_detection: SparseDebug::Zeros,\n };\n let mut copy_method = CopyMethod::Default;\n let (data_flag, size, blocks) = check_for_data(source)?;\n let sparse_flag = check_sparse_detection(source)?;\n\n if data_flag || size < 512 {\n copy_debug.offload = OffloadReflinkDebug::Avoided;\n }\n match (sparse_flag, data_flag, blocks) {\n (true, true, 0) => {\n // Handling funny files with 0 block allocation but has data\n // in it\n copy_method = CopyMethod::FSCopy;\n copy_debug.sparse_detection = SparseDebug::SeekHoleZeros;\n }\n (false, true, 0) => copy_method = CopyMethod::FSCopy,\n\n (true, false, 0) => copy_debug.sparse_detection = SparseDebug::SeekHole,\n (true, true, _) => copy_debug.sparse_detection = SparseDebug::SeekHoleZeros,\n\n (true, false, _) => copy_debug.sparse_detection = SparseDebug::SeekHole,\n\n (_, _, _) => (),\n }\n if check_dest_is_fifo(dest) {\n copy_method = CopyMethod::FSCopy;\n }\n Ok((copy_debug, copy_method))\n}\n```"}], "func_name": "handle_reflink_auto_sparse_always", "docstring": "Handles debug results when flags are \"--reflink=auto\" and \"--sparse=always\" and specifies what\ntype of copy should be used", "repo": "uutils/coreutils", "path": "src/uu/cp/src/platform/linux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/platform/linux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9f4a2960c7960e61ef2102ed7c7f36a461fdbf47d269768d642f6b3bcf0e7b34"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_reflink_never_sparse_never\n\nDocumentation:\nHandles debug results when flags are \"--reflink=auto\" and \"--sparse=auto\" and specifies what\ntype of copy should be used\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_reflink_never_sparse_never(source: &Path) -> Result {\n let mut copy_debug = CopyDebug {\n offload: OffloadReflinkDebug::Unknown,\n reflink: OffloadReflinkDebug::No,\n sparse_detection: SparseDebug::No,\n };\n let (data_flag, size, _blocks) = check_for_data(source)?;\n let sparse_flag = check_sparse_detection(source)?;\n\n if sparse_flag {\n copy_debug.sparse_detection = SparseDebug::SeekHole;\n }\n\n if data_flag || size < 512 {\n copy_debug.offload = OffloadReflinkDebug::Avoided;\n }\n Ok(copy_debug)\n}\n```"}], "func_name": "handle_reflink_never_sparse_never", "docstring": "Handles debug results when flags are \"--reflink=auto\" and \"--sparse=auto\" and specifies what\ntype of copy should be used", "repo": "uutils/coreutils", "path": "src/uu/cp/src/platform/linux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/platform/linux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0488d3fdf9ce7409b8a83abcb16e223fd9c957983685b4ed80d470224169169c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_reflink_auto_sparse_never\n\nDocumentation:\nHandles debug results when flags are \"--reflink=auto\" and \"--sparse=never\", files will be copied\nthrough cloning them with fallback switching to std::fs::copy\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_reflink_auto_sparse_never(source: &Path) -> Result {\n let mut copy_debug = CopyDebug {\n offload: OffloadReflinkDebug::Unknown,\n reflink: OffloadReflinkDebug::No,\n sparse_detection: SparseDebug::No,\n };\n\n let (data_flag, size, _blocks) = check_for_data(source)?;\n let sparse_flag = check_sparse_detection(source)?;\n\n if sparse_flag {\n copy_debug.sparse_detection = SparseDebug::SeekHole;\n }\n\n if data_flag || size < 512 {\n copy_debug.offload = OffloadReflinkDebug::Avoided;\n }\n Ok(copy_debug)\n}\n```"}], "func_name": "handle_reflink_auto_sparse_never", "docstring": "Handles debug results when flags are \"--reflink=auto\" and \"--sparse=never\", files will be copied\nthrough cloning them with fallback switching to std::fs::copy", "repo": "uutils/coreutils", "path": "src/uu/cp/src/platform/linux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/platform/linux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9777b222ab077ab5e326f9858793f723ee19b795728d8aac8fa874ec7a3613bb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_reflink_never_sparse_auto\n\nDocumentation:\nHandles debug results when flags are \"--reflink=never\" and \"--sparse=auto\" and specifies what\ntype of copy should be used\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_reflink_never_sparse_auto(\n source: &Path,\n dest: &Path,\n) -> Result<(CopyDebug, CopyMethod), std::io::Error> {\n let mut copy_debug = CopyDebug {\n offload: OffloadReflinkDebug::Unknown,\n reflink: OffloadReflinkDebug::No,\n sparse_detection: SparseDebug::No,\n };\n\n let (data_flag, size, blocks) = check_for_data(source)?;\n let sparse_flag = check_sparse_detection(source)?;\n\n let mut copy_method = CopyMethod::Default;\n if data_flag || size < 512 {\n copy_debug.offload = OffloadReflinkDebug::Avoided;\n }\n\n if sparse_flag {\n if blocks == 0 && data_flag {\n copy_method = CopyMethod::FSCopy; // Handles virtual files which have size > 0 but no\n // disk allocation\n } else {\n copy_method = CopyMethod::SparseCopyWithoutHole; // Handles regular sparse-files\n }\n copy_debug.sparse_detection = SparseDebug::SeekHole;\n }\n\n if check_dest_is_fifo(dest) {\n copy_method = CopyMethod::FSCopy;\n }\n Ok((copy_debug, copy_method))\n}\n```"}], "func_name": "handle_reflink_never_sparse_auto", "docstring": "Handles debug results when flags are \"--reflink=never\" and \"--sparse=auto\" and specifies what\ntype of copy should be used", "repo": "uutils/coreutils", "path": "src/uu/cp/src/platform/linux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/platform/linux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "534f861d493c584c839ceb268f9c0d5d652d279393d1a78ada052fcf203e4d62"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_reflink_never_sparse_always\n\nDocumentation:\nHandles debug results when flags are \"--reflink=never\" and \"--sparse=always\" and specifies what\ntype of copy should be used\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_reflink_never_sparse_always(\n source: &Path,\n dest: &Path,\n) -> Result<(CopyDebug, CopyMethod), std::io::Error> {\n let mut copy_debug = CopyDebug {\n offload: OffloadReflinkDebug::Unknown,\n reflink: OffloadReflinkDebug::No,\n sparse_detection: SparseDebug::Zeros,\n };\n let mut copy_method = CopyMethod::SparseCopy;\n\n let (data_flag, size, blocks) = check_for_data(source)?;\n let sparse_flag = check_sparse_detection(source)?;\n\n if data_flag || size < 512 {\n copy_debug.offload = OffloadReflinkDebug::Avoided;\n }\n match (sparse_flag, data_flag, blocks) {\n (true, true, 0) => {\n // Handling funny files with 0 block allocation but has data\n // in it, e.g. files in /sys and other virtual files\n copy_method = CopyMethod::FSCopy;\n copy_debug.sparse_detection = SparseDebug::SeekHoleZeros;\n }\n (false, true, 0) => copy_method = CopyMethod::FSCopy, // Handling data containing zero sized\n // files in /proc\n (true, false, 0) => copy_debug.sparse_detection = SparseDebug::SeekHole, // Handles files\n // with 0 blocks allocated in disk and\n (true, true, _) => copy_debug.sparse_detection = SparseDebug::SeekHoleZeros, // Any\n // sparse_files with data in it will display SeekHoleZeros\n (true, false, _) => {\n copy_debug.offload = OffloadReflinkDebug::Unknown;\n copy_debug.sparse_detection = SparseDebug::SeekHole;\n }\n\n (_, _, _) => (),\n }\n if check_dest_is_fifo(dest) {\n copy_method = CopyMethod::FSCopy;\n }\n\n Ok((copy_debug, copy_method))\n}\n```"}], "func_name": "handle_reflink_never_sparse_always", "docstring": "Handles debug results when flags are \"--reflink=never\" and \"--sparse=always\" and specifies what\ntype of copy should be used", "repo": "uutils/coreutils", "path": "src/uu/cp/src/platform/linux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/platform/linux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e043fa3aef172b817a2ef85f92261c35eb0f31603d18f8de900da2d8e51e21bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_on_write\n\nDocumentation:\nCopies `source` to `dest` using copy-on-write if possible.\n\nThe `source_is_fifo` flag must be set to `true` if and only if\n`source` is a FIFO (also known as a named pipe).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn copy_on_write(\n source: &Path,\n dest: &Path,\n reflink_mode: ReflinkMode,\n sparse_mode: SparseMode,\n context: &str,\n source_is_fifo: bool,\n source_is_stream: bool,\n) -> CopyResult {\n if sparse_mode != SparseMode::Auto {\n return Err(\"--sparse is only supported on linux\".to_string().into());\n }\n let mut copy_debug = CopyDebug {\n offload: OffloadReflinkDebug::Unknown,\n reflink: OffloadReflinkDebug::Unsupported,\n sparse_detection: SparseDebug::Unsupported,\n };\n\n // Extract paths in a form suitable to be passed to a syscall.\n // The unwrap() is safe because they come from the command-line and so contain non nul\n // character.\n let src = CString::new(source.as_os_str().as_bytes()).unwrap();\n let dst = CString::new(dest.as_os_str().as_bytes()).unwrap();\n\n // clonefile(2) was introduced in macOS 10.12 so we cannot statically link against it\n // for backward compatibility.\n let clonefile = CString::new(\"clonefile\").unwrap();\n let raw_pfn = unsafe { libc::dlsym(libc::RTLD_NEXT, clonefile.as_ptr()) };\n\n let mut error = 0;\n if !raw_pfn.is_null() {\n // Call clonefile(2).\n // Safety: Casting a C function pointer to a rust function value is one of the few\n // blessed uses of `transmute()`.\n unsafe {\n let pfn: extern \"C\" fn(\n src: *const libc::c_char,\n dst: *const libc::c_char,\n flags: u32,\n ) -> libc::c_int = std::mem::transmute(raw_pfn);\n error = pfn(src.as_ptr(), dst.as_ptr(), 0);\n if std::io::Error::last_os_error().kind() == std::io::ErrorKind::AlreadyExists\n // Only remove the `dest` if the `source` and `dest` are not the same\n && source != dest\n {\n // clonefile(2) fails if the destination exists. Remove it and try again. Do not\n // bother to check if removal worked because we're going to try to clone again.\n // first lets make sure the dest file is not read only\n if fs::metadata(dest).is_ok_and(|md| !md.permissions().readonly()) {\n // remove and copy again\n // TODO: rewrite this to better match linux behavior\n // linux first opens the source file and destination file then uses the file\n // descriptors to do the clone.\n let _ = fs::remove_file(dest);\n error = pfn(src.as_ptr(), dst.as_ptr(), 0);\n }\n }\n }\n }\n\n if raw_pfn.is_null() || error != 0 {\n // clonefile(2) is either not supported or it errored out (possibly because the FS does not\n // support COW).\n match reflink_mode {\n ReflinkMode::Always => {\n return Err(format!(\n \"failed to clone {} from {}: {error}\",\n source.display(),\n dest.display()\n )\n .into());\n }\n _ => {\n copy_debug.reflink = OffloadReflinkDebug::Yes;\n if source_is_stream {\n let mut src_file = File::open(source)?;\n let mode = 0o622 & !get_umask();\n let mut dst_file = OpenOptions::new()\n .create(true)\n .write(true)\n .mode(mode)\n .open(dest)?;\n\n let context = buf_copy::copy_stream(&mut src_file, &mut dst_file)\n .map_err(|_| std::io::Error::from(std::io::ErrorKind::Other))\n .map_err(|e| CpError::IoErrContext(e, context.to_owned()))?;\n\n if source_is_fifo {\n dst_file.set_permissions(src_file.metadata()?.permissions())?;\n }\n context\n } else {\n fs::copy(source, dest)\n .map_err(|e| CpError::IoErrContext(e, context.to_owned()))?\n }\n }\n };\n }\n\n Ok(copy_debug)\n}\n```"}], "func_name": "copy_on_write", "docstring": "Copies `source` to `dest` using copy-on-write if possible.\n\nThe `source_is_fifo` flag must be set to `true` if and only if\n`source` is a FIFO (also known as a named pipe).", "repo": "uutils/coreutils", "path": "src/uu/cp/src/platform/macos.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/platform/macos.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d92acaa4dec71f4123e633246f5f1d27027072d50a68d9ed86d00a1d571dfca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_on_write\n\nDocumentation:\nCopies `source` to `dest` for systems without copy-on-write\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn copy_on_write(\n source: &Path,\n dest: &Path,\n reflink_mode: ReflinkMode,\n sparse_mode: SparseMode,\n context: &str,\n) -> CopyResult {\n if reflink_mode != ReflinkMode::Never {\n return Err(\"--reflink is only supported on linux and macOS\"\n .to_string()\n .into());\n }\n if sparse_mode != SparseMode::Auto {\n return Err(\"--sparse is only supported on linux\".to_string().into());\n }\n let copy_debug = CopyDebug {\n offload: OffloadReflinkDebug::Unsupported,\n reflink: OffloadReflinkDebug::Unsupported,\n sparse_detection: SparseDebug::Unsupported,\n };\n fs::copy(source, dest).map_err(|e| CpError::IoErrContext(e, context.to_owned()))?;\n\n Ok(copy_debug)\n}\n```"}], "func_name": "copy_on_write", "docstring": "Copies `source` to `dest` for systems without copy-on-write", "repo": "uutils/coreutils", "path": "src/uu/cp/src/platform/other.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/cp/src/platform/other.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e3d631ccad57caa85136b0c078453d0a51a69ca9eb7e5d435ff0a335811ea351"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: csplit\n\nDocumentation:\nSplits a file into severals according to the command line patterns.\n\n# Errors\n\n- [`io::Error`] if there is some problem reading/writing from/to a file.\n- [`CsplitError::LineOutOfRange`] if the line number pattern is larger than the number of input\nlines.\n- [`CsplitError::LineOutOfRangeOnRepetition`], like previous but after applying the pattern\nmore than once.\n- [`CsplitError::MatchNotFound`] if no line matched a regular expression.\n- [`CsplitError::MatchNotFoundOnRepetition`], like previous but after applying the pattern\nmore than once.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn csplit(options: &CsplitOptions, patterns: &[String], input: T) -> Result<(), CsplitError>\nwhere\n T: BufRead,\n{\n let enumerated_input_lines = LinesWithNewlines::new(input)\n .map(|line| line.map_err_context(|| \"read error\".to_string()))\n .enumerate();\n let mut input_iter = InputSplitter::new(enumerated_input_lines);\n let mut split_writer = SplitWriter::new(options);\n let patterns: Vec = patterns::get_patterns(patterns)?;\n let ret = do_csplit(&mut split_writer, patterns, &mut input_iter);\n\n // consume the rest, unless there was an error\n if ret.is_ok() {\n input_iter.rewind_buffer();\n if let Some((_, line)) = input_iter.next() {\n split_writer.new_writer()?;\n split_writer.writeln(&line?)?;\n for (_, line) in input_iter {\n split_writer.writeln(&line?)?;\n }\n split_writer.finish_split();\n }\n }\n // delete files on error by default\n if ret.is_err() && !options.keep_files {\n split_writer.delete_all_splits()?;\n }\n ret\n}\n```"}], "func_name": "csplit", "docstring": "Splits a file into severals according to the command line patterns.\n\n# Errors\n\n- [`io::Error`] if there is some problem reading/writing from/to a file.\n- [`CsplitError::LineOutOfRange`] if the line number pattern is larger than the number of input\nlines.\n- [`CsplitError::LineOutOfRangeOnRepetition`], like previous but after applying the pattern\nmore than once.\n- [`CsplitError::MatchNotFound`] if no line matched a regular expression.\n- [`CsplitError::MatchNotFoundOnRepetition`], like previous but after applying the pattern\nmore than once.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/csplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/csplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54f478178b4a1288bef4dcd6d6ac102489640136dd38be76f10e7b6ff1edc6ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_writer\n\nDocumentation:\nCreates a new split and returns its filename.\n\n# Errors\n\nThe creation of the split file may fail with some [`io::Error`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_writer(&mut self) -> io::Result<()> {\n let file_name = self.options.split_name.get(self.counter);\n let file = File::create(file_name)?;\n self.current_writer = Some(BufWriter::new(file));\n self.counter += 1;\n self.size = 0;\n self.dev_null = false;\n Ok(())\n }\n```"}], "func_name": "new_writer", "docstring": "Creates a new split and returns its filename.\n\n# Errors\n\nThe creation of the split file may fail with some [`io::Error`].", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/csplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/csplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1262b558ec9483c7886743d095e30bf959e4e8b330c1dde15289165cca36f6d5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_dev_null\n\nDocumentation:\nThe current split will not keep any of the read input lines.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn as_dev_null(&mut self) {\n self.dev_null = true;\n }\n```"}], "func_name": "as_dev_null", "docstring": "The current split will not keep any of the read input lines.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/csplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/csplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8ef905c06f154174525fb93a12d914d0389649bff3ce1b820d98344a16e25db0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: writeln\n\nDocumentation:\nWrites the line to the current split.\nIf [`self.dev_null`] is true, then the line is discarded.\n\n# Errors\n\nSome [`io::Error`] may occur when attempting to write the line.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn writeln(&mut self, line: &str) -> io::Result<()> {\n if !self.dev_null {\n match self.current_writer {\n Some(ref mut current_writer) => {\n let bytes = line.as_bytes();\n current_writer.write_all(bytes)?;\n self.size += bytes.len();\n }\n None => panic!(\"trying to write to a split that was not created\"),\n }\n }\n Ok(())\n }\n```"}], "func_name": "writeln", "docstring": "Writes the line to the current split.\nIf [`self.dev_null`] is true, then the line is discarded.\n\n# Errors\n\nSome [`io::Error`] may occur when attempting to write the line.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/csplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/csplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0240731239245c25830a9ac0120812f22225721999bc2cc8ed44246328eef68f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish_split\n\nDocumentation:\nPerform some operations after completing a split, i.e., either remove it\nif the [`options::ELIDE_EMPTY_FILES`] option is enabled, or print how much bytes were written\nto it if [`options::QUIET`] is disabled.\n\n# Errors\n\nSome [`io::Error`] if the split could not be removed in case it should be elided.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn finish_split(&mut self) {\n if !self.dev_null {\n if self.options.elide_empty_files && self.size == 0 {\n self.counter -= 1;\n } else if !self.options.quiet {\n println!(\"{}\", self.size);\n }\n }\n }\n```"}], "func_name": "finish_split", "docstring": "Perform some operations after completing a split, i.e., either remove it\nif the [`options::ELIDE_EMPTY_FILES`] option is enabled, or print how much bytes were written\nto it if [`options::QUIET`] is disabled.\n\n# Errors\n\nSome [`io::Error`] if the split could not be removed in case it should be elided.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/csplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/csplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5fe2d22761ce33782e0f18306927e21f0d3203e4fa29256493ec66c9451a6111"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_all_splits\n\nDocumentation:\nRemoves all the split files that were created.\n\n# Errors\n\nReturns an [`io::Error`] if there was a problem removing a split.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn delete_all_splits(&self) -> io::Result<()> {\n let mut ret = Ok(());\n for ith in 0..self.counter {\n let file_name = self.options.split_name.get(ith);\n if let Err(err) = remove_file(file_name) {\n ret = Err(err);\n }\n }\n ret\n }\n```"}], "func_name": "delete_all_splits", "docstring": "Removes all the split files that were created.\n\n# Errors\n\nReturns an [`io::Error`] if there was a problem removing a split.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/csplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/csplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "30c47eaafa39ae1cd158a8caaa8e688507f9af19b390bfeb3f7263bb925fad07"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_to_line\n\nDocumentation:\nSplit the input stream up to the line number `n`.\n\nIf the line number `n` is smaller than the current position in the input, then an empty\nsplit is created.\n\n# Errors\n\nIn addition to errors reading/writing from/to a file, if the line number\n`n` is greater than the total available lines, then a\n[`CsplitError::LineOutOfRange`] error is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn do_to_line(\n &mut self,\n pattern_as_str: &str,\n n: usize,\n input_iter: &mut InputSplitter,\n ) -> Result<(), CsplitError>\n where\n I: Iterator)>,\n {\n input_iter.rewind_buffer();\n input_iter.set_size_of_buffer(1);\n\n let mut ret = Err(CsplitError::LineOutOfRange(pattern_as_str.to_string()));\n while let Some((ln, line)) = input_iter.next() {\n let line = line?;\n match n.cmp(&(&ln + 1)) {\n Ordering::Less => {\n assert!(\n input_iter.add_line_to_buffer(ln, line).is_none(),\n \"the buffer is big enough to contain 1 line\"\n );\n ret = Ok(());\n break;\n }\n Ordering::Equal => {\n assert!(\n self.options.suppress_matched\n || input_iter.add_line_to_buffer(ln, line).is_none(),\n \"the buffer is big enough to contain 1 line\"\n );\n ret = Ok(());\n break;\n }\n Ordering::Greater => (),\n }\n self.writeln(&line)?;\n }\n self.finish_split();\n ret\n }\n```"}], "func_name": "do_to_line", "docstring": "Split the input stream up to the line number `n`.\n\nIf the line number `n` is smaller than the current position in the input, then an empty\nsplit is created.\n\n# Errors\n\nIn addition to errors reading/writing from/to a file, if the line number\n`n` is greater than the total available lines, then a\n[`CsplitError::LineOutOfRange`] error is returned.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/csplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/csplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a83e1e36d9caea09e8f5b2efea14c55042c5d3162f2667e977cbb77e709dda91"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rewind_buffer\n\nDocumentation:\nRewind the iteration by outputting the buffer's content.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn rewind_buffer(&mut self) {\n self.rewind = true;\n }\n```"}], "func_name": "rewind_buffer", "docstring": "Rewind the iteration by outputting the buffer's content.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/csplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/csplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ecb27d9ae26d012e86820670975c70f871f9711e8d7839ad0fb00e1da19cfe75"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shrink_buffer_to_size\n\nDocumentation:\nShrink the buffer so that its length is equal to the set size, returning an iterator for\nthe elements that were too much.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn shrink_buffer_to_size(&mut self) -> impl Iterator + '_ {\n let shrink_offset = if self.buffer.len() > self.size {\n self.buffer.len() - self.size\n } else {\n 0\n };\n self.buffer\n .drain(..shrink_offset)\n .map(|(_, line)| line.unwrap())\n }\n```"}], "func_name": "shrink_buffer_to_size", "docstring": "Shrink the buffer so that its length is equal to the set size, returning an iterator for\nthe elements that were too much.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/csplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/csplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7314490833ce04feff2fb6ad8b9918eccc14adeed357efd484a2101f52885169"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: drain_buffer\n\nDocumentation:\nDrain the content of the buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn drain_buffer(&mut self) -> impl Iterator + '_ {\n self.buffer.drain(..).map(|(_, line)| line.unwrap())\n }\n```"}], "func_name": "drain_buffer", "docstring": "Drain the content of the buffer.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/csplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/csplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "26412156df79c72808c041adc601030b375a7ead2be37bcb477e4ae61adc56d9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_size_of_buffer\n\nDocumentation:\nSet the maximum number of lines to keep.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_size_of_buffer(&mut self, size: usize) {\n self.size = size;\n }\n```"}], "func_name": "set_size_of_buffer", "docstring": "Set the maximum number of lines to keep.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/csplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/csplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9389e8c79f40aab02ae12468716981e5cbb5b5f587727daa34c1deb03ff319ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_line_to_buffer\n\nDocumentation:\nAdd a line to the buffer. If the buffer has [`self.size`] elements, then its head is removed and\nthe new line is pushed to the buffer. The removed head is then available in the returned\noption.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_line_to_buffer(&mut self, ln: usize, line: String) -> Option {\n if self.rewind {\n self.buffer.insert(0, (ln, Ok(line)));\n None\n } else if self.buffer.len() >= self.size {\n let (_, head_line) = self.buffer.remove(0);\n self.buffer.push((ln, Ok(line)));\n Some(head_line.unwrap())\n } else {\n self.buffer.push((ln, Ok(line)));\n None\n }\n }\n```"}], "func_name": "add_line_to_buffer", "docstring": "Add a line to the buffer. If the buffer has [`self.size`] elements, then its head is removed and\nthe new line is pushed to the buffer. The removed head is then available in the returned\noption.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/csplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/csplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f3ec5df51854bc7df8ece9ff950de69822a1973ff40c7e76d25fe6b0fb544f47"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_patterns\n\nDocumentation:\nParses the definitions of patterns given on the command line into a list of [`Pattern`]s.\n\n# Errors\n\nIf a pattern is incorrect, a [`CsplitError::InvalidPattern`] error is returned, which may be\ndue to, e.g.,:\n- an invalid regular expression;\n- an invalid number for, e.g., the offset.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_patterns(args: &[String]) -> Result, CsplitError> {\n let patterns = extract_patterns(args)?;\n validate_line_numbers(&patterns)?;\n Ok(patterns)\n}\n```"}], "func_name": "get_patterns", "docstring": "Parses the definitions of patterns given on the command line into a list of [`Pattern`]s.\n\n# Errors\n\nIf a pattern is incorrect, a [`CsplitError::InvalidPattern`] error is returned, which may be\ndue to, e.g.,:\n- an invalid regular expression;\n- an invalid number for, e.g., the offset.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/patterns.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/patterns.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "39829c6bfbc8c9ebb02e8143f71766ca865f1b2962209f2bd00707d464821af9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: validate_line_numbers\n\nDocumentation:\nAsserts the line numbers are in increasing order, starting at 1.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn validate_line_numbers(patterns: &[Pattern]) -> Result<(), CsplitError> {\n patterns\n .iter()\n .filter_map(|pattern| match pattern {\n Pattern::UpToLine(line_number, _) => Some(line_number),\n _ => None,\n })\n .try_fold(0, |prev_ln, ¤t_ln| match (prev_ln, current_ln) {\n // a line number cannot be zero\n (_, 0) => Err(CsplitError::LineNumberIsZero),\n // two consecutive numbers should not be equal\n (n, m) if n == m => {\n show_warning!(\"line number '{n}' is the same as preceding line number\");\n Ok(n)\n }\n // a number cannot be greater than the one that follows\n (n, m) if n > m => Err(CsplitError::LineNumberSmallerThanPrevious(m, n)),\n (_, m) => Ok(m),\n })?;\n Ok(())\n}\n```"}], "func_name": "validate_line_numbers", "docstring": "Asserts the line numbers are in increasing order, starting at 1.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/patterns.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/patterns.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2508077d58dde463e64ea9ee6d6ada49b0e329f5fc1758843979bfe5ce2bfc20"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new SplitName with the given user-defined options:\n- `prefix_opt` specifies a prefix for all splits.\n- `format_opt` specifies a custom format for the suffix part of the filename, using the\n`sprintf` format notation.\n- `n_digits_opt` defines the width of the split number.\n\n# Caveats\n\nIf `prefix_opt` and `format_opt` are defined, and the `format_opt` has some string appearing\nbefore the conversion pattern (e.g., \"here-%05d\"), then it is appended to the passed prefix\nvia `prefix_opt`.\n\nIf `n_digits_opt` and `format_opt` are defined, then width defined in `format_opt` is\ntaken.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n prefix_opt: Option,\n format_opt: Option,\n n_digits_opt: Option,\n ) -> Result {\n // get the prefix\n let prefix = prefix_opt.unwrap_or_else(|| \"xx\".to_string());\n\n // the width for the split offset\n let n_digits = n_digits_opt\n .map(|opt| {\n opt.parse::()\n .map_err(|_| CsplitError::InvalidNumber(opt))\n })\n .transpose()?\n .unwrap_or(2);\n\n let format_string = format_opt.unwrap_or_else(|| format!(\"%0{n_digits}u\"));\n\n let format = match Format::::parse(format_string) {\n Ok(format) => Ok(format),\n Err(FormatError::TooManySpecs(_)) => Err(CsplitError::SuffixFormatTooManyPercents),\n Err(_) => Err(CsplitError::SuffixFormatIncorrect),\n }?;\n\n Ok(Self {\n prefix: prefix.as_bytes().to_owned(),\n format,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new SplitName with the given user-defined options:\n- `prefix_opt` specifies a prefix for all splits.\n- `format_opt` specifies a custom format for the suffix part of the filename, using the\n`sprintf` format notation.\n- `n_digits_opt` defines the width of the split number.\n\n# Caveats\n\nIf `prefix_opt` and `format_opt` are defined, and the `format_opt` has some string appearing\nbefore the conversion pattern (e.g., \"here-%05d\"), then it is appended to the passed prefix\nvia `prefix_opt`.\n\nIf `n_digits_opt` and `format_opt` are defined, then width defined in `format_opt` is\ntaken.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/split_name.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/split_name.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6760fd62e9844acdb2729e66ac658b4b9d45b5126f78162df496f161b19c5f6a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturns the filename of the i-th split.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(&self, n: usize) -> String {\n let mut v = self.prefix.clone();\n self.format.fmt(&mut v, n as u64).unwrap();\n String::from_utf8_lossy(&v).to_string()\n }\n```"}], "func_name": "get", "docstring": "Returns the filename of the i-th split.", "repo": "uutils/coreutils", "path": "src/uu/csplit/src/split_name.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/csplit/src/split_name.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "da7a5e1357a2256eccc52df95b8495fef52dd74d092a701a3382cbaa5759b612"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_format_string\n\nDocumentation:\nReturn the appropriate format string for the given settings.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn make_format_string(settings: &Settings) -> &str {\n match settings.format {\n Format::Iso8601(ref fmt) => match *fmt {\n Iso8601Format::Date => \"%F\",\n Iso8601Format::Hours => \"%FT%H%:z\",\n Iso8601Format::Minutes => \"%FT%H:%M%:z\",\n Iso8601Format::Seconds => \"%FT%T%:z\",\n Iso8601Format::Ns => \"%FT%T,%N%:z\",\n },\n Format::Rfc5322 => \"%a, %d %h %Y %T %z\",\n Format::Rfc3339(ref fmt) => match *fmt {\n Rfc3339Format::Date => \"%F\",\n Rfc3339Format::Seconds => \"%F %T%:z\",\n Rfc3339Format::Ns => \"%F %T.%N%:z\",\n },\n Format::Custom(ref fmt) => fmt,\n Format::Default => \"%a %b %e %X %Z %Y\",\n }\n}\n```"}], "func_name": "make_format_string", "docstring": "Return the appropriate format string for the given settings.", "repo": "uutils/coreutils", "path": "src/uu/date/src/date.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/date/src/date.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8d936dd3075bc7f481f252d300262a846ecdb45dc9f276e218487ba4c4098909"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_system_datetime\n\nDocumentation:\nSystem call to set date (unix).\nSee here for more:\n``\n``\n``\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_system_datetime(date: Zoned) -> UResult<()> {\n let ts = date.timestamp();\n let timespec = timespec {\n tv_sec: ts.as_second() as _,\n tv_nsec: ts.subsec_nanosecond() as _,\n };\n\n let result = unsafe { clock_settime(CLOCK_REALTIME, ×pec) };\n\n if result == 0 {\n Ok(())\n } else {\n Err(std::io::Error::last_os_error().map_err_context(|| \"cannot set date\".to_string()))\n }\n}\n```"}], "func_name": "set_system_datetime", "docstring": "System call to set date (unix).\nSee here for more:\n``\n``\n``", "repo": "uutils/coreutils", "path": "src/uu/date/src/date.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/date/src/date.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9168c92181473468f467241248f2626e7f9944dbda0e365fd6e4a652eb046cca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_system_datetime\n\nDocumentation:\nSystem call to set date (Windows).\nSee here for more:\nhttps://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-setsystemtime\nhttps://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-systemtime\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_system_datetime(date: Zoned) -> UResult<()> {\n let system_time = SYSTEMTIME {\n wYear: date.year() as u16,\n wMonth: date.month() as u16,\n // Ignored\n wDayOfWeek: 0,\n wDay: date.day() as u16,\n wHour: date.hour() as u16,\n wMinute: date.minute() as u16,\n wSecond: date.second() as u16,\n // TODO: be careful of leap seconds - valid range is [0, 999] - how to handle?\n wMilliseconds: ((date.subsec_nanosecond() / 1_000_000) % 1000) as u16,\n };\n\n let result = unsafe { SetSystemTime(&system_time) };\n\n if result == 0 {\n Err(std::io::Error::last_os_error().map_err_context(|| \"cannot set date\".to_string()))\n } else {\n Ok(())\n }\n}\n```"}], "func_name": "set_system_datetime", "docstring": "System call to set date (Windows).\nSee here for more:\nhttps://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-setsystemtime\nhttps://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-systemtime", "repo": "uutils/coreutils", "path": "src/uu/date/src/date.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/date/src/date.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f74926a9c6f390778e829a200e5235e8c0b0b7b1a0528b9d4c2df0d86615909b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: block\n\nDocumentation:\nSplit a slice into chunks, padding or truncating as necessary.\n\nThe slice `buf` is split on newlines, then each block is resized\nto `cbs` bytes, padding with spaces if necessary. This function\nexpects the input bytes to be ASCII-encoded.\n\nIf `sync` is true and there has been at least one partial record\nread from the input (as indicated in `rstat`), then leave an\nall-spaces block at the end. Otherwise, remove the last block if\nit is all spaces.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn block(buf: &[u8], cbs: usize, sync: bool, rstat: &mut ReadStat) -> Vec> {\n let mut blocks = buf\n .split(|&e| e == NEWLINE)\n .map(|split| split.to_vec())\n .fold(Vec::new(), |mut blocks, mut split| {\n if split.len() > cbs {\n rstat.records_truncated += 1;\n }\n split.resize(cbs, SPACE);\n blocks.push(split);\n\n blocks\n });\n\n // If `sync` is true and there has been at least one partial\n // record read from the input, then leave the all-spaces block at\n // the end. Otherwise, remove it.\n if let Some(last) = blocks.last() {\n if (!sync || rstat.reads_partial == 0) && last.iter().all(|&e| e == SPACE) {\n blocks.pop();\n }\n }\n\n blocks\n}\n```"}], "func_name": "block", "docstring": "Split a slice into chunks, padding or truncating as necessary.\n\nThe slice `buf` is split on newlines, then each block is resized\nto `cbs` bytes, padding with spaces if necessary. This function\nexpects the input bytes to be ASCII-encoded.\n\nIf `sync` is true and there has been at least one partial record\nread from the input (as indicated in `rstat`), then leave an\nall-spaces block at the end. Otherwise, remove the last block if\nit is all spaces.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/blocks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/blocks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "41d12c459e6b063a6cccf92ed20d7f9950b6c4f5bd63d36e32be7ed0ac1e7a5c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unblock\n\nDocumentation:\nTrims padding from each cbs-length partition of buf\nas specified by conv=unblock and cbs=N\nExpects ascii encoded data\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn unblock(buf: &[u8], cbs: usize) -> Vec {\n buf.chunks(cbs).fold(Vec::new(), |mut acc, block| {\n if let Some(last_char_idx) = block.iter().rposition(|&e| e != SPACE) {\n // Include text up to last space.\n acc.extend(&block[..=last_char_idx]);\n }\n\n acc.push(NEWLINE);\n acc\n })\n}\n```"}], "func_name": "unblock", "docstring": "Trims padding from each cbs-length partition of buf\nas specified by conv=unblock and cbs=N\nExpects ascii encoded data", "repo": "uutils/coreutils", "path": "src/uu/dd/src/blocks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/blocks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "672ac18eabfe9fd563fb5f6679f3c779fd806d5dc6f961d2798249cf583c73c7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: conv_block_unblock_helper\n\nDocumentation:\nApply the specified conversion, blocking, and/or unblocking in the right order.\n\nThe `mode` specifies the combination of conversion, blocking, and\nunblocking to apply and the order in which to apply it. This\nfunction is responsible only for applying the operations.\n\n`buf` is the buffer of input bytes to transform. This function\nmutates this input and also returns a new buffer of bytes\nrepresenting the result of the transformation.\n\n`rstat` maintains a running total of the number of partial and\ncomplete blocks read before calling this function. In certain\nsettings of `mode`, this function will update the number of\nrecords truncated; that's why `rstat` is borrowed mutably.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn conv_block_unblock_helper(\n buf: Vec,\n mode: &ConversionMode,\n rstat: &mut ReadStat,\n) -> Vec {\n fn apply_conversion(buf: Vec, ct: &ConversionTable) -> impl Iterator + '_ {\n buf.into_iter().map(|b| ct[b as usize])\n }\n\n match mode {\n ConversionMode::ConvertOnly(ct) => apply_conversion(buf, ct).collect(),\n ConversionMode::BlockThenConvert(ct, cbs, sync) => {\n let blocks = block(&buf, *cbs, *sync, rstat);\n blocks\n .into_iter()\n .flat_map(|block| apply_conversion(block, ct))\n .collect()\n }\n ConversionMode::ConvertThenBlock(ct, cbs, sync) => {\n let buf: Vec<_> = apply_conversion(buf, ct).collect();\n block(&buf, *cbs, *sync, rstat)\n .into_iter()\n .flatten()\n .collect()\n }\n ConversionMode::BlockOnly(cbs, sync) => block(&buf, *cbs, *sync, rstat)\n .into_iter()\n .flatten()\n .collect(),\n ConversionMode::UnblockThenConvert(ct, cbs) => {\n let buf = unblock(&buf, *cbs);\n apply_conversion(buf, ct).collect()\n }\n ConversionMode::ConvertThenUnblock(ct, cbs) => {\n let buf: Vec<_> = apply_conversion(buf, ct).collect();\n unblock(&buf, *cbs)\n }\n ConversionMode::UnblockOnly(cbs) => unblock(&buf, *cbs),\n }\n}\n```"}], "func_name": "conv_block_unblock_helper", "docstring": "Apply the specified conversion, blocking, and/or unblocking in the right order.\n\nThe `mode` specifies the combination of conversion, blocking, and\nunblocking to apply and the order in which to apply it. This\nfunction is responsible only for applying the operations.\n\n`buf` is the buffer of input bytes to transform. This function\nmutates this input and also returns a new buffer of bytes\nrepresenting the result of the transformation.\n\n`rstat` maintains a running total of the number of partial and\ncomplete blocks read before calling this function. In certain\nsettings of `mode`, this function will update the number of\nrecords truncated; that's why `rstat` is borrowed mutably.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/blocks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/blocks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3378bf1a94d8771d22efa333399d7a9bd16314fc9e248ed7a5d7af1cd8f49f34"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nAdd partial block buffering to the given block writer.\n\nThe internal buffer size is at most the value of `obs` as\ndefined in `inner`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new(inner: Output<'a>) -> Self {\n let obs = inner.settings.obs;\n Self {\n inner,\n buf: Vec::with_capacity(obs),\n }\n }\n```"}], "func_name": "new", "docstring": "Add partial block buffering to the given block writer.\n\nThe internal buffer size is at most the value of `obs` as\ndefined in `inner`.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/bufferedoutput.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/bufferedoutput.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba89515fb07a20aadc072932fc7d72ce463d7b05403771a45123dc816916cd6e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: flush\n\nDocumentation:\nFlush the partial block stored in the internal buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn flush(&mut self) -> std::io::Result {\n let wstat = self.inner.write_blocks(&self.buf)?;\n let n = wstat.bytes_total.try_into().unwrap();\n self.buf.drain(0..n);\n Ok(wstat)\n }\n```"}], "func_name": "flush", "docstring": "Flush the partial block stored in the internal buffer.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/bufferedoutput.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/bufferedoutput.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be2f8b0fe003fd49d17519767962afdbec747753e3b22ff5ee38c22856f94c17"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_blocks\n\nDocumentation:\nWrite the given bytes one block at a time.\n\nOnly complete blocks will be written. Partial blocks will be\nbuffered until enough bytes have been provided to complete a\nblock. The returned [`WriteStat`] object will include the\nnumber of blocks written during execution of this function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn write_blocks(&mut self, buf: &[u8]) -> std::io::Result {\n // Split the incoming buffer into two parts: the bytes to write\n // and the bytes to buffer for next time.\n //\n // If `buf` does not include enough bytes to form a full block,\n // just buffer the whole thing and write zero blocks.\n let n = self.buf.len() + buf.len();\n let rem = n % self.inner.settings.obs;\n let i = buf.len().saturating_sub(rem);\n let (to_write, to_buffer) = buf.split_at(i);\n\n // Concatenate the old partial block with the new bytes to form\n // some number of complete blocks.\n self.buf.extend_from_slice(to_write);\n\n // Write all complete blocks to the inner block writer.\n //\n // For example, if the output block size were 3, the buffered\n // partial block were `b\"ab\"` and the new incoming bytes were\n // `b\"cdefg\"`, then we would write blocks `b\"abc\"` and\n // b`\"def\"` to the inner block writer.\n let wstat = self.inner.write_blocks(&self.buf)?;\n\n // Buffer any remaining bytes as a partial block.\n //\n // Continuing the example above, the last byte `b\"g\"` would be\n // buffered as a partial block until the next call to\n // `write_blocks()`.\n self.buf.clear();\n self.buf.extend_from_slice(to_buffer);\n\n Ok(wstat)\n }\n```"}], "func_name": "write_blocks", "docstring": "Write the given bytes one block at a time.\n\nOnly complete blocks will be written. Partial blocks will be\nbuffered until enough bytes have been provided to complete a\nblock. The returned [`WriteStat`] object will include the\nnumber of blocks written during execution of this function.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/bufferedoutput.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/bufferedoutput.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "03b7d4d8682d667cd4ae5def8a4608cd1f9c7c978ddaaa72d83a9c4f46adad9c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_interval\n\nDocumentation:\nuse to construct alarm timer with duration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_interval(interval: Duration) -> Self {\n let trigger = Arc::new(AtomicU8::default());\n\n let weak_trigger = Arc::downgrade(&trigger);\n thread::spawn(move || {\n while let Some(trigger) = weak_trigger.upgrade() {\n thread::sleep(interval);\n trigger.store(ALARM_TRIGGER_TIMER, Relaxed);\n }\n });\n\n Self { interval, trigger }\n }\n```"}], "func_name": "with_interval", "docstring": "use to construct alarm timer with duration", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c828ea961b3cc4d15a297b2b5c66eccaa4e994ddcdc663fd191b71a87e47100"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: manual_trigger_fn\n\nDocumentation:\nReturns a closure that allows to manually trigger the alarm\n\nThis is useful for cases where more than one alarm even source exists\nIn case of `dd` there is the SIGUSR1/SIGINFO case where we want to\ntrigger an manual progress report.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn manual_trigger_fn(&self) -> Box {\n let weak_trigger = Arc::downgrade(&self.trigger);\n Box::new(move || {\n if let Some(trigger) = weak_trigger.upgrade() {\n trigger.store(ALARM_TRIGGER_SIGNAL, Relaxed);\n }\n })\n }\n```"}], "func_name": "manual_trigger_fn", "docstring": "Returns a closure that allows to manually trigger the alarm\n\nThis is useful for cases where more than one alarm even source exists\nIn case of `dd` there is the SIGUSR1/SIGINFO case where we want to\ntrigger an manual progress report.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ebc0329f163e4cd81757c0dcf961c115c7e8df9ced5626e35ec8cf34a58a36b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_trigger\n\nDocumentation:\nUse this function to poll for any pending alarm event\n\nReturns `ALARM_TRIGGER_NONE` for no pending event.\nReturns `ALARM_TRIGGER_TIMER` if the event was triggered by timer\nReturns `ALARM_TRIGGER_SIGNAL` if the event was triggered manually\nby the closure returned from `manual_trigger_fn`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_trigger(&self) -> u8 {\n self.trigger.swap(ALARM_TRIGGER_NONE, Relaxed)\n }\n```"}], "func_name": "get_trigger", "docstring": "Use this function to poll for any pending alarm event\n\nReturns `ALARM_TRIGGER_NONE` for no pending event.\nReturns `ALARM_TRIGGER_TIMER` if the event was triggered by timer\nReturns `ALARM_TRIGGER_SIGNAL` if the event was triggered manually\nby the closure returned from `manual_trigger_fn`", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c91c6c700d5fc5590115f5051f86e9484ab42a2b8bd7ac321614eaf4e3fe601"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: len\n\nDocumentation:\nThe length of the data source in number of bytes.\n\nIf it cannot be determined, then this function returns 0.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn len(&self) -> io::Result {\n #[allow(clippy::match_wildcard_for_single_variants)]\n match self {\n Self::File(f) => Ok(f.metadata()?.len().try_into().unwrap_or(i64::MAX)),\n _ => Ok(0),\n }\n }\n```"}], "func_name": "len", "docstring": "The length of the data source in number of bytes.\n\nIf it cannot be determined, then this function returns 0.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "adda337dd431634227798c221b293cd37e36259dea686f495f88f626fa8b3c11"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_stdin\n\nDocumentation:\nInstantiate this struct with stdin as a source.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_stdin(settings: &'a Settings) -> UResult {\n #[cfg(not(unix))]\n let mut src = {\n let f = File::from(io::stdin().as_handle().try_clone_to_owned()?);\n let is_file = if let Ok(metadata) = f.metadata() {\n // this hack is needed as there is no other way on windows\n // to differentiate between the case where `seek` works\n // on a file handle or not. i.e. when the handle is no real\n // file but a pipe, `seek` is still successful, but following\n // `read`s are not affected by the seek.\n metadata.creation_time() != 0\n } else {\n false\n };\n if is_file {\n Source::File(f)\n } else {\n Source::Stdin(io::stdin())\n }\n };\n #[cfg(unix)]\n let mut src = Source::stdin_as_file();\n #[cfg(unix)]\n if let Source::StdinFile(f) = &src {\n if settings.iflags.directory && !f.metadata()?.is_dir() {\n return Err(USimpleError::new(\n 1,\n \"setting flags for 'standard input': Not a directory\",\n ));\n }\n };\n if settings.skip > 0 {\n src.skip(settings.skip)?;\n }\n Ok(Self { src, settings })\n }\n```"}], "func_name": "new_stdin", "docstring": "Instantiate this struct with stdin as a source.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b966802e3ccb666f4f8dc8c246856b719cac66811c8fab919f07516cbce9e68b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_file\n\nDocumentation:\nInstantiate this struct with the named file as a source.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_file(filename: &Path, settings: &'a Settings) -> UResult {\n let src = {\n let mut opts = OpenOptions::new();\n opts.read(true);\n\n #[cfg(any(target_os = \"linux\", target_os = \"android\"))]\n if let Some(libc_flags) = make_linux_iflags(&settings.iflags) {\n opts.custom_flags(libc_flags);\n }\n\n opts.open(filename)\n .map_err_context(|| format!(\"failed to open {}\", filename.quote()))?\n };\n\n let mut src = Source::File(src);\n if settings.skip > 0 {\n src.skip(settings.skip)?;\n }\n Ok(Self { src, settings })\n }\n```"}], "func_name": "new_file", "docstring": "Instantiate this struct with the named file as a source.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c942a2b9e295a23f53230e43d8e87f87156c6ad2a8f8248998dd251a04718b8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fill_consecutive\n\nDocumentation:\nFills a given buffer.\nReads in increments of 'self.ibs'.\nThe start of each ibs-sized read follows the previous one.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fill_consecutive(&mut self, buf: &mut Vec) -> io::Result {\n let mut reads_complete = 0;\n let mut reads_partial = 0;\n let mut bytes_total = 0;\n\n for chunk in buf.chunks_mut(self.settings.ibs) {\n match self.read(chunk)? {\n rlen if rlen == self.settings.ibs => {\n bytes_total += rlen;\n reads_complete += 1;\n }\n rlen if rlen > 0 => {\n bytes_total += rlen;\n reads_partial += 1;\n }\n _ => break,\n }\n }\n buf.truncate(bytes_total);\n Ok(ReadStat {\n reads_complete,\n reads_partial,\n // Records are not truncated when filling.\n records_truncated: 0,\n bytes_total: bytes_total.try_into().unwrap(),\n })\n }\n```"}], "func_name": "fill_consecutive", "docstring": "Fills a given buffer.\nReads in increments of 'self.ibs'.\nThe start of each ibs-sized read follows the previous one.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c2ba202b050009e0911c82449825ac9952b83b6aa0522498bbc1740159b9263"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fill_blocks\n\nDocumentation:\nFills a given buffer.\nReads in increments of 'self.ibs'.\nThe start of each ibs-sized read is aligned to multiples of ibs; remaining space is filled with the 'pad' byte.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fill_blocks(&mut self, buf: &mut Vec, pad: u8) -> io::Result {\n let mut reads_complete = 0;\n let mut reads_partial = 0;\n let mut base_idx = 0;\n let mut bytes_total = 0;\n\n while base_idx < buf.len() {\n let next_blk = cmp::min(base_idx + self.settings.ibs, buf.len());\n let target_len = next_blk - base_idx;\n\n match self.read(&mut buf[base_idx..next_blk])? {\n 0 => break,\n rlen if rlen < target_len => {\n bytes_total += rlen;\n reads_partial += 1;\n let padding = vec![pad; target_len - rlen];\n buf.splice(base_idx + rlen..next_blk, padding.into_iter());\n }\n rlen => {\n bytes_total += rlen;\n reads_complete += 1;\n }\n }\n\n base_idx += self.settings.ibs;\n }\n\n buf.truncate(base_idx);\n Ok(ReadStat {\n reads_complete,\n reads_partial,\n records_truncated: 0,\n bytes_total: bytes_total.try_into().unwrap(),\n })\n }\n```"}], "func_name": "fill_blocks", "docstring": "Fills a given buffer.\nReads in increments of 'self.ibs'.\nThe start of each ibs-sized read is aligned to multiples of ibs; remaining space is filled with the 'pad' byte.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b61852418c470116b3de323bfd869758a4ed79ae35bfc629fd411ef022c63c57"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: truncate\n\nDocumentation:\nTruncate the underlying file to the current stream position, if possible.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn truncate(&mut self) -> io::Result<()> {\n #[allow(clippy::match_wildcard_for_single_variants)]\n match self {\n Self::File(f, _) => {\n let pos = f.stream_position()?;\n f.set_len(pos)\n }\n _ => Ok(()),\n }\n }\n```"}], "func_name": "truncate", "docstring": "Truncate the underlying file to the current stream position, if possible.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e5db7516c72f950eda0e159fa03ec9d5d50bdac648afd56d39b3bb0b7398db0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: len\n\nDocumentation:\nThe length of the data destination in number of bytes.\n\nIf it cannot be determined, then this function returns 0.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn len(&self) -> io::Result {\n #[allow(clippy::match_wildcard_for_single_variants)]\n match self {\n Self::File(f, _) => Ok(f.metadata()?.len().try_into().unwrap_or(i64::MAX)),\n _ => Ok(0),\n }\n }\n```"}], "func_name": "len", "docstring": "The length of the data destination in number of bytes.\n\nIf it cannot be determined, then this function returns 0.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3068175fc78c5c1aa18d28c9485c1d523f0002c1aba1daac3b1b83d4f7ed8574"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_sparse\n\nDocumentation:\nDecide whether the given buffer is all zeros.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_sparse(buf: &[u8]) -> bool {\n buf.iter().all(|&e| e == 0u8)\n}\n```"}], "func_name": "is_sparse", "docstring": "Decide whether the given buffer is all zeros.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd85c5692e452d24b9d345d7ddb7720de2bea163c52c056d99e507bbfd1b8334"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_stdout\n\nDocumentation:\nInstantiate this struct with stdout as a destination.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_stdout(settings: &'a Settings) -> UResult {\n let mut dst = Dest::Stdout(io::stdout());\n dst.seek(settings.seek)\n .map_err_context(|| \"write error\".to_string())?;\n Ok(Self { dst, settings })\n }\n```"}], "func_name": "new_stdout", "docstring": "Instantiate this struct with stdout as a destination.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "222c5138267f4c9149282257c690fb8c5bb78806b730ef07a0b1fc2d17733d92"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_file\n\nDocumentation:\nInstantiate this struct with the named file as a destination.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_file(filename: &Path, settings: &'a Settings) -> UResult {\n fn open_dst(path: &Path, cflags: &OConvFlags, oflags: &OFlags) -> Result {\n let mut opts = OpenOptions::new();\n opts.write(true)\n .create(!cflags.nocreat)\n .create_new(cflags.excl)\n .append(oflags.append);\n\n #[cfg(any(target_os = \"linux\", target_os = \"android\"))]\n if let Some(libc_flags) = make_linux_oflags(oflags) {\n opts.custom_flags(libc_flags);\n }\n\n opts.open(path)\n }\n\n let dst = open_dst(filename, &settings.oconv, &settings.oflags)\n .map_err_context(|| format!(\"failed to open {}\", filename.quote()))?;\n\n // Seek to the index in the output file, truncating if requested.\n //\n // Calling `set_len()` may result in an error (for example,\n // when calling it on `/dev/null`), but we don't want to\n // terminate the process when that happens. Instead, we\n // suppress the error by calling `Result::ok()`. This matches\n // the behavior of GNU `dd` when given the command-line\n // argument `of=/dev/null`.\n if !settings.oconv.notrunc {\n dst.set_len(settings.seek).ok();\n }\n\n Self::prepare_file(dst, settings)\n }\n```"}], "func_name": "new_file", "docstring": "Instantiate this struct with the named file as a destination.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1fb23246d538ff7fee23bd51cb9a6bf1d4d551ae6b761a5c3baa97c5077a6614"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_file_from_stdout\n\nDocumentation:\nInstantiate this struct with file descriptor as a destination.\n\nThis is useful e.g. for the case when the file descriptor was\nalready opened by the system (stdout) and has a state\n(current position) that shall be used.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_file_from_stdout(settings: &'a Settings) -> UResult {\n let fx = OwnedFileDescriptorOrHandle::from(io::stdout())?;\n #[cfg(any(target_os = \"linux\", target_os = \"android\"))]\n if let Some(libc_flags) = make_linux_oflags(&settings.oflags) {\n nix::fcntl::fcntl(\n fx.as_raw().as_fd(),\n F_SETFL(OFlag::from_bits_retain(libc_flags)),\n )?;\n }\n\n Self::prepare_file(fx.into_file(), settings)\n }\n```"}], "func_name": "new_file_from_stdout", "docstring": "Instantiate this struct with file descriptor as a destination.\n\nThis is useful e.g. for the case when the file descriptor was\nalready opened by the system (stdout) and has a state\n(current position) that shall be used.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e99f2fdf281df9e15fe65e57d2e6a3a69b38147eaeaa9dc7803839d84055f7c0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_block\n\nDocumentation:\nwrites a block of data. optionally retries when first try didn't complete\n\nthis is needed by gnu-test: tests/dd/stats.s\nthe write can be interrupted by a system signal.\ne.g. SIGUSR1 which is send to report status\nwithout retry, the data might not be fully written to destination.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_block(&mut self, chunk: &[u8]) -> io::Result {\n let full_len = chunk.len();\n let mut base_idx = 0;\n loop {\n match self.dst.write(&chunk[base_idx..]) {\n Ok(wlen) => {\n base_idx += wlen;\n // take iflags.fullblock as oflags shall not have this option\n if (base_idx >= full_len) || !self.settings.iflags.fullblock {\n return Ok(base_idx);\n }\n }\n Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,\n Err(e) => return Err(e),\n }\n }\n }\n```"}], "func_name": "write_block", "docstring": "writes a block of data. optionally retries when first try didn't complete\n\nthis is needed by gnu-test: tests/dd/stats.s\nthe write can be interrupted by a system signal.\ne.g. SIGUSR1 which is send to report status\nwithout retry, the data might not be fully written to destination.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17ef1d28800a7ddd574ca9778e7416aa6d705ab1f7666479fb6ae4ad90b3c2bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_blocks\n\nDocumentation:\nWrite the given bytes one block at a time.\n\nThis may write partial blocks (for example, if the underlying\ncall to [`Write::write`] writes fewer than `buf.len()`\nbytes). The returned [`WriteStat`] object will include the\nnumber of partial and complete blocks written during execution\nof this function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_blocks(&mut self, buf: &[u8]) -> io::Result {\n let mut writes_complete = 0;\n let mut writes_partial = 0;\n let mut bytes_total = 0;\n\n for chunk in buf.chunks(self.settings.obs) {\n let wlen = self.write_block(chunk)?;\n if wlen < self.settings.obs {\n writes_partial += 1;\n } else {\n writes_complete += 1;\n }\n bytes_total += wlen;\n }\n\n Ok(WriteStat {\n writes_complete,\n writes_partial,\n bytes_total: bytes_total.try_into().unwrap_or(0u128),\n })\n }\n```"}], "func_name": "write_blocks", "docstring": "Write the given bytes one block at a time.\n\nThis may write partial blocks (for example, if the underlying\ncall to [`Write::write`] writes fewer than `buf.len()`\nbytes). The returned [`WriteStat`] object will include the\nnumber of partial and complete blocks written during execution\nof this function.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6a337499833de76a05fb5c1266fca1e6572d5d9660812e3483fd81ae14365199"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sync\n\nDocumentation:\nFlush the output to disk, if configured to do so.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn sync(&mut self) -> io::Result<()> {\n if self.settings.oconv.fsync {\n self.dst.fsync()\n } else if self.settings.oconv.fdatasync {\n self.dst.fdatasync()\n } else {\n // Intentionally do nothing in this case.\n Ok(())\n }\n }\n```"}], "func_name": "sync", "docstring": "Flush the output to disk, if configured to do so.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "088f46bdfddec06ad8404640ee8120a6d3f2f8b18e2273688dbd761e63866fb1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: truncate\n\nDocumentation:\nTruncate the file to the final cursor location.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn truncate(&mut self) {\n // Calling `set_len()` may result in an error (for example,\n // when calling it on `/dev/null`), but we don't want to\n // terminate the process when that happens. Instead, we\n // suppress the error by calling `Result::ok()`. This matches\n // the behavior of GNU `dd` when given the command-line\n // argument `of=/dev/null`.\n match self {\n Self::Unbuffered(o) => o.truncate().ok(),\n Self::Buffered(o) => o.truncate().ok(),\n };\n }\n```"}], "func_name": "truncate", "docstring": "Truncate the file to the final cursor location.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44a4faa69bd976561fdb0a8172d8b31da624aa3f6d8010482a98bc4dbb6672d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: flush_caches_full_length\n\nDocumentation:\ndepending on the command line arguments, this function\ninforms the OS to flush/discard the caches for input and/or output file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn flush_caches_full_length(i: &Input, o: &Output) -> io::Result<()> {\n // TODO Better error handling for overflowing `len`.\n if i.settings.iflags.nocache {\n let offset = 0;\n #[allow(clippy::useless_conversion)]\n let len = i.src.len()?.try_into().unwrap();\n i.discard_cache(offset, len);\n }\n // Similarly, discard the system cache for the output file.\n //\n // TODO Better error handling for overflowing `len`.\n if i.settings.oflags.nocache {\n let offset = 0;\n #[allow(clippy::useless_conversion)]\n let len = o.dst.len()?.try_into().unwrap();\n o.discard_cache(offset, len);\n }\n\n Ok(())\n}\n```"}], "func_name": "flush_caches_full_length", "docstring": "depending on the command line arguments, this function\ninforms the OS to flush/discard the caches for input and/or output file.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ab3b41409aea01cd8c01c0e32284b3fa4d55efff5c1a4e68764927168dcfcda9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dd_copy\n\nDocumentation:\nCopy the given input data to this output, consuming both.\n\nThis method contains the main loop for the `dd` program. Bytes\nare read in blocks from `i` and written in blocks to this\noutput. Read/write statistics are reported to stderr as\nconfigured by the `status` command-line argument.\n\n# Errors\n\nIf there is a problem reading from the input or writing to\nthis output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn dd_copy(mut i: Input, o: Output) -> io::Result<()> {\n // The read and write statistics.\n //\n // These objects are counters, initialized to zero. After each\n // iteration of the main loop, each will be incremented by the\n // number of blocks read and written, respectively.\n let mut rstat = ReadStat::default();\n let mut wstat = WriteStat::default();\n\n // The time at which the main loop starts executing.\n //\n // When `status=progress` is given on the command-line, the\n // `dd` program reports its progress every second or so. Part\n // of its report includes the throughput in bytes per second,\n // which requires knowing how long the process has been\n // running.\n let start = Instant::now();\n\n // A good buffer size for reading.\n //\n // This is an educated guess about a good buffer size based on\n // the input and output block sizes.\n let bsize = calc_bsize(i.settings.ibs, o.settings.obs);\n\n // Start a thread that reports transfer progress.\n //\n // The `dd` program reports its progress after every block is written,\n // at most every 1 second, and only if `status=progress` is given on\n // the command-line or a SIGUSR1 signal is received. We\n // perform this reporting in a new thread so as not to take\n // any CPU time away from the actual reading and writing of\n // data. We send a `ProgUpdate` from the transmitter `prog_tx`\n // to the receives `rx`, and the receiver prints the transfer\n // information.\n let (prog_tx, rx) = mpsc::channel();\n let output_thread = thread::spawn(gen_prog_updater(rx, i.settings.status));\n\n // Whether to truncate the output file after all blocks have been written.\n let truncate = !o.settings.oconv.notrunc;\n\n // Optimization: if no blocks are to be written, then don't\n // bother allocating any buffers.\n if let Some(Num::Blocks(0) | Num::Bytes(0)) = i.settings.count {\n // Even though we are not reading anything from the input\n // file, we still need to honor the `nocache` flag, which\n // requests that we inform the system that we no longer\n // need the contents of the input file in a system cache.\n //\n flush_caches_full_length(&i, &o)?;\n return finalize(\n BlockWriter::Unbuffered(o),\n rstat,\n wstat,\n start,\n &prog_tx,\n output_thread,\n truncate,\n );\n };\n\n // Create a common buffer with a capacity of the block size.\n // This is the max size needed.\n let mut buf = vec![BUF_INIT_BYTE; bsize];\n\n // Spawn a timer thread to provide a scheduled signal indicating when we\n // should send an update of our progress to the reporting thread.\n //\n // This avoids the need to query the OS monotonic clock for every block.\n let alarm = Alarm::with_interval(Duration::from_secs(1));\n\n // The signal handler spawns an own thread that waits for signals.\n // When the signal is received, it calls a handler function.\n // We inject a handler function that manually triggers the alarm.\n #[cfg(target_os = \"linux\")]\n let signal_handler = progress::SignalHandler::install_signal_handler(alarm.manual_trigger_fn());\n #[cfg(target_os = \"linux\")]\n if let Err(e) = &signal_handler {\n if Some(StatusLevel::None) != i.settings.status {\n eprintln!(\"Internal dd Warning: Unable to register signal handler \\n\\t{e}\");\n }\n }\n\n // Index in the input file where we are reading bytes and in\n // the output file where we are writing bytes.\n //\n // These are updated on each iteration of the main loop.\n let mut read_offset = 0;\n let mut write_offset = 0;\n\n let input_nocache = i.settings.iflags.nocache;\n let output_nocache = o.settings.oflags.nocache;\n\n // Add partial block buffering, if needed.\n let mut o = if o.settings.buffered {\n BlockWriter::Buffered(BufferedOutput::new(o))\n } else {\n BlockWriter::Unbuffered(o)\n };\n\n // The main read/write loop.\n //\n // Each iteration reads blocks from the input and writes\n // blocks to this output. Read/write statistics are updated on\n // each iteration and cumulative statistics are reported to\n // the progress reporting thread.\n while below_count_limit(i.settings.count, &rstat) {\n // Read a block from the input then write the block to the output.\n //\n // As an optimization, make an educated guess about the\n // best buffer size for reading based on the number of\n // blocks already read and the number of blocks remaining.\n let loop_bsize = calc_loop_bsize(i.settings.count, &rstat, &wstat, i.settings.ibs, bsize);\n let rstat_update = read_helper(&mut i, &mut buf, loop_bsize)?;\n if rstat_update.is_empty() {\n break;\n }\n let wstat_update = o.write_blocks(&buf)?;\n\n // Discard the system file cache for the read portion of\n // the input file.\n //\n // TODO Better error handling for overflowing `offset` and `len`.\n let read_len = rstat_update.bytes_total;\n if input_nocache {\n let offset = read_offset.try_into().unwrap();\n let len = read_len.try_into().unwrap();\n i.discard_cache(offset, len);\n }\n read_offset += read_len;\n\n // Discard the system file cache for the written portion\n // of the output file.\n //\n // TODO Better error handling for overflowing `offset` and `len`.\n let write_len = wstat_update.bytes_total;\n if output_nocache {\n let offset = write_offset.try_into().unwrap();\n let len = write_len.try_into().unwrap();\n o.discard_cache(offset, len);\n }\n write_offset += write_len;\n\n // Update the read/write stats and inform the progress thread once per second.\n //\n // If the receiver is disconnected, `send()` returns an\n // error. Since it is just reporting progress and is not\n // crucial to the operation of `dd`, let's just ignore the\n // error.\n rstat += rstat_update;\n wstat += wstat_update;\n match alarm.get_trigger() {\n ALARM_TRIGGER_NONE => {}\n t @ (ALARM_TRIGGER_TIMER | ALARM_TRIGGER_SIGNAL) => {\n let tp = match t {\n ALARM_TRIGGER_TIMER => ProgUpdateType::Periodic,\n _ => ProgUpdateType::Signal,\n };\n let prog_update = ProgUpdate::new(rstat, wstat, start.elapsed(), tp);\n prog_tx.send(prog_update).unwrap_or(());\n }\n _ => {}\n }\n }\n\n finalize(o, rstat, wstat, start, &prog_tx, output_thread, truncate)\n}\n```"}], "func_name": "dd_copy", "docstring": "Copy the given input data to this output, consuming both.\n\nThis method contains the main loop for the `dd` program. Bytes\nare read in blocks from `i` and written in blocks to this\noutput. Read/write statistics are reported to stderr as\nconfigured by the `status` command-line argument.\n\n# Errors\n\nIf there is a problem reading from the input or writing to\nthis output.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c6dddec867e7fa9938d77e291fba2193264f6dc5d8179b3fbd7cb1e2f4d6aebd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finalize\n\nDocumentation:\nFlush output, print final stats, and join with the progress thread.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn finalize(\n mut output: BlockWriter,\n rstat: ReadStat,\n wstat: WriteStat,\n start: Instant,\n prog_tx: &mpsc::Sender,\n output_thread: thread::JoinHandle,\n truncate: bool,\n) -> io::Result<()> {\n // Flush the output in case a partial write has been buffered but\n // not yet written.\n let wstat_update = output.flush()?;\n\n // Sync the output, if configured to do so.\n output.sync()?;\n\n // Truncate the file to the final cursor location.\n if truncate {\n output.truncate();\n }\n\n // Print the final read/write statistics.\n let wstat = wstat + wstat_update;\n let prog_update = ProgUpdate::new(rstat, wstat, start.elapsed(), ProgUpdateType::Final);\n prog_tx.send(prog_update).unwrap_or(());\n // Wait for the output thread to finish\n output_thread\n .join()\n .expect(\"Failed to join with the output thread.\");\n\n Ok(())\n}\n```"}], "func_name": "finalize", "docstring": "Flush output, print final stats, and join with the progress thread.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6988ba1f7f511500772ca6387cefcafc4d84cda8ce6fbeca1945f5878a63e21"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_helper\n\nDocumentation:\nRead from an input (that is, a source of bytes) into the given buffer.\n\nThis function also performs any conversions as specified by\n`conv=swab` or `conv=block` command-line arguments. This function\nmutates the `buf` argument in-place. The returned [`ReadStat`]\nindicates how many blocks were read.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_helper(i: &mut Input, buf: &mut Vec, bsize: usize) -> io::Result {\n // Local Helper Fns -------------------------------------------------\n fn perform_swab(buf: &mut [u8]) {\n for base in (1..buf.len()).step_by(2) {\n buf.swap(base, base - 1);\n }\n }\n // ------------------------------------------------------------------\n // Read\n // Resize the buffer to the bsize. Any garbage data in the buffer is overwritten or truncated, so there is no need to fill with BUF_INIT_BYTE first.\n buf.resize(bsize, BUF_INIT_BYTE);\n\n let mut rstat = match i.settings.iconv.sync {\n Some(ch) => i.fill_blocks(buf, ch)?,\n _ => i.fill_consecutive(buf)?,\n };\n // Return early if no data\n if rstat.reads_complete == 0 && rstat.reads_partial == 0 {\n return Ok(rstat);\n }\n\n // Perform any conv=x[,x...] options\n if i.settings.iconv.swab {\n perform_swab(buf);\n }\n\n match i.settings.iconv.mode {\n Some(ref mode) => {\n *buf = conv_block_unblock_helper(buf.clone(), mode, &mut rstat);\n Ok(rstat)\n }\n None => Ok(rstat),\n }\n}\n```"}], "func_name": "read_helper", "docstring": "Read from an input (that is, a source of bytes) into the given buffer.\n\nThis function also performs any conversions as specified by\n`conv=swab` or `conv=block` command-line arguments. This function\nmutates the `buf` argument in-place. The returned [`ReadStat`]\nindicates how many blocks were read.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a26fd3631481e5e03a0622425f65c6a22bca723ff6b0e00dbb172de0aef9518"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stdout_canonicalized\n\nDocumentation:\nCanonicalized file name of `/dev/stdout`.\n\nFor example, if this process were invoked from the command line as\n`dd`, then this function returns the [`OsString`] form of\n`\"/dev/stdout\"`. However, if this process were invoked as `dd >\noutfile`, then this function returns the canonicalized path to\n`outfile`, something like `\"/path/to/outfile\"`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn stdout_canonicalized() -> OsString {\n match Path::new(\"/dev/stdout\").canonicalize() {\n Ok(p) => p.into_os_string(),\n Err(_) => OsString::from(\"/dev/stdout\"),\n }\n}\n```"}], "func_name": "stdout_canonicalized", "docstring": "Canonicalized file name of `/dev/stdout`.\n\nFor example, if this process were invoked from the command line as\n`dd`, then this function returns the [`OsString`] form of\n`\"/dev/stdout\"`. However, if this process were invoked as `dd >\noutfile`, then this function returns the canonicalized path to\n`outfile`, something like `\"/path/to/outfile\"`.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a70133ec82d32ed7cf5e30d407fd939b531c3b9b9c6dc491c131dff7a9aea2d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_stdout_redirected_to_seekable_file\n\nDocumentation:\nDecide whether stdout is being redirected to a seekable file.\n\nFor example, if this process were invoked from the command line as\n\n```sh\ndd if=/dev/zero bs=1 count=10 seek=5 > /dev/sda1\n```\n\nwhere `/dev/sda1` is a seekable block device then this function\nwould return true. If invoked as\n\n```sh\ndd if=/dev/zero bs=1 count=10 seek=5\n```\n\nthen this function would return false.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_stdout_redirected_to_seekable_file() -> bool {\n let s = stdout_canonicalized();\n let p = Path::new(&s);\n match File::open(p) {\n Ok(mut f) => {\n f.stream_position().is_ok() && f.seek(SeekFrom::End(0)).is_ok() && f.rewind().is_ok()\n }\n Err(_) => false,\n }\n}\n```"}], "func_name": "is_stdout_redirected_to_seekable_file", "docstring": "Decide whether stdout is being redirected to a seekable file.\n\nFor example, if this process were invoked from the command line as\n\n```sh\ndd if=/dev/zero bs=1 count=10 seek=5 > /dev/sda1\n```\n\nwhere `/dev/sda1` is a seekable block device then this function\nwould return true. If invoked as\n\n```sh\ndd if=/dev/zero bs=1 count=10 seek=5\n```\n\nthen this function would return false.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/dd.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/dd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d5da9b3e2e26109b852d1e61712bdbda790f7caea94bde179917c181c9053b69"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_magnitude_and_suffix\n\nDocumentation:\nConvert a number into a magnitude and a multi-byte unit suffix.\n\nThe returned string has a maximum length of 5 chars, for example: \"1.1kB\", \"999kB\", \"1MB\".\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn to_magnitude_and_suffix(n: u128, suffix_type: SuffixType) -> String {\n let (base, suffix) = suffix_type.base_and_suffix(n);\n // TODO To match dd on my machine, we would need to round like\n // this:\n //\n // 1049 => 1.0 kB\n // 1050 => 1.0 kB # why is this different?\n // 1051 => 1.1 kB\n // ...\n // 1149 => 1.1 kB\n // 1150 => 1.2 kB\n // ...\n // 1250 => 1.2 kB\n // 1251 => 1.3 kB\n // ..\n // 10500 => 10 kB\n // 10501 => 11 kB\n //\n let quotient = (n as f64) / (base as f64);\n if quotient < 10.0 {\n format!(\"{quotient:.1} {suffix}\")\n } else {\n format!(\"{} {suffix}\", quotient.round())\n }\n}\n```"}], "func_name": "to_magnitude_and_suffix", "docstring": "Convert a number into a magnitude and a multi-byte unit suffix.\n\nThe returned string has a maximum length of 5 chars, for example: \"1.1kB\", \"999kB\", \"1MB\".", "repo": "uutils/coreutils", "path": "src/uu/dd/src/numbers.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/numbers.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "de1f96aec04e06e5970ca5911ad40374800037e123b9f1f8d1bab58974524370"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_io_lines\n\nDocumentation:\nWrite the number of complete and partial records both read and written.\n\nThe information is written to `w`.\n\n# Examples\n\n```rust,ignore\nuse std::io::Cursor;\nuse std::time::Duration;\nuse crate::progress::{ProgUpdate, ReadStat, WriteStat};\n\nlet read_stat = ReadStat::new(1, 2, 3, 999);\nlet write_stat = WriteStat::new(4, 5, 6);\nlet duration = Duration::new(789, 0);\nlet prog_update = ProgUpdate {\nread_stat,\nwrite_stat,\nduration,\n};\n\nlet mut cursor = Cursor::new(vec![]);\nprog_update.write_io_lines(&mut cursor).unwrap();\nassert_eq!(\ncursor.get_ref(),\nb\"1+2 records in\\n3 truncated records\\n4+5 records out\\n\"\n);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_io_lines(&self, w: &mut impl Write) -> std::io::Result<()> {\n self.read_stat.report(w)?;\n self.write_stat.report(w)?;\n match self.read_stat.records_truncated {\n 0 => {}\n 1 => writeln!(w, \"1 truncated record\")?,\n n => writeln!(w, \"{n} truncated records\")?,\n }\n Ok(())\n }\n```"}], "func_name": "write_io_lines", "docstring": "Write the number of complete and partial records both read and written.\n\nThe information is written to `w`.\n\n# Examples\n\n```rust,ignore\nuse std::io::Cursor;\nuse std::time::Duration;\nuse crate::progress::{ProgUpdate, ReadStat, WriteStat};\n\nlet read_stat = ReadStat::new(1, 2, 3, 999);\nlet write_stat = WriteStat::new(4, 5, 6);\nlet duration = Duration::new(789, 0);\nlet prog_update = ProgUpdate {\nread_stat,\nwrite_stat,\nduration,\n};\n\nlet mut cursor = Cursor::new(vec![]);\nprog_update.write_io_lines(&mut cursor).unwrap();\nassert_eq!(\ncursor.get_ref(),\nb\"1+2 records in\\n3 truncated records\\n4+5 records out\\n\"\n);\n```", "repo": "uutils/coreutils", "path": "src/uu/dd/src/progress.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/progress.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "46ec2b444ad98c3b871aa21f55a573d155b5c0023691e4579ceeddfa2de1aa9e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_prog_line\n\nDocumentation:\nWrite the number of bytes written, duration, and throughput.\n\nThe information is written to `w`. If `rewrite` is `true`,\nthen a `\\r` character is written first and no newline is\nwritten at the end. When writing to `stderr`, this has the\nvisual effect of overwriting the previous characters on the\nline.\n\n# Examples\n\n```rust,ignore\nuse std::io::Cursor;\nuse std::time::Duration;\nuse crate::progress::ProgUpdate;\n\nlet prog_update = ProgUpdate {\nread_stat: Default::default(),\nwrite_stat: Default::default(),\nduration: Duration::new(1, 0), // one second\n};\n\nlet mut cursor = Cursor::new(vec![]);\nlet rewrite = false;\nprog_update.write_prog_line(&mut cursor, rewrite).unwrap();\nassert_eq!(cursor.get_ref(), b\"0 bytes copied, 1.0 s, 0.0 B/s\\n\");\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_prog_line(&self, w: &mut impl Write, rewrite: bool) -> UResult<()> {\n // The total number of bytes written as a string, in SI and IEC format.\n let btotal = self.write_stat.bytes_total;\n let btotal_metric = to_magnitude_and_suffix(btotal, SuffixType::Si);\n let btotal_bin = to_magnitude_and_suffix(btotal, SuffixType::Iec);\n\n // Compute the throughput (bytes per second) as a string.\n let duration = self.duration.as_secs_f64();\n let safe_millis = std::cmp::max(1, self.duration.as_millis());\n let rate = 1000 * (btotal / safe_millis);\n let transfer_rate = to_magnitude_and_suffix(rate, SuffixType::Si);\n\n // If we are rewriting the progress line, do write a carriage\n // return (`\\r`) at the beginning and don't write a newline\n // (`\\n`) at the end.\n let (carriage_return, newline) = if rewrite { (\"\\r\", \"\") } else { (\"\", \"\\n\") };\n\n // The duration should be formatted as in `printf %g`.\n let mut duration_str = Vec::new();\n uucore::format::num_format::Float {\n variant: FloatVariant::Shortest,\n ..Default::default()\n }\n .fmt(&mut duration_str, &duration.into())?;\n // We assume that printf will output valid UTF-8\n let duration_str = std::str::from_utf8(&duration_str).unwrap();\n\n // If the number of bytes written is sufficiently large, then\n // print a more concise representation of the number, like\n // \"1.2 kB\" and \"1.0 KiB\".\n match btotal {\n 1 => write!(\n w,\n \"{carriage_return}{btotal} byte copied, {duration_str} s, {transfer_rate}/s{newline}\",\n )?,\n 0..=999 => write!(\n w,\n \"{carriage_return}{btotal} bytes copied, {duration_str} s, {transfer_rate}/s{newline}\",\n )?,\n 1000..=1023 => write!(\n w,\n \"{carriage_return}{btotal} bytes ({btotal_metric}) copied, {duration_str} s, {transfer_rate}/s{newline}\",\n )?,\n _ => write!(\n w,\n \"{carriage_return}{btotal} bytes ({btotal_metric}, {btotal_bin}) copied, {duration_str} s, {transfer_rate}/s{newline}\",\n )?,\n };\n Ok(())\n }\n```"}], "func_name": "write_prog_line", "docstring": "Write the number of bytes written, duration, and throughput.\n\nThe information is written to `w`. If `rewrite` is `true`,\nthen a `\\r` character is written first and no newline is\nwritten at the end. When writing to `stderr`, this has the\nvisual effect of overwriting the previous characters on the\nline.\n\n# Examples\n\n```rust,ignore\nuse std::io::Cursor;\nuse std::time::Duration;\nuse crate::progress::ProgUpdate;\n\nlet prog_update = ProgUpdate {\nread_stat: Default::default(),\nwrite_stat: Default::default(),\nduration: Duration::new(1, 0), // one second\n};\n\nlet mut cursor = Cursor::new(vec![]);\nlet rewrite = false;\nprog_update.write_prog_line(&mut cursor, rewrite).unwrap();\nassert_eq!(cursor.get_ref(), b\"0 bytes copied, 1.0 s, 0.0 B/s\\n\");\n```", "repo": "uutils/coreutils", "path": "src/uu/dd/src/progress.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/progress.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "86ba85a00acc5d2f17db192d8e87231e790b34affbd006a7d041364719d1bdb4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_transfer_stats\n\nDocumentation:\nWrite all summary statistics.\n\nThis is a convenience method that calls\n[`ProgUpdate::write_io_lines`] and\n[`ProgUpdate::write_prog_line`] in that order. The information\nis written to `w`. It optionally begins by writing a new line,\nintended to handle the case of an existing progress line.\n\n# Examples\n\n```rust,ignore\nuse std::io::Cursor;\nuse std::time::Duration;\nuse crate::progress::ProgUpdate;\n\nlet prog_update = ProgUpdate {\nread_stat: Default::default(),\nwrite_stat: Default::default(),\nduration: Duration::new(1, 0), // one second\n};\nlet mut cursor = Cursor::new(vec![]);\nprog_update.write_transfer_stats(&mut cursor, false).unwrap();\nlet mut iter = cursor.get_ref().split(|v| *v == b'\\n');\nassert_eq!(iter.next().unwrap(), b\"0+0 records in\");\nassert_eq!(iter.next().unwrap(), b\"0+0 records out\");\nassert_eq!(iter.next().unwrap(), b\"0 bytes copied, 1.0 s, 0.0 B/s\");\nassert_eq!(iter.next().unwrap(), b\"\");\nassert!(iter.next().is_none());\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_transfer_stats(&self, w: &mut impl Write, new_line: bool) -> UResult<()> {\n if new_line {\n writeln!(w)?;\n }\n self.write_io_lines(w)?;\n let rewrite = false;\n self.write_prog_line(w, rewrite)?;\n Ok(())\n }\n```"}], "func_name": "write_transfer_stats", "docstring": "Write all summary statistics.\n\nThis is a convenience method that calls\n[`ProgUpdate::write_io_lines`] and\n[`ProgUpdate::write_prog_line`] in that order. The information\nis written to `w`. It optionally begins by writing a new line,\nintended to handle the case of an existing progress line.\n\n# Examples\n\n```rust,ignore\nuse std::io::Cursor;\nuse std::time::Duration;\nuse crate::progress::ProgUpdate;\n\nlet prog_update = ProgUpdate {\nread_stat: Default::default(),\nwrite_stat: Default::default(),\nduration: Duration::new(1, 0), // one second\n};\nlet mut cursor = Cursor::new(vec![]);\nprog_update.write_transfer_stats(&mut cursor, false).unwrap();\nlet mut iter = cursor.get_ref().split(|v| *v == b'\\n');\nassert_eq!(iter.next().unwrap(), b\"0+0 records in\");\nassert_eq!(iter.next().unwrap(), b\"0+0 records out\");\nassert_eq!(iter.next().unwrap(), b\"0 bytes copied, 1.0 s, 0.0 B/s\");\nassert_eq!(iter.next().unwrap(), b\"\");\nassert!(iter.next().is_none());\n```", "repo": "uutils/coreutils", "path": "src/uu/dd/src/progress.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/progress.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c08df724cfdff61e472bae6bd0a76c7727e5ba908888d26fc1b1e2b0a84967d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_io_lines\n\nDocumentation:\nPrint number of complete and partial records read and written to stderr.\n\nSee [`ProgUpdate::write_io_lines`] for more information.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn print_io_lines(&self) {\n let mut stderr = std::io::stderr();\n self.write_io_lines(&mut stderr).unwrap();\n }\n```"}], "func_name": "print_io_lines", "docstring": "Print number of complete and partial records read and written to stderr.\n\nSee [`ProgUpdate::write_io_lines`] for more information.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/progress.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/progress.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f246eb2403a95b9f955ca555917a591247c85078f0a559632fb7a1634ab1db7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reprint_prog_line\n\nDocumentation:\nRe-print the number of bytes written, duration, and throughput.\n\nSee [`ProgUpdate::write_prog_line`] for more information.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn reprint_prog_line(&self) {\n let mut stderr = std::io::stderr();\n let rewrite = true;\n self.write_prog_line(&mut stderr, rewrite).unwrap();\n }\n```"}], "func_name": "reprint_prog_line", "docstring": "Re-print the number of bytes written, duration, and throughput.\n\nSee [`ProgUpdate::write_prog_line`] for more information.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/progress.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/progress.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ccb68875453d74ed1ac7c0c34e182d914166926d64ecfcd4fc49b3e7320b71a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_transfer_stats\n\nDocumentation:\nWrite all summary statistics.\n\nSee [`ProgUpdate::write_transfer_stats`] for more information.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn print_transfer_stats(&self, new_line: bool) {\n let mut stderr = std::io::stderr();\n self.write_transfer_stats(&mut stderr, new_line).unwrap();\n }\n```"}], "func_name": "print_transfer_stats", "docstring": "Write all summary statistics.\n\nSee [`ProgUpdate::write_transfer_stats`] for more information.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/progress.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/progress.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ebe788b744152ee2e431b423df43a25088f38294540fb4d4b405110258756553"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_empty\n\nDocumentation:\nWhether this counter has zero complete reads and zero partial reads.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn is_empty(&self) -> bool {\n self.reads_complete == 0 && self.reads_partial == 0\n }\n```"}], "func_name": "is_empty", "docstring": "Whether this counter has zero complete reads and zero partial reads.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/progress.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/progress.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "56961e58596a8d638095d7a62eccd6b9b169cd05f602acb375b20ea406420265"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: report\n\nDocumentation:\nWrite the counts in the format required by `dd`.\n\n# Errors\n\nIf there is a problem writing to `w`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn report(&self, w: &mut impl Write) -> std::io::Result<()> {\n writeln!(\n w,\n \"{}+{} records in\",\n self.reads_complete, self.reads_partial\n )?;\n Ok(())\n }\n```"}], "func_name": "report", "docstring": "Write the counts in the format required by `dd`.\n\n# Errors\n\nIf there is a problem writing to `w`.", "repo": "uutils/coreutils", "path": "src/uu/dd/src/progress.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dd/src/progress.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e1adda9a4710fc3f6e7bb1e586ea506416be7acdadcc39d3233a67d9943b00b1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bases\n\nDocumentation:\nThe first ten powers of 1024 and 1000, respectively.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn bases(&self) -> [u128; 10] {\n match self {\n Self::Iec | Self::HumanReadable(HumanReadable::Binary) => IEC_BASES,\n Self::Si | Self::HumanReadable(HumanReadable::Decimal) => SI_BASES,\n }\n }\n```"}], "func_name": "bases", "docstring": "The first ten powers of 1024 and 1000, respectively.", "repo": "uutils/coreutils", "path": "src/uu/df/src/blocks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/blocks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f77d7eff04fa5aa915e7ba0fb5be7b892ec937f71ffc2f21e67436e2bd3844da"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: suffixes\n\nDocumentation:\nSuffixes for the first nine multi-byte unit suffixes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn suffixes(&self) -> [&'static str; 9] {\n match self {\n // we use \"kB\" instead of \"KB\", same as GNU df\n Self::Si => [\"B\", \"kB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"],\n Self::Iec => [\"B\", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\", \"Z\", \"Y\"],\n Self::HumanReadable(HumanReadable::Binary) => {\n [\"\", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\", \"Z\", \"Y\"]\n }\n Self::HumanReadable(HumanReadable::Decimal) => {\n [\"\", \"k\", \"M\", \"G\", \"T\", \"P\", \"E\", \"Z\", \"Y\"]\n }\n }\n }\n```"}], "func_name": "suffixes", "docstring": "Suffixes for the first nine multi-byte unit suffixes.", "repo": "uutils/coreutils", "path": "src/uu/df/src/blocks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/blocks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e3ae5d07dbaca4b9abeb494bfc45929b245e210152d7379501e653af9a24ce8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_matches\n\nDocumentation:\nConvert from command-line arguments to sequence of columns.\n\nThe set of columns that will appear in the output table can be\nspecified by command-line arguments. This function converts\nthose arguments to a [`Vec`] of [`Column`] variants.\n\n# Errors\n\nThis function returns an error if a column is specified more\nthan once in the command-line argument.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn from_matches(matches: &ArgMatches) -> Result, ColumnError> {\n match (\n matches.get_flag(OPT_PRINT_TYPE),\n matches.get_flag(OPT_INODES),\n matches.value_source(OPT_OUTPUT) == Some(ValueSource::CommandLine),\n ) {\n (false, false, false) => Ok(vec![\n Self::Source,\n Self::Size,\n Self::Used,\n Self::Avail,\n #[cfg(target_os = \"macos\")]\n Self::Capacity,\n Self::Pcent,\n Self::Target,\n ]),\n (false, false, true) => {\n // Unwrapping should not panic because in this arm of\n // the `match` statement, we know that `OPT_OUTPUT`\n // is non-empty.\n let names = matches\n .get_many::(OPT_OUTPUT)\n .unwrap()\n .map(|s| s.as_str());\n let mut seen: Vec<&str> = vec![];\n let mut columns = vec![];\n for name in names {\n if seen.contains(&name) {\n return Err(ColumnError::MultipleColumns(name.to_string()));\n }\n seen.push(name);\n // Unwrapping here should not panic because the\n // command-line argument parsing library should be\n // responsible for ensuring each comma-separated\n // string is a valid column label.\n let column = Self::parse(name).unwrap();\n columns.push(column);\n }\n Ok(columns)\n }\n (false, true, false) => Ok(vec![\n Self::Source,\n Self::Itotal,\n Self::Iused,\n Self::Iavail,\n Self::Ipcent,\n Self::Target,\n ]),\n (true, false, false) => Ok(vec![\n Self::Source,\n Self::Fstype,\n Self::Size,\n Self::Used,\n Self::Avail,\n #[cfg(target_os = \"macos\")]\n Self::Capacity,\n Self::Pcent,\n Self::Target,\n ]),\n (true, true, false) => Ok(vec![\n Self::Source,\n Self::Fstype,\n Self::Itotal,\n Self::Iused,\n Self::Iavail,\n Self::Ipcent,\n Self::Target,\n ]),\n // The command-line arguments -T and -i are each mutually\n // exclusive with --output, so the command-line argument\n // parser should reject those combinations before we get\n // to this point in the code.\n _ => unreachable!(),\n }\n }\n```"}], "func_name": "from_matches", "docstring": "Convert from command-line arguments to sequence of columns.\n\nThe set of columns that will appear in the output table can be\nspecified by command-line arguments. This function converts\nthose arguments to a [`Vec`] of [`Column`] variants.\n\n# Errors\n\nThis function returns an error if a column is specified more\nthan once in the command-line argument.", "repo": "uutils/coreutils", "path": "src/uu/df/src/columns.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/columns.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fe982a6a09ed13d00bfb8ad1276743abf695b119907c2e753fcf083b15750922"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse\n\nDocumentation:\nConvert a column name to the corresponding enumeration variant.\n\nThere are twelve valid column names, one for each variant:\n\n- \"source\"\n- \"fstype\"\n- \"itotal\"\n- \"iused\"\n- \"iavail\"\n- \"ipcent\"\n- \"size\"\n- \"used\"\n- \"avail\"\n- \"pcent\"\n- \"file\"\n- \"target\"\n\n# Errors\n\nIf the string `s` is not one of the valid column names.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse(s: &str) -> Result {\n match s {\n \"source\" => Ok(Self::Source),\n \"fstype\" => Ok(Self::Fstype),\n \"itotal\" => Ok(Self::Itotal),\n \"iused\" => Ok(Self::Iused),\n \"iavail\" => Ok(Self::Iavail),\n \"ipcent\" => Ok(Self::Ipcent),\n \"size\" => Ok(Self::Size),\n \"used\" => Ok(Self::Used),\n \"avail\" => Ok(Self::Avail),\n \"pcent\" => Ok(Self::Pcent),\n \"file\" => Ok(Self::File),\n \"target\" => Ok(Self::Target),\n _ => Err(()),\n }\n }\n```"}], "func_name": "parse", "docstring": "Convert a column name to the corresponding enumeration variant.\n\nThere are twelve valid column names, one for each variant:\n\n- \"source\"\n- \"fstype\"\n- \"itotal\"\n- \"iused\"\n- \"iavail\"\n- \"ipcent\"\n- \"size\"\n- \"used\"\n- \"avail\"\n- \"pcent\"\n- \"file\"\n- \"target\"\n\n# Errors\n\nIf the string `s` is not one of the valid column names.", "repo": "uutils/coreutils", "path": "src/uu/df/src/columns.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/columns.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ecd2322cefc345277127f55f291bfc4069b1c44e4f9b43eba7bb0e3ebbb6ba1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: alignment\n\nDocumentation:\nReturn the alignment of the specified column.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn alignment(column: &Self) -> Alignment {\n match column {\n Self::Source | Self::Target | Self::File | Self::Fstype => Alignment::Left,\n _ => Alignment::Right,\n }\n }\n```"}], "func_name": "alignment", "docstring": "Return the alignment of the specified column.", "repo": "uutils/coreutils", "path": "src/uu/df/src/columns.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/columns.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "41fd5cd4f5e513b8bf39d3d19607be17971e29e434db1fdb7c98682557a4da68"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: min_width\n\nDocumentation:\nReturn the minimum width of the specified column.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn min_width(column: &Self) -> usize {\n match column {\n // 14 = length of \"Filesystem\" plus 4 spaces\n Self::Source => 14,\n Self::Used => 5,\n Self::Size => 5,\n // the shortest headers have a length of 4 chars so we use that as the minimum width\n _ => 4,\n }\n }\n```"}], "func_name": "min_width", "docstring": "Return the minimum width of the specified column.", "repo": "uutils/coreutils", "path": "src/uu/df/src/columns.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/columns.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ec01f26549aff506ec58fbef5f49265b9bc3fd51f2291b57c2f84da198803d17"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nConvert command-line arguments into [`Options`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from(matches: &ArgMatches) -> Result {\n let include: Option> = matches\n .get_many::(OPT_TYPE)\n .map(|v| v.map(|s| s.to_string_lossy().to_string()).collect());\n let exclude: Option> = matches\n .get_many::(OPT_EXCLUDE_TYPE)\n .map(|v| v.map(|s| s.to_string_lossy().to_string()).collect());\n\n if let (Some(include), Some(exclude)) = (&include, &exclude) {\n if let Some(types) = Self::get_intersected_types(include, exclude) {\n return Err(OptionsError::FilesystemTypeBothSelectedAndExcluded(types));\n }\n }\n\n Ok(Self {\n show_local_fs: matches.get_flag(OPT_LOCAL),\n show_all_fs: matches.get_flag(OPT_ALL),\n sync: matches.get_flag(OPT_SYNC),\n block_size: read_block_size(matches).map_err(|e| match e {\n ParseSizeError::InvalidSuffix(s) => OptionsError::InvalidSuffix(s),\n ParseSizeError::SizeTooBig(_) => OptionsError::BlockSizeTooLarge(\n matches\n .get_one::(OPT_BLOCKSIZE)\n .unwrap()\n .to_string(),\n ),\n ParseSizeError::ParseFailure(s) => OptionsError::InvalidBlockSize(s),\n ParseSizeError::PhysicalMem(s) => OptionsError::InvalidBlockSize(s),\n })?,\n header_mode: {\n if matches.get_flag(OPT_HUMAN_READABLE_BINARY)\n || matches.get_flag(OPT_HUMAN_READABLE_DECIMAL)\n {\n HeaderMode::HumanReadable\n } else if matches.get_flag(OPT_PORTABILITY) {\n HeaderMode::PosixPortability\n // get_flag() doesn't work here, it always returns true because OPT_OUTPUT has\n // default values and hence is always present\n } else if matches.value_source(OPT_OUTPUT) == Some(ValueSource::CommandLine) {\n HeaderMode::Output\n } else {\n HeaderMode::Default\n }\n },\n human_readable: {\n if matches.get_flag(OPT_HUMAN_READABLE_BINARY) {\n Some(HumanReadable::Binary)\n } else if matches.get_flag(OPT_HUMAN_READABLE_DECIMAL) {\n Some(HumanReadable::Decimal)\n } else {\n None\n }\n },\n include,\n exclude,\n show_total: matches.get_flag(OPT_TOTAL),\n columns: Column::from_matches(matches).map_err(OptionsError::ColumnError)?,\n })\n }\n```"}], "func_name": "from", "docstring": "Convert command-line arguments into [`Options`].", "repo": "uutils/coreutils", "path": "src/uu/df/src/df.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/df.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c6a9d57bbbd2a34508e756769512dad2277435a05be814ab6cbd2814d72c3ee8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_included\n\nDocumentation:\nWhether to display the mount info given the inclusion settings.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_included(mi: &MountInfo, opt: &Options) -> bool {\n // Don't show remote filesystems if `--local` has been given.\n if mi.remote && opt.show_local_fs {\n return false;\n }\n\n // Don't show pseudo filesystems unless `--all` has been given.\n // The \"lofs\" filesystem is a loopback\n // filesystem present on Solaris and FreeBSD systems. It\n // is similar to a symbolic link.\n if (mi.dummy || mi.fs_type == \"lofs\") && !opt.show_all_fs {\n return false;\n }\n\n // Don't show filesystems if they have been explicitly excluded.\n if let Some(ref excludes) = opt.exclude {\n if excludes.contains(&mi.fs_type) {\n return false;\n }\n }\n if let Some(ref includes) = opt.include {\n if !includes.contains(&mi.fs_type) {\n return false;\n }\n }\n\n true\n}\n```"}], "func_name": "is_included", "docstring": "Whether to display the mount info given the inclusion settings.", "repo": "uutils/coreutils", "path": "src/uu/df/src/df.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/df.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d9a0f15adf39f82c1040e28bc8618ee555861cb3a9567b42eca64b315a6b97c1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mount_info_lt\n\nDocumentation:\nWhether the mount info in `m2` should be prioritized over `m1`.\n\nThe \"lt\" in the function name is in analogy to the\n[`std::cmp::PartialOrd::lt`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn mount_info_lt(m1: &MountInfo, m2: &MountInfo) -> bool {\n // let \"real\" devices with '/' in the name win.\n if m1.dev_name.starts_with('/') && !m2.dev_name.starts_with('/') {\n return false;\n }\n\n let m1_nearer_root = m1.mount_dir.len() < m2.mount_dir.len();\n // With bind mounts, prefer items nearer the root of the source\n let m2_below_root = !m1.mount_root.is_empty()\n && !m2.mount_root.is_empty()\n && m1.mount_root.len() > m2.mount_root.len();\n // let points towards the root of the device win.\n if m1_nearer_root && !m2_below_root {\n return false;\n }\n\n // let an entry over-mounted on a new device win, but only when\n // matching an existing mnt point, to avoid problematic\n // replacement when given inaccurate mount lists, seen with some\n // chroot environments for example.\n if m1.dev_name != m2.dev_name && m1.mount_dir == m2.mount_dir {\n return false;\n }\n\n true\n}\n```"}], "func_name": "mount_info_lt", "docstring": "Whether the mount info in `m2` should be prioritized over `m1`.\n\nThe \"lt\" in the function name is in analogy to the\n[`std::cmp::PartialOrd::lt`].", "repo": "uutils/coreutils", "path": "src/uu/df/src/df.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/df.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "772045fa03dba7a9770baba5fe001fb4656483afb7291bd77d30d77151e6115b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_best\n\nDocumentation:\nWhether to prioritize given mount info over all others on the same device.\n\nThis function decides whether the mount info `mi` is better than\nall others in `previous` that mount the same device as `mi`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_best(previous: &[MountInfo], mi: &MountInfo) -> bool {\n for seen in previous {\n if seen.dev_id == mi.dev_id && mount_info_lt(mi, seen) {\n return false;\n }\n }\n true\n}\n```"}], "func_name": "is_best", "docstring": "Whether to prioritize given mount info over all others on the same device.\n\nThis function decides whether the mount info `mi` is better than\nall others in `previous` that mount the same device as `mi`.", "repo": "uutils/coreutils", "path": "src/uu/df/src/df.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/df.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7fb661b35763ccd24f3dcecdca3086b15ebffb30bbc37f3c84b439e82bed47a2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_all_filesystems\n\nDocumentation:\nGet all currently mounted filesystems.\n\n`opt` excludes certain filesystems from consideration and allows for the synchronization of filesystems before running; see\n[`Options`] for more information.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_all_filesystems(opt: &Options) -> UResult> {\n // Run a sync call before any operation if so instructed.\n if opt.sync {\n #[cfg(not(any(windows, target_os = \"redox\")))]\n unsafe {\n #[cfg(not(target_os = \"android\"))]\n uucore::libc::sync();\n #[cfg(target_os = \"android\")]\n uucore::libc::syscall(uucore::libc::SYS_sync);\n }\n }\n\n let mut mounts = vec![];\n for mi in read_fs_list()? {\n // TODO The running time of the `is_best()` function is linear\n // in the length of `result`. That makes the running time of\n // this loop quadratic in the length of `vmi`. This could be\n // improved by a more efficient implementation of `is_best()`,\n // but `vmi` is probably not very long in practice.\n if is_included(&mi, opt) && is_best(&mounts, &mi) {\n mounts.push(mi);\n }\n }\n\n // Convert each `MountInfo` into a `Filesystem`, which contains\n // both the mount information and usage information.\n #[cfg(not(windows))]\n {\n let maybe_mount = |m| Filesystem::from_mount(&mounts, &m, None).ok();\n Ok(mounts\n .clone()\n .into_iter()\n .filter_map(maybe_mount)\n .filter(|fs| opt.show_all_fs || fs.usage.blocks > 0)\n .collect())\n }\n #[cfg(windows)]\n {\n let maybe_mount = |m| Filesystem::from_mount(&m, None).ok();\n Ok(mounts\n .into_iter()\n .filter_map(maybe_mount)\n .filter(|fs| opt.show_all_fs || fs.usage.blocks > 0)\n .collect())\n }\n}\n```"}], "func_name": "get_all_filesystems", "docstring": "Get all currently mounted filesystems.\n\n`opt` excludes certain filesystems from consideration and allows for the synchronization of filesystems before running; see\n[`Options`] for more information.", "repo": "uutils/coreutils", "path": "src/uu/df/src/df.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/df.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "297ad5472b328f7db8a9779fca5b3dc48595b96467410a242ae1dc924d5b9a0c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_named_filesystems\n\nDocumentation:\nFor each path, get the filesystem that contains that path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_named_filesystems

(paths: &[P], opt: &Options) -> UResult>\nwhere\n P: AsRef,\n{\n // The list of all mounted filesystems.\n let mounts: Vec = read_fs_list()?;\n\n let mut result = vec![];\n\n // Convert each path into a `Filesystem`, which contains\n // both the mount information and usage information.\n for path in paths {\n match Filesystem::from_path(&mounts, path) {\n Ok(fs) => {\n if is_included(&fs.mount_info, opt) {\n result.push(fs);\n }\n }\n Err(FsError::InvalidPath) => {\n show!(USimpleError::new(\n 1,\n format!(\"{}: No such file or directory\", path.as_ref().display())\n ));\n }\n Err(FsError::MountMissing) => {\n show!(USimpleError::new(1, \"no file systems processed\"));\n }\n #[cfg(not(windows))]\n Err(FsError::OverMounted) => {\n show!(USimpleError::new(\n 1,\n format!(\n \"cannot access {}: over-mounted by another device\",\n path.as_ref().quote()\n )\n ));\n }\n }\n }\n if get_exit_code() == 0 && result.is_empty() {\n show!(USimpleError::new(1, \"no file systems processed\"));\n return Ok(result);\n }\n\n Ok(result)\n}\n```"}], "func_name": "get_named_filesystems", "docstring": "For each path, get the filesystem that contains that path.", "repo": "uutils/coreutils", "path": "src/uu/df/src/df.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/df.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b1a3a05e3f722ff898fbb7b0137c842827b31fc62069354e3abb9e10a4ef96d6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mount_info\n\nDocumentation:\nInstantiate a [`MountInfo`] with the given fields.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn mount_info(dev_name: &str, mount_root: &str, mount_dir: &str) -> MountInfo {\n MountInfo {\n dev_id: String::new(),\n dev_name: String::from(dev_name),\n fs_type: String::new(),\n mount_dir: String::from(mount_dir),\n mount_option: String::new(),\n mount_root: String::from(mount_root),\n remote: false,\n dummy: false,\n }\n }\n```"}], "func_name": "mount_info", "docstring": "Instantiate a [`MountInfo`] with the given fields.", "repo": "uutils/coreutils", "path": "src/uu/df/src/df.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/df.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54b32a46f359e3b3060535c1dc75c6fd5ef63c4ebf1d4c6c8db88b26878870e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mount_info_from_path\n\nDocumentation:\nFind the mount info that best matches a given filesystem path.\n\nThis function returns the element of `mounts` on which `path` is\nmounted. If there are no matches, this function returns\n[`None`]. If there are two or more matches, then the single\n[`MountInfo`] with the device name corresponding to the entered path.\n\nIf `canonicalize` is `true`, then the `path` is canonicalized\nbefore checking whether it matches any mount directories.\n\n# See also\n\n* [`Path::canonicalize`]\n* [`MountInfo::mount_dir`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn mount_info_from_path

(\n mounts: &[MountInfo],\n path: P,\n // This is really only used for testing purposes.\n canonicalize: bool,\n) -> Result<&MountInfo, FsError>\nwhere\n P: AsRef,\n{\n // TODO Refactor this function with `Stater::find_mount_point()`\n // in the `stat` crate.\n let path = if canonicalize {\n path.as_ref()\n .canonicalize()\n .map_err(|_| FsError::InvalidPath)?\n } else {\n path.as_ref().to_path_buf()\n };\n\n // Find the potential mount point that matches entered path\n let maybe_mount_point = mounts\n .iter()\n // Create pair MountInfo, canonicalized device name\n // TODO Abstract from accessing real filesystem to\n // make code more testable\n .map(|m| (m, std::fs::canonicalize(&m.dev_name)))\n // Ignore non existing paths\n .filter(|m| m.1.is_ok())\n .map(|m| (m.0, m.1.ok().unwrap()))\n // Try to find canonicalized device name corresponding to entered path\n .find(|m| m.1.eq(&path))\n .map(|m| m.0);\n\n maybe_mount_point\n .or_else(|| {\n mounts\n .iter()\n .filter(|mi| path.starts_with(&mi.mount_dir))\n .max_by_key(|mi| mi.mount_dir.len())\n })\n .ok_or(FsError::MountMissing)\n}\n```"}], "func_name": "mount_info_from_path", "docstring": "Find the mount info that best matches a given filesystem path.\n\nThis function returns the element of `mounts` on which `path` is\nmounted. If there are no matches, this function returns\n[`None`]. If there are two or more matches, then the single\n[`MountInfo`] with the device name corresponding to the entered path.\n\nIf `canonicalize` is `true`, then the `path` is canonicalized\nbefore checking whether it matches any mount directories.\n\n# See also\n\n* [`Path::canonicalize`]\n* [`MountInfo::mount_dir`]", "repo": "uutils/coreutils", "path": "src/uu/df/src/filesystem.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/filesystem.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d3c041342dd6370048ca05e89515474c18a9e0ae50c6484d782a971f6da07feb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_path\n\nDocumentation:\nFind and create the filesystem that best matches a given path.\n\nThis function returns a new `Filesystem` derived from the\nelement of `mounts` on which `path` is mounted. If there are\nno matches, this function returns [`None`]. If there are two\nor more matches, then the single [`Filesystem`] with the\nlongest mount directory is returned.\n\nThe `path` is canonicalized before checking whether it matches\nany mount directories.\n\n# See also\n\n* [`Path::canonicalize`]\n* [`MountInfo::mount_dir`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn from_path

(mounts: &[MountInfo], path: P) -> Result\n where\n P: AsRef,\n {\n let file = path.as_ref().display().to_string();\n let canonicalize = true;\n\n let result = mount_info_from_path(mounts, path, canonicalize);\n #[cfg(windows)]\n return result.and_then(|mount_info| Self::from_mount(mount_info, Some(file)));\n #[cfg(not(windows))]\n return result.and_then(|mount_info| Self::from_mount(mounts, mount_info, Some(file)));\n }\n```"}], "func_name": "from_path", "docstring": "Find and create the filesystem that best matches a given path.\n\nThis function returns a new `Filesystem` derived from the\nelement of `mounts` on which `path` is mounted. If there are\nno matches, this function returns [`None`]. If there are two\nor more matches, then the single [`Filesystem`] with the\nlongest mount directory is returned.\n\nThe `path` is canonicalized before checking whether it matches\nany mount directories.\n\n# See also\n\n* [`Path::canonicalize`]\n* [`MountInfo::mount_dir`]", "repo": "uutils/coreutils", "path": "src/uu/df/src/filesystem.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/filesystem.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "730c86c74bc3b484e6f247995793e78d104502091d93a6748237836f8fd21492"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_assign\n\nDocumentation:\nSum the numeric values of two rows.\n\nThe `Row::fs_device` field is set to `\"total\"` and the\nremaining `String` fields are set to `\"-\"`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_assign(&mut self, rhs: Self) {\n let bytes = self.bytes + rhs.bytes;\n let bytes_used = self.bytes_used + rhs.bytes_used;\n let bytes_avail = self.bytes_avail + rhs.bytes_avail;\n let inodes = self.inodes + rhs.inodes;\n let inodes_used = self.inodes_used + rhs.inodes_used;\n *self = Self {\n file: None,\n fs_device: \"total\".into(),\n fs_type: \"-\".into(),\n fs_mount: \"-\".into(),\n bytes,\n bytes_used,\n bytes_avail,\n bytes_usage: if bytes == 0 {\n None\n } else {\n // We use \"(bytes_used + bytes_avail)\" instead of \"bytes\" because on some filesystems (e.g.\n // ext4) \"bytes\" also includes reserved blocks we ignore for the usage calculation.\n // https://www.gnu.org/software/coreutils/faq/coreutils-faq.html#df-Size-and-Used-and-Available-do-not-add-up\n Some(bytes_used as f64 / (bytes_used + bytes_avail) as f64)\n },\n // TODO Figure out how to compute this.\n #[cfg(target_os = \"macos\")]\n bytes_capacity: None,\n inodes,\n inodes_used,\n inodes_free: self.inodes_free + rhs.inodes_free,\n inodes_usage: if inodes == 0 {\n None\n } else {\n Some(inodes_used as f64 / inodes as f64)\n },\n }\n }\n```"}], "func_name": "add_assign", "docstring": "Sum the numeric values of two rows.\n\nThe `Row::fs_device` field is set to `\"total\"` and the\nremaining `String` fields are set to `\"-\"`.", "repo": "uutils/coreutils", "path": "src/uu/df/src/table.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/table.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e99e1e32a242c32f90e6597fa976cf0f7a94e3e491e82148e8ee1223c6b972c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: scaled_bytes\n\nDocumentation:\nGet a string giving the scaled version of the input number.\n\nThe scaling factor is defined in the `options` field.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn scaled_bytes(&self, size: u64) -> String {\n if let Some(h) = self.options.human_readable {\n to_magnitude_and_suffix(size.into(), SuffixType::HumanReadable(h))\n } else {\n let BlockSize::Bytes(d) = self.options.block_size;\n (size as f64 / d as f64).ceil().to_string()\n }\n }\n```"}], "func_name": "scaled_bytes", "docstring": "Get a string giving the scaled version of the input number.\n\nThe scaling factor is defined in the `options` field.", "repo": "uutils/coreutils", "path": "src/uu/df/src/table.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/table.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "758e36411cc5c3bd59303dbb599bfa9a349c557819edd217aa5ee52def0acc87"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: percentage\n\nDocumentation:\nConvert a float between 0 and 1 into a percentage string.\n\nIf `None`, return the string `\"-\"` instead.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn percentage(fraction: Option) -> String {\n match fraction {\n None => \"-\".to_string(),\n Some(x) => format!(\"{:.0}%\", (100.0 * x).ceil()),\n }\n }\n```"}], "func_name": "percentage", "docstring": "Convert a float between 0 and 1 into a percentage string.\n\nIf `None`, return the string `\"-\"` instead.", "repo": "uutils/coreutils", "path": "src/uu/df/src/table.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/table.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e5ca3293b02cd66bf568849730927e93a032a44018b9031d7be94cdc37fc8f34"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_headers\n\nDocumentation:\nReturn the headers for the specified columns.\n\nThe `options` control which column headers are returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_headers(options: &Options) -> Vec {\n let mut headers = Vec::new();\n\n for column in &options.columns {\n let header = match column {\n Column::Source => String::from(\"Filesystem\"),\n Column::Size => match options.header_mode {\n HeaderMode::HumanReadable => String::from(\"Size\"),\n HeaderMode::PosixPortability => {\n format!(\"{}-blocks\", options.block_size.as_u64())\n }\n _ => format!(\"{}-blocks\", options.block_size),\n },\n Column::Used => String::from(\"Used\"),\n Column::Avail => match options.header_mode {\n HeaderMode::HumanReadable | HeaderMode::Output => String::from(\"Avail\"),\n _ => String::from(\"Available\"),\n },\n Column::Pcent => match options.header_mode {\n HeaderMode::PosixPortability => String::from(\"Capacity\"),\n _ => String::from(\"Use%\"),\n },\n Column::Target => String::from(\"Mounted on\"),\n Column::Itotal => String::from(\"Inodes\"),\n Column::Iused => String::from(\"IUsed\"),\n Column::Iavail => String::from(\"IFree\"),\n Column::Ipcent => String::from(\"IUse%\"),\n Column::File => String::from(\"File\"),\n Column::Fstype => String::from(\"Type\"),\n #[cfg(target_os = \"macos\")]\n Column::Capacity => String::from(\"Capacity\"),\n };\n\n headers.push(header);\n }\n\n headers\n }\n```"}], "func_name": "get_headers", "docstring": "Return the headers for the specified columns.\n\nThe `options` control which column headers are returned.", "repo": "uutils/coreutils", "path": "src/uu/df/src/table.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/df/src/table.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd6985db3c8afaf5c092ec5ee3392f753e5e6a127d7597e3b6f3c0b7daa401c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: escape\n\nDocumentation:\nEscape single quotes because they are not allowed between single quotes in shell code, and code\nenclosed by single quotes is what is returned by `parse()`.\n\nWe also escape \":\" to make the \"quote\" test pass in the GNU test suite:\n\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn escape(s: &str) -> String {\n let mut result = String::new();\n let mut previous = ' ';\n\n for c in s.chars() {\n match c {\n '\\'' => result.push_str(\"'\\\\''\"),\n ':' if previous != '\\\\' => result.push_str(\"\\\\:\"),\n _ => result.push(c),\n }\n previous = c;\n }\n\n result\n}\n```"}], "func_name": "escape", "docstring": "Escape single quotes because they are not allowed between single quotes in shell code, and code\nenclosed by single quotes is what is returned by `parse()`.\n\nWe also escape \":\" to make the \"quote\" test pass in the GNU test suite:\n", "repo": "uutils/coreutils", "path": "src/uu/dircolors/src/dircolors.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/dircolors/src/dircolors.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "475edf0aa935af3cf6af1abc2391bbd0a41a93d8ffe32bc52a5a861b3196b6bc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_echo_flag\n\nDocumentation:\nChecks if an argument is a valid echo flag\nReturns true if valid echo flag found\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_echo_flag(arg: &OsString, echo_options: &mut EchoOptions) -> bool {\n let bytes = arg.as_encoded_bytes();\n if bytes.first() == Some(&b'-') && arg != \"-\" {\n // we initialize our local variables to the \"current\" options so we don't override\n // previous found flags\n let mut escape = echo_options.escape;\n let mut trailing_newline = echo_options.trailing_newline;\n\n // Process characters after the '-'\n for c in &bytes[1..] {\n match c {\n b'e' => escape = true,\n b'E' => escape = false,\n b'n' => trailing_newline = false,\n // if there is any char in an argument starting with '-' that doesn't match e/E/n\n // present means that this argument is not a flag\n _ => return false,\n }\n }\n\n // we only override the options with flags being found once we parsed the whole argument\n echo_options.escape = escape;\n echo_options.trailing_newline = trailing_newline;\n return true;\n }\n\n // argument doesn't start with '-' or is \"-\" => no flag\n false\n}\n```"}], "func_name": "is_echo_flag", "docstring": "Checks if an argument is a valid echo flag\nReturns true if valid echo flag found", "repo": "uutils/coreutils", "path": "src/uu/echo/src/echo.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/echo/src/echo.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc9c432d17cf2ff53b2e744e7cff299798bc977e07e6181a7b7a15e7a9412f45"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: filter_echo_flags\n\nDocumentation:\nProcesses command line arguments, separating flags from normal arguments\nReturns:\n- Vector of non-flag arguments\n- trailing_newline: whether to print a trailing newline\n- escape: whether to process escape sequences\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn filter_echo_flags(args: impl uucore::Args) -> (Vec, bool, bool) {\n let mut result = Vec::new();\n let mut echo_options = EchoOptions {\n trailing_newline: true,\n escape: false,\n };\n let mut args_iter = args.into_iter();\n\n // Process arguments until first non-flag is found\n for arg in &mut args_iter {\n // we parse flags and store options found in \"echo_option\". First is_echo_flag\n // call to return false will break the loop and we will collect the remaining arguments\n if !is_echo_flag(&arg, &mut echo_options) {\n // First non-flag argument stops flag processing\n result.push(arg);\n break;\n }\n }\n // Collect remaining arguments\n for arg in args_iter {\n result.push(arg);\n }\n (result, echo_options.trailing_newline, echo_options.escape)\n}\n```"}], "func_name": "filter_echo_flags", "docstring": "Processes command line arguments, separating flags from normal arguments\nReturns:\n- Vector of non-flag arguments\n- trailing_newline: whether to print a trailing newline\n- escape: whether to process escape sequences", "repo": "uutils/coreutils", "path": "src/uu/echo/src/echo.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/echo/src/echo.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "88804476ccc87450a6201c6f40ba12a03f983c5168acbbd5219951e20067a4ed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_space_or_comma\n\nDocumentation:\nDecide whether the character is either a space or a comma.\n\n# Examples\n\n```rust,ignore\nassert!(is_space_or_comma(' '))\nassert!(is_space_or_comma(','))\nassert!(!is_space_or_comma('a'))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_space_or_comma(c: char) -> bool {\n c == ' ' || c == ','\n}\n```"}], "func_name": "is_space_or_comma", "docstring": "Decide whether the character is either a space or a comma.\n\n# Examples\n\n```rust,ignore\nassert!(is_space_or_comma(' '))\nassert!(is_space_or_comma(','))\nassert!(!is_space_or_comma('a'))\n```", "repo": "uutils/coreutils", "path": "src/uu/expand/src/expand.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/expand/src/expand.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d31f43b6181ad1ad8a4300cb07413ed97f3ef63ddba44bd9cc9aeb27e40cb5e8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_digit_or_comma\n\nDocumentation:\nDecide whether the character is either a digit or a comma.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_digit_or_comma(c: char) -> bool {\n c.is_ascii_digit() || c == ','\n}\n```"}], "func_name": "is_digit_or_comma", "docstring": "Decide whether the character is either a digit or a comma.", "repo": "uutils/coreutils", "path": "src/uu/expand/src/expand.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/expand/src/expand.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "53495ffd67836b77d4fac83fc371c68f45cf54b1a08fbd8bf3366fa2cf8d9b4a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tabstops_parse\n\nDocumentation:\nParse a list of tabstops from a `--tabs` argument.\n\nThis function returns both the vector of numbers appearing in the\ncomma- or space-separated list, and also an optional mode, specified\nby either a \"/\" or a \"+\" character appearing before the final number\nin the list. This mode defines the strategy to use for computing the\nnumber of spaces to use for columns beyond the end of the tab stop\nlist specified here.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn tabstops_parse(s: &str) -> Result<(RemainingMode, Vec), ParseError> {\n // Leading commas and spaces are ignored.\n let s = s.trim_start_matches(is_space_or_comma);\n\n // If there were only commas and spaces in the string, just use the\n // default tabstops.\n if s.is_empty() {\n return Ok((RemainingMode::None, vec![DEFAULT_TABSTOP]));\n }\n\n let mut nums = vec![];\n let mut remaining_mode = RemainingMode::None;\n let mut is_specifier_already_used = false;\n for word in s.split(is_space_or_comma) {\n let bytes = word.as_bytes();\n for i in 0..bytes.len() {\n match bytes[i] {\n b'+' => remaining_mode = RemainingMode::Plus,\n b'/' => remaining_mode = RemainingMode::Slash,\n _ => {\n // Parse a number from the byte sequence.\n let s = from_utf8(&bytes[i..]).unwrap();\n match s.parse::() {\n Ok(num) => {\n // Tab size must be positive.\n if num == 0 {\n return Err(ParseError::TabSizeCannotBeZero);\n }\n\n // Tab sizes must be ascending.\n if let Some(last_stop) = nums.last() {\n if *last_stop >= num {\n return Err(ParseError::TabSizesMustBeAscending);\n }\n }\n\n if is_specifier_already_used {\n let specifier = if remaining_mode == RemainingMode::Slash {\n \"/\".to_string()\n } else {\n \"+\".to_string()\n };\n return Err(ParseError::SpecifierOnlyAllowedWithLastValue(\n specifier,\n ));\n } else if remaining_mode != RemainingMode::None {\n is_specifier_already_used = true;\n }\n\n // Append this tab stop to the list of all tabstops.\n nums.push(num);\n break;\n }\n Err(e) => {\n if *e.kind() == IntErrorKind::PosOverflow {\n return Err(ParseError::TabSizeTooLarge(s.to_string()));\n }\n\n let s = s.trim_start_matches(char::is_numeric);\n return if s.starts_with('/') || s.starts_with('+') {\n Err(ParseError::SpecifierNotAtStartOfNumber(\n s[0..1].to_string(),\n s.to_string(),\n ))\n } else {\n Err(ParseError::InvalidCharacter(s.to_string()))\n };\n }\n }\n }\n }\n }\n }\n // If no numbers could be parsed (for example, if `s` were \"+,+,+\"),\n // then just use the default tabstops.\n if nums.is_empty() {\n nums = vec![DEFAULT_TABSTOP];\n }\n\n if nums.len() < 2 {\n remaining_mode = RemainingMode::None;\n }\n Ok((remaining_mode, nums))\n}\n```"}], "func_name": "tabstops_parse", "docstring": "Parse a list of tabstops from a `--tabs` argument.\n\nThis function returns both the vector of numbers appearing in the\ncomma- or space-separated list, and also an optional mode, specified\nby either a \"/\" or a \"+\" character appearing before the final number\nin the list. This mode defines the strategy to use for computing the\nnumber of spaces to use for columns beyond the end of the tab stop\nlist specified here.", "repo": "uutils/coreutils", "path": "src/uu/expand/src/expand.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/expand/src/expand.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ebf92606a1b6de08dc012a570d5ba3cddcf3965c599986de7b80dce012fac170"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expand_shortcuts\n\nDocumentation:\nPreprocess command line arguments and expand shortcuts. For example, \"-7\" is expanded to\n\"--tabs=7\" and \"-1,3\" to \"--tabs=1 --tabs=3\".\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn expand_shortcuts(args: Vec) -> Vec {\n let mut processed_args = Vec::with_capacity(args.len());\n\n for arg in args {\n if let Some(arg) = arg.to_str() {\n if arg.starts_with('-') && arg[1..].chars().all(is_digit_or_comma) {\n arg[1..]\n .split(',')\n .filter(|s| !s.is_empty())\n .for_each(|s| processed_args.push(OsString::from(format!(\"--tabs={s}\"))));\n continue;\n }\n }\n processed_args.push(arg);\n }\n\n processed_args\n}\n```"}], "func_name": "expand_shortcuts", "docstring": "Preprocess command line arguments and expand shortcuts. For example, \"-7\" is expanded to\n\"--tabs=7\" and \"-1,3\" to \"--tabs=1 --tabs=3\".", "repo": "uutils/coreutils", "path": "src/uu/expand/src/expand.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/expand/src/expand.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d7debab682884333b70a6116af8e9f3f03dbf9927e69e71f9e6207b375c27d9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next_tabstop\n\nDocumentation:\nCompute the number of spaces to the next tabstop.\n\n`tabstops` is the sequence of tabstop locations.\n\n`col` is the index of the current cursor in the line being written.\n\nIf `remaining_mode` is [`RemainingMode::Plus`], then the last entry\nin the `tabstops` slice is interpreted as a relative number of\nspaces, which this function will return for every input value of\n`col` beyond the end of the second-to-last element of `tabstops`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn next_tabstop(tabstops: &[usize], col: usize, remaining_mode: &RemainingMode) -> usize {\n let num_tabstops = tabstops.len();\n match remaining_mode {\n RemainingMode::Plus => match tabstops[0..num_tabstops - 1].iter().find(|&&t| t > col) {\n Some(t) => t - col,\n None => {\n let step_size = tabstops[num_tabstops - 1];\n let last_fixed_tabstop = tabstops[num_tabstops - 2];\n let characters_since_last_tabstop = col - last_fixed_tabstop;\n\n let steps_required = 1 + characters_since_last_tabstop / step_size;\n steps_required * step_size - characters_since_last_tabstop\n }\n },\n RemainingMode::Slash => match tabstops[0..num_tabstops - 1].iter().find(|&&t| t > col) {\n Some(t) => t - col,\n None => tabstops[num_tabstops - 1] - col % tabstops[num_tabstops - 1],\n },\n RemainingMode::None => {\n if num_tabstops == 1 {\n tabstops[0] - col % tabstops[0]\n } else {\n match tabstops.iter().find(|&&t| t > col) {\n Some(t) => t - col,\n None => 1,\n }\n }\n }\n }\n}\n```"}], "func_name": "next_tabstop", "docstring": "Compute the number of spaces to the next tabstop.\n\n`tabstops` is the sequence of tabstop locations.\n\n`col` is the index of the current cursor in the line being written.\n\nIf `remaining_mode` is [`RemainingMode::Plus`], then the last entry\nin the `tabstops` slice is interpreted as a relative number of\nspaces, which this function will return for every input value of\n`col` beyond the end of the second-to-last element of `tabstops`.", "repo": "uutils/coreutils", "path": "src/uu/expand/src/expand.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/expand/src/expand.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1812d09cac10f0f13f4b9dff1efe9ac46e6a7e2a3dba7569804bdbf597361a2d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_end_of_expression\n\nDocumentation:\nCheck if regex pattern character iterator is at the end of a regex expression or subexpression\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_end_of_expression(pattern_chars: &I) -> bool\nwhere\n I: Iterator + Clone,\n{\n let mut pattern_chars_clone = pattern_chars.clone();\n match pattern_chars_clone.next() {\n Some('\\\\') => matches!(pattern_chars_clone.next(), Some(')' | '|')),\n None => true, // No characters left\n _ => false,\n }\n}\n```"}], "func_name": "is_end_of_expression", "docstring": "Check if regex pattern character iterator is at the end of a regex expression or subexpression", "repo": "uutils/coreutils", "path": "src/uu/expr/src/syntax_tree.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/expr/src/syntax_tree.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "05ce64ee6a827c5dd3991d9f1d7e61a1808f2a2f92c1f133a5fa7efc06cf393a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: verify_range_quantifier\n\nDocumentation:\nCheck if regex pattern character iterator is at the start of a valid range quantifier.\nThe iterator's start position is expected to be after the opening brace.\nRange quantifier ends to closing brace.\n\n# Examples of valid range quantifiers\n\n- `r\"\\{3\\}\"`\n- `r\"\\{3,\\}\"`\n- `r\"\\{,6\\}\"`\n- `r\"\\{3,6\\}\"`\n- `r\"\\{,\\}\"`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn verify_range_quantifier(pattern_chars: &I) -> Result<(), ExprError>\nwhere\n I: Iterator + Clone,\n{\n let mut pattern_chars_clone = pattern_chars.clone().peekable();\n if pattern_chars_clone.peek().is_none() {\n return Err(ExprError::UnmatchedOpeningBrace);\n }\n\n // Parse the string between braces\n let mut quantifier = String::new();\n let mut prev = '\\0';\n let mut curr_is_escaped = false;\n while let Some(curr) = pattern_chars_clone.next() {\n curr_is_escaped = prev == '\\\\' && !curr_is_escaped;\n if curr_is_escaped && curr == '}' {\n break;\n }\n if pattern_chars_clone.peek().is_none() {\n return Err(ExprError::UnmatchedOpeningBrace);\n }\n if prev != '\\0' {\n quantifier.push(prev);\n }\n prev = curr;\n }\n\n // Check if parsed quantifier is valid\n let re = Regex::new(r\"^([0-9]*,[0-9]*|[0-9]+)$\").expect(\"valid regular expression\");\n if let Some(captures) = re.captures(&quantifier) {\n let matched = captures.at(0).unwrap_or_default();\n match matched.split_once(',') {\n Some((\"\", \"\")) => Ok(()),\n Some((x, \"\") | (\"\", x)) if x.parse::().is_ok() => Ok(()),\n Some((_, \"\") | (\"\", _)) => Err(ExprError::TooBigRangeQuantifierIndex),\n Some((f, l)) => match (f.parse::(), l.parse::()) {\n (Ok(f), Ok(l)) if f > l => Err(ExprError::InvalidBracketContent),\n (Ok(_), Ok(_)) => Ok(()),\n _ => Err(ExprError::TooBigRangeQuantifierIndex),\n },\n None if matched.parse::().is_ok() => Ok(()),\n None => Err(ExprError::TooBigRangeQuantifierIndex),\n }\n } else {\n Err(ExprError::InvalidBracketContent)\n }\n}\n```"}], "func_name": "verify_range_quantifier", "docstring": "Check if regex pattern character iterator is at the start of a valid range quantifier.\nThe iterator's start position is expected to be after the opening brace.\nRange quantifier ends to closing brace.\n\n# Examples of valid range quantifiers\n\n- `r\"\\{3\\}\"`\n- `r\"\\{3,\\}\"`\n- `r\"\\{,6\\}\"`\n- `r\"\\{3,6\\}\"`\n- `r\"\\{,\\}\"`", "repo": "uutils/coreutils", "path": "src/uu/expr/src/syntax_tree.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/expr/src/syntax_tree.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3799503ddcf7fd06c7baebb99d3a36b5a1c2af4aa93d1a370578b20e185d6bc2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_posix_regex_errors\n\nDocumentation:\nCheck for errors in a supplied regular expression\n\nGNU coreutils shows messages for invalid regular expressions\ndifferently from the oniguruma library used by the regex crate.\nThis method attempts to do these checks manually in one pass\nthrough the regular expression.\n\nThis method is not comprehensively checking all cases in which\na regular expression could be invalid; any cases not caught will\nresult in a [ExprError::InvalidRegexExpression] when passing the\nregular expression through the Oniguruma bindings. This method is\nintended to just identify a few situations for which GNU coreutils\nhas specific error messages.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_posix_regex_errors(pattern: &str) -> ExprResult<()> {\n let mut escaped_parens: u64 = 0;\n let mut prev = '\\0';\n let mut curr_is_escaped = false;\n\n for curr in pattern.chars() {\n curr_is_escaped = prev == '\\\\' && !curr_is_escaped;\n match (curr_is_escaped, curr) {\n (true, '(') => escaped_parens += 1,\n (true, ')') => {\n escaped_parens = escaped_parens\n .checked_sub(1)\n .ok_or(ExprError::UnmatchedClosingParenthesis)?;\n }\n _ => {}\n }\n prev = curr;\n }\n\n match escaped_parens {\n 0 => Ok(()),\n _ => Err(ExprError::UnmatchedOpeningParenthesis),\n }\n}\n```"}], "func_name": "check_posix_regex_errors", "docstring": "Check for errors in a supplied regular expression\n\nGNU coreutils shows messages for invalid regular expressions\ndifferently from the oniguruma library used by the regex crate.\nThis method attempts to do these checks manually in one pass\nthrough the regular expression.\n\nThis method is not comprehensively checking all cases in which\na regular expression could be invalid; any cases not caught will\nresult in a [ExprError::InvalidRegexExpression] when passing the\nregular expression through the Oniguruma bindings. This method is\nintended to just identify a few situations for which GNU coreutils\nhas specific error messages.", "repo": "uutils/coreutils", "path": "src/uu/expr/src/syntax_tree.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/expr/src/syntax_tree.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7fe240e8cd00eb4cba9525cc9814a3272bdd06c796e81be701f8eb644e24186d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_truthy\n\nDocumentation:\nDetermine whether `expr` should evaluate the string as \"truthy\"\n\nTruthy strings are either empty or match the regex \"-?0+\".\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_truthy(s: &NumOrStr) -> bool {\n match s {\n NumOrStr::Num(num) => num != &BigInt::from(0),\n NumOrStr::Str(str) => {\n // Edge case: `-` followed by nothing is truthy\n if str == \"-\" {\n return true;\n }\n\n let mut bytes = str.bytes();\n\n // Empty string is falsy\n let Some(first) = bytes.next() else {\n return false;\n };\n\n let is_zero = (first == b'-' || first == b'0') && bytes.all(|b| b == b'0');\n !is_zero\n }\n }\n}\n```"}], "func_name": "is_truthy", "docstring": "Determine whether `expr` should evaluate the string as \"truthy\"\n\nTruthy strings are either empty or match the regex \"-?0+\".", "repo": "uutils/coreutils", "path": "src/uu/expr/src/syntax_tree.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/expr/src/syntax_tree.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9d6dde5d117fb9dcc781ba60a8ce2e1821344369b0a00f383129ac9dd5796c38"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_file\n\nDocumentation:\nProcess the content of a file and format it according to the provided options.\n\n# Arguments\n\n* `file_name` - The name of the file to process. A value of \"-\" represents the standard input.\n* `fmt_opts` - A reference to a `FmtOptions` struct containing the formatting options.\n* `ostream` - A mutable reference to a `BufWriter` wrapping the standard output.\n\n# Returns\n\nA `UResult<()>` indicating success or failure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_file(\n file_name: &str,\n fmt_opts: &FmtOptions,\n ostream: &mut BufWriter,\n) -> UResult<()> {\n let mut fp = BufReader::new(match file_name {\n \"-\" => Box::new(stdin()) as Box,\n _ => {\n let f = File::open(file_name)\n .map_err_context(|| format!(\"cannot open {} for reading\", file_name.quote()))?;\n if f.metadata()\n .map_err_context(|| format!(\"cannot get metadata for {}\", file_name.quote()))?\n .is_dir()\n {\n return Err(USimpleError::new(1, \"read error\".to_string()));\n }\n\n Box::new(f) as Box\n }\n });\n\n let p_stream = ParagraphStream::new(fmt_opts, &mut fp);\n for para_result in p_stream {\n match para_result {\n Err(s) => {\n ostream\n .write_all(s.as_bytes())\n .map_err_context(|| \"failed to write output\".to_string())?;\n ostream\n .write_all(b\"\\n\")\n .map_err_context(|| \"failed to write output\".to_string())?;\n }\n Ok(para) => break_lines(¶, fmt_opts, ostream)\n .map_err_context(|| \"failed to write output\".to_string())?,\n }\n }\n\n // flush the output after each file\n ostream\n .flush()\n .map_err_context(|| \"failed to write output\".to_string())?;\n\n Ok(())\n}\n```"}], "func_name": "process_file", "docstring": "Process the content of a file and format it according to the provided options.\n\n# Arguments\n\n* `file_name` - The name of the file to process. A value of \"-\" represents the standard input.\n* `fmt_opts` - A reference to a `FmtOptions` struct containing the formatting options.\n* `ostream` - A mutable reference to a `BufWriter` wrapping the standard output.\n\n# Returns\n\nA `UResult<()>` indicating success or failure.", "repo": "uutils/coreutils", "path": "src/uu/fmt/src/fmt.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/fmt/src/fmt.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5bb772302245d46363bd015f48e0850b3e155fd0feb67e75c04ca89f183f72f1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_files\n\nDocumentation:\nExtract the file names from the positional arguments, ignoring any negative width in the first\nposition.\n\n# Returns\nA `UResult<()>` with the file names, or an error if one of the file names could not be parsed\n(e.g., it is given as a negative number not in the first argument and not after a --\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extract_files(matches: &ArgMatches) -> UResult> {\n let in_first_pos = matches\n .index_of(options::FILES_OR_WIDTH)\n .is_some_and(|x| x == 1);\n let is_neg = |s: &str| s.parse::().is_ok_and(|w| w < 0);\n\n let files: UResult> = matches\n .get_many::(options::FILES_OR_WIDTH)\n .into_iter()\n .flatten()\n .enumerate()\n .filter_map(|(i, x)| {\n if is_neg(x) {\n if in_first_pos && i == 0 {\n None\n } else {\n let first_num = x.chars().nth(1).expect(\"a negative number should be at least two characters long\");\n Some(Err(\n UUsageError::new(1, format!(\"invalid option -- {first_num}; -WIDTH is recognized only when it is the first\\noption; use -w N instead\"))\n ))\n }\n } else {\n Some(Ok(x.clone()))\n }\n })\n .collect();\n\n if files.as_ref().is_ok_and(|f| f.is_empty()) {\n Ok(vec![\"-\".into()])\n } else {\n files\n }\n}\n```"}], "func_name": "extract_files", "docstring": "Extract the file names from the positional arguments, ignoring any negative width in the first\nposition.\n\n# Returns\nA `UResult<()>` with the file names, or an error if one of the file names could not be parsed\n(e.g., it is given as a negative number not in the first argument and not after a --", "repo": "uutils/coreutils", "path": "src/uu/fmt/src/fmt.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/fmt/src/fmt.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "59d843b581d4c7912b8d6618a04419303609baefebea060d8a23d0c53f694640"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: match_prefix\n\nDocumentation:\nreturns true if this line should be formatted\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn match_prefix(&self, line: &str) -> (bool, usize) {\n let Some(prefix) = &self.opts.prefix else {\n return (true, 0);\n };\n\n FileLines::match_prefix_generic(prefix, line, self.opts.xprefix)\n }\n```"}], "func_name": "match_prefix", "docstring": "returns true if this line should be formatted", "repo": "uutils/coreutils", "path": "src/uu/fmt/src/parasplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/fmt/src/parasplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "07a9783438a3abcd999f07e7c4798f7e428794c54ee2660d09dd2159f07a33d7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fold_file_bytewise\n\nDocumentation:\nFold `file` to fit `width` (number of columns), counting all characters as\none column.\n\nThis function handles folding for the `-b`/`--bytes` option, counting\ntab, backspace, and carriage return as occupying one column, identically\nto all other characters in the stream.\n\nIf `spaces` is `true`, attempt to break lines at whitespace boundaries.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fold_file_bytewise(mut file: BufReader, spaces: bool, width: usize) -> UResult<()> {\n let mut line = String::new();\n\n loop {\n if file\n .read_line(&mut line)\n .map_err_context(|| get_message(\"fold-error-readline\"))?\n == 0\n {\n break;\n }\n\n if line == \"\\n\" {\n println!();\n line.truncate(0);\n continue;\n }\n\n let len = line.len();\n let mut i = 0;\n\n while i < len {\n let width = if len - i >= width { width } else { len - i };\n let slice = {\n let slice = &line[i..i + width];\n if spaces && i + width < len {\n match slice.rfind(|c: char| c.is_whitespace() && c != '\\r') {\n Some(m) => &slice[..=m],\n None => slice,\n }\n } else {\n slice\n }\n };\n\n // Don't duplicate trailing newlines: if the slice is \"\\n\", the\n // previous iteration folded just before the end of the line and\n // has already printed this newline.\n if slice == \"\\n\" {\n break;\n }\n\n i += slice.len();\n\n let at_eol = i >= len;\n\n if at_eol {\n print!(\"{slice}\");\n } else {\n println!(\"{slice}\");\n }\n }\n\n line.truncate(0);\n }\n\n Ok(())\n}\n```"}], "func_name": "fold_file_bytewise", "docstring": "Fold `file` to fit `width` (number of columns), counting all characters as\none column.\n\nThis function handles folding for the `-b`/`--bytes` option, counting\ntab, backspace, and carriage return as occupying one column, identically\nto all other characters in the stream.\n\nIf `spaces` is `true`, attempt to break lines at whitespace boundaries.", "repo": "uutils/coreutils", "path": "src/uu/fold/src/fold.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/fold/src/fold.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "291df5c5c743088b761266beb5736606283659076a12226e4056117cbb4c075d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: find_nth_line_from_end\n\nDocumentation:\nReturn the index in `input` just after the `n`th line from the end.\n\nIf `n` exceeds the number of lines in this file, then return 0.\nThis function rewinds the cursor to the\nbeginning of the input just before returning unless there is an\nI/O error.\n\n# Errors\n\nThis function returns an error if there is a problem seeking\nthrough or reading the input.\n\n# Examples\n\nThe function returns the index of the byte immediately following\nthe line ending character of the `n`th line from the end of the\ninput:\n\n```rust,ignore\nlet mut input = Cursor::new(\"x\\ny\\nz\\n\");\nassert_eq!(find_nth_line_from_end(&mut input, 0, false).unwrap(), 6);\nassert_eq!(find_nth_line_from_end(&mut input, 1, false).unwrap(), 4);\nassert_eq!(find_nth_line_from_end(&mut input, 2, false).unwrap(), 2);\n```\n\nIf `n` exceeds the number of lines in the file, always return 0:\n\n```rust,ignore\nlet mut input = Cursor::new(\"x\\ny\\nz\\n\");\nassert_eq!(find_nth_line_from_end(&mut input, 3, false).unwrap(), 0);\nassert_eq!(find_nth_line_from_end(&mut input, 4, false).unwrap(), 0);\nassert_eq!(find_nth_line_from_end(&mut input, 1000, false).unwrap(), 0);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn find_nth_line_from_end(input: &mut R, n: u64, separator: u8) -> io::Result\nwhere\n R: Read + Seek,\n{\n let file_size = input.seek(SeekFrom::End(0))?;\n\n let mut buffer = [0u8; BUF_SIZE];\n\n let mut lines = 0u64;\n let mut check_last_byte_first_loop = true;\n let mut bytes_remaining_to_search = file_size;\n\n loop {\n // the casts here are ok, `buffer.len()` should never be above a few k\n let bytes_to_read_this_loop =\n bytes_remaining_to_search.min(buffer.len().try_into().unwrap());\n let read_start_offset = bytes_remaining_to_search - bytes_to_read_this_loop;\n let buffer = &mut buffer[..bytes_to_read_this_loop.try_into().unwrap()];\n bytes_remaining_to_search -= bytes_to_read_this_loop;\n\n input.seek(SeekFrom::Start(read_start_offset))?;\n input.read_exact(buffer)?;\n\n // Unfortunately need special handling for the case that the input file doesn't have\n // a terminating `separator` character.\n // If the input file doesn't end with a `separator` character, add an extra line to our\n // `line` counter. In the case that `n` is 0 we need to return here since we've\n // obviously found our 0th-line-from-the-end offset.\n if check_last_byte_first_loop {\n check_last_byte_first_loop = false;\n if let Some(last_byte_of_file) = buffer.last() {\n if last_byte_of_file != &separator {\n if n == 0 {\n input.rewind()?;\n return Ok(file_size);\n }\n assert_eq!(lines, 0);\n lines = 1;\n }\n };\n }\n\n for separator_offset in memrchr_iter(separator, &buffer[..]) {\n lines += 1;\n if lines == n + 1 {\n input.rewind()?;\n return Ok(read_start_offset\n + TryInto::::try_into(separator_offset).unwrap()\n + 1);\n }\n }\n if read_start_offset == 0 {\n input.rewind()?;\n return Ok(0);\n }\n }\n}\n```"}], "func_name": "find_nth_line_from_end", "docstring": "Return the index in `input` just after the `n`th line from the end.\n\nIf `n` exceeds the number of lines in this file, then return 0.\nThis function rewinds the cursor to the\nbeginning of the input just before returning unless there is an\nI/O error.\n\n# Errors\n\nThis function returns an error if there is a problem seeking\nthrough or reading the input.\n\n# Examples\n\nThe function returns the index of the byte immediately following\nthe line ending character of the `n`th line from the end of the\ninput:\n\n```rust,ignore\nlet mut input = Cursor::new(\"x\\ny\\nz\\n\");\nassert_eq!(find_nth_line_from_end(&mut input, 0, false).unwrap(), 6);\nassert_eq!(find_nth_line_from_end(&mut input, 1, false).unwrap(), 4);\nassert_eq!(find_nth_line_from_end(&mut input, 2, false).unwrap(), 2);\n```\n\nIf `n` exceeds the number of lines in the file, always return 0:\n\n```rust,ignore\nlet mut input = Cursor::new(\"x\\ny\\nz\\n\");\nassert_eq!(find_nth_line_from_end(&mut input, 3, false).unwrap(), 0);\nassert_eq!(find_nth_line_from_end(&mut input, 4, false).unwrap(), 0);\nassert_eq!(find_nth_line_from_end(&mut input, 1000, false).unwrap(), 0);\n```", "repo": "uutils/coreutils", "path": "src/uu/head/src/head.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/head/src/head.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc5a4d4f057ec784083e6c42c1a8dd9b159ec028ac63cbcc82f3056e6270a17c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_obsolete\n\nDocumentation:\nParses obsolete syntax\nhead -NUM\\[kmzv\\] // spell-checker:disable-line\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_obsolete(src: &str) -> Option, ParseError>> {\n let mut chars = src.char_indices();\n if let Some((mut num_start, '-')) = chars.next() {\n num_start += 1;\n let mut num_end = src.len();\n let mut has_num = false;\n let mut plus_possible = false;\n let mut last_char = 0 as char;\n for (n, c) in &mut chars {\n if c.is_ascii_digit() {\n has_num = true;\n plus_possible = false;\n } else if c == '+' && plus_possible {\n plus_possible = false;\n num_start += 1;\n continue;\n } else {\n num_end = n;\n last_char = c;\n break;\n }\n }\n if has_num {\n process_num_block(&src[num_start..num_end], last_char, &mut chars)\n } else {\n None\n }\n } else {\n None\n }\n}\n```"}], "func_name": "parse_obsolete", "docstring": "Parses obsolete syntax\nhead -NUM\\[kmzv\\] // spell-checker:disable-line", "repo": "uutils/coreutils", "path": "src/uu/head/src/parse.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/head/src/parse.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eeb4670bfd7602d42762fbd99cf8e4b0b3343496226cc24c4b1975c98df5d81e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_num_block\n\nDocumentation:\nProcesses the numeric block of the input string to generate the appropriate options.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_num_block(\n src: &str,\n last_char: char,\n chars: &mut std::str::CharIndices,\n) -> Option, ParseError>> {\n let num = match src.parse::() {\n Ok(n) => n,\n Err(e) if *e.kind() == std::num::IntErrorKind::PosOverflow => usize::MAX,\n _ => return Some(Err(ParseError)),\n };\n let mut quiet = false;\n let mut verbose = false;\n let mut zero_terminated = false;\n let mut multiplier = None;\n let mut c = last_char;\n loop {\n // note that here, we only match lower case 'k', 'c', and 'm'\n match c {\n // we want to preserve order\n // this also saves us 1 heap allocation\n 'q' => {\n quiet = true;\n verbose = false;\n }\n 'v' => {\n verbose = true;\n quiet = false;\n }\n 'z' => zero_terminated = true,\n 'c' => multiplier = Some(1),\n 'b' => multiplier = Some(512),\n 'k' => multiplier = Some(1024),\n 'm' => multiplier = Some(1024 * 1024),\n '\\0' => {}\n _ => return Some(Err(ParseError)),\n }\n if let Some((_, next)) = chars.next() {\n c = next;\n } else {\n break;\n }\n }\n let mut options = Vec::new();\n if quiet {\n options.push(OsString::from(\"-q\"));\n }\n if verbose {\n options.push(OsString::from(\"-v\"));\n }\n if zero_terminated {\n options.push(OsString::from(\"-z\"));\n }\n if let Some(n) = multiplier {\n options.push(OsString::from(\"-c\"));\n let num = num.saturating_mul(n);\n options.push(OsString::from(format!(\"{num}\")));\n } else {\n options.push(OsString::from(\"-n\"));\n options.push(OsString::from(format!(\"{num}\")));\n }\n Some(Ok(options))\n}\n```"}], "func_name": "process_num_block", "docstring": "Processes the numeric block of the input string to generate the appropriate options.", "repo": "uutils/coreutils", "path": "src/uu/head/src/parse.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/head/src/parse.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "87ce92139ac95bfdaea3c20d11ab32a0f9028fe9a75409c561704eda81639f25"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_num\n\nDocumentation:\nParses an -c or -n argument,\nthe bool specifies whether to read from the end\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_num(src: &str) -> Result<(u64, bool), ParseSizeError> {\n let mut size_string = src.trim();\n let mut all_but_last = false;\n\n if let Some(c) = size_string.chars().next() {\n if c == '+' || c == '-' {\n // head: '+' is not documented (8.32 man pages)\n size_string = &size_string[1..];\n if c == '-' {\n all_but_last = true;\n }\n }\n } else {\n return Err(ParseSizeError::ParseFailure(src.to_string()));\n }\n\n // remove leading zeros so that size is interpreted as decimal, not octal\n let trimmed_string = size_string.trim_start_matches('0');\n if trimmed_string.is_empty() {\n Ok((0, all_but_last))\n } else {\n parse_size_u64_max(trimmed_string).map(|n| (n, all_but_last))\n }\n}\n```"}], "func_name": "parse_num", "docstring": "Parses an -c or -n argument,\nthe bool specifies whether to read from the end", "repo": "uutils/coreutils", "path": "src/uu/head/src/parse.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/head/src/parse.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8fa7b04eb25da9842716fe7901eca51d47477565d6b2881c2f3318f8b1f54884"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_all_but_n_bytes\n\nDocumentation:\nFunction to copy all but `n` bytes from the reader to the writer.\n\nIf `n` exceeds the number of bytes in the input file then nothing is copied.\nIf no errors are encountered then the function returns the number of bytes\ncopied.\n\nAlgorithm for this function is as follows...\n1 - Chunks of the input file are read into a queue of TakeAllBuffer instances.\nChunks are read until at least we have enough data to write out the entire contents of the\nfirst TakeAllBuffer in the queue whilst still retaining at least `n` bytes in the queue.\nIf we hit EoF at any point, stop reading.\n2 - Assess whether we managed to queue up greater-than `n` bytes. If not, we must be done, in\nwhich case break and return.\n3 - Write either the full first buffer of data, or just enough bytes to get back down to having\nthe required `n` bytes of data queued.\n4 - Go back to (1).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn copy_all_but_n_bytes(\n reader: &mut impl Read,\n writer: &mut impl Write,\n n: usize,\n) -> std::io::Result {\n let mut buffers: VecDeque = VecDeque::new();\n let mut empty_buffer_pool: Vec = vec![];\n let mut buffered_bytes: usize = 0;\n let mut total_bytes_copied = 0;\n loop {\n loop {\n // Try to buffer at least enough to write the entire first buffer.\n let front_buffer = buffers.front();\n if let Some(front_buffer) = front_buffer {\n if buffered_bytes >= n + front_buffer.remaining_bytes() {\n break;\n }\n }\n let mut new_buffer = empty_buffer_pool.pop().unwrap_or_else(TakeAllBuffer::new);\n let filled_bytes = new_buffer.fill_buffer(reader)?;\n if filled_bytes == 0 {\n // filled_bytes==0 => Eof\n break;\n }\n buffers.push_back(new_buffer);\n buffered_bytes += filled_bytes;\n }\n\n // If we've got <=n bytes buffered here we have nothing left to do.\n if buffered_bytes <= n {\n break;\n }\n\n let excess_buffered_bytes = buffered_bytes - n;\n // Since we have some data buffered, can assume we have >=1 buffer - i.e. safe to unwrap.\n let front_buffer = buffers.front_mut().unwrap();\n let bytes_written = front_buffer.write_bytes_limit(writer, excess_buffered_bytes)?;\n buffered_bytes -= bytes_written;\n total_bytes_copied += bytes_written;\n // If the front buffer is empty (which it probably is), push it into the empty-buffer-pool.\n if front_buffer.is_empty() {\n empty_buffer_pool.push(buffers.pop_front().unwrap());\n }\n }\n Ok(total_bytes_copied)\n}\n```"}], "func_name": "copy_all_but_n_bytes", "docstring": "Function to copy all but `n` bytes from the reader to the writer.\n\nIf `n` exceeds the number of bytes in the input file then nothing is copied.\nIf no errors are encountered then the function returns the number of bytes\ncopied.\n\nAlgorithm for this function is as follows...\n1 - Chunks of the input file are read into a queue of TakeAllBuffer instances.\nChunks are read until at least we have enough data to write out the entire contents of the\nfirst TakeAllBuffer in the queue whilst still retaining at least `n` bytes in the queue.\nIf we hit EoF at any point, stop reading.\n2 - Assess whether we managed to queue up greater-than `n` bytes. If not, we must be done, in\nwhich case break and return.\n3 - Write either the full first buffer of data, or just enough bytes to get back down to having\nthe required `n` bytes of data queued.\n4 - Go back to (1).", "repo": "uutils/coreutils", "path": "src/uu/head/src/take.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/head/src/take.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "102b5bce99d7d4e37682458353757cd875d94ce0ad3bf806ac722488ff30678b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_all_but_n_lines\n\nDocumentation:\nFunction to copy all but `n` lines from the reader to the writer.\n\nLines are inferred from the `separator` value passed in by the client.\nIf `n` exceeds the number of lines in the input file then nothing is copied.\nThe last line in the file is not required to end with a `separator` character.\nIf no errors are encountered then they function returns the number of bytes\ncopied.\n\nAlgorithm for this function is as follows...\n1 - Chunks of the input file are read into a queue of TakeAllLinesBuffer instances.\nChunks are read until at least we have enough lines that we can write out the entire\ncontents of the first TakeAllLinesBuffer in the queue whilst still retaining at least\n`n` lines in the queue.\nIf we hit EoF at any point, stop reading.\n2 - Asses whether we managed to queue up greater-than `n` lines. If not, we must be done, in\nwhich case break and return.\n3 - Write either the full first buffer of data, or just enough lines to get back down to\nhaving the required `n` lines of data queued.\n4 - Go back to (1).\n\nNote that lines will regularly straddle multiple TakeAllLinesBuffer instances. The partial_line\nflag on TakeAllLinesBuffer tracks this, and we use that to ensure that we write out enough\nlines in the case that the input file doesn't end with a `separator` character.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn copy_all_but_n_lines(\n mut reader: R,\n writer: &mut W,\n n: usize,\n separator: u8,\n) -> std::io::Result {\n // This function requires `n` > 0. Assert it!\n assert!(n > 0);\n let mut buffers: VecDeque = VecDeque::new();\n let mut buffered_terminated_lines: usize = 0;\n let mut empty_buffers = vec![];\n let mut total_bytes_copied = 0;\n loop {\n // Try to buffer enough such that we can write out the entire first buffer.\n loop {\n // First check if we have enough lines buffered that we can write out the entire\n // front buffer. If so, break.\n let front_buffer = buffers.front();\n if let Some(front_buffer) = front_buffer {\n if buffered_terminated_lines > n + front_buffer.terminated_lines() {\n break;\n }\n }\n // Else we need to try to buffer more data...\n let mut new_buffer = empty_buffers.pop().unwrap_or_else(TakeAllLinesBuffer::new);\n let fill_result = new_buffer.fill_buffer(&mut reader, separator)?;\n if fill_result.bytes == 0 {\n // fill_result.bytes == 0 => EoF.\n break;\n }\n buffered_terminated_lines += fill_result.terminated_lines;\n buffers.push_back(new_buffer);\n }\n\n // If we've not buffered more lines than we need to hold back we must be done.\n if buffered_terminated_lines < n\n || (buffered_terminated_lines == n && !buffers.back().unwrap().partial_line())\n {\n break;\n }\n\n let excess_buffered_terminated_lines = buffered_terminated_lines - n;\n // Since we have some data buffered can assume we have at least 1 buffer, so safe to unwrap.\n let lines_to_write = if buffers.back().unwrap().partial_line() {\n excess_buffered_terminated_lines + 1\n } else {\n excess_buffered_terminated_lines\n };\n let front_buffer = buffers.front_mut().unwrap();\n let write_result = front_buffer.write_lines(writer, lines_to_write, separator)?;\n buffered_terminated_lines -= write_result.terminated_lines;\n total_bytes_copied += write_result.bytes;\n // If the front buffer is empty (which it probably is), push it into the empty-buffer-pool.\n if front_buffer.is_empty() {\n empty_buffers.push(buffers.pop_front().unwrap());\n }\n }\n Ok(total_bytes_copied)\n}\n```"}], "func_name": "copy_all_but_n_lines", "docstring": "Function to copy all but `n` lines from the reader to the writer.\n\nLines are inferred from the `separator` value passed in by the client.\nIf `n` exceeds the number of lines in the input file then nothing is copied.\nThe last line in the file is not required to end with a `separator` character.\nIf no errors are encountered then they function returns the number of bytes\ncopied.\n\nAlgorithm for this function is as follows...\n1 - Chunks of the input file are read into a queue of TakeAllLinesBuffer instances.\nChunks are read until at least we have enough lines that we can write out the entire\ncontents of the first TakeAllLinesBuffer in the queue whilst still retaining at least\n`n` lines in the queue.\nIf we hit EoF at any point, stop reading.\n2 - Asses whether we managed to queue up greater-than `n` lines. If not, we must be done, in\nwhich case break and return.\n3 - Write either the full first buffer of data, or just enough lines to get back down to\nhaving the required `n` lines of data queued.\n4 - Go back to (1).\n\nNote that lines will regularly straddle multiple TakeAllLinesBuffer instances. The partial_line\nflag on TakeAllLinesBuffer tracks this, and we use that to ensure that we write out enough\nlines in the case that the input file doesn't end with a `separator` character.", "repo": "uutils/coreutils", "path": "src/uu/head/src/take.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/head/src/take.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b8d44235cb6e0b15bd50970ea0413f643b4931c21d64e691dde120964f799209"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read\n\nDocumentation:\nRead bytes from a buffer up to the requested number of lines.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read(&mut self, buf: &mut [u8]) -> std::io::Result {\n if self.limit == 0 {\n return Ok(0);\n }\n match self.inner.read(buf) {\n Ok(0) => Ok(0),\n Ok(n) => {\n for i in memchr_iter(self.separator, &buf[..n]) {\n self.limit -= 1;\n if self.limit == 0 {\n return Ok(i + 1);\n }\n }\n Ok(n)\n }\n Err(e) => Err(e),\n }\n }\n```"}], "func_name": "read", "docstring": "Read bytes from a buffer up to the requested number of lines.", "repo": "uutils/coreutils", "path": "src/uu/head/src/take.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/head/src/take.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f94835371d43daf3e575a626d7b32b4156cbff4024dc262d0eb9468df9e6d10d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: behavior\n\nDocumentation:\nDetermine behavior, given command line arguments.\n\nIf successful, returns a filled-out Behavior struct.\n\n# Errors\n\nIn event of failure, returns an integer intended as a program return code.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn behavior(matches: &ArgMatches) -> UResult {\n let main_function = if matches.get_flag(OPT_DIRECTORY) {\n MainFunction::Directory\n } else {\n MainFunction::Standard\n };\n\n let considering_dir: bool = MainFunction::Directory == main_function;\n\n let specified_mode: Option = if matches.contains_id(OPT_MODE) {\n let x = matches.get_one::(OPT_MODE).ok_or(1)?;\n Some(mode::parse(x, considering_dir, get_umask()).map_err(|err| {\n show_error!(\"Invalid mode string: {err}\");\n 1\n })?)\n } else {\n None\n };\n\n let backup_mode = backup_control::determine_backup_mode(matches)?;\n let target_dir = matches.get_one::(OPT_TARGET_DIRECTORY).cloned();\n let no_target_dir = matches.get_flag(OPT_NO_TARGET_DIRECTORY);\n if target_dir.is_some() && no_target_dir {\n show_error!(\"Options --target-directory and --no-target-directory are mutually exclusive\");\n return Err(1.into());\n }\n\n let preserve_timestamps = matches.get_flag(OPT_PRESERVE_TIMESTAMPS);\n let compare = matches.get_flag(OPT_COMPARE);\n let strip = matches.get_flag(OPT_STRIP);\n if preserve_timestamps && compare {\n show_error!(\"Options --compare and --preserve-timestamps are mutually exclusive\");\n return Err(1.into());\n }\n if compare && strip {\n show_error!(\"Options --compare and --strip are mutually exclusive\");\n return Err(1.into());\n }\n\n let owner = matches\n .get_one::(OPT_OWNER)\n .map(|s| s.as_str())\n .unwrap_or(\"\")\n .to_string();\n\n let owner_id = if owner.is_empty() {\n None\n } else {\n match usr2uid(&owner) {\n Ok(u) => Some(u),\n Err(_) => return Err(InstallError::InvalidUser(owner.clone()).into()),\n }\n };\n\n let group = matches\n .get_one::(OPT_GROUP)\n .map(|s| s.as_str())\n .unwrap_or(\"\")\n .to_string();\n\n let group_id = if group.is_empty() {\n None\n } else {\n match grp2gid(&group) {\n Ok(g) => Some(g),\n Err(_) => return Err(InstallError::InvalidGroup(group.clone()).into()),\n }\n };\n\n let context = matches.get_one::(OPT_CONTEXT).cloned();\n\n Ok(Behavior {\n main_function,\n specified_mode,\n backup_mode,\n suffix: backup_control::determine_backup_suffix(matches),\n owner_id,\n group_id,\n verbose: matches.get_flag(OPT_VERBOSE),\n preserve_timestamps,\n compare,\n strip,\n strip_program: String::from(\n matches\n .get_one::(OPT_STRIP_PROGRAM)\n .map(|s| s.as_str())\n .unwrap_or(DEFAULT_STRIP_PROGRAM),\n ),\n create_leading: matches.get_flag(OPT_CREATE_LEADING),\n target_dir,\n no_target_dir,\n preserve_context: matches.get_flag(OPT_PRESERVE_CONTEXT),\n context,\n })\n}\n```"}], "func_name": "behavior", "docstring": "Determine behavior, given command line arguments.\n\nIf successful, returns a filled-out Behavior struct.\n\n# Errors\n\nIn event of failure, returns an integer intended as a program return code.", "repo": "uutils/coreutils", "path": "src/uu/install/src/install.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80def5f33bf6b8e97b7f5eb48f1472faa656eab71e6663dcaf271c6bb4b5c268"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: directory\n\nDocumentation:\nCreates directories.\n\nGNU man pages describe this functionality as creating 'all components of\nthe specified directories'.\n\nReturns a Result type with the Err variant containing the error message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn directory(paths: &[String], b: &Behavior) -> UResult<()> {\n if paths.is_empty() {\n Err(InstallError::DirNeedsArg.into())\n } else {\n for path in paths.iter().map(Path::new) {\n // if the path already exist, don't try to create it again\n if !path.exists() {\n // Special case to match GNU's behavior:\n // install -d foo/. should work and just create foo/\n // std::fs::create_dir(\"foo/.\"); fails in pure Rust\n // See also mkdir.rs for another occurrence of this\n let path_to_create = dir_strip_dot_for_creation(path);\n // Differently than the primary functionality\n // (MainFunction::Standard), the directory functionality should\n // create all ancestors (or components) of a directory\n // regardless of the presence of the \"-D\" flag.\n //\n // NOTE: the GNU \"install\" sets the expected mode only for the\n // target directory. All created ancestor directories will have\n // the default mode. Hence it is safe to use fs::create_dir_all\n // and then only modify the target's dir mode.\n if let Err(e) = fs::create_dir_all(path_to_create.as_path())\n .map_err_context(|| path_to_create.as_path().maybe_quote().to_string())\n {\n show!(e);\n continue;\n }\n\n if b.verbose {\n println!(\"creating directory {}\", path_to_create.quote());\n }\n }\n\n if mode::chmod(path, b.mode()).is_err() {\n // Error messages are printed by the mode::chmod function!\n uucore::error::set_exit_code(1);\n continue;\n }\n\n show_if_err!(chown_optional_user_group(path, b));\n\n // Set SELinux context for directory if needed\n #[cfg(feature = \"selinux\")]\n show_if_err!(set_selinux_context(path, b));\n }\n // If the exit code was set, or show! has been called at least once\n // (which sets the exit code as well), function execution will end after\n // this return.\n Ok(())\n }\n}\n```"}], "func_name": "directory", "docstring": "Creates directories.\n\nGNU man pages describe this functionality as creating 'all components of\nthe specified directories'.\n\nReturns a Result type with the Err variant containing the error message.", "repo": "uutils/coreutils", "path": "src/uu/install/src/install.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82468f4003154056b5955d5297f143a62d689519607aecf62a8df386df122e67"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_new_file_path\n\nDocumentation:\nTest if the path is a new file path that can be\ncreated immediately\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_new_file_path(path: &Path) -> bool {\n !path.exists()\n && (path.parent().map(Path::is_dir).unwrap_or(true)\n || path.parent().unwrap().as_os_str().is_empty()) // In case of a simple file\n}\n```"}], "func_name": "is_new_file_path", "docstring": "Test if the path is a new file path that can be\ncreated immediately", "repo": "uutils/coreutils", "path": "src/uu/install/src/install.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "36c0faa9744361d215dd37bc9e868b091aeae4a8755a9f7579f86720e5431632"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_files_into_dir\n\nDocumentation:\nCopy some files into a directory.\n\nPrints verbose information and error messages.\nReturns a Result type with the Err variant containing the error message.\n\n# Parameters\n\n_files_ must all exist as non-directories.\n_target_dir_ must be a directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn copy_files_into_dir(files: &[PathBuf], target_dir: &Path, b: &Behavior) -> UResult<()> {\n if !target_dir.is_dir() {\n return Err(InstallError::TargetDirIsntDir(target_dir.to_path_buf()).into());\n }\n for sourcepath in files {\n if let Err(err) = sourcepath\n .metadata()\n .map_err_context(|| format!(\"cannot stat {}\", sourcepath.quote()))\n {\n show!(err);\n continue;\n }\n\n if sourcepath.is_dir() {\n let err = InstallError::OmittingDirectory(sourcepath.clone());\n show!(err);\n continue;\n }\n\n let mut targetpath = target_dir.to_path_buf();\n let filename = sourcepath.components().next_back().unwrap();\n targetpath.push(filename);\n\n show_if_err!(copy(sourcepath, &targetpath, b));\n }\n // If the exit code was set, or show! has been called at least once\n // (which sets the exit code as well), function execution will end after\n // this return.\n Ok(())\n}\n```"}], "func_name": "copy_files_into_dir", "docstring": "Copy some files into a directory.\n\nPrints verbose information and error messages.\nReturns a Result type with the Err variant containing the error message.\n\n# Parameters\n\n_files_ must all exist as non-directories.\n_target_dir_ must be a directory.", "repo": "uutils/coreutils", "path": "src/uu/install/src/install.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d9b7abb55862c393e40a6f42ca8ffd55e315fb2229f496f618679f49943626da"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: chown_optional_user_group\n\nDocumentation:\nHandle incomplete user/group parings for chown.\n\nReturns a Result type with the Err variant containing the error message.\nIf the user is root, revert the uid & gid\n\n# Parameters\n\n_path_ must exist.\n\n# Errors\n\nIf the owner or group are invalid or copy system call fails, we print a verbose error and\nreturn an empty error value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn chown_optional_user_group(path: &Path, b: &Behavior) -> UResult<()> {\n // GNU coreutils doesn't print chown operations during install with verbose flag.\n let verbosity = Verbosity {\n groups_only: b.owner_id.is_none(),\n level: VerbosityLevel::Normal,\n };\n\n // Determine the owner and group IDs to be used for chown.\n let (owner_id, group_id) = if b.owner_id.is_some() || b.group_id.is_some() {\n (b.owner_id, b.group_id)\n } else if geteuid() == 0 {\n // Special case for root user.\n (Some(0), Some(0))\n } else {\n // No chown operation needed.\n return Ok(());\n };\n\n let meta = match metadata(path) {\n Ok(meta) => meta,\n Err(e) => return Err(InstallError::MetadataFailed(e).into()),\n };\n match wrap_chown(path, &meta, owner_id, group_id, false, verbosity) {\n Ok(msg) if b.verbose && !msg.is_empty() => println!(\"chown: {msg}\"),\n Ok(_) => {}\n Err(e) => return Err(InstallError::ChownFailed(path.to_path_buf(), e).into()),\n }\n\n Ok(())\n}\n```"}], "func_name": "chown_optional_user_group", "docstring": "Handle incomplete user/group parings for chown.\n\nReturns a Result type with the Err variant containing the error message.\nIf the user is root, revert the uid & gid\n\n# Parameters\n\n_path_ must exist.\n\n# Errors\n\nIf the owner or group are invalid or copy system call fails, we print a verbose error and\nreturn an empty error value.", "repo": "uutils/coreutils", "path": "src/uu/install/src/install.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5e0efd410d1da96d62b6ebc7e4ebc6d9e343338f0fc3c4f8d5ede81258791045"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: perform_backup\n\nDocumentation:\nPerform backup before overwriting.\n\n# Parameters\n\n* `to` - The destination file path.\n* `b` - The behavior configuration.\n\n# Returns\n\nReturns an Option containing the backup path, or None if backup is not needed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn perform_backup(to: &Path, b: &Behavior) -> UResult> {\n if to.exists() {\n if b.verbose {\n println!(\"removed {}\", to.quote());\n }\n let backup_path = backup_control::get_backup_path(b.backup_mode, to, &b.suffix);\n if let Some(ref backup_path) = backup_path {\n fs::rename(to, backup_path).map_err(|err| {\n InstallError::BackupFailed(to.to_path_buf(), backup_path.clone(), err)\n })?;\n }\n Ok(backup_path)\n } else {\n Ok(None)\n }\n}\n```"}], "func_name": "perform_backup", "docstring": "Perform backup before overwriting.\n\n# Parameters\n\n* `to` - The destination file path.\n* `b` - The behavior configuration.\n\n# Returns\n\nReturns an Option containing the backup path, or None if backup is not needed.", "repo": "uutils/coreutils", "path": "src/uu/install/src/install.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f84068c0e6b6da42e74c35868a80e13ffd83653adc6334c3423fedbeac2006ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_normal_file\n\nDocumentation:\nCopy a non-special file using std::fs::copy.\n\n# Parameters\n* `from` - The source file path.\n* `to` - The destination file path.\n\n# Returns\n\nReturns an empty Result or an error in case of failure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn copy_normal_file(from: &Path, to: &Path) -> UResult<()> {\n if let Err(err) = fs::copy(from, to) {\n return Err(InstallError::InstallFailed(from.to_path_buf(), to.to_path_buf(), err).into());\n }\n Ok(())\n}\n```"}], "func_name": "copy_normal_file", "docstring": "Copy a non-special file using std::fs::copy.\n\n# Parameters\n* `from` - The source file path.\n* `to` - The destination file path.\n\n# Returns\n\nReturns an empty Result or an error in case of failure.", "repo": "uutils/coreutils", "path": "src/uu/install/src/install.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f1dd7cadbe3600a5e7d188fcf89528f04d2433a46cb9336471ca5f35c2f6a94b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_file\n\nDocumentation:\nCopy a file from one path to another. Handles the certain cases of special\nfiles (e.g character specials).\n\n# Parameters\n\n* `from` - The source file path.\n* `to` - The destination file path.\n\n# Returns\n\nReturns an empty Result or an error in case of failure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn copy_file(from: &Path, to: &Path) -> UResult<()> {\n if let Ok(to_abs) = to.canonicalize() {\n if from.canonicalize()? == to_abs {\n return Err(InstallError::SameFile(from.to_path_buf(), to.to_path_buf()).into());\n }\n }\n\n if to.is_dir() && !from.is_dir() {\n return Err(InstallError::OverrideDirectoryFailed(\n to.to_path_buf().clone(),\n from.to_path_buf().clone(),\n )\n .into());\n }\n // fs::copy fails if destination is a invalid symlink.\n // so lets just remove all existing files at destination before copy.\n if let Err(e) = fs::remove_file(to) {\n if e.kind() != std::io::ErrorKind::NotFound {\n show_error!(\n \"Failed to remove existing file {}. Error: {e:?}\",\n to.display(),\n );\n }\n }\n\n let ft = match metadata(from) {\n Ok(ft) => ft.file_type(),\n Err(err) => {\n return Err(\n InstallError::InstallFailed(from.to_path_buf(), to.to_path_buf(), err).into(),\n );\n }\n };\n\n // Stream-based copying to get around the limitations of std::fs::copy\n #[cfg(unix)]\n if ft.is_char_device() || ft.is_block_device() || ft.is_fifo() {\n let mut handle = File::open(from)?;\n let mut dest = File::create(to)?;\n copy_stream(&mut handle, &mut dest)?;\n return Ok(());\n }\n\n copy_normal_file(from, to)?;\n\n Ok(())\n}\n```"}], "func_name": "copy_file", "docstring": "Copy a file from one path to another. Handles the certain cases of special\nfiles (e.g character specials).\n\n# Parameters\n\n* `from` - The source file path.\n* `to` - The destination file path.\n\n# Returns\n\nReturns an empty Result or an error in case of failure.", "repo": "uutils/coreutils", "path": "src/uu/install/src/install.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b58f65bc40e4b51127f95b55d5f8c00b86a7eb2b860a3ec595485d8c7ed6490"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: strip_file\n\nDocumentation:\nStrip a file using an external program.\n\n# Parameters\n\n* `to` - The destination file path.\n* `b` - The behavior configuration.\n\n# Returns\n\nReturns an empty Result or an error in case of failure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn strip_file(to: &Path, b: &Behavior) -> UResult<()> {\n // Check if the filename starts with a hyphen and adjust the path\n let to_str = to.as_os_str().to_str().unwrap_or_default();\n let to = if to_str.starts_with('-') {\n let mut new_path = PathBuf::from(\".\");\n new_path.push(to);\n new_path\n } else {\n to.to_path_buf()\n };\n match process::Command::new(&b.strip_program).arg(&to).status() {\n Ok(status) => {\n if !status.success() {\n // Follow GNU's behavior: if strip fails, removes the target\n let _ = fs::remove_file(to);\n return Err(InstallError::StripProgramFailed(format!(\n \"strip process terminated abnormally - exit code: {}\",\n status.code().unwrap()\n ))\n .into());\n }\n }\n Err(e) => {\n // Follow GNU's behavior: if strip fails, removes the target\n let _ = fs::remove_file(to);\n return Err(InstallError::StripProgramFailed(e.to_string()).into());\n }\n }\n Ok(())\n}\n```"}], "func_name": "strip_file", "docstring": "Strip a file using an external program.\n\n# Parameters\n\n* `to` - The destination file path.\n* `b` - The behavior configuration.\n\n# Returns\n\nReturns an empty Result or an error in case of failure.", "repo": "uutils/coreutils", "path": "src/uu/install/src/install.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "32ae0f694ad72a0c58458b9b125d48f98a3aec3484612931b4ba45deb71b47f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_ownership_and_permissions\n\nDocumentation:\nSet ownership and permissions on the destination file.\n\n# Parameters\n\n* `to` - The destination file path.\n* `b` - The behavior configuration.\n\n# Returns\n\nReturns an empty Result or an error in case of failure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_ownership_and_permissions(to: &Path, b: &Behavior) -> UResult<()> {\n // Silent the warning as we want to the error message\n #[allow(clippy::question_mark)]\n if mode::chmod(to, b.mode()).is_err() {\n return Err(InstallError::ChmodFailed(to.to_path_buf()).into());\n }\n\n chown_optional_user_group(to, b)?;\n\n Ok(())\n}\n```"}], "func_name": "set_ownership_and_permissions", "docstring": "Set ownership and permissions on the destination file.\n\n# Parameters\n\n* `to` - The destination file path.\n* `b` - The behavior configuration.\n\n# Returns\n\nReturns an empty Result or an error in case of failure.", "repo": "uutils/coreutils", "path": "src/uu/install/src/install.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3c032f9ec3b49c4fcee515ad396f0b3209b7d60afcd02c4eddc6f4207d85d5a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: preserve_timestamps\n\nDocumentation:\nPreserve timestamps on the destination file.\n\n# Parameters\n\n* `from` - The source file path.\n* `to` - The destination file path.\n\n# Returns\n\nReturns an empty Result or an error in case of failure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn preserve_timestamps(from: &Path, to: &Path) -> UResult<()> {\n let meta = match metadata(from) {\n Ok(meta) => meta,\n Err(e) => return Err(InstallError::MetadataFailed(e).into()),\n };\n\n let modified_time = FileTime::from_last_modification_time(&meta);\n let accessed_time = FileTime::from_last_access_time(&meta);\n\n if let Err(e) = set_file_times(to, accessed_time, modified_time) {\n show_error!(\"{e}\");\n // ignore error\n }\n Ok(())\n}\n```"}], "func_name": "preserve_timestamps", "docstring": "Preserve timestamps on the destination file.\n\n# Parameters\n\n* `from` - The source file path.\n* `to` - The destination file path.\n\n# Returns\n\nReturns an empty Result or an error in case of failure.", "repo": "uutils/coreutils", "path": "src/uu/install/src/install.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f062543428ed4492ca450f29a147e8a15634c6de2c4fb1fe87f427c1c11ee04"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy\n\nDocumentation:\nCopy one file to a new location, changing metadata.\n\nReturns a Result type with the Err variant containing the error message.\n\n# Parameters\n\n_from_ must exist as a non-directory.\n_to_ must be a non-existent file, whose parent directory exists.\n\n# Errors\n\nIf the copy system call fails, we print a verbose error and return an empty error value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn copy(from: &Path, to: &Path, b: &Behavior) -> UResult<()> {\n if b.compare && !need_copy(from, to, b)? {\n return Ok(());\n }\n // Declare the path here as we may need it for the verbose output below.\n let backup_path = perform_backup(to, b)?;\n\n copy_file(from, to)?;\n\n #[cfg(not(windows))]\n if b.strip {\n strip_file(to, b)?;\n }\n\n set_ownership_and_permissions(to, b)?;\n\n if b.preserve_timestamps {\n preserve_timestamps(from, to)?;\n }\n\n #[cfg(feature = \"selinux\")]\n if b.preserve_context {\n uucore::selinux::preserve_security_context(from, to)\n .map_err(|e| InstallError::SelinuxContextFailed(e.to_string()))?;\n } else if b.context.is_some() {\n set_selinux_context(to, b)?;\n }\n\n if b.verbose {\n print!(\"{} -> {}\", from.quote(), to.quote());\n match backup_path {\n Some(path) => println!(\" (backup: {})\", path.quote()),\n None => println!(),\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "copy", "docstring": "Copy one file to a new location, changing metadata.\n\nReturns a Result type with the Err variant containing the error message.\n\n# Parameters\n\n_from_ must exist as a non-directory.\n_to_ must be a non-existent file, whose parent directory exists.\n\n# Errors\n\nIf the copy system call fails, we print a verbose error and return an empty error value.", "repo": "uutils/coreutils", "path": "src/uu/install/src/install.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0e2e39a040d76d4a1a9d3a8498790a2abd1bf73b02cd3f4112a7108845ee5bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: need_copy\n\nDocumentation:\nReturn true if a file is necessary to copy. This is the case when:\n\n- _from_ or _to_ is nonexistent;\n- either file has a sticky bit or set\\[ug\\]id bit, or the user specified one;\n- either file isn't a regular file;\n- the sizes of _from_ and _to_ differ;\n- _to_'s owner differs from intended; or\n- the contents of _from_ and _to_ differ.\n\n# Parameters\n\n_from_ and _to_, if existent, must be non-directories.\n\n# Errors\n\nCrashes the program if a nonexistent owner or group is specified in _b_.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn need_copy(from: &Path, to: &Path, b: &Behavior) -> UResult {\n // Attempt to retrieve metadata for the source file.\n // If this fails, assume the file needs to be copied.\n let Ok(from_meta) = metadata(from) else {\n return Ok(true);\n };\n\n // Attempt to retrieve metadata for the destination file.\n // If this fails, assume the file needs to be copied.\n let Ok(to_meta) = metadata(to) else {\n return Ok(true);\n };\n\n // Define special file mode bits (setuid, setgid, sticky).\n let extra_mode: u32 = 0o7000;\n // Define all file mode bits (including permissions).\n // setuid || setgid || sticky || permissions\n let all_modes: u32 = 0o7777;\n\n // Check if any special mode bits are set in the specified mode,\n // source file mode, or destination file mode.\n if b.specified_mode.unwrap_or(0) & extra_mode != 0\n || from_meta.mode() & extra_mode != 0\n || to_meta.mode() & extra_mode != 0\n {\n return Ok(true);\n }\n\n // Check if the mode of the destination file differs from the specified mode.\n if b.mode() != to_meta.mode() & all_modes {\n return Ok(true);\n }\n\n // Check if either the source or destination is not a file.\n if !from_meta.is_file() || !to_meta.is_file() {\n return Ok(true);\n }\n\n // Check if the file sizes differ.\n if from_meta.len() != to_meta.len() {\n return Ok(true);\n }\n\n #[cfg(feature = \"selinux\")]\n if b.preserve_context && contexts_differ(from, to) {\n return Ok(true);\n }\n\n // TODO: if -P (#1809) and from/to contexts mismatch, return true.\n\n // Check if the owner ID is specified and differs from the destination file's owner.\n if let Some(owner_id) = b.owner_id {\n if owner_id != to_meta.uid() {\n return Ok(true);\n }\n }\n\n // Check if the group ID is specified and differs from the destination file's group.\n if let Some(group_id) = b.group_id {\n if group_id != to_meta.gid() {\n return Ok(true);\n }\n } else {\n #[cfg(not(target_os = \"windows\"))]\n // Check if the destination file's owner or group\n // differs from the effective user/group ID of the process.\n if to_meta.uid() != geteuid() || to_meta.gid() != getegid() {\n return Ok(true);\n }\n }\n\n // Check if the contents of the source and destination files differ.\n if !diff(from.to_str().unwrap(), to.to_str().unwrap()) {\n return Ok(true);\n }\n\n Ok(false)\n}\n```"}], "func_name": "need_copy", "docstring": "Return true if a file is necessary to copy. This is the case when:\n\n- _from_ or _to_ is nonexistent;\n- either file has a sticky bit or set\\[ug\\]id bit, or the user specified one;\n- either file isn't a regular file;\n- the sizes of _from_ and _to_ differ;\n- _to_'s owner differs from intended; or\n- the contents of _from_ and _to_ differ.\n\n# Parameters\n\n_from_ and _to_, if existent, must be non-directories.\n\n# Errors\n\nCrashes the program if a nonexistent owner or group is specified in _b_.", "repo": "uutils/coreutils", "path": "src/uu/install/src/install.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/install.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf802faa56b7f9ddc1420d01b899bdaca84116324cec513b74459e15493f7cd1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse\n\nDocumentation:\nTakes a user-supplied string and tries to parse to u16 mode bitmask.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse(mode_string: &str, considering_dir: bool, umask: u32) -> Result {\n if mode_string.chars().any(|c| c.is_ascii_digit()) {\n mode::parse_numeric(0, mode_string, considering_dir)\n } else {\n mode::parse_symbolic(0, mode_string, umask, considering_dir)\n }\n}\n```"}], "func_name": "parse", "docstring": "Takes a user-supplied string and tries to parse to u16 mode bitmask.", "repo": "uutils/coreutils", "path": "src/uu/install/src/mode.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/install/src/mode.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "46a568663a81b94967c64f40320bc8b7b75493856feec2abb556df9e96d7339b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_field\n\nDocumentation:\nPrint the field or empty filler if the field is not set.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_field(\n &self,\n writer: &mut impl Write,\n field: Option<&[u8]>,\n ) -> Result<(), std::io::Error> {\n let value = match field {\n Some(field) => field,\n None => self.empty,\n };\n\n writer.write_all(value)\n }\n```"}], "func_name": "print_field", "docstring": "Print the field or empty filler if the field is not set.", "repo": "uutils/coreutils", "path": "src/uu/join/src/join.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/join/src/join.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf598364cfcc8d520b8f373042c651364deb62cf3517ed96ddcd73090bbc48c1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_fields\n\nDocumentation:\nPrint each field except the one at the index.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_fields(\n &self,\n writer: &mut impl Write,\n line: &Line,\n index: usize,\n ) -> Result<(), std::io::Error> {\n for i in 0..line.field_ranges.len() {\n if i != index {\n writer.write_all(self.separator.output_separator())?;\n writer.write_all(line.get_field(i).unwrap())?;\n }\n }\n Ok(())\n }\n```"}], "func_name": "print_fields", "docstring": "Print each field except the one at the index.", "repo": "uutils/coreutils", "path": "src/uu/join/src/join.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/join/src/join.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5e2cf50273d3cf474e2fd9be2c469bcc5fe5741039e4ad62548f742e03dd0151"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_format\n\nDocumentation:\nPrint each field or the empty filler if the field is not set.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_format(&self, writer: &mut impl Write, f: F) -> Result<(), std::io::Error>\n where\n F: Fn(&Spec) -> Option<&'a [u8]>,\n {\n for i in 0..self.format.len() {\n if i > 0 {\n writer.write_all(self.separator.output_separator())?;\n }\n\n let field = match f(&self.format[i]) {\n Some(value) => value,\n None => self.empty,\n };\n\n writer.write_all(field)?;\n }\n Ok(())\n }\n```"}], "func_name": "print_format", "docstring": "Print each field or the empty filler if the field is not set.", "repo": "uutils/coreutils", "path": "src/uu/join/src/join.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/join/src/join.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "578016e01664b55f08afe971277a5e6bea7633c4d288daefcf522dbb0e8be02b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extend\n\nDocumentation:\nKeep reading line sequence until the key does not change, return\nthe first line whose key differs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extend(&mut self, input: &Input) -> UResult> {\n while let Some(line) = self.next_line(input)? {\n let diff = input.compare(self.get_current_key(), line.get_field(self.key));\n\n if diff == Ordering::Equal {\n self.seq.push(line);\n } else {\n return Ok(Some(line));\n }\n }\n\n Ok(None)\n }\n```"}], "func_name": "extend", "docstring": "Keep reading line sequence until the key does not change, return\nthe first line whose key differs.", "repo": "uutils/coreutils", "path": "src/uu/join/src/join.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/join/src/join.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09ecb4f82a3525e01380fae7602cadd9ec5d665e409c26f606d7f1af5d42b247"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_headers\n\nDocumentation:\nPrint lines in the buffers as headers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_headers(\n &self,\n writer: &mut impl Write,\n other: &State,\n repr: &Repr<'a, Sep>,\n ) -> Result<(), std::io::Error> {\n if self.has_line() {\n if other.has_line() {\n self.combine(writer, other, repr)?;\n } else {\n self.print_first_line(writer, repr)?;\n }\n } else if other.has_line() {\n other.print_first_line(writer, repr)?;\n }\n\n Ok(())\n }\n```"}], "func_name": "print_headers", "docstring": "Print lines in the buffers as headers.", "repo": "uutils/coreutils", "path": "src/uu/join/src/join.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/join/src/join.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4fa1b456520f8de1ca379de9be545271c1e23606770a6386743998624047c455"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_line\n\nDocumentation:\nGet the next line without the order check.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_line(&mut self, sep: &Sep) -> Result, std::io::Error> {\n match self.lines.next() {\n Some(value) => {\n self.line_num += 1;\n let line = Line::new(value?, sep, self.max_len);\n if line.field_ranges.len() > self.max_len {\n self.max_len = line.field_ranges.len();\n }\n Ok(Some(line))\n }\n None => Ok(None),\n }\n }\n```"}], "func_name": "read_line", "docstring": "Get the next line without the order check.", "repo": "uutils/coreutils", "path": "src/uu/join/src/join.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/join/src/join.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c084906225caec9e325a73c6081b99db796070dc9fd5f6a8408e836b2c489cee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next_line\n\nDocumentation:\nGet the next line with the order check.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn next_line(&mut self, input: &Input) -> Result, JoinError> {\n if let Some(line) = self.read_line(&input.separator)? {\n if input.check_order == CheckOrder::Disabled {\n return Ok(Some(line));\n }\n\n let diff = input.compare(self.get_current_key(), line.get_field(self.key));\n\n if diff == Ordering::Greater\n && (input.check_order == CheckOrder::Enabled\n || (self.has_unpaired && !self.has_failed))\n {\n let err_msg = get_message_with_args(\n \"join-error-not-sorted\",\n HashMap::from([\n (\"file\".to_string(), self.file_name.maybe_quote().to_string()),\n (\"line_num\".to_string(), self.line_num.to_string()),\n (\n \"content\".to_string(),\n String::from_utf8_lossy(&line.string).to_string(),\n ),\n ]),\n );\n // This is fatal if the check is enabled.\n if input.check_order == CheckOrder::Enabled {\n return Err(JoinError::UnorderedInput(err_msg));\n }\n eprintln!(\"{}: {err_msg}\", uucore::execution_phrase());\n self.has_failed = true;\n }\n\n Ok(Some(line))\n } else {\n Ok(None)\n }\n }\n```"}], "func_name": "next_line", "docstring": "Get the next line with the order check.", "repo": "uutils/coreutils", "path": "src/uu/join/src/join.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/join/src/join.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "855f558361cb496a9022de2cd851212b84fd160067da56eab7021997bd9913b1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_field_number\n\nDocumentation:\nCheck that keys for both files and for a particular file are not\ncontradictory and return the key index.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_field_number(keys: Option, key: Option) -> UResult {\n if let Some(keys) = keys {\n if let Some(key) = key {\n if keys != key {\n // Show zero-based field numbers as one-based.\n return Err(USimpleError::new(\n 1,\n get_message_with_args(\n \"join-error-incompatible-fields\",\n HashMap::from([\n (\"field1\".to_string(), (keys + 1).to_string()),\n (\"field2\".to_string(), (key + 1).to_string()),\n ]),\n ),\n ));\n }\n }\n\n return Ok(keys);\n }\n\n Ok(key.unwrap_or(0))\n}\n```"}], "func_name": "get_field_number", "docstring": "Check that keys for both files and for a particular file are not\ncontradictory and return the key index.", "repo": "uutils/coreutils", "path": "src/uu/join/src/join.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/join/src/join.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ae61fc5c7f9a76e5a8a266dd8041f526a02fd4e9984eb3c4e5e873eb453fab9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_field_number\n\nDocumentation:\nParse the specified field string as a natural number and return\nthe zero-based field number.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_field_number(value: &str) -> UResult {\n match value.parse::() {\n Ok(result) if result > 0 => Ok(result - 1),\n Err(e) if e.kind() == &IntErrorKind::PosOverflow => Ok(usize::MAX),\n _ => Err(USimpleError::new(\n 1,\n get_message_with_args(\n \"join-error-invalid-field-number\",\n HashMap::from([(\"value\".to_string(), value.quote().to_string())]),\n ),\n )),\n }\n}\n```"}], "func_name": "parse_field_number", "docstring": "Parse the specified field string as a natural number and return\nthe zero-based field number.", "repo": "uutils/coreutils", "path": "src/uu/join/src/join.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/join/src/join.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "20f34414ba0abfb68e961b71b1cc336cebe1bf35a733c696d9050cc3f0155229"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset\n\nDocumentation:\nResets the current style and returns the default ANSI reset code to\nreset all text formatting attributes. If `force` is true, the reset is\ndone even if the reset has been applied before.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn reset(&mut self, force: bool) -> &'static str {\n // todo:\n // We need to use style from `Indicator::Reset` but as of now ls colors\n // uses a fallback mechanism and because of that if `Indicator::Reset`\n // is not specified it would fallback to `Indicator::Normal` which seems\n // to be non compatible with gnu\n if self.current_style.is_some() || force {\n self.initial_reset_is_done = true;\n self.current_style = None;\n return \"\\x1b[0m\";\n }\n \"\"\n }\n```"}], "func_name": "reset", "docstring": "Resets the current style and returns the default ANSI reset code to\nreset all text formatting attributes. If `force` is true, the reset is\ndone even if the reset has been applied before.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/colors.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/colors.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cdc0bd1545293c59577adced37789cd06276d332e125ff2906c1e73c338b2047"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: color_name\n\nDocumentation:\nColors the provided name based on the style determined for the given path\nThis function is quite long because it tries to leverage DirEntry to avoid\nunnecessary calls to stat()\nand manages the symlink errors\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn color_name(\n name: OsString,\n path: &PathData,\n style_manager: &mut StyleManager,\n out: &mut BufWriter,\n target_symlink: Option<&PathData>,\n wrap: bool,\n) -> OsString {\n // Check if the file has capabilities\n #[cfg(all(unix, not(any(target_os = \"android\", target_os = \"macos\"))))]\n {\n // Skip checking capabilities if LS_COLORS=ca=:\n let capabilities = style_manager\n .colors\n .style_for_indicator(Indicator::Capabilities);\n\n let has_capabilities = if capabilities.is_none() {\n false\n } else {\n uucore::fsxattr::has_acl(path.p_buf.as_path())\n };\n\n // If the file has capabilities, use a specific style for `ca` (capabilities)\n if has_capabilities {\n return style_manager.apply_style(capabilities, name, wrap);\n }\n }\n\n if !path.must_dereference {\n // If we need to dereference (follow) a symlink, we will need to get the metadata\n if let Some(de) = &path.de {\n // There is a DirEntry, we don't need to get the metadata for the color\n return style_manager.apply_style_based_on_dir_entry(de, name, wrap);\n }\n }\n\n if let Some(target) = target_symlink {\n // use the optional target_symlink\n // Use fn get_metadata_with_deref_opt instead of get_metadata() here because ls\n // should not exit with an err, if we are unable to obtain the target_metadata\n let md_res = get_metadata_with_deref_opt(&target.p_buf, path.must_dereference);\n let md = md_res.or_else(|_| path.p_buf.symlink_metadata());\n style_manager.apply_style_based_on_metadata(path, md.ok().as_ref(), name, wrap)\n } else {\n let md_option = path.get_metadata(out);\n let symlink_metadata = path.p_buf.symlink_metadata().ok();\n let md = md_option.or(symlink_metadata.as_ref());\n style_manager.apply_style_based_on_metadata(path, md, name, wrap)\n }\n}\n```"}], "func_name": "color_name", "docstring": "Colors the provided name based on the style determined for the given path\nThis function is quite long because it tries to leverage DirEntry to avoid\nunnecessary calls to stat()\nand manages the symlink errors", "repo": "uutils/coreutils", "path": "src/uu/ls/src/colors.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/colors.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b00517ee6d323697a9afe629376da38f47fb13b5c1158f1cb93f31dbfca506d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: calculate_dired\n\nDocumentation:\nCalculates the byte positions for DIRED\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn calculate_dired(\n dired_positions: &[BytePosition],\n output_display_len: usize,\n dfn_len: usize,\n) -> (usize, usize) {\n let offset_from_previous_line = get_offset_from_previous_line(dired_positions);\n\n let start = output_display_len + offset_from_previous_line;\n let end = start + dfn_len;\n (start, end)\n}\n```"}], "func_name": "calculate_dired", "docstring": "Calculates the byte positions for DIRED", "repo": "uutils/coreutils", "path": "src/uu/ls/src/dired.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/dired.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6a2a78baaa902e8f9cd7f1cefe0754fe79bca3e4d7d10105061f16b3c100a010"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_dired_output\n\nDocumentation:\nPrints the dired output based on the given configuration and dired structure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn print_dired_output(\n config: &Config,\n dired: &DiredOutput,\n out: &mut BufWriter,\n) -> UResult<()> {\n out.flush()?;\n if !dired.dired_positions.is_empty() {\n print_positions(\"//DIRED//\", &dired.dired_positions);\n }\n if config.recursive {\n print_positions(\"//SUBDIRED//\", &dired.subdired_positions);\n }\n println!(\"//DIRED-OPTIONS// --quoting-style={}\", config.quoting_style);\n Ok(())\n}\n```"}], "func_name": "print_dired_output", "docstring": "Prints the dired output based on the given configuration and dired structure.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/dired.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/dired.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6c11ac72f04adf773e9663f24d3a88f6ed982d792859e0bedbc6e421e8afb7c6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_positions\n\nDocumentation:\nHelper function to print positions with a given prefix.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_positions(prefix: &str, positions: &Vec) {\n print!(\"{prefix}\");\n for c in positions {\n print!(\" {c}\");\n }\n println!();\n}\n```"}], "func_name": "print_positions", "docstring": "Helper function to print positions with a given prefix.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/dired.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/dired.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6908c7d1589478c93c801002dba4f83ac8499a77a022d6845a744b2edc0810a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: calculate_and_update_positions\n\nDocumentation:\nCalculates byte positions and updates the dired structure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn calculate_and_update_positions(\n dired: &mut DiredOutput,\n output_display_len: usize,\n dfn_len: usize,\n) {\n let offset = dired\n .dired_positions\n .last()\n .map_or(DIRED_TRAILING_OFFSET, |last_position| {\n last_position.start + DIRED_TRAILING_OFFSET\n });\n let start = output_display_len + offset + DIRED_TRAILING_OFFSET;\n let end = start + dfn_len;\n update_positions(dired, start, end);\n}\n```"}], "func_name": "calculate_and_update_positions", "docstring": "Calculates byte positions and updates the dired structure.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/dired.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/dired.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4bb529d5f692892cfdbe9bbf8252f2272091dd5dfc14c07b1e1405b01ac41a81"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_positions\n\nDocumentation:\nUpdates the dired positions based on the given start and end positions.\nupdate when it is the first element in the list (to manage \"total X\")\ninsert when it isn't the about total\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn update_positions(dired: &mut DiredOutput, start: usize, end: usize) {\n // padding can be 0 but as it doesn't matter\n dired.dired_positions.push(BytePosition {\n start: start + dired.padding,\n end: end + dired.padding,\n });\n // Remove the previous padding\n dired.padding = 0;\n}\n```"}], "func_name": "update_positions", "docstring": "Updates the dired positions based on the given start and end positions.\nupdate when it is the first element in the list (to manage \"total X\")\ninsert when it isn't the about total", "repo": "uutils/coreutils", "path": "src/uu/ls/src/dired.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/dired.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5aad31dc7ab4e42d559ea59c0792b3351deee9c759635013063ef3eed565c1f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_dired_arg_present\n\nDocumentation:\nChecks if the \"--dired\" or \"-D\" argument is present in the command line arguments.\nwe don't use clap here because we need to know if the argument is present\nas it can be overridden by --hyperlink\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_dired_arg_present() -> bool {\n std::env::args_os().any(|x| x == \"--dired\" || x == \"-D\")\n}\n```"}], "func_name": "is_dired_arg_present", "docstring": "Checks if the \"--dired\" or \"-D\" argument is present in the command line arguments.\nwe don't use clap here because we need to know if the argument is present\nas it can be overridden by --hyperlink", "repo": "uutils/coreutils", "path": "src/uu/ls/src/dired.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/dired.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d7ee095f3da76e5f2305f0c011ad7de9423ccb35ed476bc074d10fc8853a9677"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_recent\n\nDocumentation:\nWhether the given date is considered recent (i.e., in the last 6 months).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_recent(time: Timestamp, state: &mut ListState) -> bool {\n // According to GNU a Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952 seconds on the average.\n time > state.recent_time_threshold\n}\n```"}], "func_name": "is_recent", "docstring": "Whether the given date is considered recent (i.e., in the last 6 months).", "repo": "uutils/coreutils", "path": "src/uu/ls/src/ls.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/ls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6cf6fd5f5e1da202fc1635d60dc557727d82071ff9428620295b8412b65a821c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: format\n\nDocumentation:\nFormat the given time according to this time format style.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn format(\n &self,\n date: Zoned,\n out: &mut Vec,\n state: &mut ListState,\n ) -> Result<(), jiff::Error> {\n let recent = is_recent(date.timestamp(), state);\n let tm = BrokenDownTime::from(&date);\n let mut out = StdIoWrite(out);\n let config = jiff::fmt::strtime::Config::new().lenient(true);\n\n let fmt = match (self, recent) {\n (Self::FullIso, _) => \"%Y-%m-%d %H:%M:%S.%f %z\",\n (Self::LongIso, _) => \"%Y-%m-%d %H:%M\",\n (Self::Iso, true) => \"%m-%d %H:%M\",\n (Self::Iso, false) => \"%Y-%m-%d \",\n // TODO: Using correct locale string is not implemented.\n (Self::Locale, true) => \"%b %e %H:%M\",\n (Self::Locale, false) => \"%b %e %Y\",\n (Self::Format(fmt), _) => fmt,\n };\n\n tm.format_with_config(&config, fmt, &mut out)\n }\n```"}], "func_name": "format", "docstring": "Format the given time according to this time format style.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/ls.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/ls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dd38b1eb34f51f78fec5b0809773c382678eeb1c011ea80c30b2887a108b8103"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_format\n\nDocumentation:\nExtracts the format to display the information based on the options provided.\n\n# Returns\n\nA tuple containing the Format variant and an Option containing a &'static str\nwhich corresponds to the option used to define the format.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extract_format(options: &clap::ArgMatches) -> (Format, Option<&'static str>) {\n if let Some(format_) = options.get_one::(options::FORMAT) {\n (\n match format_.as_str() {\n \"long\" | \"verbose\" => Format::Long,\n \"single-column\" => Format::OneLine,\n \"columns\" | \"vertical\" => Format::Columns,\n \"across\" | \"horizontal\" => Format::Across,\n \"commas\" => Format::Commas,\n // below should never happen as clap already restricts the values.\n _ => unreachable!(\"Invalid field for --format\"),\n },\n Some(options::FORMAT),\n )\n } else if options.get_flag(options::format::LONG) {\n (Format::Long, Some(options::format::LONG))\n } else if options.get_flag(options::format::ACROSS) {\n (Format::Across, Some(options::format::ACROSS))\n } else if options.get_flag(options::format::COMMAS) {\n (Format::Commas, Some(options::format::COMMAS))\n } else if options.get_flag(options::format::COLUMNS) {\n (Format::Columns, Some(options::format::COLUMNS))\n } else if stdout().is_terminal() {\n (Format::Columns, None)\n } else {\n (Format::OneLine, None)\n }\n}\n```"}], "func_name": "extract_format", "docstring": "Extracts the format to display the information based on the options provided.\n\n# Returns\n\nA tuple containing the Format variant and an Option containing a &'static str\nwhich corresponds to the option used to define the format.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/ls.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/ls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2da7b43ea6a271484d0164f90faaa3598355f66c8ac71074b2b48542a71c557c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_files\n\nDocumentation:\nExtracts the type of files to display\n\n# Returns\n\nA Files variant representing the type of files to display.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extract_files(options: &clap::ArgMatches) -> Files {\n if options.get_flag(options::files::ALL) {\n Files::All\n } else if options.get_flag(options::files::ALMOST_ALL) {\n Files::AlmostAll\n } else {\n Files::Normal\n }\n}\n```"}], "func_name": "extract_files", "docstring": "Extracts the type of files to display\n\n# Returns\n\nA Files variant representing the type of files to display.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/ls.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/ls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b73f983b1bf50ab73207b52da1f8aa9d154510afde742f047fa98b7ba8234c88"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_sort\n\nDocumentation:\nExtracts the sorting method to use based on the options provided.\n\n# Returns\n\nA Sort variant representing the sorting method to use.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extract_sort(options: &clap::ArgMatches) -> Sort {\n if let Some(field) = options.get_one::(options::SORT) {\n match field.as_str() {\n \"none\" => Sort::None,\n \"name\" => Sort::Name,\n \"time\" => Sort::Time,\n \"size\" => Sort::Size,\n \"version\" => Sort::Version,\n \"extension\" => Sort::Extension,\n \"width\" => Sort::Width,\n // below should never happen as clap already restricts the values.\n _ => unreachable!(\"Invalid field for --sort\"),\n }\n } else if options.get_flag(options::sort::TIME) {\n Sort::Time\n } else if options.get_flag(options::sort::SIZE) {\n Sort::Size\n } else if options.get_flag(options::sort::NONE) {\n Sort::None\n } else if options.get_flag(options::sort::VERSION) {\n Sort::Version\n } else if options.get_flag(options::sort::EXTENSION) {\n Sort::Extension\n } else {\n Sort::Name\n }\n}\n```"}], "func_name": "extract_sort", "docstring": "Extracts the sorting method to use based on the options provided.\n\n# Returns\n\nA Sort variant representing the sorting method to use.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/ls.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/ls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e35c34b6543524a11eb9071955eec5e940c69fea60cb97db6572393129282b58"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_time\n\nDocumentation:\nExtracts the time to use based on the options provided.\n\n# Returns\n\nA Time variant representing the time to use.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extract_time(options: &clap::ArgMatches) -> Time {\n if let Some(field) = options.get_one::(options::TIME) {\n match field.as_str() {\n \"ctime\" | \"status\" => Time::Change,\n \"access\" | \"atime\" | \"use\" => Time::Access,\n \"mtime\" | \"modification\" => Time::Modification,\n \"birth\" | \"creation\" => Time::Birth,\n // below should never happen as clap already restricts the values.\n _ => unreachable!(\"Invalid field for --time\"),\n }\n } else if options.get_flag(options::time::ACCESS) {\n Time::Access\n } else if options.get_flag(options::time::CHANGE) {\n Time::Change\n } else {\n Time::Modification\n }\n}\n```"}], "func_name": "extract_time", "docstring": "Extracts the time to use based on the options provided.\n\n# Returns\n\nA Time variant representing the time to use.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/ls.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/ls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "07f0203604716ca5b6ee33febcc8d1de1d946c3ae2ed692e20dc40f57a14afa6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_color\n\nDocumentation:\nExtracts the color option to use based on the options provided.\n\n# Returns\n\nA boolean representing whether or not to use color.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extract_color(options: &clap::ArgMatches) -> bool {\n if !is_color_compatible_term() {\n return false;\n }\n\n match options.get_one::(options::COLOR) {\n None => options.contains_id(options::COLOR),\n Some(val) => match val.as_str() {\n \"\" | \"always\" | \"yes\" | \"force\" => true,\n \"auto\" | \"tty\" | \"if-tty\" => stdout().is_terminal(),\n /* \"never\" | \"no\" | \"none\" | */ _ => false,\n },\n }\n}\n```"}], "func_name": "extract_color", "docstring": "Extracts the color option to use based on the options provided.\n\n# Returns\n\nA boolean representing whether or not to use color.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/ls.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/ls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a2ca3161f441d4df2988561d966d0b517d198e99304d5b21126f919aec3e5e2b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_hyperlink\n\nDocumentation:\nExtracts the hyperlink option to use based on the options provided.\n\n# Returns\n\nA boolean representing whether to hyperlink files.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extract_hyperlink(options: &clap::ArgMatches) -> bool {\n let hyperlink = options\n .get_one::(options::HYPERLINK)\n .unwrap()\n .as_str();\n\n match hyperlink {\n \"always\" | \"yes\" | \"force\" => true,\n \"auto\" | \"tty\" | \"if-tty\" => stdout().is_terminal(),\n \"never\" | \"no\" | \"none\" => false,\n _ => unreachable!(\"should be handled by clap\"),\n }\n}\n```"}], "func_name": "extract_hyperlink", "docstring": "Extracts the hyperlink option to use based on the options provided.\n\n# Returns\n\nA boolean representing whether to hyperlink files.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/ls.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/ls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "87ea344fbbde63adcd19b00d1cdee7fa3b08eec3ad6ba86a865629c7c3c53b01"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: match_quoting_style_name\n\nDocumentation:\nMatch the argument given to --quoting-style or the QUOTING_STYLE env variable.\n\n# Arguments\n\n* `style`: the actual argument string\n* `show_control` - A boolean value representing whether or not to show control characters.\n\n# Returns\n\n* An option with None if the style string is invalid, or a `QuotingStyle` wrapped in `Some`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn match_quoting_style_name(style: &str, show_control: bool) -> Option {\n match style {\n \"literal\" => Some(QuotingStyle::Literal { show_control }),\n \"shell\" => Some(QuotingStyle::Shell {\n escape: false,\n always_quote: false,\n show_control,\n }),\n \"shell-always\" => Some(QuotingStyle::Shell {\n escape: false,\n always_quote: true,\n show_control,\n }),\n \"shell-escape\" => Some(QuotingStyle::Shell {\n escape: true,\n always_quote: false,\n show_control,\n }),\n \"shell-escape-always\" => Some(QuotingStyle::Shell {\n escape: true,\n always_quote: true,\n show_control,\n }),\n \"c\" => Some(QuotingStyle::C {\n quotes: quoting_style::Quotes::Double,\n }),\n \"escape\" => Some(QuotingStyle::C {\n quotes: quoting_style::Quotes::None,\n }),\n _ => None,\n }\n}\n```"}], "func_name": "match_quoting_style_name", "docstring": "Match the argument given to --quoting-style or the QUOTING_STYLE env variable.\n\n# Arguments\n\n* `style`: the actual argument string\n* `show_control` - A boolean value representing whether or not to show control characters.\n\n# Returns\n\n* An option with None if the style string is invalid, or a `QuotingStyle` wrapped in `Some`.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/ls.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/ls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f87d060c53b215d46fb3edc811c170cb55cdd51edbdf2436421b48e1cfe2a3a1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_quoting_style\n\nDocumentation:\nExtracts the quoting style to use based on the options provided.\nIf no options are given, it looks if a default quoting style is provided\nthrough the QUOTING_STYLE environment variable.\n\n# Arguments\n\n* `options` - A reference to a clap::ArgMatches object containing command line arguments.\n* `show_control` - A boolean value representing whether or not to show control characters.\n\n# Returns\n\nA QuotingStyle variant representing the quoting style to use.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extract_quoting_style(options: &clap::ArgMatches, show_control: bool) -> QuotingStyle {\n let opt_quoting_style = options.get_one::(options::QUOTING_STYLE);\n\n if let Some(style) = opt_quoting_style {\n match match_quoting_style_name(style, show_control) {\n Some(qs) => qs,\n None => unreachable!(\"Should have been caught by Clap\"),\n }\n } else if options.get_flag(options::quoting::LITERAL) {\n QuotingStyle::Literal { show_control }\n } else if options.get_flag(options::quoting::ESCAPE) {\n QuotingStyle::C {\n quotes: quoting_style::Quotes::None,\n }\n } else if options.get_flag(options::quoting::C) {\n QuotingStyle::C {\n quotes: quoting_style::Quotes::Double,\n }\n } else if options.get_flag(options::DIRED) {\n QuotingStyle::Literal { show_control }\n } else {\n // If set, the QUOTING_STYLE environment variable specifies a default style.\n if let Ok(style) = std::env::var(\"QUOTING_STYLE\") {\n match match_quoting_style_name(style.as_str(), show_control) {\n Some(qs) => return qs,\n None => eprintln!(\n \"{}: Ignoring invalid value of environment variable QUOTING_STYLE: '{style}'\",\n std::env::args().next().unwrap_or_else(|| \"ls\".to_string()),\n ),\n }\n }\n\n // By default, `ls` uses Shell escape quoting style when writing to a terminal file\n // descriptor and Literal otherwise.\n if stdout().is_terminal() {\n QuotingStyle::Shell {\n escape: true,\n always_quote: false,\n show_control,\n }\n } else {\n QuotingStyle::Literal { show_control }\n }\n }\n}\n```"}], "func_name": "extract_quoting_style", "docstring": "Extracts the quoting style to use based on the options provided.\nIf no options are given, it looks if a default quoting style is provided\nthrough the QUOTING_STYLE environment variable.\n\n# Arguments\n\n* `options` - A reference to a clap::ArgMatches object containing command line arguments.\n* `show_control` - A boolean value representing whether or not to show control characters.\n\n# Returns\n\nA QuotingStyle variant representing the quoting style to use.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/ls.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/ls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e4300d6f2dd1a5d917e4d4458edb60d799d77191504cdaed2bff454adc85dc74"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_indicator_style\n\nDocumentation:\nExtracts the indicator style to use based on the options provided.\n\n# Returns\n\nAn IndicatorStyle variant representing the indicator style to use.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extract_indicator_style(options: &clap::ArgMatches) -> IndicatorStyle {\n if let Some(field) = options.get_one::(options::INDICATOR_STYLE) {\n match field.as_str() {\n \"none\" => IndicatorStyle::None,\n \"file-type\" => IndicatorStyle::FileType,\n \"classify\" => IndicatorStyle::Classify,\n \"slash\" => IndicatorStyle::Slash,\n &_ => IndicatorStyle::None,\n }\n } else if let Some(field) = options.get_one::(options::indicator_style::CLASSIFY) {\n match field.as_str() {\n \"never\" | \"no\" | \"none\" => IndicatorStyle::None,\n \"always\" | \"yes\" | \"force\" => IndicatorStyle::Classify,\n \"auto\" | \"tty\" | \"if-tty\" => {\n if stdout().is_terminal() {\n IndicatorStyle::Classify\n } else {\n IndicatorStyle::None\n }\n }\n &_ => IndicatorStyle::None,\n }\n } else if options.get_flag(options::indicator_style::SLASH) {\n IndicatorStyle::Slash\n } else if options.get_flag(options::indicator_style::FILE_TYPE) {\n IndicatorStyle::FileType\n } else {\n IndicatorStyle::None\n }\n}\n```"}], "func_name": "extract_indicator_style", "docstring": "Extracts the indicator style to use based on the options provided.\n\n# Returns\n\nAn IndicatorStyle variant representing the indicator style to use.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/ls.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/ls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c02562eb48ae67a68e4c33e166b2d74176d654707827fd360e60220fe827c57e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_width\n\nDocumentation:\nParses the width value from either the command line arguments or the environment variables.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_width(width_match: Option<&String>) -> Result {\n let parse_width_from_args = |s: &str| -> Result {\n let radix = if s.starts_with('0') && s.len() > 1 {\n 8\n } else {\n 10\n };\n match u16::from_str_radix(s, radix) {\n Ok(x) => Ok(x),\n Err(e) => match e.kind() {\n IntErrorKind::PosOverflow => Ok(u16::MAX),\n _ => Err(LsError::InvalidLineWidth(s.into())),\n },\n }\n };\n\n let parse_width_from_env =\n |columns: OsString| match columns.to_str().and_then(|s| s.parse().ok()) {\n Some(columns) => columns,\n None => {\n show_error!(\n \"ignoring invalid width in environment variable COLUMNS: {}\",\n columns.quote()\n );\n DEFAULT_TERM_WIDTH\n }\n };\n\n let calculate_term_size = || match terminal_size::terminal_size() {\n Some((width, _)) => width.0,\n None => DEFAULT_TERM_WIDTH,\n };\n\n let ret = match width_match {\n Some(x) => parse_width_from_args(x)?,\n None => match std::env::var_os(\"COLUMNS\") {\n Some(columns) => parse_width_from_env(columns),\n None => calculate_term_size(),\n },\n };\n\n Ok(ret)\n}\n```"}], "func_name": "parse_width", "docstring": "Parses the width value from either the command line arguments or the environment variables.", "repo": "uutils/coreutils", "path": "src/uu/ls/src/ls.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/ls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "30794e27fd924e0d28b48560d2de3106a70b44f7a582045c49a8e6d784222840"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: show_dir_name\n\nDocumentation:\nShow the directory name in the case where several arguments are given to ls\nor the recursive flag is passed.\n\n```no-exec\n$ ls -R\n.: <- This is printed by this function\ndir1 file1 file2\n\ndir1: <- This as well\nfile11\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn show_dir_name(\n path_data: &PathData,\n out: &mut BufWriter,\n config: &Config,\n) -> std::io::Result<()> {\n let escaped_name =\n quoting_style::escape_dir_name(path_data.p_buf.as_os_str(), &config.quoting_style);\n\n let name = if config.hyperlink && !config.dired {\n create_hyperlink(&escaped_name, path_data)\n } else {\n escaped_name\n };\n\n write_os_str(out, &name)?;\n write!(out, \":\")\n}\n```"}], "func_name": "show_dir_name", "docstring": "Show the directory name in the case where several arguments are given to ls\nor the recursive flag is passed.\n\n```no-exec\n$ ls -R\n.: <- This is printed by this function\ndir1 file1 file2\n\ndir1: <- This as well\nfile11\n```", "repo": "uutils/coreutils", "path": "src/uu/ls/src/ls.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ls/src/ls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1af5c59aa60fbd263ad1449285e172926c9fcdb47d89d885c44f307e7c963cca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mkdir\n\nDocumentation:\nCreate directory at a given `path`.\n\n## Options\n\n* `recursive` --- create parent directories for the `path`, if they do not\nexist.\n* `mode` --- file mode for the directories (not implemented on windows).\n* `verbose` --- print a message for each printed directory.\n\n## Trailing dot\n\nTo match the GNU behavior, a path with the last directory being a single dot\n(like `some/path/to/.`) is created (with the dot stripped).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn mkdir(path: &Path, config: &Config) -> UResult<()> {\n if path.as_os_str().is_empty() {\n return Err(USimpleError::new(\n 1,\n get_message(\"mkdir-error-empty-directory-name\"),\n ));\n }\n // Special case to match GNU's behavior:\n // mkdir -p foo/. should work and just create foo/\n // std::fs::create_dir(\"foo/.\"); fails in pure Rust\n let path_buf = dir_strip_dot_for_creation(path);\n let path = path_buf.as_path();\n create_dir(path, false, config)\n}\n```"}], "func_name": "mkdir", "docstring": "Create directory at a given `path`.\n\n## Options\n\n* `recursive` --- create parent directories for the `path`, if they do not\nexist.\n* `mode` --- file mode for the directories (not implemented on windows).\n* `verbose` --- print a message for each printed directory.\n\n## Trailing dot\n\nTo match the GNU behavior, a path with the last directory being a single dot\n(like `some/path/to/.`) is created (with the dot stripped).", "repo": "uutils/coreutils", "path": "src/uu/mkdir/src/mkdir.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/mkdir/src/mkdir.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea2ab322b899b3f9d1ebdad7ab90ada17639a7585d56f39388220b078cf157c7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: find_last_contiguous_block_of_xs\n\nDocumentation:\nFind the start and end indices of the last contiguous block of Xs.\n\nIf no contiguous block of at least three Xs could be found, this\nfunction returns `None`.\n\n# Examples\n\n```rust,ignore\nassert_eq!(find_last_contiguous_block_of_xs(\"XXX_XXX\"), Some((4, 7)));\nassert_eq!(find_last_contiguous_block_of_xs(\"aXbXcX\"), None);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn find_last_contiguous_block_of_xs(s: &str) -> Option<(usize, usize)> {\n let j = s.rfind(\"XXX\")? + 3;\n let i = s[..j].rfind(|c| c != 'X').map_or(0, |i| i + 1);\n Some((i, j))\n}\n```"}], "func_name": "find_last_contiguous_block_of_xs", "docstring": "Find the start and end indices of the last contiguous block of Xs.\n\nIf no contiguous block of at least three Xs could be found, this\nfunction returns `None`.\n\n# Examples\n\n```rust,ignore\nassert_eq!(find_last_contiguous_block_of_xs(\"XXX_XXX\"), Some((4, 7)));\nassert_eq!(find_last_contiguous_block_of_xs(\"aXbXcX\"), None);\n```", "repo": "uutils/coreutils", "path": "src/uu/mktemp/src/mktemp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/mktemp/src/mktemp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3ed160a6c440829597f1206e8ecdf46a7c732e4173fe2cf9994b935b5b44a3b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_temp_dir\n\nDocumentation:\nCreate a temporary directory with the given parameters.\n\nThis function creates a temporary directory as a subdirectory of\n`dir`. The name of the directory is the concatenation of `prefix`,\na string of `rand` random characters, and `suffix`. The\npermissions of the directory are set to `u+rwx`\n\n# Errors\n\nIf the temporary directory could not be written to disk or if the\ngiven directory `dir` does not exist.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn make_temp_dir(dir: &Path, prefix: &str, rand: usize, suffix: &str) -> UResult {\n let mut builder = Builder::new();\n builder.prefix(prefix).rand_bytes(rand).suffix(suffix);\n\n // On *nix platforms grant read-write-execute for owner only.\n // The directory is created with these permission at creation time, using mkdir(3) syscall.\n // This is not relevant on Windows systems. See: https://docs.rs/tempfile/latest/tempfile/#security\n // `fs` is not imported on Windows anyways.\n #[cfg(not(windows))]\n builder.permissions(fs::Permissions::from_mode(0o700));\n\n match builder.tempdir_in(dir) {\n Ok(d) => {\n // `keep` consumes the TempDir without removing it\n let path = d.keep();\n Ok(path)\n }\n Err(e) if e.kind() == ErrorKind::NotFound => {\n let filename = format!(\"{prefix}{}{suffix}\", \"X\".repeat(rand));\n let path = Path::new(dir).join(filename);\n let s = path.display().to_string();\n Err(MkTempError::NotFound(get_message(\"mktemp-template-type-directory\"), s).into())\n }\n Err(e) => Err(e.into()),\n }\n}\n```"}], "func_name": "make_temp_dir", "docstring": "Create a temporary directory with the given parameters.\n\nThis function creates a temporary directory as a subdirectory of\n`dir`. The name of the directory is the concatenation of `prefix`,\na string of `rand` random characters, and `suffix`. The\npermissions of the directory are set to `u+rwx`\n\n# Errors\n\nIf the temporary directory could not be written to disk or if the\ngiven directory `dir` does not exist.", "repo": "uutils/coreutils", "path": "src/uu/mktemp/src/mktemp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/mktemp/src/mktemp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa97373b187f80963d8030ed97e5a1fe6df772a9e1802dc87676bde245030a2b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_temp_file\n\nDocumentation:\nCreate a temporary file with the given parameters.\n\nThis function creates a temporary file in the directory `dir`. The\nname of the file is the concatenation of `prefix`, a string of\n`rand` random characters, and `suffix`. The permissions of the\nfile are set to `u+rw`.\n\n# Errors\n\nIf the file could not be written to disk or if the directory does\nnot exist.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn make_temp_file(dir: &Path, prefix: &str, rand: usize, suffix: &str) -> UResult {\n let mut builder = Builder::new();\n builder.prefix(prefix).rand_bytes(rand).suffix(suffix);\n match builder.tempfile_in(dir) {\n // `keep` ensures that the file is not deleted\n Ok(named_tempfile) => match named_tempfile.keep() {\n Ok((_, pathbuf)) => Ok(pathbuf),\n Err(e) => Err(MkTempError::PersistError(e.file.path().to_path_buf()).into()),\n },\n Err(e) if e.kind() == ErrorKind::NotFound => {\n let filename = format!(\"{prefix}{}{suffix}\", \"X\".repeat(rand));\n let path = Path::new(dir).join(filename);\n let s = path.display().to_string();\n Err(MkTempError::NotFound(get_message(\"mktemp-template-type-file\"), s).into())\n }\n Err(e) => Err(e.into()),\n }\n}\n```"}], "func_name": "make_temp_file", "docstring": "Create a temporary file with the given parameters.\n\nThis function creates a temporary file in the directory `dir`. The\nname of the file is the concatenation of `prefix`, a string of\n`rand` random characters, and `suffix`. The permissions of the\nfile are set to `u+rw`.\n\n# Errors\n\nIf the file could not be written to disk or if the directory does\nnot exist.", "repo": "uutils/coreutils", "path": "src/uu/mktemp/src/mktemp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/mktemp/src/mktemp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2fe8b4adcb2b7f29653fbf43e9775448689520af06441fbe274a909b0336384e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mktemp\n\nDocumentation:\nCreate a temporary file or directory\n\nBehavior is determined by the `options` parameter, see [`Options`] for details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn mktemp(options: &Options) -> UResult {\n // Parse file path parameters from the command-line options.\n let Params {\n directory: tmpdir,\n prefix,\n num_rand_chars: rand,\n suffix,\n } = Params::from(options.clone())?;\n\n // Create the temporary file or directory, or simulate creating it.\n if options.dry_run {\n dry_exec(&tmpdir, &prefix, rand, &suffix)\n } else {\n exec(&tmpdir, &prefix, rand, &suffix, options.directory)\n }\n}\n```"}], "func_name": "mktemp", "docstring": "Create a temporary file or directory\n\nBehavior is determined by the `options` parameter, see [`Options`] for details.", "repo": "uutils/coreutils", "path": "src/uu/mktemp/src/mktemp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/mktemp/src/mktemp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f811d99f4dc8eb77689caf343b6263a55dcb5dce576056bbe1389a2d56f82ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_events\n\nDocumentation:\nProcess user input events until exit\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_events(&mut self, options: &Options) -> UResult<()> {\n loop {\n if !event::poll(Duration::from_millis(100))? {\n continue;\n }\n let mut wrong_key = None;\n match event::read()? {\n // --- Quit commands ---\n Event::Key(\n KeyEvent {\n code: KeyCode::Char('q'),\n modifiers: KeyModifiers::NONE,\n kind: KeyEventKind::Press,\n ..\n }\n | KeyEvent {\n code: KeyCode::Char('c'),\n modifiers: KeyModifiers::CONTROL,\n kind: KeyEventKind::Press,\n ..\n },\n ) => {\n reset_term()?;\n std::process::exit(0);\n }\n\n // --- Forward Navigation ---\n Event::Key(KeyEvent {\n code: KeyCode::Down | KeyCode::PageDown | KeyCode::Char(' '),\n modifiers: KeyModifiers::NONE,\n ..\n }) => {\n if self.eof_reached {\n return Ok(());\n }\n self.page_down();\n }\n Event::Key(KeyEvent {\n code: KeyCode::Enter | KeyCode::Char('j'),\n modifiers: KeyModifiers::NONE,\n ..\n }) => {\n if self.eof_reached {\n return Ok(());\n }\n self.next_line();\n }\n\n // --- Backward Navigation ---\n Event::Key(KeyEvent {\n code: KeyCode::Up | KeyCode::PageUp,\n modifiers: KeyModifiers::NONE,\n ..\n }) => {\n self.page_up();\n }\n Event::Key(KeyEvent {\n code: KeyCode::Char('k'),\n modifiers: KeyModifiers::NONE,\n ..\n }) => {\n self.prev_line();\n }\n\n // --- Terminal events ---\n Event::Resize(col, row) => {\n self.page_resize(col, row, options.lines);\n }\n\n // --- Skip key release events ---\n Event::Key(KeyEvent {\n kind: KeyEventKind::Release,\n ..\n }) => continue,\n\n // --- Handle unknown keys ---\n Event::Key(KeyEvent {\n code: KeyCode::Char(k),\n ..\n }) => wrong_key = Some(k),\n\n // --- Ignore other events ---\n _ => continue,\n }\n self.update_display(options)?;\n self.draw(wrong_key)?;\n }\n }\n```"}], "func_name": "process_events", "docstring": "Process user input events until exit", "repo": "uutils/coreutils", "path": "src/uu/more/src/more.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/more/src/more.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0666eeca6a720bf62ede8f0f8ac754c093c77e155e065ccc58ba6b33dda1220d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mv\n\nDocumentation:\nExecute the mv command. This moves 'source' to 'target', where\n'target' is a directory. If 'target' does not exist, and source is a single\nfile or directory, then 'source' will be renamed to 'target'.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn mv(files: &[OsString], opts: &Options) -> UResult<()> {\n let paths = parse_paths(files, opts);\n\n if let Some(ref name) = opts.target_dir {\n return move_files_into_dir(&paths, &PathBuf::from(name), opts);\n }\n\n match paths.len() {\n 2 => handle_two_paths(&paths[0], &paths[1], opts),\n _ => handle_multiple_paths(&paths, opts),\n }\n}\n```"}], "func_name": "mv", "docstring": "Execute the mv command. This moves 'source' to 'target', where\n'target' is a directory. If 'target' does not exist, and source is a single\nfile or directory, then 'source' will be renamed to 'target'.", "repo": "uutils/coreutils", "path": "src/uu/mv/src/mv.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/mv/src/mv.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dcd61c0870ce2b9610a3d57e7a1c3ee6fcb77e77fe3b316f3230b180722be75f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rename_with_fallback\n\nDocumentation:\nA wrapper around `fs::rename`, so that if it fails, we try falling back on\ncopying and removing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn rename_with_fallback(\n from: &Path,\n to: &Path,\n multi_progress: Option<&MultiProgress>,\n) -> io::Result<()> {\n fs::rename(from, to).or_else(|err| {\n #[cfg(windows)]\n const EXDEV: i32 = windows_sys::Win32::Foundation::ERROR_NOT_SAME_DEVICE as _;\n #[cfg(unix)]\n const EXDEV: i32 = libc::EXDEV as _;\n\n // We will only copy if:\n // 1. Files are on different devices (EXDEV error)\n // 2. On Windows, if the target file exists and source file is opened by another process\n // (MoveFileExW fails with \"Access Denied\" even if the source file has FILE_SHARE_DELETE permission)\n let should_fallback =\n matches!(err.raw_os_error(), Some(EXDEV)) || (from.is_file() && can_delete_file(from));\n if !should_fallback {\n return Err(err);\n }\n // Get metadata without following symlinks\n let metadata = from.symlink_metadata()?;\n let file_type = metadata.file_type();\n if file_type.is_symlink() {\n rename_symlink_fallback(from, to)\n } else if file_type.is_dir() {\n rename_dir_fallback(from, to, multi_progress)\n } else if is_fifo(file_type) {\n rename_fifo_fallback(from, to)\n } else {\n rename_file_fallback(from, to)\n }\n })\n}\n```"}], "func_name": "rename_with_fallback", "docstring": "A wrapper around `fs::rename`, so that if it fails, we try falling back on\ncopying and removing.", "repo": "uutils/coreutils", "path": "src/uu/mv/src/mv.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/mv/src/mv.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "07d77a056d0d5eeb83632cace4548c2dc260013d358db60aafc15a5d05d67958"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: standardize_nice_args\n\nDocumentation:\nTransform legacy arguments into a standardized form.\n\nThe following are all legal argument sequences to GNU nice:\n- \"-1\"\n- \"-n1\"\n- \"-+1\"\n- \"--1\"\n- \"-n -1\"\n\nIt looks initially like we could add handling for \"-{i}\", \"--{i}\"\nand \"-+{i}\" for integers {i} and process them normally using clap.\nHowever, the meaning of \"-1\", for example, changes depending on\nits context with legacy argument parsing. clap will not prioritize\nhyphenated values to previous arguments over matching a known\nargument. So \"-n\" \"-1\" in this case is picked up as two\narguments, not one argument with a value.\n\nGiven this context dependency, and the deep hole we end up digging\nwith clap in this case, it's much simpler to just normalize the\narguments to nice before clap starts work. Here, we insert a\nprefix of \"-n\" onto all arguments of the form \"-{i}\", \"--{i}\" and\n\"-+{i}\" which are not already preceded by \"-n\".\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn standardize_nice_args(mut args: impl uucore::Args) -> impl uucore::Args {\n let mut v = Vec::::new();\n let mut saw_n = false;\n let mut saw_command = false;\n if let Some(cmd) = args.next() {\n v.push(cmd);\n }\n for s in args {\n if saw_command {\n v.push(s);\n } else if saw_n {\n let mut new_arg: OsString = \"-n\".into();\n new_arg.push(s);\n v.push(new_arg);\n saw_n = false;\n } else if s.to_str() == Some(\"-n\")\n || s.to_str()\n .is_some_and(|s| is_prefix_of(s, \"--adjustment\", \"--a\".len()))\n {\n saw_n = true;\n } else if let Ok(s) = s.clone().into_string() {\n if let Some(stripped) = s.strip_prefix('-') {\n match stripped.parse::() {\n Ok(ix) => {\n let mut new_arg: OsString = \"-n\".into();\n new_arg.push(ix.to_string());\n v.push(new_arg);\n }\n Err(_) => {\n v.push(s.into());\n }\n }\n } else {\n saw_command = true;\n v.push(s.into());\n }\n } else {\n saw_command = true;\n v.push(s);\n }\n }\n if saw_n {\n v.push(\"-n\".into());\n }\n v.into_iter()\n}\n```"}], "func_name": "standardize_nice_args", "docstring": "Transform legacy arguments into a standardized form.\n\nThe following are all legal argument sequences to GNU nice:\n- \"-1\"\n- \"-n1\"\n- \"-+1\"\n- \"--1\"\n- \"-n -1\"\n\nIt looks initially like we could add handling for \"-{i}\", \"--{i}\"\nand \"-+{i}\" for integers {i} and process them normally using clap.\nHowever, the meaning of \"-1\", for example, changes depending on\nits context with legacy argument parsing. clap will not prioritize\nhyphenated values to previous arguments over matching a known\nargument. So \"-n\" \"-1\" in this case is picked up as two\narguments, not one argument with a value.\n\nGiven this context dependency, and the deep hole we end up digging\nwith clap in this case, it's much simpler to just normalize the\narguments to nice before clap starts work. Here, we insert a\nprefix of \"-n\" onto all arguments of the form \"-{i}\", \"--{i}\" and\n\"-+{i}\" which are not already preceded by \"-n\".", "repo": "uutils/coreutils", "path": "src/uu/nice/src/nice.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/nice/src/nice.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3541540fee40e8ff5aac9c34b7e8b3ad521e8a9299355bba2eb9640f1d1942dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next\n\nDocumentation:\nYield the next field in the input string as a tuple `(prefix, field)`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn next(&mut self) -> Option {\n let haystack = self.s?;\n\n let (prefix, field) = haystack.split_at(\n haystack\n .find(|c: char| !c.is_whitespace())\n .unwrap_or(haystack.len()),\n );\n\n let (field, rest) = field.split_at(field.find(char::is_whitespace).unwrap_or(field.len()));\n\n self.s = if rest.is_empty() { None } else { Some(rest) };\n\n Some((prefix, field))\n }\n```"}], "func_name": "next", "docstring": "Yield the next field in the input string as a tuple `(prefix, field)`.", "repo": "uutils/coreutils", "path": "src/uu/numfmt/src/format.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/numfmt/src/format.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "85cb287d24d7359597dbc2f7b66f09dd1822481e7502c5b7ef0eab3ed65c28a2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: div_round\n\nDocumentation:\nDivide numerator by denominator, with rounding.\n\nIf the result of the division is less than 10.0, round to one decimal point.\n\nOtherwise, round to an integer.\n\n# Examples:\n\n```\nuse uu_numfmt::format::div_round;\nuse uu_numfmt::options::RoundMethod;\n\n// Rounding methods:\nassert_eq!(div_round(1.01, 1.0, RoundMethod::FromZero), 1.1);\nassert_eq!(div_round(1.01, 1.0, RoundMethod::TowardsZero), 1.0);\nassert_eq!(div_round(1.01, 1.0, RoundMethod::Up), 1.1);\nassert_eq!(div_round(1.01, 1.0, RoundMethod::Down), 1.0);\nassert_eq!(div_round(1.01, 1.0, RoundMethod::Nearest), 1.0);\n\n// Division:\nassert_eq!(div_round(999.1, 1000.0, RoundMethod::FromZero), 1.0);\nassert_eq!(div_round(1001., 10., RoundMethod::FromZero), 101.);\nassert_eq!(div_round(9991., 10., RoundMethod::FromZero), 1000.);\nassert_eq!(div_round(-12.34, 1.0, RoundMethod::FromZero), -13.0);\nassert_eq!(div_round(1000.0, -3.14, RoundMethod::FromZero), -319.0);\nassert_eq!(div_round(-271828.0, -271.0, RoundMethod::FromZero), 1004.0);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn div_round(n: f64, d: f64, method: RoundMethod) -> f64 {\n let v = n / d;\n\n if v.abs() < 10.0 {\n method.round(10.0 * v) / 10.0\n } else {\n method.round(v)\n }\n}\n```"}], "func_name": "div_round", "docstring": "Divide numerator by denominator, with rounding.\n\nIf the result of the division is less than 10.0, round to one decimal point.\n\nOtherwise, round to an integer.\n\n# Examples:\n\n```\nuse uu_numfmt::format::div_round;\nuse uu_numfmt::options::RoundMethod;\n\n// Rounding methods:\nassert_eq!(div_round(1.01, 1.0, RoundMethod::FromZero), 1.1);\nassert_eq!(div_round(1.01, 1.0, RoundMethod::TowardsZero), 1.0);\nassert_eq!(div_round(1.01, 1.0, RoundMethod::Up), 1.1);\nassert_eq!(div_round(1.01, 1.0, RoundMethod::Down), 1.0);\nassert_eq!(div_round(1.01, 1.0, RoundMethod::Nearest), 1.0);\n\n// Division:\nassert_eq!(div_round(999.1, 1000.0, RoundMethod::FromZero), 1.0);\nassert_eq!(div_round(1001., 10., RoundMethod::FromZero), 101.);\nassert_eq!(div_round(9991., 10., RoundMethod::FromZero), 1000.);\nassert_eq!(div_round(-12.34, 1.0, RoundMethod::FromZero), -13.0);\nassert_eq!(div_round(1000.0, -3.14, RoundMethod::FromZero), -319.0);\nassert_eq!(div_round(-271828.0, -271.0, RoundMethod::FromZero), 1004.0);\n```", "repo": "uutils/coreutils", "path": "src/uu/numfmt/src/format.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/numfmt/src/format.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aace9670bf3dd110e109bfb30cf3e3199ed3cd7d1f6d55a07c260155883a7557"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: format_and_print\n\nDocumentation:\nFormat a line of text according to the selected options.\n\nGiven a line of text `s`, split the line into fields, transform and format\nany selected numeric fields, and print the result to stdout. Fields not\nselected for conversion are passed through unmodified.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn format_and_print(s: &str, options: &NumfmtOptions) -> Result<()> {\n match &options.delimiter {\n Some(_) => format_and_print_delimited(s, options),\n None => format_and_print_whitespace(s, options),\n }\n}\n```"}], "func_name": "format_and_print", "docstring": "Format a line of text according to the selected options.\n\nGiven a line of text `s`, split the line into fields, transform and format\nany selected numeric fields, and print the result to stdout. Fields not\nselected for conversion are passed through unmodified.", "repo": "uutils/coreutils", "path": "src/uu/numfmt/src/format.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/numfmt/src/format.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb19c84920e991da760fdc462a468b5f6c2927626d8cd06aac4fc07178935f5c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `InputDecoder` with an allocated buffer of `normal_length` + `peek_length` bytes.\n`byte_order` determines how to read multibyte formats from the buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n input: &mut I,\n normal_length: usize,\n peek_length: usize,\n byte_order: ByteOrder,\n ) -> InputDecoder {\n let bytes = vec![0; normal_length + peek_length];\n\n InputDecoder {\n input,\n data: bytes,\n reserved_peek_length: peek_length,\n used_normal_length: 0,\n used_peek_length: 0,\n byte_order,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `InputDecoder` with an allocated buffer of `normal_length` + `peek_length` bytes.\n`byte_order` determines how to read multibyte formats from the buffer.", "repo": "uutils/coreutils", "path": "src/uu/od/src/inputdecoder.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/inputdecoder.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea1f92f950004e19af743c68a7f5651dfa551ae265e26100f0b8723cdcbf8ce7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: peek_read\n\nDocumentation:\ncalls `peek_read` on the internal stream to (re)fill the buffer. Returns a\n`MemoryDecoder` providing access to the result or returns an i/o error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn peek_read(&mut self) -> io::Result {\n match self\n .input\n .peek_read(self.data.as_mut_slice(), self.reserved_peek_length)\n {\n Ok((n, p)) => {\n self.used_normal_length = n;\n self.used_peek_length = p;\n Ok(MemoryDecoder {\n data: &mut self.data,\n used_normal_length: self.used_normal_length,\n used_peek_length: self.used_peek_length,\n byte_order: self.byte_order,\n })\n }\n Err(e) => Err(e),\n }\n }\n```"}], "func_name": "peek_read", "docstring": "calls `peek_read` on the internal stream to (re)fill the buffer. Returns a\n`MemoryDecoder` providing access to the result or returns an i/o error.", "repo": "uutils/coreutils", "path": "src/uu/od/src/inputdecoder.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/inputdecoder.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "91b5a74b4ac3f0c4fbf38a96e8f3cb91be1b4fd2030744212ac6f500a3888df3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: zero_out_buffer\n\nDocumentation:\nSet a part of the internal buffer to zero.\naccess to the whole buffer is possible, not just to the valid data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn zero_out_buffer(&mut self, start: usize, end: usize) {\n for i in start..end {\n self.data[i] = 0;\n }\n }\n```"}], "func_name": "zero_out_buffer", "docstring": "Set a part of the internal buffer to zero.\naccess to the whole buffer is possible, not just to the valid data.", "repo": "uutils/coreutils", "path": "src/uu/od/src/inputdecoder.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/inputdecoder.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6136d54375dadd36559a09afc9f0584f004a395fc210623209fe17a234a36468"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clone_buffer\n\nDocumentation:\nCreates a clone of the internal buffer. The clone only contain the valid data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clone_buffer(&self, other: &mut Vec) {\n other.clone_from(self.data);\n other.resize(self.used_normal_length, 0);\n }\n```"}], "func_name": "clone_buffer", "docstring": "Creates a clone of the internal buffer. The clone only contain the valid data.", "repo": "uutils/coreutils", "path": "src/uu/od/src/inputdecoder.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/inputdecoder.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2895500540ea0542763afd70bc8f6c75f46ffaac28b9c08b6a66fd031db10f51"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_full_buffer\n\nDocumentation:\nReturns a slice to the internal buffer including the peek data starting at `start`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_full_buffer(&self, start: usize) -> &[u8] {\n &self.data[start..self.used_normal_length + self.used_peek_length]\n }\n```"}], "func_name": "get_full_buffer", "docstring": "Returns a slice to the internal buffer including the peek data starting at `start`.", "repo": "uutils/coreutils", "path": "src/uu/od/src/inputdecoder.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/inputdecoder.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3ae1dfbd9a9c371e004c0806870c2b9621872cfa201cb61de213bc247dc2f5ea"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_uint\n\nDocumentation:\nReturns a u8/u16/u32/u64 from the internal buffer at position `start`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_uint(&self, start: usize, byte_size: usize) -> u64 {\n match byte_size {\n 1 => u64::from(self.data[start]),\n 2 => u64::from(self.byte_order.read_u16(&self.data[start..start + 2])),\n 4 => u64::from(self.byte_order.read_u32(&self.data[start..start + 4])),\n 8 => self.byte_order.read_u64(&self.data[start..start + 8]),\n _ => panic!(\"Invalid byte_size: {byte_size}\"),\n }\n }\n```"}], "func_name": "read_uint", "docstring": "Returns a u8/u16/u32/u64 from the internal buffer at position `start`.", "repo": "uutils/coreutils", "path": "src/uu/od/src/inputdecoder.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/inputdecoder.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b9a0a1682ecf9faef96d2e8c4d111aafb8aa365793f2ba1ffa2afe9bf5106ddf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_float\n\nDocumentation:\nReturns a f32/f64 from the internal buffer at position `start`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_float(&self, start: usize, byte_size: usize) -> f64 {\n match byte_size {\n 2 => f64::from(f16::from_bits(\n self.byte_order.read_u16(&self.data[start..start + 2]),\n )),\n 4 => f64::from(self.byte_order.read_f32(&self.data[start..start + 4])),\n 8 => self.byte_order.read_f64(&self.data[start..start + 8]),\n _ => panic!(\"Invalid byte_size: {byte_size}\"),\n }\n }\n```"}], "func_name": "read_float", "docstring": "Returns a f32/f64 from the internal buffer at position `start`.", "repo": "uutils/coreutils", "path": "src/uu/od/src/inputdecoder.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/inputdecoder.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "631b8bbe0276a3d6986c1b45666235e50684511633a3126c4576a26f9436425f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\ncreates a new `InputOffset` using the provided values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(radix: Radix, byte_pos: u64, label: Option) -> Self {\n Self {\n radix,\n byte_pos,\n label,\n }\n }\n```"}], "func_name": "new", "docstring": "creates a new `InputOffset` using the provided values.", "repo": "uutils/coreutils", "path": "src/uu/od/src/inputoffset.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/inputoffset.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7674065b10ad1b8ffb7b6331d57c80f348a4afb96d5d3b1dae617cf59d8440fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: increase_position\n\nDocumentation:\nIncrease `byte_pos` and `label` if a label is used.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn increase_position(&mut self, n: u64) {\n self.byte_pos += n;\n if let Some(l) = self.label {\n self.label = Some(l + n);\n }\n }\n```"}], "func_name": "increase_position", "docstring": "Increase `byte_pos` and `label` if a label is used.", "repo": "uutils/coreutils", "path": "src/uu/od/src/inputoffset.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/inputoffset.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "65179bf951ad8d61ea76355a0571f52b06bd9de22471956df02080b257ed6370"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: format_byte_offset\n\nDocumentation:\nreturns a string with the current byte offset\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn format_byte_offset(&self) -> String {\n match (self.radix, self.label) {\n (Radix::Decimal, None) => format!(\"{:07}\", self.byte_pos),\n (Radix::Decimal, Some(l)) => format!(\"{:07} ({l:07})\", self.byte_pos),\n (Radix::Hexadecimal, None) => format!(\"{:06X}\", self.byte_pos),\n (Radix::Hexadecimal, Some(l)) => format!(\"{:06X} ({l:06X})\", self.byte_pos),\n (Radix::Octal, None) => format!(\"{:07o}\", self.byte_pos),\n (Radix::Octal, Some(l)) => format!(\"{:07o} ({l:07o})\", self.byte_pos),\n (Radix::NoPrefix, None) => String::new(),\n (Radix::NoPrefix, Some(l)) => format!(\"({l:07o})\"),\n }\n }\n```"}], "func_name": "format_byte_offset", "docstring": "returns a string with the current byte offset", "repo": "uutils/coreutils", "path": "src/uu/od/src/inputoffset.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/inputoffset.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a8c9433ecd3c1344c077a641832a0e5c88b7d3d4c043859f77646e672a3daf3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_final_offset\n\nDocumentation:\nPrints the byte offset followed by a newline, or nothing at all if\nboth `Radix::NoPrefix` was set and no label (--traditional) is used.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn print_final_offset(&self) {\n if self.radix != Radix::NoPrefix || self.label.is_some() {\n println!(\"{}\", self.format_byte_offset());\n }\n }\n```"}], "func_name": "print_final_offset", "docstring": "Prints the byte offset followed by a newline, or nothing at all if\nboth `Radix::NoPrefix` was set and no label (--traditional) is used.", "repo": "uutils/coreutils", "path": "src/uu/od/src/inputoffset.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/inputoffset.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f048eb89630819b2b208051f739a25868418c93daad404d333e8234fade8c2e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a FailingMockStream\n\nWhen `read` or `write` is called, it will return an error `repeat_count` times.\n`kind` and `message` can be specified to define the exact error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> Self {\n Self {\n kind,\n message,\n repeat_count,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a FailingMockStream\n\nWhen `read` or `write` is called, it will return an error `repeat_count` times.\n`kind` and `message` can be specified to define the exact error.", "repo": "uutils/coreutils", "path": "src/uu/od/src/mockstream.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/mockstream.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0aa03c88755e505581f2bdc6ce9bc25abe176cb870681b05204864a31e3037f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `OutputInfo` based on the parameters\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n line_bytes: usize,\n formats: &[ParsedFormatterItemInfo],\n output_duplicates: bool,\n ) -> Self {\n let byte_size_block = formats.iter().fold(1, |max, next| {\n cmp::max(max, next.formatter_item_info.byte_size)\n });\n let print_width_block = formats.iter().fold(1, |max, next| {\n cmp::max(\n max,\n next.formatter_item_info.print_width\n * (byte_size_block / next.formatter_item_info.byte_size),\n )\n });\n let print_width_line = print_width_block * (line_bytes / byte_size_block);\n\n let spaced_formatters =\n Self::create_spaced_formatter_info(formats, byte_size_block, print_width_block);\n\n Self {\n byte_size_line: line_bytes,\n print_width_line,\n byte_size_block,\n spaced_formatters,\n output_duplicates,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `OutputInfo` based on the parameters", "repo": "uutils/coreutils", "path": "src/uu/od/src/output_info.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/output_info.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8770990a891c57be6d443a646b2aa42bc17e1b2f179d0bfa2182f37992c80fbf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: calculate_alignment\n\nDocumentation:\ncalculates proper alignment for a single line of output\n\nMultiple representations of the same data, will be right-aligned for easy reading.\nFor example a 64 bit octal and a 32-bit decimal with a 16-bit hexadecimal looks like this:\n```ignore\n1777777777777777777777 1777777777777777777777\n4294967295 4294967295 4294967295 4294967295\nffff ffff ffff ffff ffff ffff ffff ffff\n```\nIn this example is additional spacing before the first and third decimal number,\nand there is additional spacing before the 1st, 3rd, 5th and 7th hexadecimal number.\nThis way both the octal and decimal, as well as the decimal and hexadecimal numbers\nleft align. Note that the alignment below both octal numbers is identical.\n\nThis function calculates the required spacing for a single line, given the size\nof a block, and the width of a block. The size of a block is the largest type\nand the width is width of the the type which needs the most space to print that\nnumber of bytes. So both numbers might refer to different types. All widths\ninclude a space at the front. For example the width of a 8-bit hexadecimal,\nis 3 characters, for example \" FF\".\n\nThis algorithm first calculates how many spaces needs to be added, based the\nblock size and the size of the type, and the widths of the block and the type.\nThe required spaces are spread across the available positions.\nIf the blocksize is 8, and the size of the type is 8 too, there will be just\none value in a block, so all spacing will be assigned to position 0.\nIf the blocksize is 8, and the size of the type is 2, the spacing will be\nspread across position 0, 2, 4, 6. All 4 positions will get an additional\nspace as long as there are more then 4 spaces available. If there are 2\nspaces available, they will be assigned to position 0 and 4. If there is\n1 space available, it will be assigned to position 0. This will be combined,\nFor example 7 spaces will be assigned to position 0, 2, 4, 6 like: 3, 1, 2, 1.\nAnd 7 spaces with 2 positions will be assigned to position 0 and 4 like 4, 3.\n\nHere is another example showing the alignment of 64-bit unsigned decimal numbers,\n32-bit hexadecimal number, 16-bit octal numbers and 8-bit hexadecimal numbers:\n```ignore\n18446744073709551615 18446744073709551615\nffffffff ffffffff ffffffff ffffffff\n177777 177777 177777 177777 177777 177777 177777 177777\nff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff\n```\n\nThis algorithm assumes the size of all types is a power of 2 (1, 2, 4, 8, 16, ...)\nIncrease `MAX_BYTES_PER_UNIT` to allow larger types.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn calculate_alignment(\n sf: &dyn TypeSizeInfo,\n byte_size_block: usize,\n print_width_block: usize,\n ) -> [usize; MAX_BYTES_PER_UNIT] {\n assert!(\n byte_size_block <= MAX_BYTES_PER_UNIT,\n \"{}-bits types are unsupported. Current max={}-bits.\",\n 8 * byte_size_block,\n 8 * MAX_BYTES_PER_UNIT\n );\n let mut spacing = [0; MAX_BYTES_PER_UNIT];\n\n let mut byte_size = sf.byte_size();\n let mut items_in_block = byte_size_block / byte_size;\n let thisblock_width = sf.print_width() * items_in_block;\n let mut missing_spacing = print_width_block - thisblock_width;\n\n while items_in_block > 0 {\n let avg_spacing: usize = missing_spacing / items_in_block;\n for i in 0..items_in_block {\n spacing[i * byte_size] += avg_spacing;\n missing_spacing -= avg_spacing;\n }\n\n items_in_block /= 2;\n byte_size *= 2;\n }\n\n spacing\n }\n```"}], "func_name": "calculate_alignment", "docstring": "calculates proper alignment for a single line of output\n\nMultiple representations of the same data, will be right-aligned for easy reading.\nFor example a 64 bit octal and a 32-bit decimal with a 16-bit hexadecimal looks like this:\n```ignore\n1777777777777777777777 1777777777777777777777\n4294967295 4294967295 4294967295 4294967295\nffff ffff ffff ffff ffff ffff ffff ffff\n```\nIn this example is additional spacing before the first and third decimal number,\nand there is additional spacing before the 1st, 3rd, 5th and 7th hexadecimal number.\nThis way both the octal and decimal, as well as the decimal and hexadecimal numbers\nleft align. Note that the alignment below both octal numbers is identical.\n\nThis function calculates the required spacing for a single line, given the size\nof a block, and the width of a block. The size of a block is the largest type\nand the width is width of the the type which needs the most space to print that\nnumber of bytes. So both numbers might refer to different types. All widths\ninclude a space at the front. For example the width of a 8-bit hexadecimal,\nis 3 characters, for example \" FF\".\n\nThis algorithm first calculates how many spaces needs to be added, based the\nblock size and the size of the type, and the widths of the block and the type.\nThe required spaces are spread across the available positions.\nIf the blocksize is 8, and the size of the type is 8 too, there will be just\none value in a block, so all spacing will be assigned to position 0.\nIf the blocksize is 8, and the size of the type is 2, the spacing will be\nspread across position 0, 2, 4, 6. All 4 positions will get an additional\nspace as long as there are more then 4 spaces available. If there are 2\nspaces available, they will be assigned to position 0 and 4. If there is\n1 space available, it will be assigned to position 0. This will be combined,\nFor example 7 spaces will be assigned to position 0, 2, 4, 6 like: 3, 1, 2, 1.\nAnd 7 spaces with 2 positions will be assigned to position 0 and 4 like 4, 3.\n\nHere is another example showing the alignment of 64-bit unsigned decimal numbers,\n32-bit hexadecimal number, 16-bit octal numbers and 8-bit hexadecimal numbers:\n```ignore\n18446744073709551615 18446744073709551615\nffffffff ffffffff ffffffff ffffffff\n177777 177777 177777 177777 177777 177777 177777 177777\nff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff\n```\n\nThis algorithm assumes the size of all types is a power of 2 (1, 2, 4, 8, 16, ...)\nIncrease `MAX_BYTES_PER_UNIT` to allow larger types.", "repo": "uutils/coreutils", "path": "src/uu/od/src/output_info.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/output_info.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "695d4c4f95f32c08ac9db858fd16c88abc3cfd323482458dcccf88a9ab15b907"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_inputs\n\nDocumentation:\nInterprets the command line inputs of od.\n\nReturns either an unspecified number of filenames.\nOr it will return a single filename, with an offset and optional label.\nOffset and label are specified in bytes.\n'-' is used as filename if stdin is meant. This is also returned if\nthere is no input, as stdin is the default input.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_inputs(matches: &dyn CommandLineOpts) -> Result {\n let mut input_strings = matches.inputs();\n\n if matches.opts_present(&[\"traditional\"]) {\n return parse_inputs_traditional(&input_strings);\n }\n\n // test if command line contains: [file] \n // fall-through if no (valid) offset is found\n if input_strings.len() == 1 || input_strings.len() == 2 {\n // if any of the options -A, -j, -N, -t, -v or -w are present there is no offset\n if !matches.opts_present(&[\n options::ADDRESS_RADIX,\n options::READ_BYTES,\n options::SKIP_BYTES,\n options::FORMAT,\n options::OUTPUT_DUPLICATES,\n options::WIDTH,\n ]) {\n // test if the last input can be parsed as an offset.\n let offset = parse_offset_operand(input_strings[input_strings.len() - 1]);\n if let Ok(n) = offset {\n // if there is just 1 input (stdin), an offset must start with '+'\n if input_strings.len() == 1 && input_strings[0].starts_with('+') {\n return Ok(CommandLineInputs::FileAndOffset((\"-\".to_string(), n, None)));\n }\n if input_strings.len() == 2 {\n return Ok(CommandLineInputs::FileAndOffset((\n input_strings[0].to_string(),\n n,\n None,\n )));\n }\n }\n }\n }\n\n if input_strings.is_empty() {\n input_strings.push(\"-\");\n }\n Ok(CommandLineInputs::FileNames(\n input_strings.iter().map(|&s| s.to_string()).collect(),\n ))\n}\n```"}], "func_name": "parse_inputs", "docstring": "Interprets the command line inputs of od.\n\nReturns either an unspecified number of filenames.\nOr it will return a single filename, with an offset and optional label.\nOffset and label are specified in bytes.\n'-' is used as filename if stdin is meant. This is also returned if\nthere is no input, as stdin is the default input.", "repo": "uutils/coreutils", "path": "src/uu/od/src/parse_inputs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/parse_inputs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a8c02bb3464a01721ff996b7413cf97cf8f61657470084f95486b3c6e40b8f2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_inputs_traditional\n\nDocumentation:\ninterprets inputs when --traditional is on the command line\n\nnormally returns `CommandLineInputs::FileAndOffset`, but if no offset is found,\nit returns `CommandLineInputs::FileNames` (also to differentiate from the offset == 0)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_inputs_traditional(input_strings: &[&str]) -> Result {\n match input_strings.len() {\n 0 => Ok(CommandLineInputs::FileNames(vec![\"-\".to_string()])),\n 1 => {\n let offset0 = parse_offset_operand(input_strings[0]);\n Ok(match offset0 {\n Ok(n) => CommandLineInputs::FileAndOffset((\"-\".to_string(), n, None)),\n _ => CommandLineInputs::FileNames(\n input_strings.iter().map(|&s| s.to_string()).collect(),\n ),\n })\n }\n 2 => {\n let offset0 = parse_offset_operand(input_strings[0]);\n let offset1 = parse_offset_operand(input_strings[1]);\n match (offset0, offset1) {\n (Ok(n), Ok(m)) => Ok(CommandLineInputs::FileAndOffset((\n \"-\".to_string(),\n n,\n Some(m),\n ))),\n (_, Ok(m)) => Ok(CommandLineInputs::FileAndOffset((\n input_strings[0].to_string(),\n m,\n None,\n ))),\n _ => Err(format!(\"invalid offset: {}\", input_strings[1])),\n }\n }\n 3 => {\n let offset = parse_offset_operand(input_strings[1]);\n let label = parse_offset_operand(input_strings[2]);\n match (offset, label) {\n (Ok(n), Ok(m)) => Ok(CommandLineInputs::FileAndOffset((\n input_strings[0].to_string(),\n n,\n Some(m),\n ))),\n (Err(_), _) => Err(format!(\"invalid offset: {}\", input_strings[1])),\n (_, Err(_)) => Err(format!(\"invalid label: {}\", input_strings[2])),\n }\n }\n _ => Err(format!(\n \"too many inputs after --traditional: {}\",\n input_strings[3]\n )),\n }\n}\n```"}], "func_name": "parse_inputs_traditional", "docstring": "interprets inputs when --traditional is on the command line\n\nnormally returns `CommandLineInputs::FileAndOffset`, but if no offset is found,\nit returns `CommandLineInputs::FileNames` (also to differentiate from the offset == 0)", "repo": "uutils/coreutils", "path": "src/uu/od/src/parse_inputs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/parse_inputs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "760b12f8e6c215a9192e7158b15af916d2ff27f0b65b888853ea9b21925bb329"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_offset_operand\n\nDocumentation:\nparses format used by offset and label on the command line\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_offset_operand(s: &str) -> Result {\n let mut start = 0;\n let mut len = s.len();\n let mut radix = 8;\n let mut multiply = 1;\n\n if s.starts_with('+') {\n start += 1;\n }\n\n if s[start..len].starts_with(\"0x\") || s[start..len].starts_with(\"0X\") {\n start += 2;\n radix = 16;\n } else {\n if s[start..len].ends_with('b') {\n len -= 1;\n multiply = 512;\n }\n if s[start..len].ends_with('.') {\n len -= 1;\n radix = 10;\n }\n }\n match u64::from_str_radix(&s[start..len], radix) {\n Ok(i) => Ok(i * multiply),\n Err(_) => Err(\"parse failed\"),\n }\n}\n```"}], "func_name": "parse_offset_operand", "docstring": "parses format used by offset and label on the command line", "repo": "uutils/coreutils", "path": "src/uu/od/src/parse_inputs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/parse_inputs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "806f0142c4aa5d23026bdf83ff69d1a4617e4975b3342bcadeb52741a18157f2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: peek_read\n\nDocumentation:\nReads data into a buffer.\n\nSee `PeekRead::peek_read`.\n\n# Panics\nIf `peek_size` is larger then the size of `out`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn peek_read(&mut self, out: &mut [u8], peek_size: usize) -> io::Result<(usize, usize)> {\n assert!(out.len() >= peek_size);\n match self.read(out) {\n Err(e) => Err(e),\n Ok(bytes_in_buffer) => {\n let unused = out.len() - bytes_in_buffer;\n if peek_size <= unused {\n Ok((bytes_in_buffer, 0))\n } else {\n let actual_peek_size = peek_size - unused;\n let real_size = bytes_in_buffer - actual_peek_size;\n self.write_to_tempbuffer(&out[real_size..bytes_in_buffer]);\n Ok((real_size, actual_peek_size))\n }\n }\n }\n }\n```"}], "func_name": "peek_read", "docstring": "Reads data into a buffer.\n\nSee `PeekRead::peek_read`.\n\n# Panics\nIf `peek_size` is larger then the size of `out`", "repo": "uutils/coreutils", "path": "src/uu/od/src/peekreader.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/peekreader.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5b32ac24466eb336e91347dd23319e188c7574e587cc55fba49b5a039fa14a7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sign_extend\n\nDocumentation:\nExtends a signed number in `item` of `item_bytes` bytes into a (signed) i64\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn sign_extend(item: u64, item_bytes: usize) -> i64 {\n let shift = 64 - item_bytes * 8;\n (item << shift) as i64 >> shift\n}\n```"}], "func_name": "sign_extend", "docstring": "Extends a signed number in `item` of `item_bytes` bytes into a (signed) i64", "repo": "uutils/coreutils", "path": "src/uu/od/src/prn_int.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/od/src/prn_int.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6d09a0f9a64be9524a483e6d9986cd369e73f6c83ebb391001a7bcba634582f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: recreate_arguments\n\nDocumentation:\nReturns re-written arguments which are passed to the program.\nRemoves -column and +page option as getopts cannot parse things like -3 etc\n# Arguments\n* `args` - Command line arguments\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn recreate_arguments(args: &[String]) -> Vec {\n let column_page_option = Regex::new(r\"^[-+]\\d+.*\").unwrap();\n let num_regex = Regex::new(r\"^[^-]\\d*$\").unwrap();\n let n_regex = Regex::new(r\"^-n\\s*$\").unwrap();\n let mut arguments = args.to_owned();\n let num_option = args.iter().find_position(|x| n_regex.is_match(x.trim()));\n if let Some((pos, _value)) = num_option {\n if let Some(num_val_opt) = args.get(pos + 1) {\n if !num_regex.is_match(num_val_opt) {\n let could_be_file = arguments.remove(pos + 1);\n arguments.insert(pos + 1, format!(\"{}\", NumberingMode::default().width));\n arguments.insert(pos + 2, could_be_file);\n }\n }\n }\n\n arguments\n .into_iter()\n .filter(|i| !column_page_option.is_match(i))\n .collect()\n}\n```"}], "func_name": "recreate_arguments", "docstring": "Returns re-written arguments which are passed to the program.\nRemoves -column and +page option as getopts cannot parse things like -3 etc\n# Arguments\n* `args` - Command line arguments", "repo": "uutils/coreutils", "path": "src/uu/pr/src/pr.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/pr/src/pr.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ff38072fe6a9fda1096e6b1f0790983e98d102f4ca13da488d7413bdfdb8a53f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: header_content\n\nDocumentation:\nReturns a five line header content if displaying header is not disabled by\nusing `NO_HEADER_TRAILER_OPTION` option.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn header_content(options: &OutputOptions, page: usize) -> Vec {\n if options.display_header_and_trailer {\n let first_line = format!(\n \"{} {} Page {page}\",\n options.last_modified_time, options.header\n );\n vec![\n String::new(),\n String::new(),\n first_line,\n String::new(),\n String::new(),\n ]\n } else {\n Vec::new()\n }\n}\n```"}], "func_name": "header_content", "docstring": "Returns a five line header content if displaying header is not disabled by\nusing `NO_HEADER_TRAILER_OPTION` option.", "repo": "uutils/coreutils", "path": "src/uu/pr/src/pr.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/pr/src/pr.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b22fe8b4a3101d8b2fc21d928dce029f5be19243917500c2b73745e49b95ab26"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: trailer_content\n\nDocumentation:\nReturns five empty lines as trailer content if displaying trailer\nis not disabled by using `NO_HEADER_TRAILER_OPTION`option.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn trailer_content(options: &OutputOptions) -> Vec {\n if options.display_header_and_trailer && !options.form_feed_used {\n vec![\n String::new(),\n String::new(),\n String::new(),\n String::new(),\n String::new(),\n ]\n } else {\n Vec::new()\n }\n}\n```"}], "func_name": "trailer_content", "docstring": "Returns five empty lines as trailer content if displaying trailer\nis not disabled by using `NO_HEADER_TRAILER_OPTION`option.", "repo": "uutils/coreutils", "path": "src/uu/pr/src/pr.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/pr/src/pr.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bcefe4a6869cb5dd81081f4ee9d8ee9c9387bff604555ac6da9784c0fce4195e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_start_line_number\n\nDocumentation:\nReturns starting line number for the file to be printed.\nIf -N is specified the first line number changes otherwise\ndefault is 1.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_start_line_number(opts: &OutputOptions) -> usize {\n opts.number.as_ref().map(|i| i.first_number).unwrap_or(1)\n}\n```"}], "func_name": "get_start_line_number", "docstring": "Returns starting line number for the file to be printed.\nIf -N is specified the first line number changes otherwise\ndefault is 1.", "repo": "uutils/coreutils", "path": "src/uu/pr/src/pr.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/pr/src/pr.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9e990e22a4777b80e9ac6ea277ab1233ee0bf94fc03cfbb8ed6bb6231293622b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lines_to_read_for_page\n\nDocumentation:\nReturns number of lines to read from input for constructing one page of pr output.\nIf double space -d is used lines are halved.\nIf columns --columns is used the lines are multiplied by the value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn lines_to_read_for_page(opts: &OutputOptions) -> usize {\n let content_lines_per_page = opts.content_lines_per_page;\n let columns = get_columns(opts);\n if opts.double_space {\n (content_lines_per_page / 2) * columns\n } else {\n content_lines_per_page * columns\n }\n}\n```"}], "func_name": "lines_to_read_for_page", "docstring": "Returns number of lines to read from input for constructing one page of pr output.\nIf double space -d is used lines are halved.\nIf columns --columns is used the lines are multiplied by the value.", "repo": "uutils/coreutils", "path": "src/uu/pr/src/pr.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/pr/src/pr.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "01e419a529e76a3da6a3f7350f216d2d222f26e57ce4747012757abccfc2564b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_columns\n\nDocumentation:\nReturns number of columns to output\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_columns(opts: &OutputOptions) -> usize {\n opts.column_mode_options\n .as_ref()\n .map(|i| i.columns)\n .unwrap_or(1)\n}\n```"}], "func_name": "get_columns", "docstring": "Returns number of columns to output", "repo": "uutils/coreutils", "path": "src/uu/pr/src/pr.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/pr/src/pr.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "37a703ef6e7942fc549614791f50732e25a63f551aad2218bc11bea8e0b05738"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_char_filter_file\n\nDocumentation:\nreads contents of file as unique set of characters to be used with the break-file option\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_char_filter_file(\n matches: &clap::ArgMatches,\n option: &str,\n) -> std::io::Result> {\n let filename = matches\n .get_one::(option)\n .expect(\"parsing options failed!\");\n let mut reader: Box = if filename == \"-\" {\n Box::new(stdin())\n } else {\n let file = File::open(filename)?;\n Box::new(file)\n };\n let mut buffer = String::new();\n reader.read_to_string(&mut buffer)?;\n Ok(buffer.chars().collect())\n}\n```"}], "func_name": "read_char_filter_file", "docstring": "reads contents of file as unique set of characters to be used with the break-file option", "repo": "uutils/coreutils", "path": "src/uu/ptx/src/ptx.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ptx/src/ptx.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a522b53368e7e74c2538e2f02a10bbf3a4c912e3512b8f784a01d02e56590f28"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_word_set\n\nDocumentation:\nGo through every lines in the input files and record each match occurrence as a `WordRef`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn create_word_set(config: &Config, filter: &WordFilter, file_map: &FileMap) -> BTreeSet {\n let reg = Regex::new(&filter.word_regex).unwrap();\n let ref_reg = Regex::new(&config.context_regex).unwrap();\n let mut word_set: BTreeSet = BTreeSet::new();\n for (file, lines) in file_map {\n let mut count: usize = 0;\n let offs = lines.offset;\n for line in &lines.lines {\n // if -r, exclude reference from word set\n let (ref_beg, ref_end) = match ref_reg.find(line) {\n Some(x) => (x.start(), x.end()),\n None => (0, 0),\n };\n // match words with given regex\n for mat in reg.find_iter(line) {\n let (beg, end) = (mat.start(), mat.end());\n if config.input_ref && ((beg, end) == (ref_beg, ref_end)) {\n continue;\n }\n let mut word = line[beg..end].to_owned();\n if filter.only_specified && !filter.only_set.contains(&word) {\n continue;\n }\n if filter.ignore_specified && filter.ignore_set.contains(&word) {\n continue;\n }\n if config.ignore_case {\n word = word.to_uppercase();\n }\n word_set.insert(WordRef {\n word,\n filename: file.clone(),\n global_line_nr: offs + count,\n local_line_nr: count,\n position: beg,\n position_end: end,\n });\n }\n count += 1;\n }\n }\n word_set\n}\n```"}], "func_name": "create_word_set", "docstring": "Go through every lines in the input files and record each match occurrence as a `WordRef`.", "repo": "uutils/coreutils", "path": "src/uu/ptx/src/ptx.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ptx/src/ptx.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2900f5100bcba126ee6ee5b483687fa15f1b1ae92c17197444f8079e415330f1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prepare_line_chunks\n\nDocumentation:\nExtract and prepare text chunks for formatting in both TeX and roff output\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn prepare_line_chunks(\n config: &Config,\n word_ref: &WordRef,\n line: &str,\n chars_line: &[char],\n reference: &str,\n) -> (String, String, String, String, String) {\n // Convert byte positions to character positions\n let ref_char_position = line[..word_ref.position].chars().count();\n let char_position_end = ref_char_position\n + line[word_ref.position..word_ref.position_end]\n .chars()\n .count();\n\n // Extract the text before the keyword\n let all_before = if config.input_ref {\n let before = &line[..word_ref.position];\n let before_char_count = before.chars().count();\n let trimmed_char_count = before\n .trim_start_matches(reference)\n .trim_start()\n .chars()\n .count();\n let trim_offset = before_char_count - trimmed_char_count;\n &chars_line[trim_offset..before_char_count]\n } else {\n &chars_line[..ref_char_position]\n };\n\n // Extract the keyword and text after it\n let keyword = line[word_ref.position..word_ref.position_end].to_string();\n let all_after = &chars_line[char_position_end..];\n\n // Get formatted output chunks\n let (tail, before, after, head) = get_output_chunks(all_before, &keyword, all_after, config);\n\n (tail, before, keyword, after, head)\n}\n```"}], "func_name": "prepare_line_chunks", "docstring": "Extract and prepare text chunks for formatting in both TeX and roff output", "repo": "uutils/coreutils", "path": "src/uu/ptx/src/ptx.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/ptx/src/ptx.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a261dc2db68d3c6e6e890f5dc05dfc605d4499736f9f42bc7a7731daca5f71ae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prepare_relative_options\n\nDocumentation:\nPrepare `--relative-to` and `--relative-base` options.\nConvert them to their absolute values.\nCheck if `--relative-to` is a descendant of `--relative-base`,\notherwise nullify their value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn prepare_relative_options(\n matches: &ArgMatches,\n can_mode: MissingHandling,\n resolve_mode: ResolveMode,\n) -> UResult<(Option, Option)> {\n let relative_to = matches\n .get_one::(OPT_RELATIVE_TO)\n .map(PathBuf::from);\n let relative_base = matches\n .get_one::(OPT_RELATIVE_BASE)\n .map(PathBuf::from);\n let relative_to = canonicalize_relative_option(relative_to, can_mode, resolve_mode)?;\n let relative_base = canonicalize_relative_option(relative_base, can_mode, resolve_mode)?;\n if let (Some(base), Some(to)) = (relative_base.as_deref(), relative_to.as_deref()) {\n if !to.starts_with(base) {\n return Ok((None, None));\n }\n }\n Ok((relative_to, relative_base))\n}\n```"}], "func_name": "prepare_relative_options", "docstring": "Prepare `--relative-to` and `--relative-base` options.\nConvert them to their absolute values.\nCheck if `--relative-to` is a descendant of `--relative-base`,\notherwise nullify their value.", "repo": "uutils/coreutils", "path": "src/uu/realpath/src/realpath.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/realpath/src/realpath.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "427096dfaebfd1d4c0d70e6a0ec45ba55cf5b879eeb332c4d30899704e0cfc45"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: canonicalize_relative\n\nDocumentation:\nMake `relative-to` or `relative-base` path values absolute.\n\n# Errors\n\nIf the given path is not a directory the function returns an error.\nIf some parts of the file don't exist, or symlinks make loops, or\nsome other IO error happens, the function returns error, too.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn canonicalize_relative(\n r: &Path,\n can_mode: MissingHandling,\n resolve: ResolveMode,\n) -> std::io::Result {\n let abs = canonicalize(r, can_mode, resolve)?;\n if can_mode == MissingHandling::Existing && !abs.is_dir() {\n abs.read_dir()?; // raise not a directory error\n }\n Ok(abs)\n}\n```"}], "func_name": "canonicalize_relative", "docstring": "Make `relative-to` or `relative-base` path values absolute.\n\n# Errors\n\nIf the given path is not a directory the function returns an error.\nIf some parts of the file don't exist, or symlinks make loops, or\nsome other IO error happens, the function returns error, too.", "repo": "uutils/coreutils", "path": "src/uu/realpath/src/realpath.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/realpath/src/realpath.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "13c317ac58099a423d5a14c23eca0bcbadd44ff6e59ba9f36808762d2ffb1b03"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve_path\n\nDocumentation:\nResolve a path to an absolute form and print it.\n\nIf `relative_to` and/or `relative_base` is given\nthe path is printed in a relative form to one of this options.\nSee the details in `process_relative` function.\nIf `zero` is `true`, then this function\nprints the path followed by the null byte (`'\\0'`) instead of a\nnewline character (`'\\n'`).\n\n# Errors\n\nThis function returns an error if there is a problem resolving\nsymbolic links.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn resolve_path(\n p: &Path,\n line_ending: LineEnding,\n resolve: ResolveMode,\n can_mode: MissingHandling,\n relative_to: Option<&Path>,\n relative_base: Option<&Path>,\n) -> std::io::Result<()> {\n let abs = canonicalize(p, can_mode, resolve)?;\n\n let abs = process_relative(abs, relative_base, relative_to);\n\n print_verbatim(abs)?;\n stdout().write_all(&[line_ending.into()])?;\n Ok(())\n}\n```"}], "func_name": "resolve_path", "docstring": "Resolve a path to an absolute form and print it.\n\nIf `relative_to` and/or `relative_base` is given\nthe path is printed in a relative form to one of this options.\nSee the details in `process_relative` function.\nIf `zero` is `true`, then this function\nprints the path followed by the null byte (`'\\0'`) instead of a\nnewline character (`'\\n'`).\n\n# Errors\n\nThis function returns an error if there is a problem resolving\nsymbolic links.", "repo": "uutils/coreutils", "path": "src/uu/realpath/src/realpath.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/realpath/src/realpath.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c98609b7394e225a6b53efdd2a021562b5a62b7df9bf3a43070c5ebcc83fde2a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_relative\n\nDocumentation:\nConditionally converts an absolute path to a relative form,\naccording to the rules:\n1. if only `relative_to` is given, the result is relative to `relative_to`\n2. if only `relative_base` is given, it checks whether given `path` is a descendant\nof `relative_base`, on success the result is relative to `relative_base`, otherwise\nthe result is the given `path`\n3. if both `relative_to` and `relative_base` are given, the result is relative to `relative_to`\nif `path` is a descendant of `relative_base`, otherwise the result is `path`\n\nFor more information see\n\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_relative(\n path: PathBuf,\n relative_base: Option<&Path>,\n relative_to: Option<&Path>,\n) -> PathBuf {\n if let Some(base) = relative_base {\n if path.starts_with(base) {\n make_path_relative_to(path, relative_to.unwrap_or(base))\n } else {\n path\n }\n } else if let Some(to) = relative_to {\n make_path_relative_to(path, to)\n } else {\n path\n }\n}\n```"}], "func_name": "process_relative", "docstring": "Conditionally converts an absolute path to a relative form,\naccording to the rules:\n1. if only `relative_to` is given, the result is relative to `relative_to`\n2. if only `relative_base` is given, it checks whether given `path` is a descendant\nof `relative_base`, on success the result is relative to `relative_base`, otherwise\nthe result is the given `path`\n3. if both `relative_to` and `relative_base` are given, the result is relative to `relative_to`\nif `path` is a descendant of `relative_base`, otherwise the result is `path`\n\nFor more information see\n", "repo": "uutils/coreutils", "path": "src/uu/realpath/src/realpath.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/realpath/src/realpath.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "abf56e27cb808a669078b6e3e87b06e1612e35bae6ba7a5b6bcbf076d647fb02"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove\n\nDocumentation:\nRemove (or unlink) the given files\n\nReturns true if it has encountered an error.\n\nBehavior is determined by the `options` parameter, see [`Options`] for\ndetails.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn remove(files: &[&OsStr], options: &Options) -> bool {\n let mut had_err = false;\n\n for filename in files {\n let file = Path::new(filename);\n\n had_err = match file.symlink_metadata() {\n Ok(metadata) => {\n if metadata.is_dir() {\n handle_dir(file, options)\n } else if is_symlink_dir(&metadata) {\n remove_dir(file, options)\n } else {\n remove_file(file, options)\n }\n }\n\n Err(_e) => {\n // TODO: actually print out the specific error\n // TODO: When the error is not about missing files\n // (e.g., permission), even rm -f should fail with\n // outputting the error, but there's no easy way.\n if options.force {\n false\n } else {\n show_error!(\n \"cannot remove {}: No such file or directory\",\n filename.quote()\n );\n true\n }\n }\n }\n .bitor(had_err);\n }\n\n had_err\n}\n```"}], "func_name": "remove", "docstring": "Remove (or unlink) the given files\n\nReturns true if it has encountered an error.\n\nBehavior is determined by the `options` parameter, see [`Options`] for\ndetails.", "repo": "uutils/coreutils", "path": "src/uu/rm/src/rm.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/rm/src/rm.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9f61ede29b181d6e6c2dea449f4047f8f8373180d1a31b4ae5255c6e079d9fc7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_dir_empty\n\nDocumentation:\nWhether the given directory is empty.\n\n`path` must be a directory. If there is an error reading the\ncontents of the directory, this returns `false`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_dir_empty(path: &Path) -> bool {\n match fs::read_dir(path) {\n Err(_) => false,\n Ok(iter) => iter.count() == 0,\n }\n}\n```"}], "func_name": "is_dir_empty", "docstring": "Whether the given directory is empty.\n\n`path` must be a directory. If there is an error reading the\ncontents of the directory, this returns `false`.", "repo": "uutils/coreutils", "path": "src/uu/rm/src/rm.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/rm/src/rm.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51c7988c5616951770d64fcaf6acd63a01148b0b7753b37457bc54dbbb94f84b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_dir_recursive\n\nDocumentation:\nRecursively remove the directory tree rooted at the given path.\n\nIf `path` is a file or a symbolic link, just remove it. If it is a\ndirectory, remove all of its entries recursively and then remove the\ndirectory itself. In case of an error, print the error message to\n`stderr` and return `true`. If there were no errors, return `false`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn remove_dir_recursive(path: &Path, options: &Options) -> bool {\n // Special case: if we cannot access the metadata because the\n // filename is too long, fall back to try\n // `fs::remove_dir_all()`.\n //\n // TODO This is a temporary bandage; we shouldn't need to do this\n // at all. Instead of using the full path like \"x/y/z\", which\n // causes a `InvalidFilename` error when trying to access the file\n // metadata, we should be able to use just the last part of the\n // path, \"z\", and know that it is relative to the parent, \"x/y\".\n if let Some(s) = path.to_str() {\n if s.len() > 1000 {\n match fs::remove_dir_all(path) {\n Ok(_) => return false,\n Err(e) => {\n let e = e.map_err_context(|| format!(\"cannot remove {}\", path.quote()));\n show_error!(\"{e}\");\n return true;\n }\n }\n }\n }\n\n // Base case 1: this is a file or a symbolic link.\n //\n // The symbolic link case is important because it could be a link to\n // a directory and we don't want to recurse. In particular, this\n // avoids an infinite recursion in the case of a link to the current\n // directory, like `ln -s . link`.\n if !path.is_dir() || path.is_symlink() {\n return remove_file(path, options);\n }\n\n // Base case 2: this is a non-empty directory, but the user\n // doesn't want to descend into it.\n if options.interactive == InteractiveMode::Always\n && !is_dir_empty(path)\n && !prompt_descend(path)\n {\n return false;\n }\n\n // Recursive case: this is a directory.\n let mut error = false;\n match fs::read_dir(path) {\n Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {\n // This is not considered an error.\n }\n Err(_) => error = true,\n Ok(iter) => {\n for entry in iter {\n match entry {\n Err(_) => error = true,\n Ok(entry) => {\n let child_error = remove_dir_recursive(&entry.path(), options);\n error = error || child_error;\n }\n }\n }\n }\n }\n\n // Ask the user whether to remove the current directory.\n if options.interactive == InteractiveMode::Always && !prompt_dir(path, options) {\n return false;\n }\n\n // Try removing the directory itself.\n match fs::remove_dir(path) {\n Err(_) if !error && !is_readable(path) => {\n // For compatibility with GNU test case\n // `tests/rm/unread2.sh`, show \"Permission denied\" in this\n // case instead of \"Directory not empty\".\n show_error!(\"cannot remove {}: Permission denied\", path.quote());\n error = true;\n }\n Err(e) if !error => {\n let e = e.map_err_context(|| format!(\"cannot remove {}\", path.quote()));\n show_error!(\"{e}\");\n error = true;\n }\n Err(_) => {\n // If there has already been at least one error when\n // trying to remove the children, then there is no need to\n // show another error message as we return from each level\n // of the recursion.\n }\n Ok(_) if options.verbose => println!(\"removed directory {}\", normalize(path).quote()),\n Ok(_) => {}\n }\n\n error\n}\n```"}], "func_name": "remove_dir_recursive", "docstring": "Recursively remove the directory tree rooted at the given path.\n\nIf `path` is a file or a symbolic link, just remove it. If it is a\ndirectory, remove all of its entries recursively and then remove the\ndirectory itself. In case of an error, print the error message to\n`stderr` and return `true`. If there were no errors, return `false`.", "repo": "uutils/coreutils", "path": "src/uu/rm/src/rm.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/rm/src/rm.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e6a8d81e3f400030bb8a852e8b98e231c2ca937813d32c99e866acff5c6b7f9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_dir\n\nDocumentation:\nRemove the given directory, asking the user for permission if necessary.\n\nReturns true if it has encountered an error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn remove_dir(path: &Path, options: &Options) -> bool {\n // Ask the user for permission.\n if !prompt_dir(path, options) {\n return false;\n }\n\n // Called to remove a symlink_dir (windows) without \"-r\"/\"-R\" or \"-d\".\n if !options.dir && !options.recursive {\n show_error!(\"cannot remove {}: Is a directory\", path.quote());\n return true;\n }\n\n // Try to remove the directory.\n match fs::remove_dir(path) {\n Ok(_) => {\n if options.verbose {\n println!(\"removed directory {}\", normalize(path).quote());\n }\n false\n }\n Err(e) => {\n let e = e.map_err_context(|| format!(\"cannot remove {}\", path.quote()));\n show_error!(\"{e}\");\n true\n }\n }\n}\n```"}], "func_name": "remove_dir", "docstring": "Remove the given directory, asking the user for permission if necessary.\n\nReturns true if it has encountered an error.", "repo": "uutils/coreutils", "path": "src/uu/rm/src/rm.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/rm/src/rm.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf4a735691b72f51af940629972d45c5468ca702bdd5b9be6c04d66955290770"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: path_is_current_or_parent_directory\n\nDocumentation:\nChecks if the path is referring to current or parent directory , if it is referring to current or any parent directory in the file tree e.g '/../..' , '../..'\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn path_is_current_or_parent_directory(path: &Path) -> bool {\n let path_str = os_str_as_bytes(path.as_os_str());\n let dir_separator = MAIN_SEPARATOR as u8;\n if let Ok(path_bytes) = path_str {\n return path_bytes == ([b'.'])\n || path_bytes == ([b'.', b'.'])\n || path_bytes.ends_with(&[dir_separator, b'.'])\n || path_bytes.ends_with(&[dir_separator, b'.', b'.'])\n || path_bytes.ends_with(&[dir_separator, b'.', dir_separator])\n || path_bytes.ends_with(&[dir_separator, b'.', b'.', dir_separator]);\n }\n false\n}\n```"}], "func_name": "path_is_current_or_parent_directory", "docstring": "Checks if the path is referring to current or parent directory , if it is referring to current or any parent directory in the file tree e.g '/../..' , '../..'", "repo": "uutils/coreutils", "path": "src/uu/rm/src/rm.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/rm/src/rm.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bcd50f2c4c22dd9a0c91bca066307a50fa7d0d809be970984bc1650137e8e056"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clean_trailing_slashes\n\nDocumentation:\nRemoves trailing slashes, for example 'd/../////' yield 'd/../' required to fix rm-r4 GNU test\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn clean_trailing_slashes(path: &Path) -> &Path {\n let path_str = os_str_as_bytes(path.as_os_str());\n let dir_separator = MAIN_SEPARATOR as u8;\n\n if let Ok(path_bytes) = path_str {\n let mut idx = if path_bytes.len() > 1 {\n path_bytes.len() - 1\n } else {\n return path;\n };\n // Checks if element at the end is a '/'\n if path_bytes[idx] == dir_separator {\n for i in (1..path_bytes.len()).rev() {\n // Will break at the start of the continuous sequence of '/', eg: \"abc//////\" , will break at\n // \"abc/\", this will clean ////// to the root '/', so we have to be careful to not\n // delete the root.\n if path_bytes[i - 1] != dir_separator {\n idx = i;\n break;\n }\n }\n #[cfg(unix)]\n return Path::new(OsStr::from_bytes(&path_bytes[0..=idx]));\n\n #[cfg(not(unix))]\n // Unwrapping is fine here as os_str_as_bytes() would return an error on non unix\n // systems with non utf-8 characters and thus bypass the if let Ok branch\n return Path::new(std::str::from_utf8(&path_bytes[0..=idx]).unwrap());\n }\n }\n path\n}\n```"}], "func_name": "clean_trailing_slashes", "docstring": "Removes trailing slashes, for example 'd/../////' yield 'd/../' required to fix rm-r4 GNU test", "repo": "uutils/coreutils", "path": "src/uu/rm/src/rm.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/rm/src/rm.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6d7b76ede23afb374123d2f3179cae0bcc5e13baade5fd62d1bd55916c64e1bc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: execute_command\n\nDocumentation:\nThe actual return type of this function should be `UResult`.\nHowever, until the *never* type is stabilized, one way to indicate to the\ncompiler the only valid return type is to say \"if this returns, it will\nalways return an error\".\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn execute_command(command: &OsStr, arguments: &[OsString]) -> UResult<()> {\n let c_command = os_str_to_c_string(command).map_err(RunconError::new)?;\n\n let argv_storage: Vec = arguments\n .iter()\n .map(AsRef::as_ref)\n .map(os_str_to_c_string)\n .collect::>()\n .map_err(RunconError::new)?;\n\n let mut argv: Vec<*const c_char> = Vec::with_capacity(arguments.len().saturating_add(2));\n argv.push(c_command.as_ptr());\n argv.extend(argv_storage.iter().map(AsRef::as_ref).map(CStr::as_ptr));\n argv.push(ptr::null());\n\n unsafe { libc::execvp(c_command.as_ptr(), argv.as_ptr()) };\n\n let err = io::Error::last_os_error();\n let exit_status = if err.kind() == io::ErrorKind::NotFound {\n error_exit_status::NOT_FOUND\n } else {\n error_exit_status::COULD_NOT_EXECUTE\n };\n\n let err = Error::from_io1(\"runcon-operation-executing-command\", command, err);\n Err(RunconError::with_code(exit_status, err).into())\n}\n```"}], "func_name": "execute_command", "docstring": "The actual return type of this function should be `UResult`.\nHowever, until the *never* type is stabilized, one way to indicate to the\ncompiler the only valid return type is to say \"if this returns, it will\nalways return an error\".", "repo": "uutils/coreutils", "path": "src/uu/runcon/src/runcon.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/runcon/src/runcon.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ccfd1eb4dc7473b9b37ebe262ff7fc182defae556ff017fa6ba1bd9c385c6227"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_zero\n\nDocumentation:\nDecide whether this number is zero (either positive or negative).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_zero(&self) -> bool {\n // We would like to implement `num_traits::Zero`, but it\n // requires an addition implementation, and we don't want to\n // implement that here.\n self.number.is_zero()\n }\n```"}], "func_name": "is_zero", "docstring": "Decide whether this number is zero (either positive or negative).", "repo": "uutils/coreutils", "path": "src/uu/seq/src/number.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/seq/src/number.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a416ea7465c42678f087ff53e8c0783086c59c49254024d26833a1b6c8c0ba24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: num_fractional_digits\n\nDocumentation:\nConvenience function for getting the number of fractional digits.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn num_fractional_digits(s: &str) -> usize {\n s.parse::()\n .unwrap()\n .num_fractional_digits\n .unwrap()\n }\n```"}], "func_name": "num_fractional_digits", "docstring": "Convenience function for getting the number of fractional digits.", "repo": "uutils/coreutils", "path": "src/uu/seq/src/numberparse.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/seq/src/numberparse.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2c41c7b94cb647f7f69fde771b33ec230451f5bbc00c81dfe47f0c4ff0495175"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: num_fractional_digits_is_none\n\nDocumentation:\nConvenience function for making sure the number of fractional digits is \"None\"\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn num_fractional_digits_is_none(s: &str) -> bool {\n s.parse::()\n .unwrap()\n .num_fractional_digits\n .is_none()\n }\n```"}], "func_name": "num_fractional_digits_is_none", "docstring": "Convenience function for making sure the number of fractional digits is \"None\"", "repo": "uutils/coreutils", "path": "src/uu/seq/src/numberparse.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/seq/src/numberparse.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e2448bc8affe6f27a96db9b2780012c05616b1c5b0c89d4687af43c083e2ab57"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fast_print_seq\n\nDocumentation:\nInteger print, default format, positive increment: fast code path\nthat avoids reformating digit at all iterations.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fast_print_seq(\n mut stdout: impl Write,\n first: &BigUint,\n increment: u64,\n last: &BigUint,\n separator: &str,\n terminator: &str,\n padding: usize,\n) -> std::io::Result<()> {\n // Nothing to do, just return.\n if last < first {\n return Ok(());\n }\n\n // Do at most u64::MAX loops. We can print in the order of 1e8 digits per second,\n // u64::MAX is 1e19, so it'd take hundreds of years for this to complete anyway.\n // TODO: we can move this test to `print_seq` if we care about this case.\n let loop_cnt = ((last - first) / increment).to_u64().unwrap_or(u64::MAX);\n\n // Format the first number.\n let first_str = first.to_string();\n\n // Makeshift log10.ceil\n let last_length = last.to_string().len();\n\n // Allocate a large u8 buffer, that contains a preformatted string\n // of the number followed by the `separator`.\n //\n // | ... head space ... | number | separator |\n // ^0 ^ start ^ num_end ^ size (==buf.len())\n //\n // We keep track of start in this buffer, as the number grows.\n // When printing, we take a slice between start and end.\n let size = last_length.max(padding) + separator.len();\n // Fill with '0', this is needed for equal_width, and harmless otherwise.\n let mut buf = vec![b'0'; size];\n let buf = buf.as_mut_slice();\n\n let num_end = buf.len() - separator.len();\n let mut start = num_end - first_str.len();\n\n // Initialize buf with first and separator.\n buf[start..num_end].copy_from_slice(first_str.as_bytes());\n buf[num_end..].copy_from_slice(separator.as_bytes());\n\n // Normally, if padding is > 0, it should be equal to last_length,\n // so start would be == 0, but there are corner cases.\n start = start.min(num_end - padding);\n\n // Prepare the number to increment with as a string\n let inc_str = increment.to_string();\n let inc_str = inc_str.as_bytes();\n\n for _ in 0..loop_cnt {\n stdout.write_all(&buf[start..])?;\n fast_inc(buf, &mut start, num_end, inc_str);\n }\n // Write the last number without separator, but with terminator.\n stdout.write_all(&buf[start..num_end])?;\n write!(stdout, \"{terminator}\")?;\n stdout.flush()?;\n Ok(())\n}\n```"}], "func_name": "fast_print_seq", "docstring": "Integer print, default format, positive increment: fast code path\nthat avoids reformating digit at all iterations.", "repo": "uutils/coreutils", "path": "src/uu/seq/src/seq.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/seq/src/seq.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa197d84da8091d9b132e6cf8cc90e8ffba6e42f69dafe9e93a36fee63b05e06"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_seq\n\nDocumentation:\nArbitrary precision decimal number code path (\"slow\" path)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_seq(\n range: RangeFloat,\n separator: &str,\n terminator: &str,\n format: &Format,\n fast_allowed: bool,\n padding: usize, // Used by fast path only\n) -> std::io::Result<()> {\n let stdout = stdout().lock();\n let mut stdout = BufWriter::new(stdout);\n let (first, increment, last) = range;\n\n if fast_allowed {\n // Test if we can use fast code path.\n // First try to convert the range to BigUint (u64 for the increment).\n let (first_bui, increment_u64, last_bui) = (\n first.to_biguint(),\n increment.to_biguint().and_then(|x| x.to_u64()),\n last.to_biguint(),\n );\n if let (Some(first_bui), Some(increment_u64), Some(last_bui)) =\n (first_bui, increment_u64, last_bui)\n {\n return fast_print_seq(\n stdout,\n &first_bui,\n increment_u64,\n &last_bui,\n separator,\n terminator,\n padding,\n );\n }\n }\n\n let mut value = first;\n\n let mut is_first_iteration = true;\n while !done_printing(&value, &increment, &last) {\n if !is_first_iteration {\n stdout.write_all(separator.as_bytes())?;\n }\n format.fmt(&mut stdout, &value)?;\n // TODO Implement augmenting addition.\n value = value + increment.clone();\n is_first_iteration = false;\n }\n if !is_first_iteration {\n stdout.write_all(terminator.as_bytes())?;\n }\n stdout.flush()?;\n Ok(())\n}\n```"}], "func_name": "print_seq", "docstring": "Arbitrary precision decimal number code path (\"slow\" path)", "repo": "uutils/coreutils", "path": "src/uu/seq/src/seq.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/seq/src/seq.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63411aa342afc2ebb317941ce1ef72aa33984b3cfcc2c8c1a0c93a133a6d2184"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check\n\nDocumentation:\nCheck if the file at `path` is ordered.\n\n# Returns\n\nThe code we should exit with.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> {\n let max_allowed_cmp = if settings.unique {\n // If `unique` is enabled, the previous line must compare _less_ to the next one.\n Ordering::Less\n } else {\n // Otherwise, the line previous line must compare _less or equal_ to the next one.\n Ordering::Equal\n };\n let file = open(path)?;\n let (recycled_sender, recycled_receiver) = sync_channel(2);\n let (loaded_sender, loaded_receiver) = sync_channel(2);\n thread::spawn({\n let settings = settings.clone();\n move || reader(file, &recycled_receiver, &loaded_sender, &settings)\n });\n for _ in 0..2 {\n let _ = recycled_sender.send(RecycledChunk::new(if settings.buffer_size < 100 * 1024 {\n // when the buffer size is smaller than 100KiB we choose it instead of the default.\n // this improves testability.\n settings.buffer_size\n } else {\n 100 * 1024\n }));\n }\n\n let mut prev_chunk: Option = None;\n let mut line_idx = 0;\n for chunk in loaded_receiver {\n line_idx += 1;\n if let Some(prev_chunk) = prev_chunk.take() {\n // Check if the first element of the new chunk is greater than the last\n // element from the previous chunk\n let prev_last = prev_chunk.lines().last().unwrap();\n let new_first = chunk.lines().first().unwrap();\n\n if compare_by(\n prev_last,\n new_first,\n settings,\n prev_chunk.line_data(),\n chunk.line_data(),\n ) > max_allowed_cmp\n {\n return Err(SortError::Disorder {\n file: path.to_owned(),\n line_number: line_idx,\n line: new_first.line.to_owned(),\n silent: settings.check_silent,\n }\n .into());\n }\n let _ = recycled_sender.send(prev_chunk.recycle());\n }\n\n for (a, b) in chunk.lines().iter().tuple_windows() {\n line_idx += 1;\n if compare_by(a, b, settings, chunk.line_data(), chunk.line_data()) > max_allowed_cmp {\n return Err(SortError::Disorder {\n file: path.to_owned(),\n line_number: line_idx,\n line: b.line.to_owned(),\n silent: settings.check_silent,\n }\n .into());\n }\n }\n\n prev_chunk = Some(chunk);\n }\n Ok(())\n}\n```"}], "func_name": "check", "docstring": "Check if the file at `path` is ordered.\n\n# Returns\n\nThe code we should exit with.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/check.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/check.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51639879280a2c875db7b124e5a1f2e51064e6de2d7ee86ac28fb5ee780643bf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reader\n\nDocumentation:\nThe function running on the reader thread.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reader(\n mut file: Box,\n receiver: &Receiver,\n sender: &SyncSender,\n settings: &GlobalSettings,\n) -> UResult<()> {\n let mut carry_over = vec![];\n for recycled_chunk in receiver {\n let should_continue = chunks::read(\n sender,\n recycled_chunk,\n None,\n &mut carry_over,\n &mut file,\n &mut iter::empty(),\n settings.line_ending.into(),\n settings,\n )?;\n if !should_continue {\n break;\n }\n }\n Ok(())\n}\n```"}], "func_name": "reader", "docstring": "The function running on the reader thread.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/check.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/check.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9f36969a6787ca2a948e193c75764a94f35cdb1c0bb11e52f7b32edbbf357639"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: recycle\n\nDocumentation:\nDestroy this chunk and return its components to be reused.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn recycle(mut self) -> RecycledChunk {\n let recycled_contents = self.with_dependent_mut(|_, contents| {\n contents.lines.clear();\n contents.line_data.selections.clear();\n contents.line_data.num_infos.clear();\n contents.line_data.parsed_floats.clear();\n contents.line_data.line_num_floats.clear();\n let lines = unsafe {\n // SAFETY: It is safe to (temporarily) transmute to a vector of lines with a longer lifetime,\n // because the vector is empty.\n // Transmuting is necessary to make recycling possible. See https://github.com/rust-lang/rfcs/pull/2802\n // for a rfc to make this unnecessary. Its example is similar to the code here.\n std::mem::transmute::>, Vec>>(std::mem::take(\n &mut contents.lines,\n ))\n };\n let selections = unsafe {\n // SAFETY: (same as above) It is safe to (temporarily) transmute to a vector of &str with a longer lifetime,\n // because the vector is empty.\n std::mem::transmute::, Vec<&'static str>>(std::mem::take(\n &mut contents.line_data.selections,\n ))\n };\n (\n lines,\n selections,\n std::mem::take(&mut contents.line_data.num_infos),\n std::mem::take(&mut contents.line_data.parsed_floats),\n std::mem::take(&mut contents.line_data.line_num_floats),\n )\n });\n RecycledChunk {\n lines: recycled_contents.0,\n selections: recycled_contents.1,\n num_infos: recycled_contents.2,\n parsed_floats: recycled_contents.3,\n line_num_floats: recycled_contents.4,\n buffer: self.into_owner(),\n }\n }\n```"}], "func_name": "recycle", "docstring": "Destroy this chunk and return its components to be reused.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/chunks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/chunks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9292afe7030ecf0fd54716214b916ba01ce3a808e50056f654aae74ef2723fe9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_lines\n\nDocumentation:\nSplit `read` into `Line`s, and add them to `lines`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_lines<'a>(\n read: &'a str,\n lines: &mut Vec>,\n line_data: &mut LineData<'a>,\n separator: u8,\n settings: &GlobalSettings,\n) {\n let read = read.strip_suffix(separator as char).unwrap_or(read);\n\n assert!(lines.is_empty());\n assert!(line_data.selections.is_empty());\n assert!(line_data.num_infos.is_empty());\n assert!(line_data.parsed_floats.is_empty());\n assert!(line_data.line_num_floats.is_empty());\n let mut token_buffer = vec![];\n lines.extend(\n read.split(separator as char)\n .enumerate()\n .map(|(index, line)| Line::create(line, index, line_data, &mut token_buffer, settings)),\n );\n}\n```"}], "func_name": "parse_lines", "docstring": "Split `read` into `Line`s, and add them to `lines`.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/chunks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/chunks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a998a64b57c59c0d0d55a5b0292c3ffc0441a3e899c6b58d8c8f9eea29c928ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_to_buffer\n\nDocumentation:\nRead from `file` into `buffer`.\n\nThis function makes sure that at least two lines are read (unless we reach EOF and there's no next file),\ngrowing the buffer if necessary.\nThe last line is likely to not have been fully read into the buffer. Its bytes must be copied to\nthe front of the buffer for the next invocation so that it can be continued to be read\n(see the return values and `start_offset`).\n\n# Arguments\n\n* `file`: The file to start reading from.\n* `next_files`: When `file` reaches EOF, it is updated to `next_files.next()` if that is `Some`,\nand this function continues reading.\n* `buffer`: The buffer that is filled with bytes. Its contents will mostly be overwritten (see `start_offset`\nas well). It will be grown up to `max_buffer_size` if necessary, but it will always grow to read at least two lines.\n* `max_buffer_size`: Grow the buffer to at most this length. If None, the buffer will not grow, unless needed to read at least two lines.\n* `start_offset`: The amount of bytes at the start of `buffer` that were carried over\nfrom the previous read and should not be overwritten.\n* `separator`: The byte that separates lines.\n\n# Returns\n\n* The amount of bytes in `buffer` that can now be interpreted as lines.\nThe remaining bytes must be copied to the start of the buffer for the next invocation,\nif another invocation is necessary, which is determined by the other return value.\n* Whether this function should be called again.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_to_buffer(\n file: &mut T,\n next_files: &mut impl Iterator>,\n buffer: &mut Vec,\n max_buffer_size: Option,\n start_offset: usize,\n separator: u8,\n) -> UResult<(usize, bool)> {\n let mut read_target = &mut buffer[start_offset..];\n let mut last_file_target_size = read_target.len();\n loop {\n match file.read(read_target) {\n Ok(0) => {\n if read_target.is_empty() {\n // chunk is full\n if let Some(max_buffer_size) = max_buffer_size {\n if max_buffer_size > buffer.len() {\n // we can grow the buffer\n let prev_len = buffer.len();\n if buffer.len() < max_buffer_size / 2 {\n buffer.resize(buffer.len() * 2, 0);\n } else {\n buffer.resize(max_buffer_size, 0);\n }\n read_target = &mut buffer[prev_len..];\n continue;\n }\n }\n let mut sep_iter = memchr_iter(separator, buffer).rev();\n let last_line_end = sep_iter.next();\n if sep_iter.next().is_some() {\n // We read enough lines.\n let end = last_line_end.unwrap();\n // We want to include the separator here, because it shouldn't be carried over.\n return Ok((end + 1, true));\n } else {\n // We need to read more lines\n let len = buffer.len();\n // resize the vector to 10 KB more\n buffer.resize(len + 1024 * 10, 0);\n read_target = &mut buffer[len..];\n }\n } else {\n // This file has been fully read.\n let mut leftover_len = read_target.len();\n if last_file_target_size != leftover_len {\n // The file was not empty.\n let read_len = buffer.len() - leftover_len;\n if buffer[read_len - 1] != separator {\n // The file did not end with a separator. We have to insert one.\n buffer[read_len] = separator;\n leftover_len -= 1;\n }\n let read_len = buffer.len() - leftover_len;\n read_target = &mut buffer[read_len..];\n }\n if let Some(next_file) = next_files.next() {\n // There is another file.\n last_file_target_size = leftover_len;\n *file = next_file?;\n } else {\n // This was the last file.\n let read_len = buffer.len() - leftover_len;\n return Ok((read_len, false));\n }\n }\n }\n Ok(n) => {\n read_target = &mut read_target[n..];\n }\n Err(e) if e.kind() == ErrorKind::Interrupted => {\n // retry\n }\n Err(e) => return Err(USimpleError::new(2, e.to_string())),\n }\n }\n}\n```"}], "func_name": "read_to_buffer", "docstring": "Read from `file` into `buffer`.\n\nThis function makes sure that at least two lines are read (unless we reach EOF and there's no next file),\ngrowing the buffer if necessary.\nThe last line is likely to not have been fully read into the buffer. Its bytes must be copied to\nthe front of the buffer for the next invocation so that it can be continued to be read\n(see the return values and `start_offset`).\n\n# Arguments\n\n* `file`: The file to start reading from.\n* `next_files`: When `file` reaches EOF, it is updated to `next_files.next()` if that is `Some`,\nand this function continues reading.\n* `buffer`: The buffer that is filled with bytes. Its contents will mostly be overwritten (see `start_offset`\nas well). It will be grown up to `max_buffer_size` if necessary, but it will always grow to read at least two lines.\n* `max_buffer_size`: Grow the buffer to at most this length. If None, the buffer will not grow, unless needed to read at least two lines.\n* `start_offset`: The amount of bytes at the start of `buffer` that were carried over\nfrom the previous read and should not be overwritten.\n* `separator`: The byte that separates lines.\n\n# Returns\n\n* The amount of bytes in `buffer` that can now be interpreted as lines.\nThe remaining bytes must be copied to the start of the buffer for the next invocation,\nif another invocation is necessary, which is determined by the other return value.\n* Whether this function should be called again.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/chunks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/chunks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad9ca66b30aafac372eecba36c194c41135a923088ee2b41ba3f206b95d029a4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ext_sort\n\nDocumentation:\nSort files by using auxiliary files for storing intermediate chunks (if needed), and output the result.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ext_sort(\n files: &mut impl Iterator>>,\n settings: &GlobalSettings,\n output: Output,\n tmp_dir: &mut TmpDirWrapper,\n) -> UResult<()> {\n let (sorted_sender, sorted_receiver) = std::sync::mpsc::sync_channel(1);\n let (recycled_sender, recycled_receiver) = std::sync::mpsc::sync_channel(1);\n thread::spawn({\n let settings = settings.clone();\n move || sorter(&recycled_receiver, &sorted_sender, &settings)\n });\n if settings.compress_prog.is_some() {\n reader_writer::<_, WriteableCompressedTmpFile>(\n files,\n settings,\n &sorted_receiver,\n recycled_sender,\n output,\n tmp_dir,\n )\n } else {\n reader_writer::<_, WriteablePlainTmpFile>(\n files,\n settings,\n &sorted_receiver,\n recycled_sender,\n output,\n tmp_dir,\n )\n }\n}\n```"}], "func_name": "ext_sort", "docstring": "Sort files by using auxiliary files for storing intermediate chunks (if needed), and output the result.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/ext_sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/ext_sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2cc68ae229b6cf6450d53f1afbeabe7e8a939df1601fccb5a25221e3d118feba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sorter\n\nDocumentation:\nThe function that is executed on the sorter thread.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn sorter(receiver: &Receiver, sender: &SyncSender, settings: &GlobalSettings) {\n while let Ok(mut payload) = receiver.recv() {\n payload.with_dependent_mut(|_, contents| {\n sort_by(&mut contents.lines, settings, &contents.line_data);\n });\n if sender.send(payload).is_err() {\n // The receiver has gone away, likely because the other thread hit an error.\n // We stop silently because the actual error is printed by the other thread.\n return;\n }\n }\n}\n```"}], "func_name": "sorter", "docstring": "The function that is executed on the sorter thread.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/ext_sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/ext_sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e1faec5c25a6d40a74dbda74b23e1de9815536290689b7b350f78125ca32edd4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_write_loop\n\nDocumentation:\nThe function that is executed on the reader/writer thread.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_write_loop(\n mut files: impl Iterator>>,\n tmp_dir: &mut TmpDirWrapper,\n separator: u8,\n buffer_size: usize,\n settings: &GlobalSettings,\n receiver: &Receiver,\n sender: SyncSender,\n) -> UResult> {\n let mut file = files.next().unwrap()?;\n\n let mut carry_over = vec![];\n // kick things off with two reads\n for _ in 0..2 {\n let should_continue = chunks::read(\n &sender,\n RecycledChunk::new(if START_BUFFER_SIZE < buffer_size {\n START_BUFFER_SIZE\n } else {\n buffer_size\n }),\n Some(buffer_size),\n &mut carry_over,\n &mut file,\n &mut files,\n separator,\n settings,\n )?;\n\n if !should_continue {\n drop(sender);\n // We have already read the whole input. Since we are in our first two reads,\n // this means that we can fit the whole input into memory. Bypass writing below and\n // handle this case in a more straightforward way.\n return Ok(if let Ok(first_chunk) = receiver.recv() {\n if let Ok(second_chunk) = receiver.recv() {\n ReadResult::SortedTwoChunks([first_chunk, second_chunk])\n } else {\n ReadResult::SortedSingleChunk(first_chunk)\n }\n } else {\n ReadResult::EmptyInput\n });\n }\n }\n\n let mut sender_option = Some(sender);\n let mut tmp_files = vec![];\n loop {\n let Ok(chunk) = receiver.recv() else {\n return Ok(ReadResult::WroteChunksToFile { tmp_files });\n };\n\n let tmp_file = write::(\n &chunk,\n tmp_dir.next_file()?,\n settings.compress_prog.as_deref(),\n separator,\n )?;\n tmp_files.push(tmp_file);\n\n let recycled_chunk = chunk.recycle();\n\n if let Some(sender) = &sender_option {\n let should_continue = chunks::read(\n sender,\n recycled_chunk,\n None,\n &mut carry_over,\n &mut file,\n &mut files,\n separator,\n settings,\n )?;\n if !should_continue {\n sender_option = None;\n }\n }\n }\n}\n```"}], "func_name": "read_write_loop", "docstring": "The function that is executed on the reader/writer thread.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/ext_sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/ext_sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "71bf397b17f24564bd893e5e3340174443ec83b458a6887a18a9e1270ed5f30a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write\n\nDocumentation:\nWrite the lines in `chunk` to `file`, separated by `separator`.\n`compress_prog` is used to optionally compress file contents.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write(\n chunk: &Chunk,\n file: (File, PathBuf),\n compress_prog: Option<&str>,\n separator: u8,\n) -> UResult {\n let mut tmp_file = I::create(file, compress_prog)?;\n write_lines(chunk.lines(), tmp_file.as_write(), separator);\n tmp_file.finished_writing()\n}\n```"}], "func_name": "write", "docstring": "Write the lines in `chunk` to `file`, separated by `separator`.\n`compress_prog` is used to optionally compress file contents.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/ext_sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/ext_sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1cdf0d97f1bb90ffc89b92d8fd51a9b0d81c941f02d45f1a18f8f82875522a82"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: replace_output_file_in_input_files\n\nDocumentation:\nIf the output file occurs in the input files as well, copy the contents of the output file\nand replace its occurrences in the inputs with that copy.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn replace_output_file_in_input_files(\n files: &mut [OsString],\n output: Option<&OsStr>,\n tmp_dir: &mut TmpDirWrapper,\n) -> UResult<()> {\n let mut copy: Option = None;\n if let Some(Ok(output_path)) = output.map(|path| Path::new(path).canonicalize()) {\n for file in files {\n if let Ok(file_path) = Path::new(file).canonicalize() {\n if file_path == output_path {\n if let Some(copy) = © {\n *file = copy.clone().into_os_string();\n } else {\n let (_file, copy_path) = tmp_dir.next_file()?;\n fs::copy(file_path, ©_path)\n .map_err(|error| SortError::OpenTmpFileFailed { error })?;\n *file = copy_path.clone().into_os_string();\n copy = Some(copy_path);\n }\n }\n }\n }\n }\n Ok(())\n}\n```"}], "func_name": "replace_output_file_in_input_files", "docstring": "If the output file occurs in the input files as well, copy the contents of the output file\nand replace its occurrences in the inputs with that copy.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/merge.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/merge.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "99f6d82ab67e160253cd6b17c7a3606f61d57d37531371f8146a4959cba99a33"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: merge\n\nDocumentation:\nMerge pre-sorted `Box`s.\n\nIf `settings.merge_batch_size` is greater than the length of `files`, intermediate files will be used.\nIf `settings.compress_prog` is `Some`, intermediate files will be compressed with it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn merge(\n files: &mut [OsString],\n settings: &GlobalSettings,\n output: Output,\n tmp_dir: &mut TmpDirWrapper,\n) -> UResult<()> {\n replace_output_file_in_input_files(files, output.as_output_name(), tmp_dir)?;\n let files = files\n .iter()\n .map(|file| open(file).map(|file| PlainMergeInput { inner: file }));\n if settings.compress_prog.is_none() {\n merge_with_file_limit::<_, _, WriteablePlainTmpFile>(files, settings, output, tmp_dir)\n } else {\n merge_with_file_limit::<_, _, WriteableCompressedTmpFile>(files, settings, output, tmp_dir)\n }\n}\n```"}], "func_name": "merge", "docstring": "Merge pre-sorted `Box`s.\n\nIf `settings.merge_batch_size` is greater than the length of `files`, intermediate files will be used.\nIf `settings.compress_prog` is `Some`, intermediate files will be compressed with it.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/merge.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/merge.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7412410465515875fb9a7e75feef1a878d5cf36028ac69ddeddae7d9a5221389"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_all\n\nDocumentation:\nWrite the merged contents to the output file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_all(self, settings: &GlobalSettings, output: Output) -> UResult<()> {\n let mut out = output.into_write();\n self.write_all_to(settings, &mut out)\n }\n```"}], "func_name": "write_all", "docstring": "Write the merged contents to the output file.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/merge.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/merge.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cab78431358e2194412220692c5f8ec43bf32a019b5e70f5eb34395c3c735748"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_byte_count\n\nDocumentation:\nParse a SIZE string into a number of bytes.\nA size string comprises an integer and an optional unit.\nThe unit may be k, K, m, M, g, G, t, T, P, E, Z, Y (powers of 1024), or b which is 1.\nDefault is K.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_byte_count(input: &str) -> Result {\n // GNU sort (8.32) valid: 1b, k, K, m, M, g, G, t, T, P, E, Z, Y\n // GNU sort (8.32) invalid: b, B, 1B, p, e, z, y\n let size = Parser::default()\n .with_allow_list(&[\n \"b\", \"k\", \"K\", \"m\", \"M\", \"g\", \"G\", \"t\", \"T\", \"P\", \"E\", \"Z\", \"Y\", \"R\", \"Q\", \"%\",\n ])\n .with_default_unit(\"K\")\n .with_b_byte_count(true)\n .parse(input.trim())?;\n\n usize::try_from(size).map_err(|_| {\n ParseSizeError::SizeTooBig(format!(\"Buffer size {size} does not fit in address space\"))\n })\n }\n```"}], "func_name": "parse_byte_count", "docstring": "Parse a SIZE string into a number of bytes.\nA size string comprises an integer and an optional unit.\nThe unit may be k, K, m, M, g, G, t, T, P, E, Z, Y (powers of 1024), or b which is 1.\nDefault is K.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8e4a37ef565a980caf4bb67648df654bc7ffb8514d8e2e0ee1cba2e4594f37ec"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init_precomputed\n\nDocumentation:\nPrecompute some data needed for sorting.\nThis function **must** be called before starting to sort, and `GlobalSettings` may not be altered\nafterwards.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn init_precomputed(&mut self) {\n self.precomputed.needs_tokens = self.selectors.iter().any(|s| s.needs_tokens);\n self.precomputed.selections_per_line =\n self.selectors.iter().filter(|s| s.needs_selection).count();\n self.precomputed.num_infos_per_line = self\n .selectors\n .iter()\n .filter(|s| matches!(s.settings.mode, SortMode::Numeric | SortMode::HumanNumeric))\n .count();\n self.precomputed.floats_per_line = self\n .selectors\n .iter()\n .filter(|s| matches!(s.settings.mode, SortMode::GeneralNumeric))\n .count();\n }\n```"}], "func_name": "init_precomputed", "docstring": "Precompute some data needed for sorting.\nThis function **must** be called before starting to sort, and `GlobalSettings` may not be altered\nafterwards.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4b38ea830f1d17c70c7f4ef62d9e95c8ac94327ab637d4cc3be207c0cf778752"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_compatibility\n\nDocumentation:\nChecks if the supplied combination of `mode`, `ignore_non_printing` and `dictionary_order` is allowed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_compatibility(\n mode: SortMode,\n ignore_non_printing: bool,\n dictionary_order: bool,\n ) -> Result<(), String> {\n if matches!(\n mode,\n SortMode::Numeric | SortMode::HumanNumeric | SortMode::GeneralNumeric | SortMode::Month\n ) {\n if dictionary_order {\n return Err(format!(\n \"options '-{}{}' are incompatible\",\n 'd',\n mode.get_short_name().unwrap()\n ));\n } else if ignore_non_printing {\n return Err(format!(\n \"options '-{}{}' are incompatible\",\n 'i',\n mode.get_short_name().unwrap()\n ));\n }\n }\n Ok(())\n }\n```"}], "func_name": "check_compatibility", "docstring": "Checks if the supplied combination of `mode`, `ignore_non_printing` and `dictionary_order` is allowed.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f115bfc8157071d77b8293e42d56bfb4d60d68260c97c647ba78787829287afb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create\n\nDocumentation:\nCreates a new `Line`.\n\nIf additional data is needed for sorting it is added to `line_data`.\n`token_buffer` allows to reuse the allocation for tokens.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn create(\n line: &'a str,\n index: usize,\n line_data: &mut LineData<'a>,\n token_buffer: &mut Vec,\n settings: &GlobalSettings,\n ) -> Self {\n token_buffer.clear();\n if settings.precomputed.needs_tokens {\n tokenize(line, settings.separator, token_buffer);\n }\n if settings.mode == SortMode::Numeric {\n // exclude inf, nan, scientific notation\n let line_num_float = (!line.contains(char::is_alphabetic))\n .then(|| line.parse::().ok())\n .flatten();\n line_data.line_num_floats.push(line_num_float);\n }\n for (selector, selection) in settings\n .selectors\n .iter()\n .map(|selector| (selector, selector.get_selection(line, token_buffer)))\n {\n match selection {\n Selection::AsBigDecimal(parsed_float) => line_data.parsed_floats.push(parsed_float),\n Selection::WithNumInfo(str, num_info) => {\n line_data.num_infos.push(num_info);\n line_data.selections.push(str);\n }\n Selection::Str(str) => {\n if selector.needs_selection {\n line_data.selections.push(str);\n }\n }\n }\n }\n Self { line, index }\n }\n```"}], "func_name": "create", "docstring": "Creates a new `Line`.\n\nIf additional data is needed for sorting it is added to `line_data`.\n`token_buffer` allows to reuse the allocation for tokens.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4862c33bd5742d7e34591c0eb5162f7beaf549beb5c00337e547d3652c894e74"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_debug\n\nDocumentation:\nWrites indicators for the selections this line matched. The original line content is NOT expected\nto be already printed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_debug(\n &self,\n settings: &GlobalSettings,\n writer: &mut impl Write,\n ) -> std::io::Result<()> {\n // We do not consider this function performance critical, as debug output is only useful for small files,\n // which are not a performance problem in any case. Therefore there aren't any special performance\n // optimizations here.\n\n let line = self.line.replace('\\t', \">\");\n writeln!(writer, \"{line}\")?;\n\n let mut fields = vec![];\n tokenize(self.line, settings.separator, &mut fields);\n for selector in &settings.selectors {\n let mut selection = selector.get_range(self.line, Some(&fields));\n match selector.settings.mode {\n SortMode::Numeric | SortMode::HumanNumeric => {\n // find out which range is used for numeric comparisons\n let (_, num_range) = NumInfo::parse(\n &self.line[selection.clone()],\n &NumInfoParseSettings {\n accept_si_units: selector.settings.mode == SortMode::HumanNumeric,\n ..Default::default()\n },\n );\n let initial_selection = selection.clone();\n\n // Shorten selection to num_range.\n selection.start += num_range.start;\n selection.end = selection.start + num_range.len();\n\n if num_range == (0..0) {\n // This was not a valid number.\n // Report no match at the first non-whitespace character.\n let leading_whitespace = self.line[selection.clone()]\n .find(|c: char| !c.is_whitespace())\n .unwrap_or(0);\n selection.start += leading_whitespace;\n selection.end += leading_whitespace;\n } else {\n // include a trailing si unit\n if selector.settings.mode == SortMode::HumanNumeric\n && self.line[selection.end..initial_selection.end].starts_with(\n &['k', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'R', 'Q'][..],\n )\n {\n selection.end += 1;\n }\n\n // include leading zeroes, a leading minus or a leading decimal point\n while self.line[initial_selection.start..selection.start]\n .ends_with(&['-', '0', '.'][..])\n {\n selection.start -= 1;\n }\n }\n }\n SortMode::GeneralNumeric => {\n let initial_selection = &self.line[selection.clone()];\n\n let leading = get_leading_gen(initial_selection);\n\n // Shorten selection to leading.\n selection.start += leading.start;\n selection.end = selection.start + leading.len();\n }\n SortMode::Month => {\n let initial_selection = &self.line[selection.clone()];\n\n let mut month_chars = initial_selection\n .char_indices()\n .skip_while(|(_, c)| c.is_whitespace());\n\n let month = if month_parse(initial_selection) == Month::Unknown {\n // We failed to parse a month, which is equivalent to matching nothing.\n // Add the \"no match for key\" marker to the first non-whitespace character.\n let first_non_whitespace = month_chars.next();\n first_non_whitespace.map_or(\n initial_selection.len()..initial_selection.len(),\n |(idx, _)| idx..idx,\n )\n } else {\n // We parsed a month. Match the first three non-whitespace characters, which must be the month we parsed.\n month_chars.next().unwrap().0\n ..month_chars\n .nth(2)\n .map_or(initial_selection.len(), |(idx, _)| idx)\n };\n\n // Shorten selection to month.\n selection.start += month.start;\n selection.end = selection.start + month.len();\n }\n _ => {}\n }\n\n write!(\n writer,\n \"{}\",\n \" \".repeat(UnicodeWidthStr::width(&line[..selection.start]))\n )?;\n\n if selection.is_empty() {\n writeln!(writer, \"^ no match for key\")?;\n } else {\n writeln!(\n writer,\n \"{}\",\n \"_\".repeat(UnicodeWidthStr::width(&line[selection]))\n )?;\n }\n }\n\n if settings.mode != SortMode::Random\n && !settings.stable\n && !settings.unique\n && (settings.dictionary_order\n || settings.ignore_leading_blanks\n || settings.ignore_case\n || settings.ignore_non_printing\n || settings.mode != SortMode::Default\n || settings\n .selectors\n .last()\n .is_none_or(|selector| selector != &FieldSelector::default()))\n {\n // A last resort comparator is in use, underline the whole line.\n if self.line.is_empty() {\n writeln!(writer, \"^ no match for key\")?;\n } else {\n writeln!(\n writer,\n \"{}\",\n \"_\".repeat(UnicodeWidthStr::width(line.as_str()))\n )?;\n }\n }\n Ok(())\n }\n```"}], "func_name": "print_debug", "docstring": "Writes indicators for the selections this line matched. The original line content is NOT expected\nto be already printed.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "98b9c1c6cb485fbedc25a77a1d54b7d4b014d6d7fba406eb375ef17d77fa06a1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tokenize\n\nDocumentation:\nTokenize a line into fields. The result is stored into `token_buffer`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn tokenize(line: &str, separator: Option, token_buffer: &mut Vec) {\n assert!(token_buffer.is_empty());\n if let Some(separator) = separator {\n tokenize_with_separator(line, separator, token_buffer);\n } else {\n tokenize_default(line, token_buffer);\n }\n}\n```"}], "func_name": "tokenize", "docstring": "Tokenize a line into fields. The result is stored into `token_buffer`.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "abda219a07de6272c2a8aad66a7e3144578bd5f381add81c39dc509903e56826"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tokenize_default\n\nDocumentation:\nBy default fields are separated by the first whitespace after non-whitespace.\nWhitespace is included in fields at the start.\nThe result is stored into `token_buffer`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn tokenize_default(line: &str, token_buffer: &mut Vec) {\n token_buffer.push(0..0);\n // pretend that there was whitespace in front of the line\n let mut previous_was_whitespace = true;\n for (idx, char) in line.char_indices() {\n if char.is_whitespace() {\n if !previous_was_whitespace {\n token_buffer.last_mut().unwrap().end = idx;\n token_buffer.push(idx..0);\n }\n previous_was_whitespace = true;\n } else {\n previous_was_whitespace = false;\n }\n }\n token_buffer.last_mut().unwrap().end = line.len();\n}\n```"}], "func_name": "tokenize_default", "docstring": "By default fields are separated by the first whitespace after non-whitespace.\nWhitespace is included in fields at the start.\nThe result is stored into `token_buffer`.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc58972cdc4e344fea968614a80586c1ec8fff4e75d341da8ed4ed211d805a25"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tokenize_with_separator\n\nDocumentation:\nSplit between separators. These separators are not included in fields.\nThe result is stored into `token_buffer`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn tokenize_with_separator(line: &str, separator: char, token_buffer: &mut Vec) {\n let separator_indices = line\n .char_indices()\n .filter_map(|(i, c)| if c == separator { Some(i) } else { None });\n let mut start = 0;\n for sep_idx in separator_indices {\n token_buffer.push(start..sep_idx);\n start = sep_idx + 1;\n }\n if start < line.len() {\n token_buffer.push(start..line.len());\n }\n}\n```"}], "func_name": "tokenize_with_separator", "docstring": "Split between separators. These separators are not included in fields.\nThe result is stored into `token_buffer`.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c019fb3b6dcaa598ac32649d6d73ba01406be4eecafd9a33707e08df2b5659e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: split_key_options\n\nDocumentation:\nSplits this position into the actual position and the attached options.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn split_key_options(position: &str) -> (&str, &str) {\n if let Some((options_start, _)) = position.char_indices().find(|(_, c)| c.is_alphabetic()) {\n position.split_at(options_start)\n } else {\n (position, \"\")\n }\n }\n```"}], "func_name": "split_key_options", "docstring": "Splits this position into the actual position and the attached options.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d20000ea698d511072cefed918c5294c34e836d461cda7a86b407d2fa7aaee9b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_key_settings\n\nDocumentation:\nApplies `options` to `key_settings`, returning if the 'b'-flag (ignore blanks) was present.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_key_settings(\n options: &str,\n key_settings: &mut KeySettings,\n ) -> Result {\n let mut ignore_blanks = false;\n for option in options.chars() {\n match option {\n 'M' => key_settings.set_sort_mode(SortMode::Month)?,\n 'b' => ignore_blanks = true,\n 'd' => key_settings.set_dictionary_order()?,\n 'f' => key_settings.ignore_case = true,\n 'g' => key_settings.set_sort_mode(SortMode::GeneralNumeric)?,\n 'h' => key_settings.set_sort_mode(SortMode::HumanNumeric)?,\n 'i' => key_settings.set_ignore_non_printing()?,\n 'n' => key_settings.set_sort_mode(SortMode::Numeric)?,\n 'R' => key_settings.set_sort_mode(SortMode::Random)?,\n 'r' => key_settings.reverse = true,\n 'V' => key_settings.set_sort_mode(SortMode::Version)?,\n c => return Err(format!(\"invalid option: '{c}'\")),\n }\n }\n Ok(ignore_blanks)\n }\n```"}], "func_name": "parse_key_settings", "docstring": "Applies `options` to `key_settings`, returning if the 'b'-flag (ignore blanks) was present.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ffa3ffc94391c21efeae7ed7f4db64e5308b1b3f30618f6913ed04974f5326b1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_selection\n\nDocumentation:\nGet the selection that corresponds to this selector for the line.\nIf needs_fields returned false, tokens may be empty.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_selection<'a>(&self, line: &'a str, tokens: &[Field]) -> Selection<'a> {\n // `get_range` expects `None` when we don't need tokens and would get confused by an empty vector.\n let tokens = if self.needs_tokens {\n Some(tokens)\n } else {\n None\n };\n let mut range = &line[self.get_range(line, tokens)];\n if self.settings.mode == SortMode::Numeric || self.settings.mode == SortMode::HumanNumeric {\n // Parse NumInfo for this number.\n let (info, num_range) = NumInfo::parse(\n range,\n &NumInfoParseSettings {\n accept_si_units: self.settings.mode == SortMode::HumanNumeric,\n ..Default::default()\n },\n );\n // Shorten the range to what we need to pass to numeric_str_cmp later.\n range = &range[num_range];\n Selection::WithNumInfo(range, info)\n } else if self.settings.mode == SortMode::GeneralNumeric {\n // Parse this number as BigDecimal, as this is the requirement for general numeric sorting.\n Selection::AsBigDecimal(general_bd_parse(&range[get_leading_gen(range)]))\n } else {\n // This is not a numeric sort, so we don't need a NumCache.\n Selection::Str(range)\n }\n }\n```"}], "func_name": "get_selection", "docstring": "Get the selection that corresponds to this selector for the line.\nIf needs_fields returned false, tokens may be empty.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bfcb9c6b988659e1202ee7df08a48ee2bfc78924b544fc5d618416e98f222bc8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_range\n\nDocumentation:\nLook up the range in the line that corresponds to this selector.\nIf needs_fields returned false, tokens must be None.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_range(&self, line: &str, tokens: Option<&[Field]>) -> Range {\n enum Resolution {\n // The start index of the resolved character, inclusive\n StartOfChar(usize),\n // The end index of the resolved character, exclusive.\n // This is only returned if the character index is 0.\n EndOfChar(usize),\n // The resolved character would be in front of the first character\n TooLow,\n // The resolved character would be after the last character\n TooHigh,\n }\n\n // Get the index for this line given the KeyPosition\n fn resolve_index(\n line: &str,\n tokens: Option<&[Field]>,\n position: &KeyPosition,\n ) -> Resolution {\n if matches!(tokens, Some(tokens) if tokens.len() < position.field) {\n Resolution::TooHigh\n } else if position.char == 0 {\n let end = tokens.unwrap()[position.field - 1].end;\n if end == 0 {\n Resolution::TooLow\n } else {\n Resolution::EndOfChar(end)\n }\n } else {\n let mut idx = if position.field == 1 {\n // The first field always starts at 0.\n // We don't need tokens for this case.\n 0\n } else {\n tokens.unwrap()[position.field - 1].start\n };\n // strip blanks if needed\n if position.ignore_blanks {\n idx += line[idx..]\n .char_indices()\n .find(|(_, c)| !c.is_whitespace())\n .map_or(line[idx..].len(), |(idx, _)| idx);\n }\n // apply the character index\n idx += line[idx..]\n .char_indices()\n .nth(position.char - 1)\n .map_or(line[idx..].len(), |(idx, _)| idx);\n if idx >= line.len() {\n Resolution::TooHigh\n } else {\n Resolution::StartOfChar(idx)\n }\n }\n }\n\n match resolve_index(line, tokens, &self.from) {\n Resolution::StartOfChar(from) => {\n let to = self.to.as_ref().map(|to| resolve_index(line, tokens, to));\n\n let mut range = match to {\n Some(Resolution::StartOfChar(mut to)) => {\n // We need to include the character at `to`.\n to += line[to..].chars().next().map_or(1, char::len_utf8);\n from..to\n }\n Some(Resolution::EndOfChar(to)) => from..to,\n // If `to` was not given or the match would be after the end of the line,\n // match everything until the end of the line.\n None | Some(Resolution::TooHigh) => from..line.len(),\n // If `to` is before the start of the line, report no match.\n // This can happen if the line starts with a separator.\n Some(Resolution::TooLow) => 0..0,\n };\n if range.start > range.end {\n range.end = range.start;\n }\n range\n }\n Resolution::TooLow | Resolution::EndOfChar(_) => {\n unreachable!(\n \"This should only happen if the field start index is 0, but that should already have caused an error.\"\n )\n }\n // While for comparisons it's only important that this is an empty slice,\n // to produce accurate debug output we need to match an empty slice at the end of the line.\n Resolution::TooHigh => line.len()..line.len(),\n }\n }\n```"}], "func_name": "get_range", "docstring": "Look up the range in the line that corresponds to this selector.\nIf needs_fields returned false, tokens must be None.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb7b3e1b34b6abdb3128436c00c0a5aaf9ef23d7f3324a520624ada6b53cc549"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_sort_mode_arg\n\nDocumentation:\nCreates an `Arg` that conflicts with all other sort modes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn make_sort_mode_arg(mode: &'static str, short: char, help: &'static str) -> Arg {\n let mut arg = Arg::new(mode)\n .short(short)\n .long(mode)\n .help(help)\n .action(ArgAction::SetTrue);\n for possible_mode in &options::modes::ALL_SORT_MODES {\n if *possible_mode != mode {\n arg = arg.conflicts_with(possible_mode);\n }\n }\n arg\n}\n```"}], "func_name": "make_sort_mode_arg", "docstring": "Creates an `Arg` that conflicts with all other sort modes.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8ef170efdb0095245c784161309bfbeb83ce339c332ac8eec08d41a17144d109"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: general_numeric_compare\n\nDocumentation:\nCompares two floats, with errors and non-numerics assumed to be -inf.\nStops coercing at the first non-numeric char.\nWe explicitly need to convert to f64 in this case.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn general_numeric_compare(\n a: &GeneralBigDecimalParseResult,\n b: &GeneralBigDecimalParseResult,\n) -> Ordering {\n a.partial_cmp(b).unwrap()\n}\n```"}], "func_name": "general_numeric_compare", "docstring": "Compares two floats, with errors and non-numerics assumed to be -inf.\nStops coercing at the first non-numeric char.\nWe explicitly need to convert to f64 in this case.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bad1f8c6ba00e3f8165175490b17ffa45283f2f9e18289e8639e516ffb3b42f2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: month_parse\n\nDocumentation:\nParse the beginning string into a Month, returning Month::Unknown on errors.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn month_parse(line: &str) -> Month {\n let line = line.trim();\n\n const MONTHS: [(&str, Month); 12] = [\n (\"JAN\", Month::January),\n (\"FEB\", Month::February),\n (\"MAR\", Month::March),\n (\"APR\", Month::April),\n (\"MAY\", Month::May),\n (\"JUN\", Month::June),\n (\"JUL\", Month::July),\n (\"AUG\", Month::August),\n (\"SEP\", Month::September),\n (\"OCT\", Month::October),\n (\"NOV\", Month::November),\n (\"DEC\", Month::December),\n ];\n\n for (month_str, month) in &MONTHS {\n if line.is_char_boundary(month_str.len())\n && line[..month_str.len()].eq_ignore_ascii_case(month_str)\n {\n return *month;\n }\n }\n\n Month::Unknown\n}\n```"}], "func_name": "month_parse", "docstring": "Parse the beginning string into a Month, returning Month::Unknown on errors.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/sort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/sort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4628ccab52e1b07cdbba593725ffbea7fd270dba72efc5786e22169fa9e05117"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait_if_signal\n\nDocumentation:\nFunction just waits if signal handler was called\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn wait_if_signal(&self) {\n let _lock = self.lock.lock().unwrap();\n }\n```"}], "func_name": "wait_if_signal", "docstring": "Function just waits if signal handler was called", "repo": "uutils/coreutils", "path": "src/uu/sort/src/tmp_dir.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/tmp_dir.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "df8bd83f295e28b09f3a2bd0b5b38320464b1e9bfb5620222c80c238d2e94b0f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_tmp_dir\n\nDocumentation:\nRemove the directory at `path` by deleting its child files and then itself.\nErrors while deleting child files are ignored.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn remove_tmp_dir(path: &Path) -> std::io::Result<()> {\n if let Ok(read_dir) = std::fs::read_dir(path) {\n for file in read_dir.flatten() {\n // if we fail to delete the file here it was probably deleted by another thread\n // in the meantime, but that's ok.\n let _ = std::fs::remove_file(file.path());\n }\n }\n std::fs::remove_dir(path)\n}\n```"}], "func_name": "remove_tmp_dir", "docstring": "Remove the directory at `path` by deleting its child files and then itself.\nErrors while deleting child files are ignored.", "repo": "uutils/coreutils", "path": "src/uu/sort/src/tmp_dir.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/sort/src/tmp_dir.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca0717bc54455b60a38cecb2a693a961f45eed360fcc202b7d78770c27d9d832"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: radix\n\nDocumentation:\nThe radix to use when representing the suffix string as digits.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn radix(&self) -> u8 {\n match self {\n Self::Alphabetic => 26,\n Self::Decimal => 10,\n Self::Hexadecimal => 16,\n }\n }\n```"}], "func_name": "radix", "docstring": "The radix to use when representing the suffix string as digits.", "repo": "uutils/coreutils", "path": "src/uu/split/src/filenames.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/filenames.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b80845b8c5860ef099acca1cb1972bd16c00eac105b4f489413412d4ad5f4341"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nParse the suffix type, start, length and additional suffix from the command-line arguments\nas well process suffix length auto-widening and auto-width scenarios\n\nSuffix auto-widening: Determine if the output file names suffix is allowed to dynamically auto-widen,\ni.e. change (increase) suffix length dynamically as more files need to be written into.\nSuffix length auto-widening rules are (in the order they are applied):\n- ON by default\n- OFF when suffix start N is specified via long option with a value\n`--numeric-suffixes=N` or `--hex-suffixes=N`\n- OFF when suffix length N is specified, except for N=0 (see edge cases below)\n`-a N` or `--suffix-length=N`\n- OFF if suffix length is auto pre-calculated (auto-width)\n\nSuffix auto-width: Determine if the the output file names suffix length should be automatically pre-calculated\nbased on number of files that need to written into, having number of files known upfront\nSuffix length auto pre-calculation rules:\n- Pre-calculate new suffix length when `-n`/`--number` option (N, K/N, l/N, l/K/N, r/N, r/K/N)\nis used, where N is number of chunks = number of files to write into\nand suffix start < N number of files\nas in `split --numeric-suffixes=1 --number=r/100 file`\n- Do NOT pre-calculate new suffix length otherwise, i.e. when\nsuffix start >= N number of files\nas in `split --numeric-suffixes=100 --number=r/100 file`\nOR when suffix length N is specified, except for N=0 (see edge cases below)\n`-a N` or `--suffix-length=N`\n\nEdge case:\n- If suffix length is specified as 0 in a command line,\nfirst apply auto-width calculations and if still 0\nset it to default value.\nDo NOT change auto-widening value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from(matches: &ArgMatches, strategy: &Strategy) -> Result {\n let stype: SuffixType;\n\n // Defaults\n let mut start = 0;\n let mut auto_widening = true;\n let default_length: usize = 2;\n\n // Check if the user is specifying one or more than one suffix\n // Any combination of suffixes is allowed\n // Since all suffixes are setup with 'overrides_with_all()' against themselves and each other,\n // last one wins, all others are ignored\n match (\n matches.contains_id(OPT_NUMERIC_SUFFIXES),\n matches.contains_id(OPT_HEX_SUFFIXES),\n matches.get_flag(OPT_NUMERIC_SUFFIXES_SHORT),\n matches.get_flag(OPT_HEX_SUFFIXES_SHORT),\n ) {\n (true, _, _, _) => {\n stype = SuffixType::Decimal;\n // if option was specified, but without value - this will return None as there is no default value\n if let Some(opt) = matches.get_one::(OPT_NUMERIC_SUFFIXES) {\n start = opt\n .parse::()\n .map_err(|_| SuffixError::NotParsable(opt.to_string()))?;\n auto_widening = false;\n }\n }\n (_, true, _, _) => {\n stype = SuffixType::Hexadecimal;\n // if option was specified, but without value - this will return None as there is no default value\n if let Some(opt) = matches.get_one::(OPT_HEX_SUFFIXES) {\n start = usize::from_str_radix(opt, 16)\n .map_err(|_| SuffixError::NotParsable(opt.to_string()))?;\n auto_widening = false;\n }\n }\n (_, _, true, _) => stype = SuffixType::Decimal, // short numeric suffix '-d'\n (_, _, _, true) => stype = SuffixType::Hexadecimal, // short hex suffix '-x'\n _ => stype = SuffixType::Alphabetic, // no numeric/hex suffix, using default alphabetic\n }\n\n // Get suffix length and a flag to indicate if it was specified with command line option\n let (mut length, is_length_cmd_opt) =\n if let Some(v) = matches.get_one::(OPT_SUFFIX_LENGTH) {\n // suffix length was specified in command line\n (\n v.parse::()\n .map_err(|_| SuffixError::NotParsable(v.to_string()))?,\n true,\n )\n } else {\n // no suffix length option was specified in command line\n // set to default value\n (default_length, false)\n };\n\n // Disable dynamic auto-widening if suffix length was specified in command line with value > 0\n if is_length_cmd_opt && length > 0 {\n auto_widening = false;\n }\n\n // Auto pre-calculate new suffix length (auto-width) if necessary\n if let Strategy::Number(number_type) = strategy {\n let chunks = number_type.num_chunks();\n let required_length = ((start as u64 + chunks) as f64)\n .log(stype.radix() as f64)\n .ceil() as usize;\n\n if (start as u64) < chunks && !(is_length_cmd_opt && length > 0) {\n // with auto-width ON the auto-widening is OFF\n auto_widening = false;\n\n // do not reduce suffix length with auto-width\n if length < required_length {\n length = required_length;\n }\n }\n\n if length < required_length {\n return Err(SuffixError::TooSmall(required_length));\n }\n }\n\n // Check edge case when suffix length == 0 was specified in command line\n // Set it to default value\n if is_length_cmd_opt && length == 0 {\n length = default_length;\n }\n\n let additional = matches\n .get_one::(OPT_ADDITIONAL_SUFFIX)\n .unwrap()\n .to_string();\n if additional.chars().any(is_separator) {\n return Err(SuffixError::ContainsSeparator(additional));\n }\n\n let result = Self {\n stype,\n length,\n start,\n auto_widening,\n additional,\n };\n\n Ok(result)\n }\n```"}], "func_name": "from", "docstring": "Parse the suffix type, start, length and additional suffix from the command-line arguments\nas well process suffix length auto-widening and auto-width scenarios\n\nSuffix auto-widening: Determine if the output file names suffix is allowed to dynamically auto-widen,\ni.e. change (increase) suffix length dynamically as more files need to be written into.\nSuffix length auto-widening rules are (in the order they are applied):\n- ON by default\n- OFF when suffix start N is specified via long option with a value\n`--numeric-suffixes=N` or `--hex-suffixes=N`\n- OFF when suffix length N is specified, except for N=0 (see edge cases below)\n`-a N` or `--suffix-length=N`\n- OFF if suffix length is auto pre-calculated (auto-width)\n\nSuffix auto-width: Determine if the the output file names suffix length should be automatically pre-calculated\nbased on number of files that need to written into, having number of files known upfront\nSuffix length auto pre-calculation rules:\n- Pre-calculate new suffix length when `-n`/`--number` option (N, K/N, l/N, l/K/N, r/N, r/K/N)\nis used, where N is number of chunks = number of files to write into\nand suffix start < N number of files\nas in `split --numeric-suffixes=1 --number=r/100 file`\n- Do NOT pre-calculate new suffix length otherwise, i.e. when\nsuffix start >= N number of files\nas in `split --numeric-suffixes=100 --number=r/100 file`\nOR when suffix length N is specified, except for N=0 (see edge cases below)\n`-a N` or `--suffix-length=N`\n\nEdge case:\n- If suffix length is specified as 0 in a command line,\nfirst apply auto-width calculations and if still 0\nset it to default value.\nDo NOT change auto-widening value", "repo": "uutils/coreutils", "path": "src/uu/split/src/filenames.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/filenames.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0cb8a762dc39cf513e9c1db963dcac0f8d7a69bbec6ccfdd5ce3c375e7c3c87a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: increment\n\nDocumentation:\nIncrement this number to its successor.\n\nIf incrementing this number would result in an overflow beyond\nthe maximum representable number, then return\n[`Err(Overflow)`]. The [`FixedWidthNumber`] overflows, but\n[`DynamicWidthNumber`] does not.\n\nThe [`DynamicWidthNumber`] follows a non-standard incrementing\nprocedure that is used specifically for the `split` program.\nSee the [`DynamicWidthNumber`] documentation for more\ninformation.\n\n# Errors\n\nThis method returns [`Err(Overflow)`] when attempting to\nincrement beyond the largest representable number.\n\n# Examples\n\nOverflowing:\n\n```rust,ignore\n\nuse crate::number::FixedWidthNumber;\nuse crate::number::Number;\nuse crate::number::Overflow;\n\n// Radix 3, width of 1 digit.\nlet mut number = Number::FixedWidth(FixedWidthNumber::new(3, 1));\nnumber.increment().unwrap(); // from 0 to 1\nnumber.increment().unwrap(); // from 1 to 2\nassert!(number.increment().is_err());\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn increment(&mut self) -> Result<(), Overflow> {\n match self {\n Self::FixedWidth(number) => number.increment(),\n Self::DynamicWidth(number) => number.increment(),\n }\n }\n```"}], "func_name": "increment", "docstring": "Increment this number to its successor.\n\nIf incrementing this number would result in an overflow beyond\nthe maximum representable number, then return\n[`Err(Overflow)`]. The [`FixedWidthNumber`] overflows, but\n[`DynamicWidthNumber`] does not.\n\nThe [`DynamicWidthNumber`] follows a non-standard incrementing\nprocedure that is used specifically for the `split` program.\nSee the [`DynamicWidthNumber`] documentation for more\ninformation.\n\n# Errors\n\nThis method returns [`Err(Overflow)`] when attempting to\nincrement beyond the largest representable number.\n\n# Examples\n\nOverflowing:\n\n```rust,ignore\n\nuse crate::number::FixedWidthNumber;\nuse crate::number::Number;\nuse crate::number::Overflow;\n\n// Radix 3, width of 1 digit.\nlet mut number = Number::FixedWidth(FixedWidthNumber::new(3, 1));\nnumber.increment().unwrap(); // from 0 to 1\nnumber.increment().unwrap(); // from 1 to 2\nassert!(number.increment().is_err());\n```", "repo": "uutils/coreutils", "path": "src/uu/split/src/number.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/number.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "864167d22f528baa95b8fec8d76dfb1338238259027d8d9347a886983ae4db79"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nInstantiate a number of the given radix and width.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(radix: u8, width: usize, mut suffix_start: usize) -> Result {\n let mut digits = vec![0_u8; width];\n\n for i in (0..digits.len()).rev() {\n let remainder = (suffix_start % (radix as usize)) as u8;\n suffix_start /= radix as usize;\n digits[i] = remainder;\n if suffix_start == 0 {\n break;\n }\n }\n if suffix_start == 0 {\n Ok(Self { radix, digits })\n } else {\n Err(Overflow)\n }\n }\n```"}], "func_name": "new", "docstring": "Instantiate a number of the given radix and width.", "repo": "uutils/coreutils", "path": "src/uu/split/src/number.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/number.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca54f93248e1b9a1268cec84f4e7aad8648ca32bc21fc76b7c8e927aa6801aa4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: increment\n\nDocumentation:\nIncrement this number.\n\nThis method adds one to this number. If incrementing this\nnumber would require more digits than are available with the\nspecified width, then this method returns [`Err(Overflow)`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn increment(&mut self) -> Result<(), Overflow> {\n for i in (0..self.digits.len()).rev() {\n // Increment the current digit.\n self.digits[i] += 1;\n\n // If the digit overflows, then set it to 0 and continue\n // to the next iteration to increment the next most\n // significant digit. Otherwise, terminate the loop, since\n // there will be no further changes to any higher order\n // digits.\n if self.digits[i] == self.radix {\n self.digits[i] = 0;\n } else {\n break;\n }\n }\n\n // Return an error on overflow, which is signified by all zeros.\n if self.digits == vec![0; self.digits.len()] {\n Err(Overflow)\n } else {\n Ok(())\n }\n }\n```"}], "func_name": "increment", "docstring": "Increment this number.\n\nThis method adds one to this number. If incrementing this\nnumber would require more digits than are available with the\nspecified width, then this method returns [`Err(Overflow)`].", "repo": "uutils/coreutils", "path": "src/uu/split/src/number.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/number.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2dcb50406635d551ca35541486819a7b943288559c96e3e9758e700884ce6ec7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_obsolete\n\nDocumentation:\nExtract obsolete shorthand (if any) for specifying lines in following scenarios (and similar)\n`split -22 file` would mean `split -l 22 file`\n`split -2de file` would mean `split -l 2 -d -e file`\n`split -x300e file` would mean `split -x -l 300 -e file`\n`split -x300e -22 file` would mean `split -x -e -l 22 file` (last obsolete lines option wins)\nfollowing GNU `split` behavior\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_obsolete(args: impl uucore::Args) -> (Vec, Option) {\n let mut obs_lines = None;\n let mut preceding_long_opt_req_value = false;\n let mut preceding_short_opt_req_value = false;\n\n let filtered_args = args\n .filter_map(|os_slice| {\n filter_args(\n os_slice,\n &mut obs_lines,\n &mut preceding_long_opt_req_value,\n &mut preceding_short_opt_req_value,\n )\n })\n .collect();\n\n (filtered_args, obs_lines)\n}\n```"}], "func_name": "handle_obsolete", "docstring": "Extract obsolete shorthand (if any) for specifying lines in following scenarios (and similar)\n`split -22 file` would mean `split -l 22 file`\n`split -2de file` would mean `split -l 2 -d -e file`\n`split -x300e file` would mean `split -x -l 300 -e file`\n`split -x300e -22 file` would mean `split -x -e -l 22 file` (last obsolete lines option wins)\nfollowing GNU `split` behavior", "repo": "uutils/coreutils", "path": "src/uu/split/src/split.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/split.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d6946a0fc9899d8999c37dca0295e48d64d0c83e7a48e007a38d92b88f529518"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: filter_args\n\nDocumentation:\nHelper function to [`handle_obsolete`]\nFilters out obsolete lines option from args\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn filter_args(\n os_slice: OsString,\n obs_lines: &mut Option,\n preceding_long_opt_req_value: &mut bool,\n preceding_short_opt_req_value: &mut bool,\n) -> Option {\n let filter: Option;\n if let Some(slice) = os_slice.to_str() {\n if should_extract_obs_lines(\n slice,\n preceding_long_opt_req_value,\n preceding_short_opt_req_value,\n ) {\n // start of the short option string\n // that can have obsolete lines option value in it\n filter = handle_extract_obs_lines(slice, obs_lines);\n } else {\n // either not a short option\n // or a short option that cannot have obsolete lines value in it\n filter = Some(OsString::from(slice));\n }\n handle_preceding_options(\n slice,\n preceding_long_opt_req_value,\n preceding_short_opt_req_value,\n );\n } else {\n // Cannot cleanly convert os_slice to UTF-8\n // Do not process and return as-is\n // This will cause failure later on, but we should not handle it here\n // and let clap panic on invalid UTF-8 argument\n filter = Some(os_slice);\n }\n filter\n}\n```"}], "func_name": "filter_args", "docstring": "Helper function to [`handle_obsolete`]\nFilters out obsolete lines option from args", "repo": "uutils/coreutils", "path": "src/uu/split/src/split.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/split.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4fff2be72552b6c39eace76cc888a0a65702bc90e57a03c98090bfc15ec5923d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: should_extract_obs_lines\n\nDocumentation:\nHelper function to [`filter_args`]\nChecks if the slice is a true short option (and not hyphen prefixed value of an option)\nand if so, a short option that can contain obsolete lines value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn should_extract_obs_lines(\n slice: &str,\n preceding_long_opt_req_value: &bool,\n preceding_short_opt_req_value: &bool,\n) -> bool {\n slice.starts_with('-')\n && !slice.starts_with(\"--\")\n && !preceding_long_opt_req_value\n && !preceding_short_opt_req_value\n && !slice.starts_with(\"-a\")\n && !slice.starts_with(\"-b\")\n && !slice.starts_with(\"-C\")\n && !slice.starts_with(\"-l\")\n && !slice.starts_with(\"-n\")\n && !slice.starts_with(\"-t\")\n}\n```"}], "func_name": "should_extract_obs_lines", "docstring": "Helper function to [`filter_args`]\nChecks if the slice is a true short option (and not hyphen prefixed value of an option)\nand if so, a short option that can contain obsolete lines value", "repo": "uutils/coreutils", "path": "src/uu/split/src/split.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/split.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c45c0579c8699155b08397ae2afcb97688b3d999d935c35017b80ff997575582"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_extract_obs_lines\n\nDocumentation:\nHelper function to [`filter_args`]\nExtracts obsolete lines numeric part from argument slice\nand filters it out\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_extract_obs_lines(slice: &str, obs_lines: &mut Option) -> Option {\n let mut obs_lines_extracted: Vec = vec![];\n let mut obs_lines_end_reached = false;\n let filtered_slice: Vec = slice\n .chars()\n .filter(|c| {\n // To correctly process scenario like '-x200a4'\n // we need to stop extracting digits once alphabetic character is encountered\n // after we already have something in obs_lines_extracted\n if c.is_ascii_digit() && !obs_lines_end_reached {\n obs_lines_extracted.push(*c);\n false\n } else {\n if !obs_lines_extracted.is_empty() {\n obs_lines_end_reached = true;\n }\n true\n }\n })\n .collect();\n\n if obs_lines_extracted.is_empty() {\n // no obsolete lines value found/extracted\n Some(OsString::from(slice))\n } else {\n // obsolete lines value was extracted\n let extracted: String = obs_lines_extracted.iter().collect();\n *obs_lines = Some(extracted);\n if filtered_slice.get(1).is_some() {\n // there were some short options in front of or after obsolete lines value\n // i.e. '-xd100' or '-100de' or similar, which after extraction of obsolete lines value\n // would look like '-xd' or '-de' or similar\n let filtered_slice: String = filtered_slice.iter().collect();\n Some(OsString::from(filtered_slice))\n } else {\n None\n }\n }\n}\n```"}], "func_name": "handle_extract_obs_lines", "docstring": "Helper function to [`filter_args`]\nExtracts obsolete lines numeric part from argument slice\nand filters it out", "repo": "uutils/coreutils", "path": "src/uu/split/src/split.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/split.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "298e9b2ea3e185639f7a175db90a839872c5374a9db32a4d8627fb99f2e0d373"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_preceding_options\n\nDocumentation:\nHelper function to [`handle_extract_obs_lines`]\nCaptures if current slice is a preceding option\nthat requires value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_preceding_options(\n slice: &str,\n preceding_long_opt_req_value: &mut bool,\n preceding_short_opt_req_value: &mut bool,\n) {\n // capture if current slice is a preceding long option that requires value and does not use '=' to assign that value\n // following slice should be treaded as value for this option\n // even if it starts with '-' (which would be treated as hyphen prefixed value)\n if slice.starts_with(\"--\") {\n *preceding_long_opt_req_value = &slice[2..] == OPT_BYTES\n || &slice[2..] == OPT_LINE_BYTES\n || &slice[2..] == OPT_LINES\n || &slice[2..] == OPT_ADDITIONAL_SUFFIX\n || &slice[2..] == OPT_FILTER\n || &slice[2..] == OPT_NUMBER\n || &slice[2..] == OPT_SUFFIX_LENGTH\n || &slice[2..] == OPT_SEPARATOR;\n }\n // capture if current slice is a preceding short option that requires value and does not have value in the same slice (value separated by whitespace)\n // following slice should be treaded as value for this option\n // even if it starts with '-' (which would be treated as hyphen prefixed value)\n *preceding_short_opt_req_value = slice == \"-b\"\n || slice == \"-C\"\n || slice == \"-l\"\n || slice == \"-n\"\n || slice == \"-a\"\n || slice == \"-t\";\n // slice is a value\n // reset preceding option flags\n if !slice.starts_with('-') {\n *preceding_short_opt_req_value = false;\n *preceding_long_opt_req_value = false;\n }\n}\n```"}], "func_name": "handle_preceding_options", "docstring": "Helper function to [`handle_extract_obs_lines`]\nCaptures if current slice is a preceding option\nthat requires value", "repo": "uutils/coreutils", "path": "src/uu/split/src/split.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/split.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4efbb3d74b595de2ce011f6478c975a7f3fa256cc1473284b9221cae9a7e04d2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: num_chunks\n\nDocumentation:\nThe number of chunks for this number type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn num_chunks(&self) -> u64 {\n match self {\n Self::Bytes(n) => *n,\n Self::KthBytes(_, n) => *n,\n Self::Lines(n) => *n,\n Self::KthLines(_, n) => *n,\n Self::RoundRobin(n) => *n,\n Self::KthRoundRobin(_, n) => *n,\n }\n }\n```"}], "func_name": "num_chunks", "docstring": "The number of chunks for this number type.", "repo": "uutils/coreutils", "path": "src/uu/split/src/strategy.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/strategy.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6a12d7b2e85a4bf1e53bfe6bdc0fa4830db0379f89cd084023d94a22fb30211e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nParse a `NumberType` from a string.\n\nThe following strings are valid arguments:\n\n```ignore\n\"N\"\n\"K/N\"\n\"l/N\"\n\"l/K/N\"\n\"r/N\"\n\"r/K/N\"\n```\n\nThe `N` represents the number of chunks and the `K` represents\na chunk number.\n\n# Errors\n\nIf the string is not one of the valid number types,\nif `K` is not a non-negative integer,\nor if `K` is 0,\nor if `N` is not a positive integer,\nor if `K` is greater than `N`\nthen this function returns [`NumberTypeError`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from(s: &str) -> Result {\n fn is_invalid_chunk(chunk_number: u64, num_chunks: u64) -> bool {\n chunk_number > num_chunks || chunk_number == 0\n }\n let mut parts = s.splitn(4, '/');\n match (parts.next(), parts.next(), parts.next(), parts.next()) {\n (Some(n_str), None, None, None) => {\n let num_chunks = parse_size_u64(n_str)\n .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_string()))?;\n if num_chunks > 0 {\n Ok(Self::Bytes(num_chunks))\n } else {\n Err(NumberTypeError::NumberOfChunks(s.to_string()))\n }\n }\n (Some(k_str), Some(n_str), None, None)\n if !k_str.starts_with('l') && !k_str.starts_with('r') =>\n {\n let num_chunks = parse_size_u64(n_str)\n .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_string()))?;\n let chunk_number = parse_size_u64(k_str)\n .map_err(|_| NumberTypeError::ChunkNumber(k_str.to_string()))?;\n if is_invalid_chunk(chunk_number, num_chunks) {\n return Err(NumberTypeError::ChunkNumber(k_str.to_string()));\n }\n Ok(Self::KthBytes(chunk_number, num_chunks))\n }\n (Some(\"l\"), Some(n_str), None, None) => {\n let num_chunks = parse_size_u64(n_str)\n .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_string()))?;\n Ok(Self::Lines(num_chunks))\n }\n (Some(\"l\"), Some(k_str), Some(n_str), None) => {\n let num_chunks = parse_size_u64(n_str)\n .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_string()))?;\n let chunk_number = parse_size_u64(k_str)\n .map_err(|_| NumberTypeError::ChunkNumber(k_str.to_string()))?;\n if is_invalid_chunk(chunk_number, num_chunks) {\n return Err(NumberTypeError::ChunkNumber(k_str.to_string()));\n }\n Ok(Self::KthLines(chunk_number, num_chunks))\n }\n (Some(\"r\"), Some(n_str), None, None) => {\n let num_chunks = parse_size_u64(n_str)\n .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_string()))?;\n Ok(Self::RoundRobin(num_chunks))\n }\n (Some(\"r\"), Some(k_str), Some(n_str), None) => {\n let num_chunks = parse_size_u64(n_str)\n .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_string()))?;\n let chunk_number = parse_size_u64(k_str)\n .map_err(|_| NumberTypeError::ChunkNumber(k_str.to_string()))?;\n if is_invalid_chunk(chunk_number, num_chunks) {\n return Err(NumberTypeError::ChunkNumber(k_str.to_string()));\n }\n Ok(Self::KthRoundRobin(chunk_number, num_chunks))\n }\n _ => Err(NumberTypeError::NumberOfChunks(s.to_string())),\n }\n }\n```"}], "func_name": "from", "docstring": "Parse a `NumberType` from a string.\n\nThe following strings are valid arguments:\n\n```ignore\n\"N\"\n\"K/N\"\n\"l/N\"\n\"l/K/N\"\n\"r/N\"\n\"r/K/N\"\n```\n\nThe `N` represents the number of chunks and the `K` represents\na chunk number.\n\n# Errors\n\nIf the string is not one of the valid number types,\nif `K` is not a non-negative integer,\nor if `K` is 0,\nor if `N` is not a positive integer,\nor if `K` is greater than `N`\nthen this function returns [`NumberTypeError`].", "repo": "uutils/coreutils", "path": "src/uu/split/src/strategy.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/strategy.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "11c822dad21e2a3622743cd2f9790b0667a6152267b3953726dedf1e41bab4a4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nParse a strategy from the command-line arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from(matches: &ArgMatches, obs_lines: Option<&str>) -> Result {\n fn get_and_parse(\n matches: &ArgMatches,\n option: &str,\n strategy: fn(u64) -> Strategy,\n error: fn(ParseSizeError) -> StrategyError,\n ) -> Result {\n let s = matches.get_one::(option).unwrap();\n let n = parse_size_u64_max(s).map_err(error)?;\n if n > 0 {\n Ok(strategy(n))\n } else {\n Err(error(ParseSizeError::ParseFailure(s.to_string())))\n }\n }\n // Check that the user is not specifying more than one strategy.\n //\n // Note: right now, this exact behavior cannot be handled by\n // overrides_with_all() due to obsolete lines value option\n match (\n obs_lines,\n matches.value_source(OPT_LINES) == Some(ValueSource::CommandLine),\n matches.value_source(OPT_BYTES) == Some(ValueSource::CommandLine),\n matches.value_source(OPT_LINE_BYTES) == Some(ValueSource::CommandLine),\n matches.value_source(OPT_NUMBER) == Some(ValueSource::CommandLine),\n ) {\n (Some(v), false, false, false, false) => {\n let v = parse_size_u64_max(v).map_err(|_| {\n StrategyError::Lines(ParseSizeError::ParseFailure(v.to_string()))\n })?;\n if v > 0 {\n Ok(Self::Lines(v))\n } else {\n Err(StrategyError::Lines(ParseSizeError::ParseFailure(\n v.to_string(),\n )))\n }\n }\n (None, false, false, false, false) => Ok(Self::Lines(1000)),\n (None, true, false, false, false) => {\n get_and_parse(matches, OPT_LINES, Self::Lines, StrategyError::Lines)\n }\n (None, false, true, false, false) => {\n get_and_parse(matches, OPT_BYTES, Self::Bytes, StrategyError::Bytes)\n }\n (None, false, false, true, false) => get_and_parse(\n matches,\n OPT_LINE_BYTES,\n Self::LineBytes,\n StrategyError::Bytes,\n ),\n (None, false, false, false, true) => {\n let s = matches.get_one::(OPT_NUMBER).unwrap();\n let number_type = NumberType::from(s).map_err(StrategyError::NumberType)?;\n Ok(Self::Number(number_type))\n }\n _ => Err(StrategyError::MultipleWays),\n }\n }\n```"}], "func_name": "from", "docstring": "Parse a strategy from the command-line arguments.", "repo": "uutils/coreutils", "path": "src/uu/split/src/strategy.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/strategy.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "70d58d3a146798f720b5d9d7f0d01a1ae3faae85ec837d3a2b3095da760ac58f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: instantiate_current_writer\n\nDocumentation:\nGet a file writer\n\nUnlike the unix version of this function, this _always_ returns\na file writer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn instantiate_current_writer(\n _filter: Option<&str>,\n filename: &str,\n is_new: bool,\n) -> Result>> {\n let file = if is_new {\n // create new file\n std::fs::OpenOptions::new()\n .write(true)\n .create(true)\n .truncate(true)\n .open(Path::new(&filename))\n .map_err(|_| Error::other(format!(\"unable to open '{filename}'; aborting\")))?\n } else {\n // re-open file that we previously created to append to it\n std::fs::OpenOptions::new()\n .append(true)\n .open(Path::new(&filename))\n .map_err(|_| Error::other(format!(\"unable to re-open '{filename}'; aborting\")))?\n };\n Ok(BufWriter::new(Box::new(file) as Box))\n}\n```"}], "func_name": "instantiate_current_writer", "docstring": "Get a file writer\n\nUnlike the unix version of this function, this _always_ returns\na file writer", "repo": "uutils/coreutils", "path": "src/uu/split/src/platform/windows.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/split/src/platform/windows.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a9f0212301176f8df96f0adc899cc91a77610c3b20b5cf835b34984c46ba6e95"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_bound\n\nDocumentation:\nchecks if the string is within the specified bound,\nif it gets out of bound, error out by printing sub-string from index `beg` to`end`,\nwhere `beg` & `end` is the beginning and end index of sub-string, respectively\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_bound(slice: &str, bound: usize, beg: usize, end: usize) -> UResult<()> {\n if end >= bound {\n return Err(USimpleError::new(\n 1,\n format!(\"{}: invalid directive\", slice[beg..end].quote()),\n ));\n }\n Ok(())\n}\n```"}], "func_name": "check_bound", "docstring": "checks if the string is within the specified bound,\nif it gets out of bound, error out by printing sub-string from index `beg` to`end`,\nwhere `beg` & `end` is the beginning and end index of sub-string, respectively", "repo": "uutils/coreutils", "path": "src/uu/stat/src/stat.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/stat/src/stat.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8ea0ba02d297b8947298c8170aacd4a8b6c2cc1578db205e6542dc9cd12bedf7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pad_and_print\n\nDocumentation:\npads the string with zeroes or spaces and prints it\n\n# Example\n```ignore\nuu_stat::pad_and_print(\"1\", false, 5, Padding::Zero) == \"00001\";\n```\ncurrently only supports '0' & ' ' as the padding character\nbecause the format specification of print! does not support general\nfill characters.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn pad_and_print(result: &str, left: bool, width: usize, padding: Padding) {\n match (left, padding) {\n (false, Padding::Zero) => print!(\"{result:0>width$}\"),\n (false, Padding::Space) => print!(\"{result:>width$}\"),\n (true, Padding::Zero) => print!(\"{result:0 print!(\"{result: print_str(s, &flags, width, precision),\n OutputType::Integer(num) => print_integer(*num, &flags, width, precision, padding_char),\n OutputType::Unsigned(num) => print_unsigned(*num, &flags, width, precision, padding_char),\n OutputType::UnsignedOct(num) => {\n print_unsigned_oct(*num, &flags, width, precision, padding_char);\n }\n OutputType::UnsignedHex(num) => {\n print_unsigned_hex(*num, &flags, width, precision, padding_char);\n }\n OutputType::Float(num) => {\n print_float(*num, &flags, width, precision, padding_char);\n }\n OutputType::Unknown => print!(\"?\"),\n }\n}\n```"}], "func_name": "print_it", "docstring": "Prints a formatted output based on the provided output type, flags, width, and precision.\n\n# Arguments\n\n* `output` - A reference to the OutputType enum containing the value to be printed.\n* `flags` - A Flags struct containing formatting flags.\n* `width` - The width of the field for the printed output.\n* `precision` - How many digits of precision, if any.\n\nThis function delegates the printing process to more specialized functions depending on the output type.", "repo": "uutils/coreutils", "path": "src/uu/stat/src/stat.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/stat/src/stat.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8cdc2dae530e9162bf3690e55f3e3692280c99adf35f3ec7d0d111c81f3fe6a2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: determine_padding_char\n\nDocumentation:\nDetermines the padding character based on the provided flags and precision.\n\n# Arguments\n\n* `flags` - A reference to the Flags struct containing formatting flags.\n\n# Returns\n\n* Padding - An instance of the Padding enum representing the padding character.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn determine_padding_char(flags: &Flags) -> Padding {\n if flags.zero && !flags.left {\n Padding::Zero\n } else {\n Padding::Space\n }\n}\n```"}], "func_name": "determine_padding_char", "docstring": "Determines the padding character based on the provided flags and precision.\n\n# Arguments\n\n* `flags` - A reference to the Flags struct containing formatting flags.\n\n# Returns\n\n* Padding - An instance of the Padding enum representing the padding character.", "repo": "uutils/coreutils", "path": "src/uu/stat/src/stat.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/stat/src/stat.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "19ff3ceb898ed88a3e99746d44a4dfb32d0b971017341f9b6c982ddc2259f0d8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_str\n\nDocumentation:\nPrints a string value based on the provided flags, width, and precision.\n\n# Arguments\n\n* `s` - The string to be printed.\n* `flags` - A reference to the Flags struct containing formatting flags.\n* `width` - The width of the field for the printed string.\n* `precision` - How many digits of precision, if any.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_str(s: &str, flags: &Flags, width: usize, precision: Precision) {\n let s = match precision {\n Precision::Number(p) if p < s.len() => &s[..p],\n _ => s,\n };\n pad_and_print(s, flags.left, width, Padding::Space);\n}\n```"}], "func_name": "print_str", "docstring": "Prints a string value based on the provided flags, width, and precision.\n\n# Arguments\n\n* `s` - The string to be printed.\n* `flags` - A reference to the Flags struct containing formatting flags.\n* `width` - The width of the field for the printed string.\n* `precision` - How many digits of precision, if any.", "repo": "uutils/coreutils", "path": "src/uu/stat/src/stat.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/stat/src/stat.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2afcd331ac8cfadcc8218e6fdcf38c18139e0293409a21a3cb274b72fae6caeb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_integer\n\nDocumentation:\nPrints an integer value based on the provided flags, width, and precision.\n\n# Arguments\n\n* `num` - The integer value to be printed.\n* `flags` - A reference to the Flags struct containing formatting flags.\n* `width` - The width of the field for the printed integer.\n* `precision` - How many digits of precision, if any.\n* `padding_char` - The padding character as determined by `determine_padding_char`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_integer(\n num: i64,\n flags: &Flags,\n width: usize,\n precision: Precision,\n padding_char: Padding,\n) {\n let num = num.to_string();\n let arg = if flags.group {\n group_num(&num)\n } else {\n Cow::Borrowed(num.as_str())\n };\n let prefix = if flags.sign {\n \"+\"\n } else if flags.space {\n \" \"\n } else {\n \"\"\n };\n let extended = match precision {\n Precision::NotSpecified => format!(\"{prefix}{arg}\"),\n Precision::NoNumber => format!(\"{prefix}{arg}\"),\n Precision::Number(p) => format!(\"{prefix}{arg:0>p$}\"),\n };\n pad_and_print(&extended, flags.left, width, padding_char);\n}\n```"}], "func_name": "print_integer", "docstring": "Prints an integer value based on the provided flags, width, and precision.\n\n# Arguments\n\n* `num` - The integer value to be printed.\n* `flags` - A reference to the Flags struct containing formatting flags.\n* `width` - The width of the field for the printed integer.\n* `precision` - How many digits of precision, if any.\n* `padding_char` - The padding character as determined by `determine_padding_char`.", "repo": "uutils/coreutils", "path": "src/uu/stat/src/stat.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/stat/src/stat.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5d193b2a0acd15fdbb5706cb69ff8347f113de30e20efca86bee20bd5e62f36"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: precision_trunc\n\nDocumentation:\nTruncate a float to the given number of digits after the decimal point.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn precision_trunc(num: f64, precision: Precision) -> String {\n // GNU `stat` doesn't round, it just seems to truncate to the\n // given precision:\n //\n // $ stat -c \"%.5Y\" /dev/pts/ptmx\n // 1736344012.76399\n // $ stat -c \"%.4Y\" /dev/pts/ptmx\n // 1736344012.7639\n // $ stat -c \"%.3Y\" /dev/pts/ptmx\n // 1736344012.763\n //\n // Contrast this with `printf`, which seems to round the\n // numbers:\n //\n // $ printf \"%.5f\\n\" 1736344012.76399\n // 1736344012.76399\n // $ printf \"%.4f\\n\" 1736344012.76399\n // 1736344012.7640\n // $ printf \"%.3f\\n\" 1736344012.76399\n // 1736344012.764\n //\n let num_str = num.to_string();\n let n = num_str.len();\n match (num_str.find('.'), precision) {\n (None, Precision::NotSpecified) => num_str,\n (None, Precision::NoNumber) => num_str,\n (None, Precision::Number(0)) => num_str,\n (None, Precision::Number(p)) => format!(\"{num_str}.{zeros}\", zeros = \"0\".repeat(p)),\n (Some(i), Precision::NotSpecified) => num_str[..i].to_string(),\n (Some(_), Precision::NoNumber) => num_str,\n (Some(i), Precision::Number(0)) => num_str[..i].to_string(),\n (Some(i), Precision::Number(p)) if p < n - i => num_str[..i + 1 + p].to_string(),\n (Some(i), Precision::Number(p)) => {\n format!(\"{num_str}{zeros}\", zeros = \"0\".repeat(p - (n - i - 1)))\n }\n }\n}\n```"}], "func_name": "precision_trunc", "docstring": "Truncate a float to the given number of digits after the decimal point.", "repo": "uutils/coreutils", "path": "src/uu/stat/src/stat.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/stat/src/stat.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "db50534339ab53fa6731354fc572484ac2bb819c51099b3f1c276ade90c48477"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_unsigned\n\nDocumentation:\nPrints an unsigned integer value based on the provided flags, width, and precision.\n\n# Arguments\n\n* `num` - The unsigned integer value to be printed.\n* `flags` - A reference to the Flags struct containing formatting flags.\n* `width` - The width of the field for the printed unsigned integer.\n* `precision` - How many digits of precision, if any.\n* `padding_char` - The padding character as determined by `determine_padding_char`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_unsigned(\n num: u64,\n flags: &Flags,\n width: usize,\n precision: Precision,\n padding_char: Padding,\n) {\n let num = num.to_string();\n let s = if flags.group {\n group_num(&num)\n } else {\n Cow::Borrowed(num.as_str())\n };\n let s = match precision {\n Precision::NotSpecified => s,\n Precision::NoNumber => s,\n Precision::Number(p) => format!(\"{s:0>p$}\").into(),\n };\n pad_and_print(&s, flags.left, width, padding_char);\n}\n```"}], "func_name": "print_unsigned", "docstring": "Prints an unsigned integer value based on the provided flags, width, and precision.\n\n# Arguments\n\n* `num` - The unsigned integer value to be printed.\n* `flags` - A reference to the Flags struct containing formatting flags.\n* `width` - The width of the field for the printed unsigned integer.\n* `precision` - How many digits of precision, if any.\n* `padding_char` - The padding character as determined by `determine_padding_char`.", "repo": "uutils/coreutils", "path": "src/uu/stat/src/stat.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/stat/src/stat.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fefd7234863dc742bf33f57e3135da4440e489435db3d070225287ca4fe8f739"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_unsigned_oct\n\nDocumentation:\nPrints an unsigned octal integer value based on the provided flags, width, and precision.\n\n# Arguments\n\n* `num` - The unsigned octal integer value to be printed.\n* `flags` - A reference to the Flags struct containing formatting flags.\n* `width` - The width of the field for the printed unsigned octal integer.\n* `precision` - How many digits of precision, if any.\n* `padding_char` - The padding character as determined by `determine_padding_char`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_unsigned_oct(\n num: u32,\n flags: &Flags,\n width: usize,\n precision: Precision,\n padding_char: Padding,\n) {\n let prefix = if flags.alter { \"0\" } else { \"\" };\n let s = match precision {\n Precision::NotSpecified => format!(\"{prefix}{num:o}\"),\n Precision::NoNumber => format!(\"{prefix}{num:o}\"),\n Precision::Number(p) => format!(\"{prefix}{num:0>p$o}\"),\n };\n pad_and_print(&s, flags.left, width, padding_char);\n}\n```"}], "func_name": "print_unsigned_oct", "docstring": "Prints an unsigned octal integer value based on the provided flags, width, and precision.\n\n# Arguments\n\n* `num` - The unsigned octal integer value to be printed.\n* `flags` - A reference to the Flags struct containing formatting flags.\n* `width` - The width of the field for the printed unsigned octal integer.\n* `precision` - How many digits of precision, if any.\n* `padding_char` - The padding character as determined by `determine_padding_char`.", "repo": "uutils/coreutils", "path": "src/uu/stat/src/stat.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/stat/src/stat.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0b7cfbfd35c3b0e5cffed5b99d6bf0e10321835436b2f08deb5364600cc5f0e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_unsigned_hex\n\nDocumentation:\nPrints an unsigned hexadecimal integer value based on the provided flags, width, and precision.\n\n# Arguments\n\n* `num` - The unsigned hexadecimal integer value to be printed.\n* `flags` - A reference to the Flags struct containing formatting flags.\n* `width` - The width of the field for the printed unsigned hexadecimal integer.\n* `precision` - How many digits of precision, if any.\n* `padding_char` - The padding character as determined by `determine_padding_char`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_unsigned_hex(\n num: u64,\n flags: &Flags,\n width: usize,\n precision: Precision,\n padding_char: Padding,\n) {\n let prefix = if flags.alter { \"0x\" } else { \"\" };\n let s = match precision {\n Precision::NotSpecified => format!(\"{prefix}{num:x}\"),\n Precision::NoNumber => format!(\"{prefix}{num:x}\"),\n Precision::Number(p) => format!(\"{prefix}{num:0>p$x}\"),\n };\n pad_and_print(&s, flags.left, width, padding_char);\n}\n```"}], "func_name": "print_unsigned_hex", "docstring": "Prints an unsigned hexadecimal integer value based on the provided flags, width, and precision.\n\n# Arguments\n\n* `num` - The unsigned hexadecimal integer value to be printed.\n* `flags` - A reference to the Flags struct containing formatting flags.\n* `width` - The width of the field for the printed unsigned hexadecimal integer.\n* `precision` - How many digits of precision, if any.\n* `padding_char` - The padding character as determined by `determine_padding_char`.", "repo": "uutils/coreutils", "path": "src/uu/stat/src/stat.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/stat/src/stat.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad1c1a392c30cd671f8834e5cd37a483bb54d85ad7df1bbb74c4b5a7cfb2f620"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: buffer_tac_regex\n\nDocumentation:\nPrint lines of a buffer in reverse, with line separator given as a regex.\n\n`data` contains the bytes of the file.\n\n`pattern` is the regular expression given as a\n[`regex::bytes::Regex`] (not a [`regex::Regex`], since the input is\ngiven as a slice of bytes). If `before` is `true`, then each match\nof this pattern in `data` is interpreted as the start of a line. If\n`before` is `false`, then each match of this pattern is interpreted\nas the end of a line.\n\nThis function writes each line in `data` to [`std::io::Stdout`] in\nreverse.\n\n# Errors\n\nIf there is a problem writing to `stdout`, then this function\nreturns [`std::io::Error`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn buffer_tac_regex(\n data: &[u8],\n pattern: ®ex::bytes::Regex,\n before: bool,\n) -> std::io::Result<()> {\n let out = stdout();\n let mut out = BufWriter::new(out.lock());\n\n // The index of the line separator for the current line.\n //\n // As we scan through the `data` from right to left, we update this\n // variable each time we find a new line separator. We restrict our\n // regular expression search to only those bytes up to the line\n // separator.\n let mut this_line_end = data.len();\n\n // The index of the start of the next line in the `data`.\n //\n // As we scan through the `data` from right to left, we update this\n // variable each time we find a new line.\n //\n // If `before` is `true`, then each line starts immediately before\n // the line separator. Otherwise, each line starts immediately after\n // the line separator.\n let mut following_line_start = data.len();\n\n // Iterate over each byte in the buffer in reverse. When we find a\n // line separator, write the line to stdout.\n //\n // The `before` flag controls whether the line separator appears at\n // the end of the line (as in \"abc\\ndef\\n\") or at the beginning of\n // the line (as in \"/abc/def\").\n for i in (0..data.len()).rev() {\n // Determine if there is a match for `pattern` starting at index\n // `i` in `data`. Only search up to the line ending that was\n // found previously.\n if let Some(match_) = pattern.find_at(&data[..this_line_end], i) {\n // Record this index as the ending of the current line.\n this_line_end = i;\n\n // The length of the match (that is, the line separator), in bytes.\n let slen = match_.end() - match_.start();\n\n if before {\n out.write_all(&data[i..following_line_start])?;\n following_line_start = i;\n } else {\n out.write_all(&data[i + slen..following_line_start])?;\n following_line_start = i + slen;\n }\n }\n }\n\n // After the loop terminates, write whatever bytes are remaining at\n // the beginning of the buffer.\n out.write_all(&data[0..following_line_start])?;\n out.flush()?;\n Ok(())\n}\n```"}], "func_name": "buffer_tac_regex", "docstring": "Print lines of a buffer in reverse, with line separator given as a regex.\n\n`data` contains the bytes of the file.\n\n`pattern` is the regular expression given as a\n[`regex::bytes::Regex`] (not a [`regex::Regex`], since the input is\ngiven as a slice of bytes). If `before` is `true`, then each match\nof this pattern in `data` is interpreted as the start of a line. If\n`before` is `false`, then each match of this pattern is interpreted\nas the end of a line.\n\nThis function writes each line in `data` to [`std::io::Stdout`] in\nreverse.\n\n# Errors\n\nIf there is a problem writing to `stdout`, then this function\nreturns [`std::io::Error`].", "repo": "uutils/coreutils", "path": "src/uu/tac/src/tac.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tac/src/tac.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44a3f910735c799d0228d6f528c40602acdb2b8417b30855b8aa780ea6701c99"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: buffer_tac\n\nDocumentation:\nWrite lines from `data` to stdout in reverse.\n\nThis function writes to [`stdout`] each line appearing in `data`,\nstarting with the last line and ending with the first line. The\n`separator` parameter defines what characters to use as a line\nseparator.\n\nIf `before` is `false`, then this function assumes that the\n`separator` appears at the end of each line, as in `\"abc\\ndef\\n\"`.\nIf `before` is `true`, then this function assumes that the\n`separator` appears at the beginning of each line, as in\n`\"/abc/def\"`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn buffer_tac(data: &[u8], before: bool, separator: &str) -> std::io::Result<()> {\n let out = stdout();\n let mut out = BufWriter::new(out.lock());\n\n // The number of bytes in the line separator.\n let slen = separator.len();\n\n // The index of the start of the next line in the `data`.\n //\n // As we scan through the `data` from right to left, we update this\n // variable each time we find a new line.\n //\n // If `before` is `true`, then each line starts immediately before\n // the line separator. Otherwise, each line starts immediately after\n // the line separator.\n let mut following_line_start = data.len();\n\n // Iterate over each byte in the buffer in reverse. When we find a\n // line separator, write the line to stdout.\n //\n // The `before` flag controls whether the line separator appears at\n // the end of the line (as in \"abc\\ndef\\n\") or at the beginning of\n // the line (as in \"/abc/def\").\n for i in memmem::rfind_iter(data, separator) {\n if before {\n out.write_all(&data[i..following_line_start])?;\n following_line_start = i;\n } else {\n out.write_all(&data[i + slen..following_line_start])?;\n following_line_start = i + slen;\n }\n }\n\n // After the loop terminates, write whatever bytes are remaining at\n // the beginning of the buffer.\n out.write_all(&data[0..following_line_start])?;\n out.flush()?;\n Ok(())\n}\n```"}], "func_name": "buffer_tac", "docstring": "Write lines from `data` to stdout in reverse.\n\nThis function writes to [`stdout`] each line appearing in `data`,\nstarting with the last line and ending with the first line. The\n`separator` parameter defines what characters to use as a line\nseparator.\n\nIf `before` is `false`, then this function assumes that the\n`separator` appears at the end of each line, as in `\"abc\\ndef\\n\"`.\nIf `before` is `true`, then this function assumes that the\n`separator` appears at the beginning of each line, as in\n`\"/abc/def\"`.", "repo": "uutils/coreutils", "path": "src/uu/tac/src/tac.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tac/src/tac.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc30e6ebb650aec9de8ae6c7b6b3b40b401f66612c37a8a857abc6c51a3d9a86"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_warnings\n\nDocumentation:\nCheck [`Settings`] for problematic configurations of tail originating from user provided\ncommand line arguments and print appropriate warnings.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check_warnings(&self) {\n if self.retry {\n if self.follow.is_none() {\n show_warning!(\"{}\", get_message(\"tail-warning-retry-ignored\"));\n } else if self.follow == Some(FollowMode::Descriptor) {\n show_warning!(\"{}\", get_message(\"tail-warning-retry-only-effective\"));\n }\n }\n\n if self.pid != 0 {\n if self.follow.is_none() {\n show_warning!(\"{}\", get_message(\"tail-warning-pid-ignored\"));\n } else if !platform::supports_pid_checks(self.pid) {\n show_warning!(\"{}\", get_message(\"tail-warning-pid-not-supported\"));\n }\n }\n\n // This warning originates from gnu's tail implementation of the equivalent warning. If the\n // user wants to follow stdin, but tail is blocking indefinitely anyways, because of stdin\n // as `tty` (but no otherwise blocking stdin), then we print a warning that `--follow`\n // cannot be applied under these circumstances and is therefore ineffective.\n if self.follow.is_some() && self.has_stdin() {\n let blocking_stdin = self.pid == 0\n && self.follow == Some(FollowMode::Descriptor)\n && self.num_inputs() == 1\n && Handle::stdin().is_ok_and(|handle| {\n handle\n .as_file()\n .metadata()\n .is_ok_and(|meta| !meta.is_file())\n });\n\n if !blocking_stdin && std::io::stdin().is_terminal() {\n show_warning!(\n \"{}\",\n get_message(\"tail-warning-following-stdin-ineffective\")\n );\n }\n }\n }\n```"}], "func_name": "check_warnings", "docstring": "Check [`Settings`] for problematic configurations of tail originating from user provided\ncommand line arguments and print appropriate warnings.", "repo": "uutils/coreutils", "path": "src/uu/tail/src/args.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/args.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8886a51734346f6b810efe6bfa3b9fab9c454a2119240bfe04a192088a43882c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: verify\n\nDocumentation:\nVerify [`Settings`] and try to find unsolvable misconfigurations of tail originating from\nuser provided command line arguments. In contrast to [`Settings::check_warnings`] these\nmisconfigurations usually lead to the immediate exit or abortion of the running `tail`\nprocess.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn verify(&self) -> VerificationResult {\n // Mimic GNU's tail for `tail -F`\n if self.inputs.iter().any(|i| i.is_stdin()) && self.follow == Some(FollowMode::Name) {\n return VerificationResult::CannotFollowStdinByName;\n }\n\n // Mimic GNU's tail for -[nc]0 without -f and exit immediately\n if self.follow.is_none()\n && matches!(\n self.mode,\n FilterMode::Lines(Signum::MinusZero, _) | FilterMode::Bytes(Signum::MinusZero)\n )\n {\n return VerificationResult::NoOutput;\n }\n\n VerificationResult::Ok\n }\n```"}], "func_name": "verify", "docstring": "Verify [`Settings`] and try to find unsolvable misconfigurations of tail originating from\nuser provided command line arguments. In contrast to [`Settings::check_warnings`] these\nmisconfigurations usually lead to the immediate exit or abortion of the running `tail`\nprocess.", "repo": "uutils/coreutils", "path": "src/uu/tail/src/args.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/args.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b00ed4fb0b3859cef83a07f404544ac9aad1923e8791cb4bec08ef95b4d6462"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_chunk\n\nDocumentation:\nCreate a new chunk from an existing chunk. The new chunk's buffer will be copied from the\nold chunk's buffer, copying the slice `[offset..old_chunk.bytes]` into the new chunk's\nbuffer but starting at 0 instead of offset. If the offset is larger or equal to\n`chunk.lines` then a new empty `BytesChunk` is returned.\n\n# Arguments\n\n* `chunk`: The chunk to create a new `BytesChunk` chunk from\n* `offset`: Start to copy the old chunk's buffer from this position. May not be larger\nthan `chunk.bytes`.\n\n# Examples\n\n```rust,ignore\nlet mut chunk = BytesChunk::new();\nchunk.buffer[1] = 1;\nchunk.bytes = 2;\nlet new_chunk = BytesChunk::from_chunk(&chunk, 0);\nassert_eq!(2, new_chunk.get_buffer().len());\nassert_eq!(&[0, 1], new_chunk.get_buffer());\n\nlet new_chunk = BytesChunk::from_chunk(&chunk, 1);\nassert_eq!(1, new_chunk.get_buffer().len());\nassert_eq!(&[1], new_chunk.get_buffer());\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_chunk(chunk: &Self, offset: usize) -> Self {\n if offset >= chunk.bytes {\n return Self::new();\n }\n\n let mut buffer: ChunkBuffer = [0; BUFFER_SIZE];\n let slice = chunk.get_buffer_with(offset);\n buffer[..slice.len()].copy_from_slice(slice);\n Self {\n buffer,\n bytes: chunk.bytes - offset,\n }\n }\n```"}], "func_name": "from_chunk", "docstring": "Create a new chunk from an existing chunk. The new chunk's buffer will be copied from the\nold chunk's buffer, copying the slice `[offset..old_chunk.bytes]` into the new chunk's\nbuffer but starting at 0 instead of offset. If the offset is larger or equal to\n`chunk.lines` then a new empty `BytesChunk` is returned.\n\n# Arguments\n\n* `chunk`: The chunk to create a new `BytesChunk` chunk from\n* `offset`: Start to copy the old chunk's buffer from this position. May not be larger\nthan `chunk.bytes`.\n\n# Examples\n\n```rust,ignore\nlet mut chunk = BytesChunk::new();\nchunk.buffer[1] = 1;\nchunk.bytes = 2;\nlet new_chunk = BytesChunk::from_chunk(&chunk, 0);\nassert_eq!(2, new_chunk.get_buffer().len());\nassert_eq!(&[0, 1], new_chunk.get_buffer());\n\nlet new_chunk = BytesChunk::from_chunk(&chunk, 1);\nassert_eq!(1, new_chunk.get_buffer().len());\nassert_eq!(&[1], new_chunk.get_buffer());\n```", "repo": "uutils/coreutils", "path": "src/uu/tail/src/chunks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/chunks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ed8e386a41d0f35bccd5638e5e782a7cb006a22c96ab2a20c0a2b78beb6885e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fill\n\nDocumentation:\nFills `self.buffer` with maximal [`BUFFER_SIZE`] number of bytes, draining the reader by\nthat number of bytes. If EOF is reached (so 0 bytes are read), then returns\n[`UResult`] or else the result with [`Some(bytes)`] where bytes is the number of bytes\nread from the source.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fill(&mut self, filehandle: &mut impl BufRead) -> UResult> {\n let num_bytes = filehandle.read(&mut self.buffer)?;\n self.bytes = num_bytes;\n if num_bytes == 0 {\n return Ok(None);\n }\n\n Ok(Some(self.bytes))\n }\n```"}], "func_name": "fill", "docstring": "Fills `self.buffer` with maximal [`BUFFER_SIZE`] number of bytes, draining the reader by\nthat number of bytes. If EOF is reached (so 0 bytes are read), then returns\n[`UResult`] or else the result with [`Some(bytes)`] where bytes is the number of bytes\nread from the source.", "repo": "uutils/coreutils", "path": "src/uu/tail/src/chunks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/chunks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ed6e148efc71b19129944dfe8d1d42dd77de08b73599bdb91a5855c100e7ce26"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new [`BytesChunkBuffer`].\n\n# Arguments\n\n* `num_print`: The number of bytes to print\n\n# Examples\n\n```rust,ignore\nlet mut chunk = BytesChunk::new();\nchunk.buffer[1] = 1;\nchunk.bytes = 2;\nlet new_chunk = BytesChunk::from_chunk(&chunk, 0);\nassert_eq!(2, new_chunk.get_buffer().len());\nassert_eq!(&[0, 1], new_chunk.get_buffer());\n\nlet new_chunk = BytesChunk::from_chunk(&chunk, 1);\nassert_eq!(1, new_chunk.get_buffer().len());\nassert_eq!(&[1], new_chunk.get_buffer());\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(num_print: u64) -> Self {\n Self {\n bytes: 0,\n num_print,\n chunks: VecDeque::new(),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new [`BytesChunkBuffer`].\n\n# Arguments\n\n* `num_print`: The number of bytes to print\n\n# Examples\n\n```rust,ignore\nlet mut chunk = BytesChunk::new();\nchunk.buffer[1] = 1;\nchunk.bytes = 2;\nlet new_chunk = BytesChunk::from_chunk(&chunk, 0);\nassert_eq!(2, new_chunk.get_buffer().len());\nassert_eq!(&[0, 1], new_chunk.get_buffer());\n\nlet new_chunk = BytesChunk::from_chunk(&chunk, 1);\nassert_eq!(1, new_chunk.get_buffer().len());\nassert_eq!(&[1], new_chunk.get_buffer());\n```", "repo": "uutils/coreutils", "path": "src/uu/tail/src/chunks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/chunks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a4f42fea5130f02e39a286c1de442b74521136081ac290128df12cd9033bb6cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fill\n\nDocumentation:\nFills this buffer with chunks and consumes the reader completely. This method ensures that\nthere are exactly as many chunks as needed to match `self.num_print` bytes, so there are\nin sum exactly `self.num_print` bytes stored in all chunks. The method returns an iterator\nover these chunks. If there are no chunks, for example because the piped stdin contained no\nbytes, or `num_print = 0` then `iterator.next` returns None.\n\n# Examples\n\n```rust,ignore\nuse crate::chunks::BytesChunkBuffer;\nuse std::io::{BufReader, Cursor};\n\nlet mut reader = BufReader::new(Cursor::new(\"\"));\nlet num_print = 0;\nlet mut chunks = BytesChunkBuffer::new(num_print);\nchunks.fill(&mut reader).unwrap();\n\nlet mut reader = BufReader::new(Cursor::new(\"a\"));\nlet num_print = 1;\nlet mut chunks = BytesChunkBuffer::new(num_print);\nchunks.fill(&mut reader).unwrap();\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fill(&mut self, reader: &mut impl BufRead) -> UResult<()> {\n let mut chunk = Box::new(BytesChunk::new());\n\n // fill chunks with all bytes from reader and reuse already instantiated chunks if possible\n while chunk.fill(reader)?.is_some() {\n self.bytes += chunk.bytes as u64;\n self.chunks.push_back(chunk);\n\n let first = &self.chunks[0];\n if self.bytes - first.bytes as u64 > self.num_print {\n chunk = self.chunks.pop_front().unwrap();\n self.bytes -= chunk.bytes as u64;\n } else {\n chunk = Box::new(BytesChunk::new());\n }\n }\n\n // quit early if there are no chunks for example in case the pipe was empty\n if self.chunks.is_empty() {\n return Ok(());\n }\n\n let chunk = self.chunks.pop_front().unwrap();\n\n // calculate the offset in the first chunk and put the calculated chunk as first element in\n // the self.chunks collection. The calculated offset must be in the range 0 to BUFFER_SIZE\n // and is therefore safely convertible to a usize without losses.\n let offset = self.bytes.saturating_sub(self.num_print) as usize;\n self.chunks\n .push_front(Box::new(BytesChunk::from_chunk(&chunk, offset)));\n\n Ok(())\n }\n```"}], "func_name": "fill", "docstring": "Fills this buffer with chunks and consumes the reader completely. This method ensures that\nthere are exactly as many chunks as needed to match `self.num_print` bytes, so there are\nin sum exactly `self.num_print` bytes stored in all chunks. The method returns an iterator\nover these chunks. If there are no chunks, for example because the piped stdin contained no\nbytes, or `num_print = 0` then `iterator.next` returns None.\n\n# Examples\n\n```rust,ignore\nuse crate::chunks::BytesChunkBuffer;\nuse std::io::{BufReader, Cursor};\n\nlet mut reader = BufReader::new(Cursor::new(\"\"));\nlet num_print = 0;\nlet mut chunks = BytesChunkBuffer::new(num_print);\nchunks.fill(&mut reader).unwrap();\n\nlet mut reader = BufReader::new(Cursor::new(\"a\"));\nlet num_print = 1;\nlet mut chunks = BytesChunkBuffer::new(num_print);\nchunks.fill(&mut reader).unwrap();\n```", "repo": "uutils/coreutils", "path": "src/uu/tail/src/chunks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/chunks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ccbf3adca272da69e6a8c0b93fcb587c435984aac35a466b650170c6cce86fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fill\n\nDocumentation:\nFills `self.buffer` with maximal [`BUFFER_SIZE`] number of bytes, draining the reader by\nthat number of bytes. This function works like the [`BytesChunk::fill`] function besides\nthat this function also counts and stores the number of lines encountered while reading from\nthe `filehandle`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fill(&mut self, filehandle: &mut impl BufRead) -> UResult> {\n match self.chunk.fill(filehandle)? {\n None => {\n self.lines = 0;\n Ok(None)\n }\n Some(bytes) => {\n self.lines = self.count_lines();\n Ok(Some(bytes))\n }\n }\n }\n```"}], "func_name": "fill", "docstring": "Fills `self.buffer` with maximal [`BUFFER_SIZE`] number of bytes, draining the reader by\nthat number of bytes. This function works like the [`BytesChunk::fill`] function besides\nthat this function also counts and stores the number of lines encountered while reading from\nthe `filehandle`.", "repo": "uutils/coreutils", "path": "src/uu/tail/src/chunks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/chunks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94c7a9a893a4ddcf353edce3d0e0b17cee936da97cf277c19777aa08f2523480"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_lines\n\nDocumentation:\nPrint the bytes contained in this buffer calculated with the given offset in number of\nlines.\n\n# Arguments\n\n* `writer`: must implement [`Write`]\n* `offset`: An offset in number of lines.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn print_lines(&self, writer: &mut impl Write, offset: usize) -> UResult<()> {\n self.print_bytes(writer, self.calculate_bytes_offset_from(offset))\n }\n```"}], "func_name": "print_lines", "docstring": "Print the bytes contained in this buffer calculated with the given offset in number of\nlines.\n\n# Arguments\n\n* `writer`: must implement [`Write`]\n* `offset`: An offset in number of lines.", "repo": "uutils/coreutils", "path": "src/uu/tail/src/chunks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/chunks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "99b746b879b7e6374eb3d8c9856b2f138933c7029fbb78ad67835ff9b29d9210"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_bytes\n\nDocumentation:\nPrint the bytes contained in this buffer beginning from the given offset in number of bytes.\n\n# Arguments\n\n* `writer`: must implement [`Write`]\n* `offset`: An offset in number of bytes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn print_bytes(&self, writer: &mut impl Write, offset: usize) -> UResult<()> {\n writer.write_all(self.get_buffer_with(offset))?;\n Ok(())\n }\n```"}], "func_name": "print_bytes", "docstring": "Print the bytes contained in this buffer beginning from the given offset in number of bytes.\n\n# Arguments\n\n* `writer`: must implement [`Write`]\n* `offset`: An offset in number of bytes.", "repo": "uutils/coreutils", "path": "src/uu/tail/src/chunks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/chunks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "28154015eaa36235c960af3cd5b6feecc085bdb1da4c9a926c4783384f90a964"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fill\n\nDocumentation:\nFills this buffer with chunks and consumes the reader completely. This method ensures that\nthere are exactly as many chunks as needed to match `self.num_print` lines, so there are\nin sum exactly `self.num_print` lines stored in all chunks. The method returns an iterator\nover these chunks. If there are no chunks, for example because the piped stdin contained no\nlines, or `num_print = 0` then `iterator.next` will return None.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fill(&mut self, reader: &mut impl BufRead) -> UResult<()> {\n let mut chunk = Box::new(LinesChunk::new(self.delimiter));\n\n while chunk.fill(reader)?.is_some() {\n self.lines += chunk.lines as u64;\n self.chunks.push_back(chunk);\n\n let first = &self.chunks[0];\n if self.lines - first.lines as u64 > self.num_print {\n chunk = self.chunks.pop_front().unwrap();\n\n self.lines -= chunk.lines as u64;\n } else {\n chunk = Box::new(LinesChunk::new(self.delimiter));\n }\n }\n\n if self.chunks.is_empty() {\n // chunks is empty when a file is empty so quitting early here\n return Ok(());\n } else {\n let length = &self.chunks.len();\n let last = &mut self.chunks[length - 1];\n if !last.get_buffer().ends_with(&[self.delimiter]) {\n last.lines += 1;\n self.lines += 1;\n }\n }\n\n // skip unnecessary chunks and save the first chunk which may hold some lines we have to\n // print\n let chunk = loop {\n // it's safe to call unwrap here because there is at least one chunk and sorting out\n // more chunks than exist shouldn't be possible.\n let chunk = self.chunks.pop_front().unwrap();\n\n // skip is true as long there are enough lines left in the other stored chunks.\n let skip = self.lines - chunk.lines as u64 > self.num_print;\n if skip {\n self.lines -= chunk.lines as u64;\n } else {\n break chunk;\n }\n };\n\n // Calculate the number of lines to skip in the current chunk. The calculated value must be\n // in the range 0 to BUFFER_SIZE and is therefore safely convertible to a usize without\n // losses.\n let skip_lines = self.lines.saturating_sub(self.num_print) as usize;\n let chunk = LinesChunk::from_chunk(&chunk, skip_lines);\n self.chunks.push_front(Box::new(chunk));\n\n Ok(())\n }\n```"}], "func_name": "fill", "docstring": "Fills this buffer with chunks and consumes the reader completely. This method ensures that\nthere are exactly as many chunks as needed to match `self.num_print` lines, so there are\nin sum exactly `self.num_print` lines stored in all chunks. The method returns an iterator\nover these chunks. If there are no chunks, for example because the piped stdin contained no\nlines, or `num_print = 0` then `iterator.next` will return None.", "repo": "uutils/coreutils", "path": "src/uu/tail/src/chunks.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/chunks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1e4304e353ef1e0305817e020bca5b749822ef47e65d84723b8ac7ceac5d9fb6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_obsolete\n\nDocumentation:\nParses obsolete syntax\ntail -\\[NUM\\]\\[bcl\\]\\[f\\] and tail +\\[NUM\\]\\[bcl\\]\\[f\\]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_obsolete(src: &OsString) -> Option> {\n let Some(mut rest) = src.to_str() else {\n return Some(Err(ParseError::InvalidEncoding));\n };\n let sign = if let Some(r) = rest.strip_prefix('-') {\n rest = r;\n '-'\n } else if let Some(r) = rest.strip_prefix('+') {\n rest = r;\n '+'\n } else {\n return None;\n };\n\n let end_num = rest\n .find(|c: char| !c.is_ascii_digit())\n .unwrap_or(rest.len());\n let has_num = !rest[..end_num].is_empty();\n let num: u64 = if has_num {\n if let Ok(num) = rest[..end_num].parse() {\n num\n } else {\n return Some(Err(ParseError::OutOfRange));\n }\n } else {\n 10\n };\n rest = &rest[end_num..];\n\n let mode = if let Some(r) = rest.strip_prefix('l') {\n rest = r;\n 'l'\n } else if let Some(r) = rest.strip_prefix('c') {\n rest = r;\n 'c'\n } else if let Some(r) = rest.strip_prefix('b') {\n rest = r;\n 'b'\n } else {\n 'l'\n };\n\n let follow = rest.contains('f');\n if !rest.chars().all(|f| f == 'f') {\n // GNU allows an arbitrary amount of following fs, but nothing else\n if sign == '-' && has_num {\n return Some(Err(ParseError::Context));\n }\n return None;\n }\n\n let multiplier = if mode == 'b' { 512 } else { 1 };\n let Some(num) = num.checked_mul(multiplier) else {\n return Some(Err(ParseError::Overflow));\n };\n\n Some(Ok(ObsoleteArgs {\n num,\n plus: sign == '+',\n lines: mode == 'l',\n follow,\n }))\n}\n```"}], "func_name": "parse_obsolete", "docstring": "Parses obsolete syntax\ntail -\\[NUM\\]\\[bcl\\]\\[f\\] and tail +\\[NUM\\]\\[bcl\\]\\[f\\]", "repo": "uutils/coreutils", "path": "src/uu/tail/src/parse.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/parse.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "53647bdd4ef59d3d1ba9d5c74d3cf65c756f1b942f45805c49f97875eebd8503"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_seekable\n\nDocumentation:\nTest if File is seekable.\nSet the current position offset to `current_offset`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_seekable(&mut self, current_offset: u64) -> bool {\n self.stream_position().is_ok()\n && self.seek(SeekFrom::End(0)).is_ok()\n && self.seek(SeekFrom::Start(current_offset)).is_ok()\n }\n```"}], "func_name": "is_seekable", "docstring": "Test if File is seekable.\nSet the current position offset to `current_offset`.", "repo": "uutils/coreutils", "path": "src/uu/tail/src/paths.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/paths.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "43443825c4677484917ec377486d927a9764ab1f0acdd17bbf5b9dd2f2109808"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: got_truncated\n\nDocumentation:\nReturn true if the file was modified and is now shorter\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn got_truncated(&self, other: &Metadata) -> UResult {\n Ok(other.len() < self.len() && other.modified()? != self.modified()?)\n }\n```"}], "func_name": "got_truncated", "docstring": "Return true if the file was modified and is now shorter", "repo": "uutils/coreutils", "path": "src/uu/tail/src/paths.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/paths.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a7a3db53daa4f177ffaa000a64ac648bdf887d3e1aeaa85a253d75ce20471a61"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_orphan\n\nDocumentation:\nReturn true if `path` does not have an existing parent directory\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_orphan(&self) -> bool {\n !matches!(self.parent(), Some(parent) if parent.is_dir())\n }\n```"}], "func_name": "is_orphan", "docstring": "Return true if `path` does not have an existing parent directory", "repo": "uutils/coreutils", "path": "src/uu/tail/src/paths.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/paths.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17fed10d28cba05154ba447d92a6f1e9f7229f505893087dade9b85353ad9add"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bounded_tail\n\nDocumentation:\nWhen tail'ing a file, we do not need to read the whole file from start to\nfinish just to find the last n lines or bytes. Instead, we can seek to the\nend of the file, and then read the file \"backwards\" in blocks of size\n`BLOCK_SIZE` until we find the location of the first line/byte. This ends up\nbeing a nice performance win for very large files.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn bounded_tail(file: &mut File, settings: &Settings) {\n debug_assert!(!settings.presume_input_pipe);\n\n // Find the position in the file to start printing from.\n match &settings.mode {\n FilterMode::Lines(Signum::Negative(count), delimiter) => {\n backwards_thru_file(file, *count, *delimiter);\n }\n FilterMode::Lines(Signum::Positive(count), delimiter) if count > &1 => {\n let i = forwards_thru_file(file, *count - 1, *delimiter).unwrap();\n file.seek(SeekFrom::Start(i as u64)).unwrap();\n }\n FilterMode::Lines(Signum::MinusZero, _) => {\n return;\n }\n FilterMode::Bytes(Signum::Negative(count)) => {\n let len = file.seek(SeekFrom::End(0)).unwrap();\n file.seek(SeekFrom::End(-((*count).min(len) as i64)))\n .unwrap();\n }\n FilterMode::Bytes(Signum::Positive(count)) if count > &1 => {\n // GNU `tail` seems to index bytes and lines starting at 1, not\n // at 0. It seems to treat `+0` and `+1` as the same thing.\n file.seek(SeekFrom::Start(*count - 1)).unwrap();\n }\n FilterMode::Bytes(Signum::MinusZero) => {\n return;\n }\n _ => {}\n }\n\n // Print the target section of the file.\n let stdout = stdout();\n let mut stdout = stdout.lock();\n io::copy(file, &mut stdout).unwrap();\n}\n```"}], "func_name": "bounded_tail", "docstring": "When tail'ing a file, we do not need to read the whole file from start to\nfinish just to find the last n lines or bytes. Instead, we can seek to the\nend of the file, and then read the file \"backwards\" in blocks of size\n`BLOCK_SIZE` until we find the location of the first line/byte. This ends up\nbeing a nice performance win for very large files.", "repo": "uutils/coreutils", "path": "src/uu/tail/src/tail.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/tail.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a74a9209ae1d3ff8090d4338d0457023f7b05b409cc4dcdb8712c84961020ac8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nWrapper for HashMap::insert using Path::canonicalize\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert(&mut self, k: &Path, v: PathData, update_last: bool) {\n let k = Self::canonicalize_path(k);\n if update_last {\n self.last = Some(k.clone());\n }\n let _ = self.map.insert(k, v);\n }\n```"}], "func_name": "insert", "docstring": "Wrapper for HashMap::insert using Path::canonicalize", "repo": "uutils/coreutils", "path": "src/uu/tail/src/follow/files.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/follow/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e9b84327a0318466ab15e23d99d7435dca0e38d03e340a8165636b07d378050"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: canonicalize_path\n\nDocumentation:\nCanonicalize `path` if it is not already an absolute path\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn canonicalize_path(path: &Path) -> PathBuf {\n if path.is_relative() && !path.is_stdin() {\n if let Ok(p) = path.canonicalize() {\n return p;\n }\n }\n path.to_owned()\n }\n```"}], "func_name": "canonicalize_path", "docstring": "Canonicalize `path` if it is not already an absolute path", "repo": "uutils/coreutils", "path": "src/uu/tail/src/follow/files.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/follow/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f812ed4851b74353143841d66c484a7e8b77659997b7490d609e797c7f1aacc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: only_stdin_remaining\n\nDocumentation:\nReturn true if there is only stdin remaining\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn only_stdin_remaining(&self) -> bool {\n self.map.len() == 1 && (self.map.contains_key(Path::new(text::DASH)))\n }\n```"}], "func_name": "only_stdin_remaining", "docstring": "Return true if there is only stdin remaining", "repo": "uutils/coreutils", "path": "src/uu/tail/src/follow/files.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/follow/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fb0890d14b4cca9653056358a840c3b145f83031f1e79568426d2920874f31b3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: files_remaining\n\nDocumentation:\nReturn true if there is at least one \"tailable\" path (or stdin) remaining\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn files_remaining(&self) -> bool {\n for path in self.map.keys() {\n if path.is_tailable() || path.is_stdin() {\n return true;\n }\n }\n false\n }\n```"}], "func_name": "files_remaining", "docstring": "Return true if there is at least one \"tailable\" path (or stdin) remaining", "repo": "uutils/coreutils", "path": "src/uu/tail/src/follow/files.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/follow/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a304480b1c1aed94f781bdbe6198a0e97012987df70eda27f3dc276cd32d967"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: no_files_remaining\n\nDocumentation:\nReturns true if there are no files remaining\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn no_files_remaining(&self, settings: &Settings) -> bool {\n self.map.is_empty() || !self.files_remaining() && !settings.retry\n }\n```"}], "func_name": "no_files_remaining", "docstring": "Returns true if there are no files remaining", "repo": "uutils/coreutils", "path": "src/uu/tail/src/follow/files.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/follow/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2fcf1a2e585173e95c7bc8062a59d54613fcf9e43a64e285518da074dd2dc808"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_reader\n\nDocumentation:\nSet `reader` to None to indicate that `path` is not an existing file anymore.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reset_reader(&mut self, path: &Path) {\n self.get_mut(path).reader = None;\n }\n```"}], "func_name": "reset_reader", "docstring": "Set `reader` to None to indicate that `path` is not an existing file anymore.", "repo": "uutils/coreutils", "path": "src/uu/tail/src/follow/files.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/follow/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "509007001251de2abd025ea4b608029c7ddace5d0b4150be2716eb96df6dfcb8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_reader\n\nDocumentation:\nReopen the file at the monitored `path`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn update_reader(&mut self, path: &Path) -> UResult<()> {\n /*\n BUG: If it's not necessary to reopen a file, GNU's tail calls seek to offset 0.\n However we can't call seek here because `BufRead` does not implement `Seek`.\n As a workaround we always reopen the file even though this might not always\n be necessary.\n */\n self.get_mut(path)\n .reader\n .replace(Box::new(BufReader::new(File::open(path)?)));\n Ok(())\n }\n```"}], "func_name": "update_reader", "docstring": "Reopen the file at the monitored `path`", "repo": "uutils/coreutils", "path": "src/uu/tail/src/follow/files.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/follow/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c22735edb3582024f6a835f24cfd5395fc2cd7ed75162a2df8229d3c4ca02e9f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_metadata\n\nDocumentation:\nReload metadata from `path`, or `metadata`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn update_metadata(&mut self, path: &Path, metadata: Option) {\n self.get_mut(path).metadata = if metadata.is_some() {\n metadata\n } else {\n path.metadata().ok()\n };\n }\n```"}], "func_name": "update_metadata", "docstring": "Reload metadata from `path`, or `metadata`", "repo": "uutils/coreutils", "path": "src/uu/tail/src/follow/files.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/follow/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b7cdd0e4f940a27e458adf65925ba2e2d83d8928ce25dfd15852619835ae3c1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tail_file\n\nDocumentation:\nRead new data from `path` and print it to stdout\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn tail_file(&mut self, path: &Path, verbose: bool) -> UResult {\n let mut chunks = BytesChunkBuffer::new(u64::MAX);\n if let Some(reader) = self.get_mut(path).reader.as_mut() {\n chunks.fill(reader)?;\n }\n if chunks.has_data() {\n if self.needs_header(path, verbose) {\n let display_name = self.get(path).display_name.clone();\n self.header_printer.print(display_name.as_str());\n }\n\n let mut writer = BufWriter::new(stdout().lock());\n chunks.print(&mut writer)?;\n writer.flush()?;\n\n self.last.replace(path.to_owned());\n self.update_metadata(path, None);\n Ok(true)\n } else {\n Ok(false)\n }\n }\n```"}], "func_name": "tail_file", "docstring": "Read new data from `path` and print it to stdout", "repo": "uutils/coreutils", "path": "src/uu/tail/src/follow/files.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/follow/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "db9175c1e192a31a64bcee4fea00bd467204d93a0a848a65e3f0c453bf426b4f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: needs_header\n\nDocumentation:\nDecide if printing `path` needs a header based on when it was last printed\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn needs_header(&self, path: &Path, verbose: bool) -> bool {\n if verbose {\n if let Some(ref last) = self.last {\n !last.eq(&path)\n } else {\n true\n }\n } else {\n false\n }\n }\n```"}], "func_name": "needs_header", "docstring": "Decide if printing `path` needs a header based on when it was last printed", "repo": "uutils/coreutils", "path": "src/uu/tail/src/follow/files.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/follow/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0b473c62f92d2de640de4988a6a705edcbc840bc9f575d5abb5353f01e670116"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: watch_with_parent\n\nDocumentation:\nWrapper for `notify::Watcher::watch` to also add the parent directory of `path` if necessary.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn watch_with_parent(&mut self, path: &Path) -> UResult<()> {\n let mut path = path.to_owned();\n #[cfg(target_os = \"linux\")]\n if path.is_file() {\n /*\n NOTE: Using the parent directory instead of the file is a workaround.\n This workaround follows the recommendation of the notify crate authors:\n > On some platforms, if the `path` is renamed or removed while being watched, behavior may\n > be unexpected. See discussions in [#165] and [#166]. If less surprising behavior is wanted\n > one may non-recursively watch the _parent_ directory as well and manage related events.\n NOTE: Adding both: file and parent results in duplicate/wrong events.\n Tested for notify::InotifyWatcher and for notify::PollWatcher.\n */\n if let Some(parent) = path.parent() {\n // clippy::assigning_clones added with Rust 1.78\n // Rust version = 1.76 on OpenBSD stable/7.5\n #[cfg_attr(not(target_os = \"openbsd\"), allow(clippy::assigning_clones))]\n if parent.is_dir() {\n path = parent.to_owned();\n } else {\n path = PathBuf::from(\".\");\n }\n } else {\n return Err(USimpleError::new(\n 1,\n get_message_with_args(\n \"tail-error-cannot-watch-parent-directory\",\n HashMap::from([(\"path\".to_string(), path.display().to_string())]),\n ),\n ));\n };\n }\n if path.is_relative() {\n path = path.canonicalize()?;\n }\n\n // for syscalls: 2x \"inotify_add_watch\" (\"filename\" and \".\") and 1x \"inotify_rm_watch\"\n self.watch(&path, RecursiveMode::NonRecursive)?;\n Ok(())\n }\n```"}], "func_name": "watch_with_parent", "docstring": "Wrapper for `notify::Watcher::watch` to also add the parent directory of `path` if necessary.", "repo": "uutils/coreutils", "path": "src/uu/tail/src/follow/watch.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tail/src/follow/watch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8ff6f3a564b86c94bcc4bbff4bfb4c1ba58b30c18355622720d88196ccb4a0e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open\n\nDocumentation:\nTries to open the indicated file and return it. Reports an error if that's not possible.\nIf that error should lead to program termination, this function returns Some(Err()),\notherwise it returns None.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn open(\n name: &str,\n append: bool,\n output_error: Option<&OutputErrorMode>,\n) -> Option> {\n let path = PathBuf::from(name);\n let mut options = OpenOptions::new();\n let mode = if append {\n options.append(true)\n } else {\n options.truncate(true)\n };\n match mode.write(true).create(true).open(path.as_path()) {\n Ok(file) => Some(Ok(NamedWriter {\n inner: Box::new(file),\n name: name.to_owned(),\n })),\n Err(f) => {\n show_error!(\"{}: {f}\", name.maybe_quote());\n match output_error {\n Some(OutputErrorMode::Exit | OutputErrorMode::ExitNoPipe) => Some(Err(f)),\n _ => None,\n }\n }\n }\n}\n```"}], "func_name": "open", "docstring": "Tries to open the indicated file and return it. Reports an error if that's not possible.\nIf that error should lead to program termination, this function returns Some(Err()),\notherwise it returns None.", "repo": "uutils/coreutils", "path": "src/uu/tee/src/tee.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tee/src/tee.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a810f84a8451f818c4b11183d09c2af7b4f44cdefbedf9c78000a4a18beed3a1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new Symbol from an OsString.\n\nReturns Symbol::None in place of None\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(token: Option) -> Self {\n match token {\n Some(s) => match s.to_str() {\n Some(t) => match t {\n \"(\" => Self::LParen,\n \"!\" => Self::Bang,\n \"-a\" | \"-o\" => Self::BoolOp(s),\n \"=\" | \"==\" | \"!=\" | \"<\" | \">\" => Self::Op(Operator::String(s)),\n \"-eq\" | \"-ge\" | \"-gt\" | \"-le\" | \"-lt\" | \"-ne\" => Self::Op(Operator::Int(s)),\n \"-ef\" | \"-nt\" | \"-ot\" => Self::Op(Operator::File(s)),\n \"-n\" | \"-z\" => Self::UnaryOp(UnaryOperator::StrlenOp(s)),\n \"-b\" | \"-c\" | \"-d\" | \"-e\" | \"-f\" | \"-g\" | \"-G\" | \"-h\" | \"-k\" | \"-L\" | \"-N\"\n | \"-O\" | \"-p\" | \"-r\" | \"-s\" | \"-S\" | \"-t\" | \"-u\" | \"-w\" | \"-x\" => {\n Self::UnaryOp(UnaryOperator::FiletestOp(s))\n }\n _ => Self::Literal(s),\n },\n None => Self::Literal(s),\n },\n None => Self::None,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new Symbol from an OsString.\n\nReturns Symbol::None in place of None", "repo": "uutils/coreutils", "path": "src/uu/test/src/parser.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/test/src/parser.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d8a52b9f50f158f917edc6d974b911e3e28df8734884d44fa267670147e6037"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_literal\n\nDocumentation:\nConvert this Symbol into a Symbol::Literal, useful for cases where\ntest treats an operator as a string operand (test has no reserved\nwords).\n\n# Panics\n\nPanics if `self` is Symbol::None\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn into_literal(self) -> Self {\n Self::Literal(match self {\n Self::LParen => OsString::from(\"(\"),\n Self::Bang => OsString::from(\"!\"),\n Self::BoolOp(s)\n | Self::Literal(s)\n | Self::Op(Operator::String(s) | Operator::Int(s) | Operator::File(s))\n | Self::UnaryOp(UnaryOperator::StrlenOp(s) | UnaryOperator::FiletestOp(s)) => s,\n Self::None => panic!(),\n })\n }\n```"}], "func_name": "into_literal", "docstring": "Convert this Symbol into a Symbol::Literal, useful for cases where\ntest treats an operator as a string operand (test has no reserved\nwords).\n\n# Panics\n\nPanics if `self` is Symbol::None", "repo": "uutils/coreutils", "path": "src/uu/test/src/parser.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/test/src/parser.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1897e00d447266d7460dfec31ceb5dbd76e52cfa079a3c5be96a639e6ae2677c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: eval\n\nDocumentation:\nEvaluate a stack of Symbols, returning the result of the evaluation or\nan error message if evaluation failed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn eval(stack: &mut Vec) -> ParseResult {\n macro_rules! pop_literal {\n () => {\n match stack.pop() {\n Some(Symbol::Literal(s)) => s,\n _ => panic!(),\n }\n };\n }\n\n let s = stack.pop();\n\n match s {\n Some(Symbol::Bang) => {\n let result = eval(stack)?;\n\n Ok(!result)\n }\n Some(Symbol::Op(Operator::String(op))) => {\n let b = pop_literal!();\n let a = pop_literal!();\n match op.to_string_lossy().as_ref() {\n \"!=\" => Ok(a != b),\n \"<\" => Ok(a < b),\n \">\" => Ok(a > b),\n _ => Ok(a == b),\n }\n }\n Some(Symbol::Op(Operator::Int(op))) => {\n let b = pop_literal!();\n let a = pop_literal!();\n\n Ok(integers(&a, &b, &op)?)\n }\n Some(Symbol::Op(Operator::File(op))) => {\n let b = pop_literal!();\n let a = pop_literal!();\n Ok(files(&a, &b, &op)?)\n }\n Some(Symbol::UnaryOp(UnaryOperator::StrlenOp(op))) => {\n let s = match stack.pop() {\n Some(Symbol::Literal(s)) => s,\n Some(Symbol::None) => OsString::from(\"\"),\n None => {\n return Ok(true);\n }\n _ => {\n return Err(ParseError::MissingArgument(op.quote().to_string()));\n }\n };\n\n Ok(if op == \"-z\" {\n s.is_empty()\n } else {\n !s.is_empty()\n })\n }\n Some(Symbol::UnaryOp(UnaryOperator::FiletestOp(op))) => {\n let op = op.to_str().unwrap();\n\n let f = pop_literal!();\n\n Ok(match op {\n \"-b\" => path(&f, &PathCondition::BlockSpecial),\n \"-c\" => path(&f, &PathCondition::CharacterSpecial),\n \"-d\" => path(&f, &PathCondition::Directory),\n \"-e\" => path(&f, &PathCondition::Exists),\n \"-f\" => path(&f, &PathCondition::Regular),\n \"-g\" => path(&f, &PathCondition::GroupIdFlag),\n \"-G\" => path(&f, &PathCondition::GroupOwns),\n \"-h\" => path(&f, &PathCondition::SymLink),\n \"-k\" => path(&f, &PathCondition::Sticky),\n \"-L\" => path(&f, &PathCondition::SymLink),\n \"-N\" => path(&f, &PathCondition::ExistsModifiedLastRead),\n \"-O\" => path(&f, &PathCondition::UserOwns),\n \"-p\" => path(&f, &PathCondition::Fifo),\n \"-r\" => path(&f, &PathCondition::Readable),\n \"-S\" => path(&f, &PathCondition::Socket),\n \"-s\" => path(&f, &PathCondition::NonEmpty),\n \"-t\" => isatty(&f)?,\n \"-u\" => path(&f, &PathCondition::UserIdFlag),\n \"-w\" => path(&f, &PathCondition::Writable),\n \"-x\" => path(&f, &PathCondition::Executable),\n _ => panic!(),\n })\n }\n Some(Symbol::Literal(s)) => Ok(!s.is_empty()),\n Some(Symbol::None) | None => Ok(false),\n Some(Symbol::BoolOp(op)) => {\n if (op == \"-a\" || op == \"-o\") && stack.len() < 2 {\n return Err(ParseError::UnaryOperatorExpected(op.quote().to_string()));\n }\n\n let b = eval(stack)?;\n let a = eval(stack)?;\n\n Ok(if op == \"-a\" { a && b } else { a || b })\n }\n _ => Err(ParseError::ExpectedValue),\n }\n}\n```"}], "func_name": "eval", "docstring": "Evaluate a stack of Symbols, returning the result of the evaluation or\nan error message if evaluation failed.", "repo": "uutils/coreutils", "path": "src/uu/test/src/test.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/test/src/test.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb77b870c519eec682d27e4692add7b21af81846c042e20f867f8470ce30739e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: integers\n\nDocumentation:\nOperations to compare integers\n`a` is the left hand side\n`b` is the left hand side\n`op` the operation (ex: -eq, -lt, etc)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn integers(a: &OsStr, b: &OsStr, op: &OsStr) -> ParseResult {\n // Parse the two inputs\n let a: i128 = a\n .to_str()\n .and_then(|s| s.parse().ok())\n .ok_or_else(|| ParseError::InvalidInteger(a.quote().to_string()))?;\n\n let b: i128 = b\n .to_str()\n .and_then(|s| s.parse().ok())\n .ok_or_else(|| ParseError::InvalidInteger(b.quote().to_string()))?;\n\n // Do the maths\n Ok(match op.to_str() {\n Some(\"-eq\") => a == b,\n Some(\"-ne\") => a != b,\n Some(\"-gt\") => a > b,\n Some(\"-ge\") => a >= b,\n Some(\"-lt\") => a < b,\n Some(\"-le\") => a <= b,\n _ => return Err(ParseError::UnknownOperator(op.quote().to_string())),\n })\n}\n```"}], "func_name": "integers", "docstring": "Operations to compare integers\n`a` is the left hand side\n`b` is the left hand side\n`op` the operation (ex: -eq, -lt, etc)", "repo": "uutils/coreutils", "path": "src/uu/test/src/test.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/test/src/test.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3873edc8063f61507adc1bddc1ee85e071438e2c128bc89c36ef529941cd7c28"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: files\n\nDocumentation:\nOperations to compare files metadata\n`a` is the left hand side\n`b` is the left hand side\n`op` the operation (ex: -ef, -nt, etc)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn files(a: &OsStr, b: &OsStr, op: &OsStr) -> ParseResult {\n // Don't manage the error. GNU doesn't show error when doing\n // test foo -nt bar\n let (Ok(f_a), Ok(f_b)) = (fs::metadata(a), fs::metadata(b)) else {\n return Ok(false);\n };\n\n Ok(match op.to_str() {\n #[cfg(unix)]\n Some(\"-ef\") => f_a.ino() == f_b.ino() && f_a.dev() == f_b.dev(),\n #[cfg(not(unix))]\n Some(\"-ef\") => unimplemented!(),\n Some(\"-nt\") => f_a.modified().unwrap() > f_b.modified().unwrap(),\n Some(\"-ot\") => f_a.modified().unwrap() < f_b.modified().unwrap(),\n _ => return Err(ParseError::UnknownOperator(op.quote().to_string())),\n })\n}\n```"}], "func_name": "files", "docstring": "Operations to compare files metadata\n`a` is the left hand side\n`b` is the left hand side\n`op` the operation (ex: -ef, -nt, etc)", "repo": "uutils/coreutils", "path": "src/uu/test/src/test.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/test/src/test.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3e2a0f6b5aa501b3bdcb4fb74785c26415969d87c1366dec110d195f06693d89"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unblock_sigchld\n\nDocumentation:\nRemove pre-existing SIGCHLD handlers that would make waiting for the child's exit code fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn unblock_sigchld() {\n unsafe {\n nix::sys::signal::signal(\n nix::sys::signal::Signal::SIGCHLD,\n nix::sys::signal::SigHandler::SigDfl,\n )\n .unwrap();\n }\n}\n```"}], "func_name": "unblock_sigchld", "docstring": "Remove pre-existing SIGCHLD handlers that would make waiting for the child's exit code fail.", "repo": "uutils/coreutils", "path": "src/uu/timeout/src/timeout.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/timeout/src/timeout.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "af7b5e9002276a3ee6337067286c1200f21b965f622ef5375ea947c98ea991d9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: report_if_verbose\n\nDocumentation:\nReport that a signal is being sent if the verbose flag is set.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn report_if_verbose(signal: usize, cmd: &str, verbose: bool) {\n if verbose {\n let s = signal_name_by_value(signal).unwrap();\n show_error!(\n \"{}\",\n get_message_with_args(\n \"timeout-verbose-sending-signal\",\n HashMap::from([\n (\"signal\".to_string(), s.to_string()),\n (\"command\".to_string(), cmd.quote().to_string())\n ])\n )\n );\n }\n}\n```"}], "func_name": "report_if_verbose", "docstring": "Report that a signal is being sent if the verbose flag is set.", "repo": "uutils/coreutils", "path": "src/uu/timeout/src/timeout.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/timeout/src/timeout.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "58158710378a1929ba5296bc5c43bbda12e8a1187cf3dcdde589f814d0ecf25d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait_or_kill_process\n\nDocumentation:\nWait for a child process and send a kill signal if it does not terminate.\n\nThis function waits for the child `process` for the time period\ngiven by `duration`. If the child process does not terminate\nwithin that time, we send the `SIGKILL` signal to it. If `verbose`\nis `true`, then a message is printed to `stderr` when that\nhappens.\n\nIf the child process terminates within the given time period and\n`preserve_status` is `true`, then the status code of the child\nprocess is returned. If the child process terminates within the\ngiven time period and `preserve_status` is `false`, then 124 is\nreturned. If the child does not terminate within the time period,\nthen 137 is returned. Finally, if there is an error while waiting\nfor the child process to terminate, then 124 is returned.\n\n# Errors\n\nIf there is a problem sending the `SIGKILL` signal or waiting for\nthe process after that signal is sent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn wait_or_kill_process(\n process: &mut Child,\n cmd: &str,\n duration: Duration,\n preserve_status: bool,\n foreground: bool,\n verbose: bool,\n) -> std::io::Result {\n match process.wait_or_timeout(duration) {\n Ok(Some(status)) => {\n if preserve_status {\n Ok(status.code().unwrap_or_else(|| status.signal().unwrap()))\n } else {\n Ok(ExitStatus::TimeoutFailed.into())\n }\n }\n Ok(None) => {\n let signal = signal_by_name_or_value(\"KILL\").unwrap();\n report_if_verbose(signal, cmd, verbose);\n send_signal(process, signal, foreground);\n process.wait()?;\n Ok(ExitStatus::SignalSent(signal).into())\n }\n Err(_) => Ok(ExitStatus::WaitingFailed.into()),\n }\n}\n```"}], "func_name": "wait_or_kill_process", "docstring": "Wait for a child process and send a kill signal if it does not terminate.\n\nThis function waits for the child `process` for the time period\ngiven by `duration`. If the child process does not terminate\nwithin that time, we send the `SIGKILL` signal to it. If `verbose`\nis `true`, then a message is printed to `stderr` when that\nhappens.\n\nIf the child process terminates within the given time period and\n`preserve_status` is `true`, then the status code of the child\nprocess is returned. If the child process terminates within the\ngiven time period and `preserve_status` is `false`, then 124 is\nreturned. If the child does not terminate within the time period,\nthen 137 is returned. Finally, if there is an error while waiting\nfor the child process to terminate, then 124 is returned.\n\n# Errors\n\nIf there is a problem sending the `SIGKILL` signal or waiting for\nthe process after that signal is sent.", "repo": "uutils/coreutils", "path": "src/uu/timeout/src/timeout.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/timeout/src/timeout.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d443f9afae8c018225b886d4bbf0f20c6e719c60cfe49c45d2a048164174c898"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: timeout\n\nDocumentation:\nTODO: Improve exit codes, and make them consistent with the GNU Coreutils exit codes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn timeout(\n cmd: &[String],\n duration: Duration,\n signal: usize,\n kill_after: Option,\n foreground: bool,\n preserve_status: bool,\n verbose: bool,\n) -> UResult<()> {\n if !foreground {\n unsafe { libc::setpgid(0, 0) };\n }\n #[cfg(unix)]\n enable_pipe_errors()?;\n\n let process = &mut process::Command::new(&cmd[0])\n .args(&cmd[1..])\n .stdin(Stdio::inherit())\n .stdout(Stdio::inherit())\n .stderr(Stdio::inherit())\n .spawn()\n .map_err(|err| {\n let status_code = if err.kind() == ErrorKind::NotFound {\n // FIXME: not sure which to use\n 127\n } else {\n // FIXME: this may not be 100% correct...\n 126\n };\n USimpleError::new(\n status_code,\n get_message_with_args(\n \"timeout-error-failed-to-execute-process\",\n HashMap::from([(\"error\".to_string(), err.to_string())]),\n ),\n )\n })?;\n unblock_sigchld();\n // Wait for the child process for the specified time period.\n //\n // If the process exits within the specified time period (the\n // `Ok(Some(_))` arm), then return the appropriate status code.\n //\n // If the process does not exit within that time (the `Ok(None)`\n // arm) and `kill_after` is specified, then try sending `SIGKILL`.\n //\n // TODO The structure of this block is extremely similar to the\n // structure of `wait_or_kill_process()`. They can probably be\n // refactored into some common function.\n match process.wait_or_timeout(duration) {\n Ok(Some(status)) => Err(status\n .code()\n .unwrap_or_else(|| preserve_signal_info(status.signal().unwrap()))\n .into()),\n Ok(None) => {\n report_if_verbose(signal, &cmd[0], verbose);\n send_signal(process, signal, foreground);\n match kill_after {\n None => {\n let status = process.wait()?;\n if preserve_status {\n if let Some(ec) = status.code() {\n Err(ec.into())\n } else if let Some(sc) = status.signal() {\n Err(ExitStatus::SignalSent(sc.try_into().unwrap()).into())\n } else {\n Err(ExitStatus::CommandTimedOut.into())\n }\n } else {\n Err(ExitStatus::CommandTimedOut.into())\n }\n }\n Some(kill_after) => {\n match wait_or_kill_process(\n process,\n &cmd[0],\n kill_after,\n preserve_status,\n foreground,\n verbose,\n ) {\n Ok(status) => Err(status.into()),\n Err(e) => Err(USimpleError::new(\n ExitStatus::TimeoutFailed.into(),\n e.to_string(),\n )),\n }\n }\n }\n }\n Err(_) => {\n // We're going to return ERR_EXIT_STATUS regardless of\n // whether `send_signal()` succeeds or fails\n send_signal(process, signal, foreground);\n Err(ExitStatus::TimeoutFailed.into())\n }\n }\n}\n```"}], "func_name": "timeout", "docstring": "TODO: Improve exit codes, and make them consistent with the GNU Coreutils exit codes.", "repo": "uutils/coreutils", "path": "src/uu/timeout/src/timeout.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/timeout/src/timeout.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e22caac4af8ae10f70664b3527c4b14017f31ad5cb6790af9b10a5b216c7eae1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: datetime_to_filetime\n\nDocumentation:\nConvert a DateTime with a TZ offset into a FileTime\n\nThe DateTime is converted into a unix timestamp from which the FileTime is\nconstructed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn datetime_to_filetime(dt: &DateTime) -> FileTime {\n FileTime::from_unix_time(dt.timestamp(), dt.timestamp_subsec_nanos())\n}\n```"}], "func_name": "datetime_to_filetime", "docstring": "Convert a DateTime with a TZ offset into a FileTime\n\nThe DateTime is converted into a unix timestamp from which the FileTime is\nconstructed.", "repo": "uutils/coreutils", "path": "src/uu/touch/src/touch.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/touch/src/touch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f100b8f1318479071904bac29d40c712875b864c4d84c8733bd2ea541f5c0e1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_year\n\nDocumentation:\nConvert a two-digit year string to the corresponding number.\n\n`s` must be of length two or more. The last two bytes of `s` are\nassumed to be the two digits of the year.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_year(s: &str) -> u8 {\n let bytes = s.as_bytes();\n let n = bytes.len();\n let y1 = bytes[n - 2] - b'0';\n let y2 = bytes[n - 1] - b'0';\n 10 * y1 + y2\n}\n```"}], "func_name": "get_year", "docstring": "Convert a two-digit year string to the corresponding number.\n\n`s` must be of length two or more. The last two bytes of `s` are\nassumed to be the two digits of the year.", "repo": "uutils/coreutils", "path": "src/uu/touch/src/touch.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/touch/src/touch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f9e8681feb7b20cc08c84d8fec470e4355700d87d9375d95014514c34aecaf6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_first_filename_timestamp\n\nDocumentation:\nWhether the first filename should be interpreted as a timestamp.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_first_filename_timestamp(\n reference: Option<&OsString>,\n date: Option<&str>,\n timestamp: Option<&str>,\n files: &[&String],\n) -> bool {\n if timestamp.is_none()\n && reference.is_none()\n && date.is_none()\n && files.len() >= 2\n // env check is last as the slowest op\n && matches!(std::env::var(\"_POSIX2_VERSION\").as_deref(), Ok(\"199209\"))\n {\n let s = files[0];\n all_digits(s) && (s.len() == 8 || (s.len() == 10 && (69..=99).contains(&get_year(s))))\n } else {\n false\n }\n}\n```"}], "func_name": "is_first_filename_timestamp", "docstring": "Whether the first filename should be interpreted as a timestamp.", "repo": "uutils/coreutils", "path": "src/uu/touch/src/touch.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/touch/src/touch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e12af418da55cda79dc58c2b7eedab2cc2333e2180791f71ab0bb4365a5ce1e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shr2\n\nDocumentation:\nCycle the last two characters to the beginning of the string.\n\n`s` must have length at least two.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn shr2(s: &str) -> String {\n let n = s.len();\n let (a, b) = s.split_at(n - 2);\n let mut result = String::with_capacity(n);\n result.push_str(b);\n result.push_str(a);\n result\n}\n```"}], "func_name": "shr2", "docstring": "Cycle the last two characters to the beginning of the string.\n\n`s` must have length at least two.", "repo": "uutils/coreutils", "path": "src/uu/touch/src/touch.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/touch/src/touch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a41c92da4c77c70c35ffa5eb556982d49631380fee2c5b9998d15ae76bda8ec"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: touch\n\nDocumentation:\nExecute the touch command.\n\n# Errors\n\nPossible causes:\n- The user doesn't have permission to access the file\n- One of the directory components of the file path doesn't exist.\n\nIt will return an `Err` on the first error. However, for any of the files,\nif all of the following are true, it will print the error and continue touching\nthe rest of the files.\n- `opts.strict` is `false`\n- The file doesn't already exist\n- `-c`/`--no-create` was passed (`opts.no_create`)\n- Either `-h`/`--no-dereference` was passed (`opts.no_deref`) or the file couldn't be created\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn touch(files: &[InputFile], opts: &Options) -> Result<(), TouchError> {\n let (atime, mtime) = match &opts.source {\n Source::Reference(reference) => {\n let (atime, mtime) = stat(reference, !opts.no_deref)\n .map_err(|e| TouchError::ReferenceFileInaccessible(reference.to_owned(), e))?;\n\n (atime, mtime)\n }\n Source::Now => {\n let now = datetime_to_filetime(&Local::now());\n (now, now)\n }\n &Source::Timestamp(ts) => (ts, ts),\n };\n\n let (atime, mtime) = if let Some(date) = &opts.date {\n (\n parse_date(\n filetime_to_datetime(&atime).ok_or_else(|| TouchError::InvalidFiletime(atime))?,\n date,\n )?,\n parse_date(\n filetime_to_datetime(&mtime).ok_or_else(|| TouchError::InvalidFiletime(mtime))?,\n date,\n )?,\n )\n } else {\n (atime, mtime)\n };\n\n for (ind, file) in files.iter().enumerate() {\n let (path, is_stdout) = match file {\n InputFile::Stdout => (Cow::Owned(pathbuf_from_stdout()?), true),\n InputFile::Path(path) => (Cow::Borrowed(path), false),\n };\n touch_file(&path, is_stdout, opts, atime, mtime).map_err(|e| {\n TouchError::TouchFileError {\n path: path.into_owned(),\n index: ind,\n error: e,\n }\n })?;\n }\n\n Ok(())\n}\n```"}], "func_name": "touch", "docstring": "Execute the touch command.\n\n# Errors\n\nPossible causes:\n- The user doesn't have permission to access the file\n- One of the directory components of the file path doesn't exist.\n\nIt will return an `Err` on the first error. However, for any of the files,\nif all of the following are true, it will print the error and continue touching\nthe rest of the files.\n- `opts.strict` is `false`\n- The file doesn't already exist\n- `-c`/`--no-create` was passed (`opts.no_create`)\n- Either `-h`/`--no-dereference` was passed (`opts.no_deref`) or the file couldn't be created", "repo": "uutils/coreutils", "path": "src/uu/touch/src/touch.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/touch/src/touch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a23f735fa52535844c252deeda1fc0b290408acfab418fe1eb1ae7b935d2d3ca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: touch_file\n\nDocumentation:\nCreate or update the timestamp for a single file.\n\n# Arguments\n\n- `path` - The path to the file to create/update timestamp for\n- `is_stdout` - Stdout is handled specially, see [`update_times`] for more info\n- `atime` - Access time to set for the file\n- `mtime` - Modification time to set for the file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn touch_file(\n path: &Path,\n is_stdout: bool,\n opts: &Options,\n atime: FileTime,\n mtime: FileTime,\n) -> UResult<()> {\n let filename = if is_stdout {\n String::from(\"-\")\n } else {\n path.display().to_string()\n };\n\n let metadata_result = if opts.no_deref {\n path.symlink_metadata()\n } else {\n path.metadata()\n };\n\n if let Err(e) = metadata_result {\n if e.kind() != ErrorKind::NotFound {\n return Err(e.map_err_context(|| format!(\"setting times of {}\", filename.quote())));\n }\n\n if opts.no_create {\n return Ok(());\n }\n\n if opts.no_deref {\n let e = USimpleError::new(\n 1,\n format!(\n \"setting times of {}: No such file or directory\",\n filename.quote()\n ),\n );\n if opts.strict {\n return Err(e);\n }\n show!(e);\n return Ok(());\n }\n\n if let Err(e) = File::create(path) {\n // we need to check if the path is the path to a directory (ends with a separator)\n // we can't use File::create to create a directory\n // we cannot use path.is_dir() because it calls fs::metadata which we already called\n // when stable, we can change to use e.kind() == std::io::ErrorKind::IsADirectory\n let is_directory = if let Some(last_char) = path.to_string_lossy().chars().last() {\n last_char == std::path::MAIN_SEPARATOR\n } else {\n false\n };\n if is_directory {\n let custom_err = Error::other(\"No such file or directory\");\n return Err(\n custom_err.map_err_context(|| format!(\"cannot touch {}\", filename.quote()))\n );\n }\n let e = e.map_err_context(|| format!(\"cannot touch {}\", path.quote()));\n if opts.strict {\n return Err(e);\n }\n show!(e);\n return Ok(());\n };\n\n // Minor optimization: if no reference time, timestamp, or date was specified, we're done.\n if opts.source == Source::Now && opts.date.is_none() {\n return Ok(());\n }\n }\n\n update_times(path, is_stdout, opts, atime, mtime)\n}\n```"}], "func_name": "touch_file", "docstring": "Create or update the timestamp for a single file.\n\n# Arguments\n\n- `path` - The path to the file to create/update timestamp for\n- `is_stdout` - Stdout is handled specially, see [`update_times`] for more info\n- `atime` - Access time to set for the file\n- `mtime` - Modification time to set for the file", "repo": "uutils/coreutils", "path": "src/uu/touch/src/touch.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/touch/src/touch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a24c75af2ba5dffcf2ff48a62e9c1594b3f7bce431f04b81630898330557df06"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: determine_atime_mtime_change\n\nDocumentation:\nReturns which of the times (access, modification) are to be changed.\n\nNote that \"-a\" and \"-m\" may be passed together; this is not an xor.\n- If `-a` is passed but not `-m`, only access time is changed\n- If `-m` is passed but not `-a`, only modification time is changed\n- If neither or both are passed, both times are changed\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn determine_atime_mtime_change(matches: &ArgMatches) -> ChangeTimes {\n // If `--time` is given, Some(true) if equivalent to `-a`, Some(false) if equivalent to `-m`\n // If `--time` not given, None\n let time_access_only = if matches.contains_id(options::TIME) {\n matches\n .get_one::(options::TIME)\n .map(|time| time.contains(\"access\") || time.contains(\"atime\") || time.contains(\"use\"))\n } else {\n None\n };\n\n let atime_only = matches.get_flag(options::ACCESS) || time_access_only.unwrap_or_default();\n let mtime_only = matches.get_flag(options::MODIFICATION) || !time_access_only.unwrap_or(true);\n\n if atime_only && !mtime_only {\n ChangeTimes::AtimeOnly\n } else if mtime_only && !atime_only {\n ChangeTimes::MtimeOnly\n } else {\n ChangeTimes::Both\n }\n}\n```"}], "func_name": "determine_atime_mtime_change", "docstring": "Returns which of the times (access, modification) are to be changed.\n\nNote that \"-a\" and \"-m\" may be passed together; this is not an xor.\n- If `-a` is passed but not `-m`, only access time is changed\n- If `-m` is passed but not `-a`, only modification time is changed\n- If neither or both are passed, both times are changed", "repo": "uutils/coreutils", "path": "src/uu/touch/src/touch.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/touch/src/touch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d834af76b0a1a64a1aa1f93664c0c12c1dd46e63c28dbcc90509d82b472f66c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_times\n\nDocumentation:\nUpdating file access and modification times based on user-specified options\n\nIf the file is not stdout (`!is_stdout`) and `-h`/`--no-dereference` was\npassed, then, if the given file is a symlink, its own times will be updated,\nrather than the file it points to.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn update_times(\n path: &Path,\n is_stdout: bool,\n opts: &Options,\n atime: FileTime,\n mtime: FileTime,\n) -> UResult<()> {\n // If changing \"only\" atime or mtime, grab the existing value of the other.\n let (atime, mtime) = match opts.change_times {\n ChangeTimes::AtimeOnly => (\n atime,\n stat(path, !opts.no_deref)\n .map_err_context(|| format!(\"failed to get attributes of {}\", path.quote()))?\n .1,\n ),\n ChangeTimes::MtimeOnly => (\n stat(path, !opts.no_deref)\n .map_err_context(|| format!(\"failed to get attributes of {}\", path.quote()))?\n .0,\n mtime,\n ),\n ChangeTimes::Both => (atime, mtime),\n };\n\n // sets the file access and modification times for a file or a symbolic link.\n // The filename, access time (atime), and modification time (mtime) are provided as inputs.\n\n if opts.no_deref && !is_stdout {\n set_symlink_file_times(path, atime, mtime)\n } else {\n set_file_times(path, atime, mtime)\n }\n .map_err_context(|| format!(\"setting times of {}\", path.quote()))\n}\n```"}], "func_name": "update_times", "docstring": "Updating file access and modification times based on user-specified options\n\nIf the file is not stdout (`!is_stdout`) and `-h`/`--no-dereference` was\npassed, then, if the given file is a symlink, its own times will be updated,\nrather than the file it points to.", "repo": "uutils/coreutils", "path": "src/uu/touch/src/touch.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/touch/src/touch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dd9190c8ab7f2451b80b5359f80687d410b19377b57648437fb2fc7160c82dd8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stat\n\nDocumentation:\nGet metadata of the provided path\nIf `follow` is `true`, the function will try to follow symlinks\nIf `follow` is `false` or the symlink is broken, the function will return metadata of the symlink itself\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn stat(path: &Path, follow: bool) -> std::io::Result<(FileTime, FileTime)> {\n let metadata = if follow {\n fs::metadata(path).or_else(|_| fs::symlink_metadata(path))\n } else {\n fs::symlink_metadata(path)\n }?;\n\n Ok((\n FileTime::from_last_access_time(&metadata),\n FileTime::from_last_modification_time(&metadata),\n ))\n}\n```"}], "func_name": "stat", "docstring": "Get metadata of the provided path\nIf `follow` is `true`, the function will try to follow symlinks\nIf `follow` is `false` or the symlink is broken, the function will return metadata of the symlink itself", "repo": "uutils/coreutils", "path": "src/uu/touch/src/touch.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/touch/src/touch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba08768dce96ab6059d26ad4a7ff9febb70a6ee2755119974b581d1b6b49e3f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prepend_century\n\nDocumentation:\nPrepends 19 or 20 to the year if it is a 2 digit year\n\nGNU `touch` behavior:\n\n- 68 and before is interpreted as 20xx\n- 69 and after is interpreted as 19xx\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn prepend_century(s: &str) -> UResult {\n let first_two_digits = s[..2]\n .parse::()\n .map_err(|_| USimpleError::new(1, format!(\"invalid date ts format {}\", s.quote())))?;\n Ok(format!(\n \"{}{s}\",\n if first_two_digits > 68 { 19 } else { 20 }\n ))\n}\n```"}], "func_name": "prepend_century", "docstring": "Prepends 19 or 20 to the year if it is a 2 digit year\n\nGNU `touch` behavior:\n\n- 68 and before is interpreted as 20xx\n- 69 and after is interpreted as 19xx", "repo": "uutils/coreutils", "path": "src/uu/touch/src/touch.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/touch/src/touch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a9836a846c89b34354fea965a822a3ada3516fd7fa7bf546f934b1385e7f805"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: chain\n\nDocumentation:\nTakes two SymbolTranslators and creates a new SymbolTranslator over both in sequence.\n\nThis behaves pretty much identical to [`Iterator::chain`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn chain(self, other: T) -> ChainedSymbolTranslator\n where\n Self: Sized,\n {\n ChainedSymbolTranslator:: {\n stage_a: self,\n stage_b: other,\n }\n }\n```"}], "func_name": "chain", "docstring": "Takes two SymbolTranslators and creates a new SymbolTranslator over both in sequence.\n\nThis behaves pretty much identical to [`Iterator::chain`].", "repo": "uutils/coreutils", "path": "src/uu/tr/src/operation.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tr/src/operation.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fdd78ad768dbae5c798ad81dd1ab77772055729e4dc501c01a023f8763096d62"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_size\n\nDocumentation:\nCompute a target size in bytes for this truncate mode.\n\n`fsize` is the size of the reference file, in bytes.\n\nIf the mode is [`TruncateMode::Reduce`] and the value to\nreduce by is greater than `fsize`, then this function returns\n0 (since it cannot return a negative number).\n\n# Examples\n\nExtending a file of 10 bytes by 5 bytes:\n\n```rust,ignore\nlet mode = TruncateMode::Extend(5);\nlet fsize = 10;\nassert_eq!(mode.to_size(fsize), 15);\n```\n\nReducing a file by more than its size results in 0:\n\n```rust,ignore\nlet mode = TruncateMode::Reduce(5);\nlet fsize = 3;\nassert_eq!(mode.to_size(fsize), 0);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn to_size(&self, fsize: u64) -> u64 {\n match self {\n Self::Absolute(size) => *size,\n Self::Extend(size) => fsize + size,\n Self::Reduce(size) => {\n if *size > fsize {\n 0\n } else {\n fsize - size\n }\n }\n Self::AtMost(size) => fsize.min(*size),\n Self::AtLeast(size) => fsize.max(*size),\n Self::RoundDown(size) => fsize - fsize % size,\n Self::RoundUp(size) => fsize + fsize % size,\n }\n }\n```"}], "func_name": "to_size", "docstring": "Compute a target size in bytes for this truncate mode.\n\n`fsize` is the size of the reference file, in bytes.\n\nIf the mode is [`TruncateMode::Reduce`] and the value to\nreduce by is greater than `fsize`, then this function returns\n0 (since it cannot return a negative number).\n\n# Examples\n\nExtending a file of 10 bytes by 5 bytes:\n\n```rust,ignore\nlet mode = TruncateMode::Extend(5);\nlet fsize = 10;\nassert_eq!(mode.to_size(fsize), 15);\n```\n\nReducing a file by more than its size results in 0:\n\n```rust,ignore\nlet mode = TruncateMode::Reduce(5);\nlet fsize = 3;\nassert_eq!(mode.to_size(fsize), 0);\n```", "repo": "uutils/coreutils", "path": "src/uu/truncate/src/truncate.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/truncate/src/truncate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "366158b033819f1722ca09d97028db5a7007c96ad7951e17baa62ceaa89a9df2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: file_truncate\n\nDocumentation:\nTruncate the named file to the specified size.\n\nIf `create` is true, then the file will be created if it does not\nalready exist. If `size` is larger than the number of bytes in the\nfile, then the file will be padded with zeros. If `size` is smaller\nthan the number of bytes in the file, then the file will be\ntruncated and any bytes beyond `size` will be lost.\n\n# Errors\n\nIf the file could not be opened, or there was a problem setting the\nsize of the file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn file_truncate(filename: &str, create: bool, size: u64) -> UResult<()> {\n #[cfg(unix)]\n if let Ok(metadata) = metadata(filename) {\n if metadata.file_type().is_fifo() {\n return Err(USimpleError::new(\n 1,\n get_message_with_args(\n \"truncate-error-cannot-open-no-device\",\n HashMap::from([(\"filename\".to_string(), filename.quote().to_string())]),\n ),\n ));\n }\n }\n\n let path = Path::new(filename);\n match OpenOptions::new().write(true).create(create).open(path) {\n Ok(file) => file.set_len(size),\n Err(e) if e.kind() == ErrorKind::NotFound && !create => Ok(()),\n Err(e) => Err(e),\n }\n .map_err_context(|| {\n get_message_with_args(\n \"truncate-error-cannot-open-for-writing\",\n HashMap::from([(\"filename\".to_string(), filename.quote().to_string())]),\n )\n })\n}\n```"}], "func_name": "file_truncate", "docstring": "Truncate the named file to the specified size.\n\nIf `create` is true, then the file will be created if it does not\nalready exist. If `size` is larger than the number of bytes in the\nfile, then the file will be padded with zeros. If `size` is smaller\nthan the number of bytes in the file, then the file will be\ntruncated and any bytes beyond `size` will be lost.\n\n# Errors\n\nIf the file could not be opened, or there was a problem setting the\nsize of the file.", "repo": "uutils/coreutils", "path": "src/uu/truncate/src/truncate.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/truncate/src/truncate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "632ca356dccb97bc6a10f993d54f472c3fbf63303990e7b94fa6bbf721da4b6f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: truncate_reference_and_size\n\nDocumentation:\nTruncate files to a size relative to a given file.\n\n`rfilename` is the name of the reference file.\n\n`size_string` gives the size relative to the reference file to which\nto set the target files. For example, \"+3K\" means \"set each file to\nbe three kilobytes larger than the size of the reference file\".\n\nIf `create` is true, then each file will be created if it does not\nalready exist.\n\n# Errors\n\nIf any file could not be opened, or there was a problem setting\nthe size of at least one file.\n\nIf at least one file is a named pipe (also known as a fifo).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn truncate_reference_and_size(\n rfilename: &str,\n size_string: &str,\n filenames: &[String],\n create: bool,\n) -> UResult<()> {\n let mode = match parse_mode_and_size(size_string) {\n Err(e) => {\n return Err(USimpleError::new(\n 1,\n get_message_with_args(\n \"truncate-error-invalid-number\",\n HashMap::from([(\"error\".to_string(), e.to_string())]),\n ),\n ));\n }\n Ok(TruncateMode::Absolute(_)) => {\n return Err(USimpleError::new(\n 1,\n get_message(\"truncate-error-must-specify-relative-size\"),\n ));\n }\n Ok(m) => m,\n };\n\n if let TruncateMode::RoundDown(0) | TruncateMode::RoundUp(0) = mode {\n return Err(USimpleError::new(\n 1,\n get_message(\"truncate-error-division-by-zero\"),\n ));\n }\n\n let metadata = metadata(rfilename).map_err(|e| match e.kind() {\n ErrorKind::NotFound => USimpleError::new(\n 1,\n get_message_with_args(\n \"truncate-error-cannot-stat-no-such-file\",\n HashMap::from([(\"filename\".to_string(), rfilename.quote().to_string())]),\n ),\n ),\n _ => e.map_err_context(String::new),\n })?;\n\n let fsize = metadata.len();\n let tsize = mode.to_size(fsize);\n\n for filename in filenames {\n file_truncate(filename, create, tsize)?;\n }\n\n Ok(())\n}\n```"}], "func_name": "truncate_reference_and_size", "docstring": "Truncate files to a size relative to a given file.\n\n`rfilename` is the name of the reference file.\n\n`size_string` gives the size relative to the reference file to which\nto set the target files. For example, \"+3K\" means \"set each file to\nbe three kilobytes larger than the size of the reference file\".\n\nIf `create` is true, then each file will be created if it does not\nalready exist.\n\n# Errors\n\nIf any file could not be opened, or there was a problem setting\nthe size of at least one file.\n\nIf at least one file is a named pipe (also known as a fifo).", "repo": "uutils/coreutils", "path": "src/uu/truncate/src/truncate.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/truncate/src/truncate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ed2c8dd5d25f3b00177e6fad8a805bcec39c7c4a90912e9a36f4902f1e24b09b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: truncate_reference_file_only\n\nDocumentation:\nTruncate files to match the size of a given reference file.\n\n`rfilename` is the name of the reference file.\n\nIf `create` is true, then each file will be created if it does not\nalready exist.\n\n# Errors\n\nIf any file could not be opened, or there was a problem setting\nthe size of at least one file.\n\nIf at least one file is a named pipe (also known as a fifo).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn truncate_reference_file_only(\n rfilename: &str,\n filenames: &[String],\n create: bool,\n) -> UResult<()> {\n let metadata = metadata(rfilename).map_err(|e| match e.kind() {\n ErrorKind::NotFound => USimpleError::new(\n 1,\n get_message_with_args(\n \"truncate-error-cannot-stat-no-such-file\",\n HashMap::from([(\"filename\".to_string(), rfilename.quote().to_string())]),\n ),\n ),\n _ => e.map_err_context(String::new),\n })?;\n\n let tsize = metadata.len();\n\n for filename in filenames {\n file_truncate(filename, create, tsize)?;\n }\n\n Ok(())\n}\n```"}], "func_name": "truncate_reference_file_only", "docstring": "Truncate files to match the size of a given reference file.\n\n`rfilename` is the name of the reference file.\n\nIf `create` is true, then each file will be created if it does not\nalready exist.\n\n# Errors\n\nIf any file could not be opened, or there was a problem setting\nthe size of at least one file.\n\nIf at least one file is a named pipe (also known as a fifo).", "repo": "uutils/coreutils", "path": "src/uu/truncate/src/truncate.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/truncate/src/truncate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5676ceeaade558da38402a1ffaf3c3f08ac31740d8f6a1161e9b5436e1eaf0d6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: truncate_size_only\n\nDocumentation:\nTruncate files to a specified size.\n\n`size_string` gives either an absolute size or a relative size. A\nrelative size adjusts the size of each file relative to its current\nsize. For example, \"3K\" means \"set each file to be three kilobytes\"\nwhereas \"+3K\" means \"set each file to be three kilobytes larger than\nits current size\".\n\nIf `create` is true, then each file will be created if it does not\nalready exist.\n\n# Errors\n\nIf any file could not be opened, or there was a problem setting\nthe size of at least one file.\n\nIf at least one file is a named pipe (also known as a fifo).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn truncate_size_only(size_string: &str, filenames: &[String], create: bool) -> UResult<()> {\n let mode = parse_mode_and_size(size_string).map_err(|e| {\n USimpleError::new(\n 1,\n get_message_with_args(\n \"truncate-error-invalid-number\",\n HashMap::from([(\"error\".to_string(), e.to_string())]),\n ),\n )\n })?;\n\n if let TruncateMode::RoundDown(0) | TruncateMode::RoundUp(0) = mode {\n return Err(USimpleError::new(\n 1,\n get_message(\"truncate-error-division-by-zero\"),\n ));\n }\n\n for filename in filenames {\n let fsize = match metadata(filename) {\n Ok(m) => {\n #[cfg(unix)]\n if m.file_type().is_fifo() {\n return Err(USimpleError::new(\n 1,\n get_message_with_args(\n \"truncate-error-cannot-open-no-device\",\n HashMap::from([(\"filename\".to_string(), filename.quote().to_string())]),\n ),\n ));\n }\n m.len()\n }\n Err(_) => 0,\n };\n let tsize = mode.to_size(fsize);\n // TODO: Fix duplicate call to stat\n file_truncate(filename, create, tsize)?;\n }\n\n Ok(())\n}\n```"}], "func_name": "truncate_size_only", "docstring": "Truncate files to a specified size.\n\n`size_string` gives either an absolute size or a relative size. A\nrelative size adjusts the size of each file relative to its current\nsize. For example, \"3K\" means \"set each file to be three kilobytes\"\nwhereas \"+3K\" means \"set each file to be three kilobytes larger than\nits current size\".\n\nIf `create` is true, then each file will be created if it does not\nalready exist.\n\n# Errors\n\nIf any file could not be opened, or there was a problem setting\nthe size of at least one file.\n\nIf at least one file is a named pipe (also known as a fifo).", "repo": "uutils/coreutils", "path": "src/uu/truncate/src/truncate.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/truncate/src/truncate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac3ef6bf69135f3b103c8baf6354142a44c1adb1c5d47f10e36e0d7ed3f21244"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_modifier\n\nDocumentation:\nDecide whether a character is one of the size modifiers, like '+' or '<'.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_modifier(c: char) -> bool {\n c == '+' || c == '-' || c == '<' || c == '>' || c == '/' || c == '%'\n}\n```"}], "func_name": "is_modifier", "docstring": "Decide whether a character is one of the size modifiers, like '+' or '<'.", "repo": "uutils/coreutils", "path": "src/uu/truncate/src/truncate.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/truncate/src/truncate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f068163a8271c037bbc0bbcd87a19fe7299539e9eb1f110127a79a677cbe2fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_mode_and_size\n\nDocumentation:\nParse a size string with optional modifier symbol as its first character.\n\nA size string is as described in [`parse_size_u64`]. The first character\nof `size_string` might be a modifier symbol, like `'+'` or\n`'<'`. The first element of the pair returned by this function\nindicates which modifier symbol was present, or\n[`TruncateMode::Absolute`] if none.\n\n# Panics\n\nIf `size_string` is empty, or if no number could be parsed from the\ngiven string (for example, if the string were `\"abc\"`).\n\n# Examples\n\n```rust,ignore\nassert_eq!(parse_mode_and_size(\"+123\"), (TruncateMode::Extend, 123));\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_mode_and_size(size_string: &str) -> Result {\n // Trim any whitespace.\n let mut size_string = size_string.trim();\n\n // Get the modifier character from the size string, if any. For\n // example, if the argument is \"+123\", then the modifier is '+'.\n if let Some(c) = size_string.chars().next() {\n if is_modifier(c) {\n size_string = &size_string[1..];\n }\n parse_size_u64(size_string).map(match c {\n '+' => TruncateMode::Extend,\n '-' => TruncateMode::Reduce,\n '<' => TruncateMode::AtMost,\n '>' => TruncateMode::AtLeast,\n '/' => TruncateMode::RoundDown,\n '%' => TruncateMode::RoundUp,\n _ => TruncateMode::Absolute,\n })\n } else {\n Err(ParseSizeError::ParseFailure(size_string.to_string()))\n }\n}\n```"}], "func_name": "parse_mode_and_size", "docstring": "Parse a size string with optional modifier symbol as its first character.\n\nA size string is as described in [`parse_size_u64`]. The first character\nof `size_string` might be a modifier symbol, like `'+'` or\n`'<'`. The first element of the pair returned by this function\nindicates which modifier symbol was present, or\n[`TruncateMode::Absolute`] if none.\n\n# Panics\n\nIf `size_string` is empty, or if no number could be parsed from the\ngiven string (for example, if the string were `\"abc\"`).\n\n# Examples\n\n```rust,ignore\nassert_eq!(parse_mode_and_size(\"+123\"), (TruncateMode::Extend, 123));\n```", "repo": "uutils/coreutils", "path": "src/uu/truncate/src/truncate.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/truncate/src/truncate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a714cfae34386a6594fd988bd2c75380d9c938144ba36cd60aa08bb0627f2938"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove\n\nDocumentation:\nFind the element `x` in `vec` and remove it, returning its index.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn remove(vec: &mut Vec, x: T) -> Option\nwhere\n T: PartialEq,\n{\n vec.iter().position(|item| *item == x).inspect(|i| {\n vec.remove(*i);\n })\n}\n```"}], "func_name": "remove", "docstring": "Find the element `x` in `vec` and remove it, returning its index.", "repo": "uutils/coreutils", "path": "src/uu/tsort/src/tsort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tsort/src/tsort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f52d7e11f781f45c5fa3dc0ea05097621d8ccb8628f8ffb13995b119b5f7ae74"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_tsort\n\nDocumentation:\nImplementation of algorithm T from TAOCP (Don. Knuth), vol. 1.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn run_tsort(&mut self) {\n // First, we find nodes that have no prerequisites (independent nodes).\n // If no such node exists, then there is a cycle.\n let mut independent_nodes_queue: VecDeque<&'input str> = self\n .nodes\n .iter()\n .filter_map(|(&name, node)| {\n if node.predecessor_count == 0 {\n Some(name)\n } else {\n None\n }\n })\n .collect();\n\n // To make sure the resulting ordering is deterministic we\n // need to order independent nodes.\n //\n // FIXME: this doesn't comply entirely with the GNU coreutils\n // implementation.\n independent_nodes_queue.make_contiguous().sort_unstable();\n\n while !self.nodes.is_empty() {\n // Get the next node (breaking any cycles necessary to do so).\n let v = self.find_next_node(&mut independent_nodes_queue);\n println!(\"{v}\");\n if let Some(node_to_process) = self.nodes.remove(v) {\n for successor_name in node_to_process.successor_names {\n let successor_node = self.nodes.get_mut(successor_name).unwrap();\n successor_node.predecessor_count -= 1;\n if successor_node.predecessor_count == 0 {\n // If we find nodes without any other prerequisites, we add them to the queue.\n independent_nodes_queue.push_back(successor_name);\n }\n }\n }\n }\n }\n```"}], "func_name": "run_tsort", "docstring": "Implementation of algorithm T from TAOCP (Don. Knuth), vol. 1.", "repo": "uutils/coreutils", "path": "src/uu/tsort/src/tsort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tsort/src/tsort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d9785f53d659d999e66ea4eeb9094943bfe5bbcb095721acaac06e9fd5bd7566"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: indegree\n\nDocumentation:\nGet the in-degree of the node with the given name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn indegree(&self, name: &str) -> Option {\n self.nodes.get(name).map(|data| data.predecessor_count)\n }\n```"}], "func_name": "indegree", "docstring": "Get the in-degree of the node with the given name.", "repo": "uutils/coreutils", "path": "src/uu/tsort/src/tsort.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/tsort/src/tsort.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e38ce4a703a4f85129146bfaa56834cd4522be8aafd63c7cab585100646d732"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_obsolete\n\nDocumentation:\nExtract obsolete shorthands (if any) for skip fields and skip chars options\nfollowing GNU `uniq` behavior\n\nExamples for obsolete skip fields option\n`uniq -1 file` would equal `uniq -f1 file`\n`uniq -1 -2 -3 file` would equal `uniq -f123 file`\n`uniq -1 -2 -f5 file` would equal `uniq -f5 file`\n`uniq -u20s4 file` would equal `uniq -u -f20 -s4 file`\n`uniq -D1w3 -3 file` would equal `uniq -D -f3 -w3 file`\n\nExamples for obsolete skip chars option\n`uniq +1 file` would equal `uniq -s1 file`\n`uniq +1 -s2 file` would equal `uniq -s2 file`\n`uniq -s2 +3 file` would equal `uniq -s3 file`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_obsolete(args: impl uucore::Args) -> (Vec, Option, Option) {\n let mut skip_fields_old = None;\n let mut skip_chars_old = None;\n let mut preceding_long_opt_req_value = false;\n let mut preceding_short_opt_req_value = false;\n\n let filtered_args = args\n .filter_map(|os_slice| {\n filter_args(\n os_slice,\n &mut skip_fields_old,\n &mut skip_chars_old,\n &mut preceding_long_opt_req_value,\n &mut preceding_short_opt_req_value,\n )\n })\n .collect();\n\n // exacted String values (if any) for skip_fields_old and skip_chars_old\n // are guaranteed to consist of ascii digit chars only at this point\n // so, it is safe to parse into usize and collapse Result into Option\n let skip_fields_old: Option = skip_fields_old.and_then(|v| v.parse::().ok());\n let skip_chars_old: Option = skip_chars_old.and_then(|v| v.parse::().ok());\n\n (filtered_args, skip_fields_old, skip_chars_old)\n}\n```"}], "func_name": "handle_obsolete", "docstring": "Extract obsolete shorthands (if any) for skip fields and skip chars options\nfollowing GNU `uniq` behavior\n\nExamples for obsolete skip fields option\n`uniq -1 file` would equal `uniq -f1 file`\n`uniq -1 -2 -3 file` would equal `uniq -f123 file`\n`uniq -1 -2 -f5 file` would equal `uniq -f5 file`\n`uniq -u20s4 file` would equal `uniq -u -f20 -s4 file`\n`uniq -D1w3 -3 file` would equal `uniq -D -f3 -w3 file`\n\nExamples for obsolete skip chars option\n`uniq +1 file` would equal `uniq -s1 file`\n`uniq +1 -s2 file` would equal `uniq -s2 file`\n`uniq -s2 +3 file` would equal `uniq -s3 file`", "repo": "uutils/coreutils", "path": "src/uu/uniq/src/uniq.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/uniq/src/uniq.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "14b88947a9bf1ff9ae6175d5fbc201cc078ee8e7b7541cd6a5e3a256facfc194"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: should_extract_obs_skip_fields\n\nDocumentation:\nHelper function to [`filter_args`]\nChecks if the slice is a true short option (and not hyphen prefixed value of an option)\nand if so, a short option that can contain obsolete skip fields value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn should_extract_obs_skip_fields(\n slice: &str,\n preceding_long_opt_req_value: &bool,\n preceding_short_opt_req_value: &bool,\n) -> bool {\n slice.starts_with('-')\n && !slice.starts_with(\"--\")\n && !preceding_long_opt_req_value\n && !preceding_short_opt_req_value\n && !slice.starts_with(\"-s\")\n && !slice.starts_with(\"-f\")\n && !slice.starts_with(\"-w\")\n}\n```"}], "func_name": "should_extract_obs_skip_fields", "docstring": "Helper function to [`filter_args`]\nChecks if the slice is a true short option (and not hyphen prefixed value of an option)\nand if so, a short option that can contain obsolete skip fields value", "repo": "uutils/coreutils", "path": "src/uu/uniq/src/uniq.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/uniq/src/uniq.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "de02625133f2b7b5d47e8b237ba33475c34b1f1a0f35f6702f97b6a384ebf82f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: should_extract_obs_skip_chars\n\nDocumentation:\nHelper function to [`filter_args`]\nChecks if the slice is a true obsolete skip chars short option\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn should_extract_obs_skip_chars(\n slice: &str,\n preceding_long_opt_req_value: &bool,\n preceding_short_opt_req_value: &bool,\n) -> bool {\n slice.starts_with('+')\n && posix_version().is_some_and(|v| v <= OBSOLETE)\n && !preceding_long_opt_req_value\n && !preceding_short_opt_req_value\n && slice.chars().nth(1).is_some_and(|c| c.is_ascii_digit())\n}\n```"}], "func_name": "should_extract_obs_skip_chars", "docstring": "Helper function to [`filter_args`]\nChecks if the slice is a true obsolete skip chars short option", "repo": "uutils/coreutils", "path": "src/uu/uniq/src/uniq.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/uniq/src/uniq.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f19aa1c90a043d8a7df599b8646ca1728ef7ef6798d090548ab7f502d4837f2a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_preceding_options\n\nDocumentation:\nHelper function to [`filter_args`]\nCaptures if current slice is a preceding option\nthat requires value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_preceding_options(\n slice: &str,\n preceding_long_opt_req_value: &mut bool,\n preceding_short_opt_req_value: &mut bool,\n) {\n // capture if current slice is a preceding long option that requires value and does not use '=' to assign that value\n // following slice should be treaded as value for this option\n // even if it starts with '-' (which would be treated as hyphen prefixed value)\n if slice.starts_with(\"--\") {\n use options as O;\n *preceding_long_opt_req_value = &slice[2..] == O::SKIP_CHARS\n || &slice[2..] == O::SKIP_FIELDS\n || &slice[2..] == O::CHECK_CHARS\n || &slice[2..] == O::GROUP\n || &slice[2..] == O::ALL_REPEATED;\n }\n // capture if current slice is a preceding short option that requires value and does not have value in the same slice (value separated by whitespace)\n // following slice should be treaded as value for this option\n // even if it starts with '-' (which would be treated as hyphen prefixed value)\n *preceding_short_opt_req_value = slice == \"-s\" || slice == \"-f\" || slice == \"-w\";\n // slice is a value\n // reset preceding option flags\n if !slice.starts_with('-') {\n *preceding_short_opt_req_value = false;\n *preceding_long_opt_req_value = false;\n }\n}\n```"}], "func_name": "handle_preceding_options", "docstring": "Helper function to [`filter_args`]\nCaptures if current slice is a preceding option\nthat requires value", "repo": "uutils/coreutils", "path": "src/uu/uniq/src/uniq.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/uniq/src/uniq.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "22da1bd2840415988967a14d9b4e1c1c4120fda2f509f8ad31b806eb2da2a6f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_extract_obs_skip_fields\n\nDocumentation:\nHelper function to [`filter_args`]\nExtracts obsolete skip fields numeric part from argument slice\nand filters it out\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_extract_obs_skip_fields(\n slice: &str,\n skip_fields_old: &mut Option,\n) -> Option {\n let mut obs_extracted: Vec = vec![];\n let mut obs_end_reached = false;\n let mut obs_overwritten_by_new = false;\n let filtered_slice: Vec = slice\n .chars()\n .filter(|c| {\n if c.eq(&'f') {\n // any extracted obsolete skip fields value up to this point should be discarded\n // as the new/documented option for skip fields was used after it\n // i.e. in situation like `-u12f3`\n // The obsolete skip fields value should still be extracted, filtered out\n // but the skip_fields_old should be set to None instead of Some(String) later on\n obs_overwritten_by_new = true;\n }\n // To correctly process scenario like '-u20s4' or '-D1w3', etc\n // we need to stop extracting digits once alphabetic character is encountered\n // after we already have something in obs_extracted\n if c.is_ascii_digit() && !obs_end_reached {\n obs_extracted.push(*c);\n false\n } else {\n if !obs_extracted.is_empty() {\n obs_end_reached = true;\n }\n true\n }\n })\n .collect();\n\n if obs_extracted.is_empty() {\n // no obsolete value found/extracted\n Some(OsString::from(slice))\n } else {\n // obsolete value was extracted\n // unless there was new/documented option for skip fields used after it\n // set the skip_fields_old value (concatenate to it if there was a value there already)\n if obs_overwritten_by_new {\n *skip_fields_old = None;\n } else {\n let mut extracted: String = obs_extracted.iter().collect();\n if let Some(val) = skip_fields_old {\n extracted.push_str(val);\n }\n *skip_fields_old = Some(extracted);\n }\n if filtered_slice.get(1).is_some() {\n // there were some short options in front of or after obsolete lines value\n // i.e. '-u20s4' or '-D1w3' or similar, which after extraction of obsolete lines value\n // would look like '-us4' or '-Dw3' or similar\n let filtered_slice: String = filtered_slice.iter().collect();\n Some(OsString::from(filtered_slice))\n } else {\n None\n }\n }\n}\n```"}], "func_name": "handle_extract_obs_skip_fields", "docstring": "Helper function to [`filter_args`]\nExtracts obsolete skip fields numeric part from argument slice\nand filters it out", "repo": "uutils/coreutils", "path": "src/uu/uniq/src/uniq.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/uniq/src/uniq.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "356e9b4f30ea07167b4fb3bc6ec072209c5ab12dec9a76325c079034f5f1c505"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_extract_obs_skip_chars\n\nDocumentation:\nHelper function to [`filter_args`]\nExtracts obsolete skip chars numeric part from argument slice\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_extract_obs_skip_chars(\n slice: &str,\n skip_chars_old: &mut Option,\n) -> Option {\n let mut obs_extracted: Vec = vec![];\n let mut slice_chars = slice.chars();\n slice_chars.next(); // drop leading '+' character\n for c in slice_chars {\n if c.is_ascii_digit() {\n obs_extracted.push(c);\n } else {\n // for obsolete skip chars option the whole value after '+' should be numeric\n // so, if any non-digit characters are encountered in the slice (i.e. `+1q`, etc)\n // set skip_chars_old to None and return whole slice back.\n // It will be parsed by clap and panic with appropriate error message\n *skip_chars_old = None;\n return Some(OsString::from(slice));\n }\n }\n if obs_extracted.is_empty() {\n // no obsolete value found/extracted\n // i.e. it was just '+' character alone\n Some(OsString::from(slice))\n } else {\n // successfully extracted numeric value\n // capture it and return None to filter out the whole slice\n *skip_chars_old = Some(obs_extracted.iter().collect());\n None\n }\n}\n```"}], "func_name": "handle_extract_obs_skip_chars", "docstring": "Helper function to [`filter_args`]\nExtracts obsolete skip chars numeric part from argument slice", "repo": "uutils/coreutils", "path": "src/uu/uniq/src/uniq.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/uniq/src/uniq.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3559ce15cd1d440eb1046d21f4de2c63fc86f903bfacd6d3005d42637a3210ea"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: map_clap_errors\n\nDocumentation:\nMaps Clap errors to USimpleError and overrides 3 specific ones\nto meet requirements of GNU tests for `uniq`.\nUnfortunately these overrides are necessary, since several GNU tests\nfor `uniq` hardcode and require the exact wording of the error message\nand it is not compatible with how Clap formats and displays those error messages.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn map_clap_errors(clap_error: Error) -> Box {\n let footer = get_message(\"uniq-error-try-help\");\n let override_arg_conflict = get_message(\"uniq-error-group-mutually-exclusive\") + \"\\n\" + &footer;\n let override_group_badoption = get_message(\"uniq-error-group-badoption\") + \"\\n\" + &footer;\n let override_all_repeated_badoption =\n get_message(\"uniq-error-all-repeated-badoption\") + \"\\n\" + &footer;\n\n let error_message = match clap_error.kind() {\n ErrorKind::ArgumentConflict => override_arg_conflict,\n ErrorKind::InvalidValue\n if clap_error\n .get(ContextKind::InvalidValue)\n .is_some_and(|v| v.to_string() == \"badoption\")\n && clap_error\n .get(ContextKind::InvalidArg)\n .is_some_and(|v| v.to_string().starts_with(\"--group\")) =>\n {\n override_group_badoption\n }\n ErrorKind::InvalidValue\n if clap_error\n .get(ContextKind::InvalidValue)\n .is_some_and(|v| v.to_string() == \"badoption\")\n && clap_error\n .get(ContextKind::InvalidArg)\n .is_some_and(|v| v.to_string().starts_with(\"--all-repeated\")) =>\n {\n override_all_repeated_badoption\n }\n _ => return clap_error.into(),\n };\n USimpleError::new(1, error_message)\n}\n```"}], "func_name": "map_clap_errors", "docstring": "Maps Clap errors to USimpleError and overrides 3 specific ones\nto meet requirements of GNU tests for `uniq`.\nUnfortunately these overrides are necessary, since several GNU tests\nfor `uniq` hardcode and require the exact wording of the error message\nand it is not compatible with how Clap formats and displays those error messages.", "repo": "uutils/coreutils", "path": "src/uu/uniq/src/uniq.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/uniq/src/uniq.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a16622f373cddc293d0a685e0a6b2abdac11c21b23ce8e791f5316e8d958f5b5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_uptime\n\nDocumentation:\nDefault uptime behaviour i.e. when no file argument is given.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn default_uptime() -> UResult<()> {\n print_time();\n print_uptime(None)?;\n print_nusers(None);\n print_loadavg();\n\n Ok(())\n}\n```"}], "func_name": "default_uptime", "docstring": "Default uptime behaviour i.e. when no file argument is given.", "repo": "uutils/coreutils", "path": "src/uu/uptime/src/uptime.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/uptime/src/uptime.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bcfb159f27ff3575dd575ff8a5704d7376bd3e89bc4596c501114e9d5d363ce0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: count_bytes_chars_and_lines_fast\n\nDocumentation:\nReturns a WordCount that counts the number of bytes, lines, and/or the number of Unicode characters encoded in UTF-8 read via a Reader.\n\nThis corresponds to the `-c`, `-l` and `-m` command line flags to wc.\n\n# Arguments\n\n* `R` - A Reader from which the UTF-8 stream will be read.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn count_bytes_chars_and_lines_fast<\n R: Read,\n const COUNT_BYTES: bool,\n const COUNT_CHARS: bool,\n const COUNT_LINES: bool,\n>(\n handle: &mut R,\n) -> (WordCount, Option) {\n let mut total = WordCount::default();\n let buf: &mut [u8] = &mut AlignedBuffer::default().data;\n loop {\n match handle.read(buf) {\n Ok(0) => return (total, None),\n Ok(n) => {\n if COUNT_BYTES {\n total.bytes += n;\n }\n if COUNT_CHARS {\n total.chars += bytecount::num_chars(&buf[..n]);\n }\n if COUNT_LINES {\n total.lines += bytecount::count(&buf[..n], b'\\n');\n }\n }\n Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,\n Err(e) => return (total, Some(e)),\n }\n }\n}\n```"}], "func_name": "count_bytes_chars_and_lines_fast", "docstring": "Returns a WordCount that counts the number of bytes, lines, and/or the number of Unicode characters encoded in UTF-8 read via a Reader.\n\nThis corresponds to the `-c`, `-l` and `-m` command line flags to wc.\n\n# Arguments\n\n* `R` - A Reader from which the UTF-8 stream will be read.", "repo": "uutils/coreutils", "path": "src/uu/wc/src/count_fast.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/wc/src/count_fast.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9ace1cec93fe944d1e7028f5178a958d5bc58d27657da286f4cae6a1fdf72032"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_borrowed\n\nDocumentation:\nTranslates Path(Cow::Owned(_)) to Path(Cow::Borrowed(_)).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn as_borrowed(&'a self) -> Self {\n match self {\n Self::Path(p) => Self::Path(Cow::Borrowed(p.borrow())),\n Self::Stdin(k) => Self::Stdin(*k),\n }\n }\n```"}], "func_name": "as_borrowed", "docstring": "Translates Path(Cow::Owned(_)) to Path(Cow::Borrowed(_)).", "repo": "uutils/coreutils", "path": "src/uu/wc/src/wc.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/wc/src/wc.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b2113beed57f30cbd7e67ee2f5587271c71bf36d1ca2e5875bb029f6e07c399d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_title\n\nDocumentation:\nConverts input to title that appears in stats.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn to_title(&self) -> Option> {\n match self {\n Self::Path(path) => {\n let path = path.as_os_str();\n if path.to_string_lossy().contains('\\n') {\n Some(Cow::Owned(quoting_style::escape_name(path, QS_ESCAPE)))\n } else {\n Some(Cow::Borrowed(path))\n }\n }\n Self::Stdin(StdinKind::Explicit) => Some(Cow::Borrowed(OsStr::new(STDIN_REPR))),\n Self::Stdin(StdinKind::Implicit) => None,\n }\n }\n```"}], "func_name": "to_title", "docstring": "Converts input to title that appears in stats.", "repo": "uutils/coreutils", "path": "src/uu/wc/src/wc.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/wc/src/wc.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb332b026bba88266ea96d56e93abd1c20c15805d4d370bef80582f549f09421"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: path_display\n\nDocumentation:\nConverts input into the form that appears in errors.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn path_display(&self) -> String {\n match self {\n Self::Path(path) => escape_name_wrapper(path.as_os_str()),\n Self::Stdin(_) => get_message(\"wc-standard-input\"),\n }\n }\n```"}], "func_name": "path_display", "docstring": "Converts input into the form that appears in errors.", "repo": "uutils/coreutils", "path": "src/uu/wc/src/wc.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/wc/src/wc.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb347df5c2f040e312435d2881144e8138e051a7c0c2140b2a1f7ca624f93f7b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_as_files0\n\nDocumentation:\nWhen given --files0-from, we may be given a path or stdin. Either may be a stream or\na regular file. If given a file less than 10 MiB, it will be consumed and turned into\na Vec of Input::Paths which can be scanned to determine the widths of the columns that\nwill ultimately be printed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn try_as_files0(&self) -> UResult>>> {\n match self {\n Self::Path(path) => match fs::metadata(path) {\n Ok(meta) if meta.is_file() && meta.len() <= (10 << 20) => Ok(Some(\n files0_iter_file(path)?.collect::, _>>()?,\n )),\n _ => Ok(None),\n },\n Self::Stdin(_) if is_stdin_small_file() => {\n Ok(Some(files0_iter_stdin().collect::, _>>()?))\n }\n Self::Stdin(_) => Ok(None),\n }\n }\n```"}], "func_name": "try_as_files0", "docstring": "When given --files0-from, we may be given a path or stdin. Either may be a stream or\na regular file. If given a file less than 10 MiB, it will be consumed and turned into\na Vec of Input::Paths which can be scanned to determine the widths of the columns that\nwill ultimately be printed.", "repo": "uutils/coreutils", "path": "src/uu/wc/src/wc.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/wc/src/wc.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f9180e4f5fbeb6c28e036ce837c6f90ce9be481d33377e4779d593f6d93b9f43"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: word_count_from_input\n\nDocumentation:\nIf we fail opening a file, we only show the error. If we fail reading the\nfile, we show a count for what we managed to read.\n\nTherefore, the reading implementations always return a total and sometimes\nreturn an error: (WordCount, Option).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn word_count_from_input(input: &Input<'_>, settings: &Settings) -> CountResult {\n let (total, maybe_err) = match input {\n Input::Stdin(_) => word_count_from_reader(io::stdin().lock(), settings),\n Input::Path(path) => match File::open(path) {\n Ok(f) => word_count_from_reader(f, settings),\n Err(err) => return CountResult::Failure(err),\n },\n };\n match maybe_err {\n None => CountResult::Success(total),\n Some(err) => CountResult::Interrupted(total, err),\n }\n}\n```"}], "func_name": "word_count_from_input", "docstring": "If we fail opening a file, we only show the error. If we fail reading the\nfile, we show a count for what we managed to read.\n\nTherefore, the reading implementations always return a total and sometimes\nreturn an error: (WordCount, Option).", "repo": "uutils/coreutils", "path": "src/uu/wc/src/wc.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/wc/src/wc.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d6b71fcc81f388d6c515d10db7528f4a7cb3d0ad7579307fa3c2defa432f721"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compute_number_width\n\nDocumentation:\nCompute the number of digits needed to represent all counts in all inputs.\n\nFor [`Inputs::Stdin`], [`MINIMUM_WIDTH`] is returned, unless there is only one counter number\nto be printed, in which case 1 is returned.\n\nFor [`Inputs::Files0From`], [`MINIMUM_WIDTH`] is returned.\n\nAn [`Inputs::Paths`] may include zero or more \"-\" entries, each of which represents reading\nfrom `stdin`. The presence of any such entry causes this function to return a width that is at\nleast [`MINIMUM_WIDTH`].\n\nIf an [`Inputs::Paths`] contains only one path and only one number needs to be printed then\nthis function is optimized to return 1 without making any calls to get file metadata.\n\nIf file metadata could not be read from any of the [`Input::Path`] input, that input does not\naffect number width computation. Otherwise, the file sizes from the files' metadata are summed\nand the number of digits in that total size is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compute_number_width(inputs: &Inputs, settings: &Settings) -> usize {\n match inputs {\n Inputs::Stdin if settings.number_enabled() == 1 => 1,\n Inputs::Stdin => MINIMUM_WIDTH,\n Inputs::Files0From(_) => 1,\n Inputs::Paths(inputs) => {\n if settings.number_enabled() == 1 && inputs.len() == 1 {\n return 1;\n }\n\n let mut minimum_width = 1;\n let mut total: u64 = 0;\n for input in inputs {\n match input {\n Input::Stdin(_) => minimum_width = MINIMUM_WIDTH,\n Input::Path(path) => {\n if let Ok(meta) = fs::metadata(path) {\n if meta.is_file() {\n total += meta.len();\n } else {\n minimum_width = MINIMUM_WIDTH;\n }\n }\n }\n }\n }\n\n if total == 0 {\n minimum_width\n } else {\n let total_width = (1 + total.ilog10())\n .try_into()\n .expect(\"ilog of a u64 should fit into a usize\");\n max(total_width, minimum_width)\n }\n }\n }\n}\n```"}], "func_name": "compute_number_width", "docstring": "Compute the number of digits needed to represent all counts in all inputs.\n\nFor [`Inputs::Stdin`], [`MINIMUM_WIDTH`] is returned, unless there is only one counter number\nto be printed, in which case 1 is returned.\n\nFor [`Inputs::Files0From`], [`MINIMUM_WIDTH`] is returned.\n\nAn [`Inputs::Paths`] may include zero or more \"-\" entries, each of which represents reading\nfrom `stdin`. The presence of any such entry causes this function to return a width that is at\nleast [`MINIMUM_WIDTH`].\n\nIf an [`Inputs::Paths`] contains only one path and only one number needs to be printed then\nthis function is optimized to return 1 without making any calls to get file metadata.\n\nIf file metadata could not be read from any of the [`Input::Path`] input, that input does not\naffect number width computation. Otherwise, the file sizes from the files' metadata are summed\nand the number of digits in that total size is returned.", "repo": "uutils/coreutils", "path": "src/uu/wc/src/wc.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/wc/src/wc.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a618ab44ed96bd65913ba131cc5a320f75cdfe8f213d7a74d5a91bd8a3b26dec"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: files0_iter_stdin\n\nDocumentation:\nTo be used with `--files0-from=-`, this applies a filter on the results of files0_iter to\ntranslate '-' into the appropriate error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn files0_iter_stdin<'a>() -> impl Iterator> {\n files0_iter(io::stdin().lock(), STDIN_REPR.into()).map(|i| match i {\n Ok(Input::Stdin(_)) => Err(WcError::StdinReprNotAllowed.into()),\n _ => i,\n })\n}\n```"}], "func_name": "files0_iter_stdin", "docstring": "To be used with `--files0-from=-`, this applies a filter on the results of files0_iter to\ntranslate '-' into the appropriate error.", "repo": "uutils/coreutils", "path": "src/uu/wc/src/wc.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/wc/src/wc.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "71811a118629ae6e6efc2c5ce675771b034d01ee13dd137183961f6c6dc73901"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_complete_offsets\n\nDocumentation:\n(consumed_from_input, None): not enough input\n(consumed_from_input, Some(Err(()))): error bytes in buffer\n(consumed_from_input, Some(Ok(()))): UTF-8 string in buffer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn try_complete_offsets(&mut self, input: &[u8]) -> (usize, Option>) {\n let initial_buffer_len = self.buffer_len as usize;\n let copied_from_input;\n {\n let unwritten = &mut self.buffer[initial_buffer_len..];\n copied_from_input = cmp::min(unwritten.len(), input.len());\n unwritten[..copied_from_input].copy_from_slice(&input[..copied_from_input]);\n }\n let spliced = &self.buffer[..initial_buffer_len + copied_from_input];\n match str::from_utf8(spliced) {\n Ok(_) => {\n self.buffer_len = spliced.len() as u8;\n (copied_from_input, Some(Ok(())))\n }\n Err(error) => {\n let valid_up_to = error.valid_up_to();\n if valid_up_to > 0 {\n let consumed = valid_up_to.checked_sub(initial_buffer_len).unwrap();\n self.buffer_len = valid_up_to as u8;\n (consumed, Some(Ok(())))\n } else {\n match error.error_len() {\n Some(invalid_sequence_length) => {\n let consumed = invalid_sequence_length\n .checked_sub(initial_buffer_len)\n .unwrap();\n self.buffer_len = invalid_sequence_length as u8;\n (consumed, Some(Err(())))\n }\n None => {\n self.buffer_len = spliced.len() as u8;\n (copied_from_input, None)\n }\n }\n }\n }\n }\n }\n```"}], "func_name": "try_complete_offsets", "docstring": "(consumed_from_input, None): not enough input\n(consumed_from_input, Some(Err(()))): error bytes in buffer\n(consumed_from_input, Some(Ok(()))): UTF-8 string in buffer", "repo": "uutils/coreutils", "path": "src/uu/wc/src/utf8/mod.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uu/wc/src/utf8/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5f1747233b6e07894555b604f50569c1da808c755cb18d4812e99e17df3f2d8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: format_usage\n\nDocumentation:\nGenerate the usage string for clap.\n\nThis function does two things. It indents all but the first line to align\nthe lines because clap adds \"Usage: \" to the first line. And it replaces\nall occurrences of `{}` with the execution phrase and returns the resulting\n`String`. It does **not** support more advanced formatting features such\nas `{0}`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn format_usage(s: &str) -> String {\n let s = s.replace('\\n', &format!(\"\\n{}\", \" \".repeat(7)));\n s.replace(\"{}\", crate::execution_phrase())\n}\n```"}], "func_name": "format_usage", "docstring": "Generate the usage string for clap.\n\nThis function does two things. It indents all but the first line to align\nthe lines because clap adds \"Usage: \" to the first line. And it replaces\nall occurrences of `{}` with the execution phrase and returns the resulting\n`String`. It does **not** support more advanced formatting features such\nas `{0}`.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5cfacd8bb3ca629022323d61898e248705e18462cb5c1e6671fba8ca7c2c032b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_utility_is_second_arg\n\nDocumentation:\nChange the value of `UTILITY_IS_SECOND_ARG` to true\nUsed to specify that the utility is the second argument.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_utility_is_second_arg() {\n crate::macros::UTILITY_IS_SECOND_ARG.store(true, Ordering::SeqCst);\n}\n```"}], "func_name": "set_utility_is_second_arg", "docstring": "Change the value of `UTILITY_IS_SECOND_ARG` to true\nUsed to specify that the utility is the second argument.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "688229d0d517930bd26e7112825a5e609382e52098e88d0980cb7d464896990d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: collect_lossy\n\nDocumentation:\nCollects the iterator into a `Vec`, lossily converting the `OsString`s to `Strings`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn collect_lossy(self) -> Vec {\n self.map(|s| s.to_string_lossy().into_owned()).collect()\n }\n```"}], "func_name": "collect_lossy", "docstring": "Collects the iterator into a `Vec`, lossily converting the `OsString`s to `Strings`.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d23242b0cc82b07aacc75cd3d5b07ace560e3131e895c3c3d725ea759b805c27"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: collect_ignore\n\nDocumentation:\nCollects the iterator into a `Vec`, removing any elements that contain invalid encoding.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn collect_ignore(self) -> Vec {\n self.filter_map(|s| s.into_string().ok()).collect()\n }\n```"}], "func_name": "collect_ignore", "docstring": "Collects the iterator into a `Vec`, removing any elements that contain invalid encoding.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "773af65544327621649d329b0a2334939c32061d24b773e9cef89e2433436908"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_yes\n\nDocumentation:\nRead a line from stdin and check whether the first character is `'y'` or `'Y'`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_yes() -> bool {\n let mut s = String::new();\n match std::io::stdin().read_line(&mut s) {\n Ok(_) => matches!(s.chars().next(), Some('y' | 'Y')),\n _ => false,\n }\n}\n```"}], "func_name": "read_yes", "docstring": "Read a line from stdin and check whether the first character is `'y'` or `'Y'`", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a15458c3975da073c41e5b934cd66b9f983d42fabf73d7bd0595cd810a2948e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: os_str_as_bytes\n\nDocumentation:\nConverts an `OsStr` to a UTF-8 `&[u8]`.\n\nThis always succeeds on unix platforms,\nand fails on other platforms if the string can't be coerced to UTF-8.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn os_str_as_bytes(os_string: &OsStr) -> mods::error::UResult<&[u8]> {\n #[cfg(unix)]\n let bytes = os_string.as_bytes();\n\n #[cfg(not(unix))]\n let bytes = os_string\n .to_str()\n .ok_or_else(|| {\n mods::error::UUsageError::new(1, \"invalid UTF-8 was detected in one or more arguments\")\n })?\n .as_bytes();\n\n Ok(bytes)\n}\n```"}], "func_name": "os_str_as_bytes", "docstring": "Converts an `OsStr` to a UTF-8 `&[u8]`.\n\nThis always succeeds on unix platforms,\nand fails on other platforms if the string can't be coerced to UTF-8.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ae4bd1fcdf09c5f316f7034e346f62a9fbc1d63c35a7c39a9e532c31cfc20d02"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: os_str_as_bytes_lossy\n\nDocumentation:\nPerforms a potentially lossy conversion from `OsStr` to UTF-8 bytes.\n\nThis is always lossless on unix platforms,\nand wraps [`OsStr::to_string_lossy`] on non-unix platforms.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn os_str_as_bytes_lossy(os_string: &OsStr) -> Cow<[u8]> {\n #[cfg(unix)]\n let bytes = Cow::from(os_string.as_bytes());\n\n #[cfg(not(unix))]\n let bytes = match os_string.to_string_lossy() {\n Cow::Borrowed(slice) => Cow::from(slice.as_bytes()),\n Cow::Owned(owned) => Cow::from(owned.into_bytes()),\n };\n\n bytes\n}\n```"}], "func_name": "os_str_as_bytes_lossy", "docstring": "Performs a potentially lossy conversion from `OsStr` to UTF-8 bytes.\n\nThis is always lossless on unix platforms,\nand wraps [`OsStr::to_string_lossy`] on non-unix platforms.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc22999d35f2e053cea38f38ecd82783dcd2cf6e51fb6523a1bd7a0464e10c16"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: os_str_from_bytes\n\nDocumentation:\nConverts a `&[u8]` to an `&OsStr`,\nor parses it as UTF-8 into an [`OsString`] on non-unix platforms.\n\nThis always succeeds on unix platforms,\nand fails on other platforms if the bytes can't be parsed as UTF-8.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn os_str_from_bytes(bytes: &[u8]) -> mods::error::UResult> {\n #[cfg(unix)]\n let os_str = Cow::Borrowed(OsStr::from_bytes(bytes));\n #[cfg(not(unix))]\n let os_str = Cow::Owned(OsString::from(str::from_utf8(bytes).map_err(|_| {\n mods::error::UUsageError::new(1, \"Unable to transform bytes into OsStr\")\n })?));\n\n Ok(os_str)\n}\n```"}], "func_name": "os_str_from_bytes", "docstring": "Converts a `&[u8]` to an `&OsStr`,\nor parses it as UTF-8 into an [`OsString`] on non-unix platforms.\n\nThis always succeeds on unix platforms,\nand fails on other platforms if the bytes can't be parsed as UTF-8.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e65590d31a7da29c87ea3280559b6f6b1f25afa90ee99b02d6330000a1769aa8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: os_string_from_vec\n\nDocumentation:\nConverts a `Vec` into an `OsString`, parsing as UTF-8 on non-unix platforms.\n\nThis always succeeds on unix platforms,\nand fails on other platforms if the bytes can't be parsed as UTF-8.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn os_string_from_vec(vec: Vec) -> mods::error::UResult {\n #[cfg(unix)]\n let s = OsString::from_vec(vec);\n #[cfg(not(unix))]\n let s = OsString::from(String::from_utf8(vec).map_err(|_| {\n mods::error::UUsageError::new(1, \"invalid UTF-8 was detected in one or more arguments\")\n })?);\n\n Ok(s)\n}\n```"}], "func_name": "os_string_from_vec", "docstring": "Converts a `Vec` into an `OsString`, parsing as UTF-8 on non-unix platforms.\n\nThis always succeeds on unix platforms,\nand fails on other platforms if the bytes can't be parsed as UTF-8.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "90a2f0b83e9f34194d2e0b84f29b599c5969f2383f19a7336b7d33e5c90fc1b5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_byte_lines\n\nDocumentation:\nEquivalent to `std::BufRead::lines` which outputs each line as a `Vec`,\nwhich avoids panicking on non UTF-8 input.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_byte_lines(\n mut buf_reader: BufReader,\n) -> impl Iterator> {\n iter::from_fn(move || {\n let mut buf = Vec::with_capacity(256);\n let size = buf_reader.read_until(b'\\n', &mut buf).ok()?;\n\n if size == 0 {\n return None;\n }\n\n // Trim (\\r)\\n\n if buf.ends_with(b\"\\n\") {\n buf.pop();\n if buf.ends_with(b\"\\r\") {\n buf.pop();\n }\n }\n\n Some(buf)\n })\n}\n```"}], "func_name": "read_byte_lines", "docstring": "Equivalent to `std::BufRead::lines` which outputs each line as a `Vec`,\nwhich avoids panicking on non UTF-8 input.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "64bde99af3b942eb88dc815304890d71d6977f5ade143ea5da28ec2886862101"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_os_string_lines\n\nDocumentation:\nEquivalent to `std::BufRead::lines` which outputs each line as an `OsString`\nThis won't panic on non UTF-8 characters on Unix,\nbut it still will on Windows.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_os_string_lines(\n buf_reader: BufReader,\n) -> impl Iterator {\n read_byte_lines(buf_reader).map(|byte_line| os_string_from_vec(byte_line).expect(\"UTF-8 error\"))\n}\n```"}], "func_name": "read_os_string_lines", "docstring": "Equivalent to `std::BufRead::lines` which outputs each line as an `OsString`\nThis won't panic on non UTF-8 characters on Unix,\nbut it still will on Windows.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c938e2919795527932950de285578366c1af9fa2e496ebc97c15ed0b62a8bfd2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: determine_backup_suffix\n\nDocumentation:\nObtain the suffix to use for a backup.\n\nIn order of precedence, this function obtains the backup suffix\n\n1. From the '-S' or '--suffix' CLI argument, if present\n2. From the \"SIMPLE_BACKUP_SUFFIX\" environment variable, if present\n3. By using the default '~' if none of the others apply\n\nThis function directly takes [`clap::ArgMatches`] as argument and looks for\nthe '-S' and '--suffix' arguments itself.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn determine_backup_suffix(matches: &ArgMatches) -> String {\n let supplied_suffix = matches.get_one::(arguments::OPT_SUFFIX);\n if let Some(suffix) = supplied_suffix {\n String::from(suffix)\n } else {\n env::var(\"SIMPLE_BACKUP_SUFFIX\").unwrap_or_else(|_| DEFAULT_BACKUP_SUFFIX.to_owned())\n }\n}\n```"}], "func_name": "determine_backup_suffix", "docstring": "Obtain the suffix to use for a backup.\n\nIn order of precedence, this function obtains the backup suffix\n\n1. From the '-S' or '--suffix' CLI argument, if present\n2. From the \"SIMPLE_BACKUP_SUFFIX\" environment variable, if present\n3. By using the default '~' if none of the others apply\n\nThis function directly takes [`clap::ArgMatches`] as argument and looks for\nthe '-S' and '--suffix' arguments itself.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/backup_control.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/backup_control.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d0ade345a163e53126ae98789bbe2fb7bc9c6b94ca88a173ea17b3de2b87a87"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: determine_backup_mode\n\nDocumentation:\nDetermine the \"mode\" for the backup operation to perform, if any.\n\nParses the backup options according to the [GNU manual][1], and converts\nthem to an instance of `BackupMode` for further processing.\n\nTakes [`clap::ArgMatches`] as argument which **must** contain the options\nfrom [`arguments::backup()`] and [`arguments::backup_no_args()`]. Otherwise\nthe `NoBackup` mode is returned unconditionally.\n\nIt is recommended for anyone who would like to implement the\nbackup-functionality to use the arguments prepared in the `arguments`\nsubmodule (see examples)\n\n[1]: https://www.gnu.org/software/coreutils/manual/html_node/Backup-options.html\n\n\n# Errors\n\nIf an argument supplied directly to the long `backup` option, or read in\nthrough the `VERSION CONTROL` env var is ambiguous (i.e. may resolve to\nmultiple backup modes) or invalid, an [`InvalidArgument`][10] or\n[`AmbiguousArgument`][11] error is returned, respectively.\n\n[10]: BackupError::InvalidArgument\n[11]: BackupError::AmbiguousArgument\n\n\n# Examples\n\nHere's how one would integrate the backup mode determination into an\napplication.\n\n```\n#[macro_use]\nextern crate uucore;\nuse uucore::backup_control::{self, BackupMode};\nuse clap::{Command, Arg, ArgMatches};\n\nfn main() {\nlet matches = Command::new(\"command\")\n.arg(backup_control::arguments::backup())\n.arg(backup_control::arguments::backup_no_args())\n.get_matches_from(vec![\n\"command\", \"-b\", \"--backup=t\"\n]);\n\nlet backup_mode = backup_control::determine_backup_mode(&matches).unwrap();\nassert_eq!(backup_mode, BackupMode::Numbered)\n}\n```\n\nThis example shows an ambiguous input, as 'n' may resolve to 4 different\nbackup modes.\n\n\n```\n#[macro_use]\nextern crate uucore;\nuse uucore::backup_control::{self, BackupMode, BackupError};\nuse clap::{Command, Arg, ArgMatches};\n\nfn main() {\nlet matches = Command::new(\"command\")\n.arg(backup_control::arguments::backup())\n.arg(backup_control::arguments::backup_no_args())\n.get_matches_from(vec![\n\"command\", \"-b\", \"--backup=n\"\n]);\n\nlet backup_mode = backup_control::determine_backup_mode(&matches);\n\nassert!(backup_mode.is_err());\nlet err = backup_mode.unwrap_err();\n// assert_eq!(err, BackupError::AmbiguousArgument);\n// Use uucore functionality to show the error to the user\nshow!(err);\n}\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn determine_backup_mode(matches: &ArgMatches) -> UResult {\n if matches.contains_id(arguments::OPT_BACKUP) {\n // Use method to determine the type of backups to make. When this option\n // is used but method is not specified, then the value of the\n // VERSION_CONTROL environment variable is used. And if VERSION_CONTROL\n // is not set, the default backup type is 'existing'.\n if let Some(method) = matches.get_one::(arguments::OPT_BACKUP) {\n // Second argument is for the error string that is returned.\n match_method(method, \"backup type\")\n } else if let Ok(method) = env::var(\"VERSION_CONTROL\") {\n // Second argument is for the error string that is returned.\n match_method(&method, \"$VERSION_CONTROL\")\n } else {\n // Default if no argument is provided to '--backup'\n Ok(BackupMode::Existing)\n }\n } else if matches.get_flag(arguments::OPT_BACKUP_NO_ARG) {\n // the short form of this option, -b does not accept any argument.\n // if VERSION_CONTROL is not set then using -b is equivalent to\n // using --backup=existing.\n if let Ok(method) = env::var(\"VERSION_CONTROL\") {\n match_method(&method, \"$VERSION_CONTROL\")\n } else {\n Ok(BackupMode::Existing)\n }\n } else {\n // No option was present at all\n Ok(BackupMode::None)\n }\n}\n```"}], "func_name": "determine_backup_mode", "docstring": "Determine the \"mode\" for the backup operation to perform, if any.\n\nParses the backup options according to the [GNU manual][1], and converts\nthem to an instance of `BackupMode` for further processing.\n\nTakes [`clap::ArgMatches`] as argument which **must** contain the options\nfrom [`arguments::backup()`] and [`arguments::backup_no_args()`]. Otherwise\nthe `NoBackup` mode is returned unconditionally.\n\nIt is recommended for anyone who would like to implement the\nbackup-functionality to use the arguments prepared in the `arguments`\nsubmodule (see examples)\n\n[1]: https://www.gnu.org/software/coreutils/manual/html_node/Backup-options.html\n\n\n# Errors\n\nIf an argument supplied directly to the long `backup` option, or read in\nthrough the `VERSION CONTROL` env var is ambiguous (i.e. may resolve to\nmultiple backup modes) or invalid, an [`InvalidArgument`][10] or\n[`AmbiguousArgument`][11] error is returned, respectively.\n\n[10]: BackupError::InvalidArgument\n[11]: BackupError::AmbiguousArgument\n\n\n# Examples\n\nHere's how one would integrate the backup mode determination into an\napplication.\n\n```\n#[macro_use]\nextern crate uucore;\nuse uucore::backup_control::{self, BackupMode};\nuse clap::{Command, Arg, ArgMatches};\n\nfn main() {\nlet matches = Command::new(\"command\")\n.arg(backup_control::arguments::backup())\n.arg(backup_control::arguments::backup_no_args())\n.get_matches_from(vec![\n\"command\", \"-b\", \"--backup=t\"\n]);\n\nlet backup_mode = backup_control::determine_backup_mode(&matches).unwrap();\nassert_eq!(backup_mode, BackupMode::Numbered)\n}\n```\n\nThis example shows an ambiguous input, as 'n' may resolve to 4 different\nbackup modes.\n\n\n```\n#[macro_use]\nextern crate uucore;\nuse uucore::backup_control::{self, BackupMode, BackupError};\nuse clap::{Command, Arg, ArgMatches};\n\nfn main() {\nlet matches = Command::new(\"command\")\n.arg(backup_control::arguments::backup())\n.arg(backup_control::arguments::backup_no_args())\n.get_matches_from(vec![\n\"command\", \"-b\", \"--backup=n\"\n]);\n\nlet backup_mode = backup_control::determine_backup_mode(&matches);\n\nassert!(backup_mode.is_err());\nlet err = backup_mode.unwrap_err();\n// assert_eq!(err, BackupError::AmbiguousArgument);\n// Use uucore functionality to show the error to the user\nshow!(err);\n}\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/backup_control.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/backup_control.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1e0cb2ba1c22c1b4786f1d27c349c47d36c1a3cc98d8217159c432a785d20084"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: match_method\n\nDocumentation:\nMatch a backup option string to a `BackupMode`.\n\nThe GNU manual specifies that abbreviations to options are valid as long as\nthey aren't ambiguous. This function matches the given `method` argument\nagainst all valid backup options (via `starts_with`), and returns a valid\n[`BackupMode`] if exactly one backup option matches the `method` given.\n\n`origin` is required in order to format the generated error message\nproperly, when an error occurs.\n\n\n# Errors\n\nIf `method` is invalid or ambiguous (i.e. may resolve to multiple backup\nmodes), an [`InvalidArgument`][10] or [`AmbiguousArgument`][11] error is\nreturned, respectively.\n\n[10]: BackupError::InvalidArgument\n[11]: BackupError::AmbiguousArgument\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn match_method(method: &str, origin: &str) -> UResult {\n let matches: Vec<&&str> = BACKUP_CONTROL_VALUES\n .iter()\n .filter(|val| val.starts_with(method))\n .collect();\n if matches.len() == 1 {\n match *matches[0] {\n \"simple\" | \"never\" => Ok(BackupMode::Simple),\n \"numbered\" | \"t\" => Ok(BackupMode::Numbered),\n \"existing\" | \"nil\" => Ok(BackupMode::Existing),\n \"none\" | \"off\" => Ok(BackupMode::None),\n _ => unreachable!(), // cannot happen as we must have exactly one match\n // from the list above.\n }\n } else if matches.is_empty() {\n Err(BackupError::InvalidArgument(method.to_string(), origin.to_string()).into())\n } else {\n Err(BackupError::AmbiguousArgument(method.to_string(), origin.to_string()).into())\n }\n}\n```"}], "func_name": "match_method", "docstring": "Match a backup option string to a `BackupMode`.\n\nThe GNU manual specifies that abbreviations to options are valid as long as\nthey aren't ambiguous. This function matches the given `method` argument\nagainst all valid backup options (via `starts_with`), and returns a valid\n[`BackupMode`] if exactly one backup option matches the `method` given.\n\n`origin` is required in order to format the generated error message\nproperly, when an error occurs.\n\n\n# Errors\n\nIf `method` is invalid or ambiguous (i.e. may resolve to multiple backup\nmodes), an [`InvalidArgument`][10] or [`AmbiguousArgument`][11] error is\nreturned, respectively.\n\n[10]: BackupError::InvalidArgument\n[11]: BackupError::AmbiguousArgument", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/backup_control.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/backup_control.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d65e695700922295965bbfc834f8fd4f05b4c8ff7b58f93b54a41c5a99564672"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: source_is_target_backup\n\nDocumentation:\nReturns true if the source file is likely to be the simple backup file for the target file.\n\n# Arguments\n\n* `source` - A Path reference that holds the source (backup) file path.\n* `target` - A Path reference that holds the target file path.\n* `suffix` - Str that holds the backup suffix.\n\n# Examples\n\n```\nuse std::path::Path;\nuse uucore::backup_control::source_is_target_backup;\nlet source = Path::new(\"data.txt~\");\nlet target = Path::new(\"data.txt\");\nlet suffix = String::from(\"~\");\n\nassert_eq!(source_is_target_backup(&source, &target, &suffix), true);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn source_is_target_backup(source: &Path, target: &Path, suffix: &str) -> bool {\n let source_filename = source.to_string_lossy();\n let target_backup_filename = format!(\"{}{suffix}\", target.to_string_lossy());\n source_filename == target_backup_filename\n}\n```"}], "func_name": "source_is_target_backup", "docstring": "Returns true if the source file is likely to be the simple backup file for the target file.\n\n# Arguments\n\n* `source` - A Path reference that holds the source (backup) file path.\n* `target` - A Path reference that holds the target file path.\n* `suffix` - Str that holds the backup suffix.\n\n# Examples\n\n```\nuse std::path::Path;\nuse uucore::backup_control::source_is_target_backup;\nlet source = Path::new(\"data.txt~\");\nlet target = Path::new(\"data.txt\");\nlet suffix = String::from(\"~\");\n\nassert_eq!(source_is_target_backup(&source, &target, &suffix), true);\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/backup_control.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/backup_control.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f21b05085ded0fe63c240d3f82c3d764de9edb6465e917e5fd54e6d0711faf3c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_sha3\n\nDocumentation:\nCreates a SHA3 hasher instance based on the specified bits argument.\n\n# Returns\n\nReturns a UResult of a tuple containing the algorithm name, the hasher instance, and\nthe output length in bits or an Err if an unsupported output size is provided, or if\nthe `--bits` flag is missing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_sha3(bits: Option) -> UResult {\n match bits {\n Some(224) => Ok(HashAlgorithm {\n name: \"SHA3_224\",\n create_fn: Box::new(|| Box::new(Sha3_224::new())),\n bits: 224,\n }),\n Some(256) => Ok(HashAlgorithm {\n name: \"SHA3_256\",\n create_fn: Box::new(|| Box::new(Sha3_256::new())),\n bits: 256,\n }),\n Some(384) => Ok(HashAlgorithm {\n name: \"SHA3_384\",\n create_fn: Box::new(|| Box::new(Sha3_384::new())),\n bits: 384,\n }),\n Some(512) => Ok(HashAlgorithm {\n name: \"SHA3_512\",\n create_fn: Box::new(|| Box::new(Sha3_512::new())),\n bits: 512,\n }),\n\n Some(_) => Err(ChecksumError::InvalidOutputSizeForSha3.into()),\n None => Err(ChecksumError::BitsRequiredForSha3.into()),\n }\n}\n```"}], "func_name": "create_sha3", "docstring": "Creates a SHA3 hasher instance based on the specified bits argument.\n\n# Returns\n\nReturns a UResult of a tuple containing the algorithm name, the hasher instance, and\nthe output length in bits or an Err if an unsupported output size is provided, or if\nthe `--bits` flag is missing.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e20f2aba14e88d72596e86da4014462f3c38e8300516028e17461c11d54d2e65"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_bool\n\nDocumentation:\nCreates a `FileChecksumResult` from a digest comparison that\neither succeeded or failed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_bool(checksum_correct: bool) -> Self {\n if checksum_correct {\n FileChecksumResult::Ok\n } else {\n FileChecksumResult::Failed\n }\n }\n```"}], "func_name": "from_bool", "docstring": "Creates a `FileChecksumResult` from a digest comparison that\neither succeeded or failed.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cfa3d73768f6771f85ce6be993f946f757726fd2e75e9d5e5ba6fcef0506dfef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: can_display\n\nDocumentation:\nThe cli options might prevent to display on the outcome of the\ncomparison on STDOUT.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn can_display(&self, verbose: ChecksumVerbose) -> bool {\n match self {\n FileChecksumResult::Ok => verbose.over_quiet(),\n FileChecksumResult::Failed => verbose.over_status(),\n FileChecksumResult::CantOpen => true,\n }\n }\n```"}], "func_name": "can_display", "docstring": "The cli options might prevent to display on the outcome of the\ncomparison on STDOUT.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18ef15aa0ce936ac419ae207dc5e1fdf4bc1f928cd514d0a7139e3a443a1027f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_file_report\n\nDocumentation:\nPrint to the given buffer the checksum validation status of a file which\nname might contain non-utf-8 characters.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_file_report(\n mut w: W,\n filename: &[u8],\n result: FileChecksumResult,\n prefix: &str,\n verbose: ChecksumVerbose,\n) {\n if result.can_display(verbose) {\n let _ = write!(w, \"{prefix}\");\n let _ = w.write_all(filename);\n let _ = writeln!(w, \": {result}\");\n }\n}\n```"}], "func_name": "print_file_report", "docstring": "Print to the given buffer the checksum validation status of a file which\nname might contain non-utf-8 characters.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1634e926ddfa64b1780813488b9824d6b2b92c89959a375895354f4660b55b50"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_algo_based\n\nDocumentation:\nparse [tagged output format]\nNormally the format is simply space separated but openssl does not\nrespect the gnu definition.\n\n[tagged output format]: https://www.gnu.org/software/coreutils/manual/html_node/cksum-output-modes.html#cksum-output-modes-1\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_algo_based(line: &[u8]) -> Option {\n // r\"\\MD5 (a\\\\ b) = abc123\",\n // BLAKE2b(44)= a45a4c4883cce4b50d844fab460414cc2080ca83690e74d850a9253e757384366382625b218c8585daee80f34dc9eb2f2fde5fb959db81cd48837f9216e7b0fa\n let trimmed = line.trim_ascii_start();\n let algo_start = if trimmed.starts_with(b\"\\\\\") { 1 } else { 0 };\n let rest = &trimmed[algo_start..];\n\n enum SubCase {\n Posix,\n OpenSSL,\n }\n // find the next parenthesis using byte search (not next whitespace) because openssl's\n // tagged format does not put a space before (filename)\n\n let par_idx = rest.iter().position(|&b| b == b'(')?;\n let sub_case = if rest[par_idx - 1] == b' ' {\n SubCase::Posix\n } else {\n SubCase::OpenSSL\n };\n\n let algo_substring = match sub_case {\n SubCase::Posix => &rest[..par_idx - 1],\n SubCase::OpenSSL => &rest[..par_idx],\n };\n let mut algo_parts = algo_substring.splitn(2, |&b| b == b'-');\n let algo = algo_parts.next()?;\n\n // Parse algo_bits if present\n let algo_bits = algo_parts\n .next()\n .and_then(|s| std::str::from_utf8(s).ok()?.parse::().ok());\n\n // Check algo format: uppercase ASCII or digits or \"BLAKE2b\"\n let is_valid_algo = algo == b\"BLAKE2b\"\n || algo\n .iter()\n .all(|&b| b.is_ascii_uppercase() || b.is_ascii_digit());\n if !is_valid_algo {\n return None;\n }\n // SAFETY: we just validated the contents of algo, we can unsafely make a\n // String from it\n let algo_utf8 = unsafe { String::from_utf8_unchecked(algo.to_vec()) };\n // stripping '(' not ' (' since we matched on ( not whitespace because of openssl.\n let after_paren = rest.get(par_idx + 1..)?;\n let (filename, checksum) = match sub_case {\n SubCase::Posix => ByteSliceExt::rsplit_once(after_paren, b\") = \")?,\n SubCase::OpenSSL => ByteSliceExt::rsplit_once(after_paren, b\")= \")?,\n };\n\n fn is_valid_checksum(checksum: &[u8]) -> bool {\n if checksum.is_empty() {\n return false;\n }\n\n let mut parts = checksum.splitn(2, |&b| b == b'=');\n let main = parts.next().unwrap(); // Always exists since checksum isn't empty\n let padding = parts.next().unwrap_or_default(); // Empty if no '='\n\n main.iter()\n .all(|&b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/')\n && !main.is_empty()\n && padding.len() <= 2\n && padding.iter().all(|&b| b == b'=')\n }\n if !is_valid_checksum(checksum) {\n return None;\n }\n // SAFETY: we just validated the contents of checksum, we can unsafely make a\n // String from it\n let checksum_utf8 = unsafe { String::from_utf8_unchecked(checksum.to_vec()) };\n\n Some(LineInfo {\n algo_name: Some(algo_utf8),\n algo_bit_len: algo_bits,\n checksum: checksum_utf8,\n filename: filename.to_vec(),\n format: LineFormat::AlgoBased,\n })\n }\n```"}], "func_name": "parse_algo_based", "docstring": "parse [tagged output format]\nNormally the format is simply space separated but openssl does not\nrespect the gnu definition.\n\n[tagged output format]: https://www.gnu.org/software/coreutils/manual/html_node/cksum-output-modes.html#cksum-output-modes-1", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "64891d6431e4641396596b966b189af6badaeb09027c0c1aa2a488f907ab94ae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_untagged\n\nDocumentation:\nparse [untagged output format]\nThe format is simple, either \" \" or\n\" *\"\n\n[untagged output format]: https://www.gnu.org/software/coreutils/manual/html_node/cksum-output-modes.html#cksum-output-modes-1\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_untagged(line: &[u8]) -> Option {\n let space_idx = line.iter().position(|&b| b == b' ')?;\n let checksum = &line[..space_idx];\n if !checksum.iter().all(|&b| b.is_ascii_hexdigit()) || checksum.is_empty() {\n return None;\n }\n // SAFETY: we just validated the contents of checksum, we can unsafely make a\n // String from it\n let checksum_utf8 = unsafe { String::from_utf8_unchecked(checksum.to_vec()) };\n\n let rest = &line[space_idx..];\n let filename = rest\n .strip_prefix(b\" \")\n .or_else(|| rest.strip_prefix(b\" *\"))?;\n\n Some(LineInfo {\n algo_name: None,\n algo_bit_len: None,\n checksum: checksum_utf8,\n filename: filename.to_vec(),\n format: LineFormat::Untagged,\n })\n }\n```"}], "func_name": "parse_untagged", "docstring": "parse [untagged output format]\nThe format is simple, either \" \" or\n\" *\"\n\n[untagged output format]: https://www.gnu.org/software/coreutils/manual/html_node/cksum-output-modes.html#cksum-output-modes-1", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f114c13cffdf4217f0f75abf5d4a78c93b63afd2c710939951fdbb972ace1599"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse\n\nDocumentation:\nReturns a `LineInfo` parsed from a checksum line.\nThe function will run 3 parsers against the line and select the first one that matches\nto populate the fields of the struct.\nHowever, there is a catch to handle regarding the handling of `cached_line_format`.\nIn case of non-algo-based format, if `cached_line_format` is Some, it must take the priority\nover the detected format. Otherwise, we must set it the the detected format.\nThis specific behavior is emphasized by the test\n`test_hashsum::test_check_md5sum_only_one_space`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse(s: impl AsRef, cached_line_format: &mut Option) -> Option {\n let line_bytes = os_str_as_bytes(s.as_ref()).ok()?;\n\n if let Some(info) = LineFormat::parse_algo_based(line_bytes) {\n return Some(info);\n }\n if let Some(cached_format) = cached_line_format {\n match cached_format {\n LineFormat::Untagged => LineFormat::parse_untagged(line_bytes),\n LineFormat::SingleSpace => LineFormat::parse_single_space(line_bytes),\n _ => unreachable!(\"we never catch the algo based format\"),\n }\n } else if let Some(info) = LineFormat::parse_untagged(line_bytes) {\n *cached_line_format = Some(LineFormat::Untagged);\n Some(info)\n } else if let Some(info) = LineFormat::parse_single_space(line_bytes) {\n *cached_line_format = Some(LineFormat::SingleSpace);\n Some(info)\n } else {\n None\n }\n }\n```"}], "func_name": "parse", "docstring": "Returns a `LineInfo` parsed from a checksum line.\nThe function will run 3 parsers against the line and select the first one that matches\nto populate the fields of the struct.\nHowever, there is a catch to handle regarding the handling of `cached_line_format`.\nIn case of non-algo-based format, if `cached_line_format` is Some, it must take the priority\nover the detected format. Otherwise, we must set it the the detected format.\nThis specific behavior is emphasized by the test\n`test_hashsum::test_check_md5sum_only_one_space`.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b6bd48a33bc00704ce6305255ed7937f3102c4fcb67d301e944d8ad9284611f8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_expected_digest_as_hex_string\n\nDocumentation:\nExtract the expected digest from the checksum string\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_expected_digest_as_hex_string(\n line_info: &LineInfo,\n len_hint: Option,\n) -> Option> {\n let ck = &line_info.checksum;\n\n let against_hint = |len| len_hint.is_none_or(|l| l == len);\n\n if ck.len() % 2 != 0 {\n // If the length of the digest is not a multiple of 2, then it\n // must be improperly formatted (1 hex digit is 2 characters)\n return None;\n }\n\n // If the digest can be decoded as hexadecimal AND its length matches the\n // one expected (in case it's given), just go with it.\n if ck.as_bytes().iter().all(u8::is_ascii_hexdigit) && against_hint(ck.len()) {\n return Some(Cow::Borrowed(ck));\n }\n\n // If hexadecimal digest fails for any reason, interpret the digest as base 64.\n BASE64\n .decode(ck.as_bytes()) // Decode the string as encoded base64\n .map(hex::encode) // Encode it back as hexadecimal\n .map(Cow::::Owned)\n .ok()\n .and_then(|s| {\n // Check the digest length\n if against_hint(s.len()) { Some(s) } else { None }\n })\n}\n```"}], "func_name": "get_expected_digest_as_hex_string", "docstring": "Extract the expected digest from the checksum string", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf004c2c76e85d8268700b55ada2efebebf9b62ea50f2a1d6863edb690314066"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_file_to_check\n\nDocumentation:\nReturns a reader that reads from the specified file, or from stdin if `filename_to_check` is \"-\".\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_file_to_check(\n filename: &OsStr,\n opts: ChecksumOptions,\n) -> Result, LineCheckError> {\n let filename_bytes = os_str_as_bytes(filename).expect(\"UTF-8 error\");\n let filename_lossy = String::from_utf8_lossy(filename_bytes);\n if filename == \"-\" {\n Ok(Box::new(stdin())) // Use stdin if \"-\" is specified in the checksum file\n } else {\n let failed_open = || {\n print_file_report(\n std::io::stdout(),\n filename_bytes,\n FileChecksumResult::CantOpen,\n \"\",\n opts.verbose,\n );\n };\n match File::open(filename) {\n Ok(f) => {\n if f.metadata()\n .map_err(|_| LineCheckError::CantOpenFile)?\n .is_dir()\n {\n show!(USimpleError::new(\n 1,\n format!(\"{filename_lossy}: Is a directory\")\n ));\n // also regarded as a failed open\n failed_open();\n Err(LineCheckError::FileIsDirectory)\n } else {\n Ok(Box::new(f))\n }\n }\n Err(err) => {\n if !opts.ignore_missing {\n // yes, we have both stderr and stdout here\n show!(err.map_err_context(|| filename_lossy.to_string()));\n failed_open();\n }\n // we could not open the file but we want to continue\n Err(LineCheckError::FileNotFound)\n }\n }\n }\n}\n```"}], "func_name": "get_file_to_check", "docstring": "Returns a reader that reads from the specified file, or from stdin if `filename_to_check` is \"-\".", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "38919751c21692aedcf2fb1d86be7c39c14bbda96f89f812f220ef3f820da002"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_input_file\n\nDocumentation:\nReturns a reader to the list of checksums\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_input_file(filename: &OsStr) -> UResult> {\n match File::open(filename) {\n Ok(f) => {\n if f.metadata()?.is_dir() {\n Err(\n io::Error::other(format!(\"{}: Is a directory\", filename.to_string_lossy()))\n .into(),\n )\n } else {\n Ok(Box::new(f))\n }\n }\n Err(_) => Err(io::Error::other(format!(\n \"{}: No such file or directory\",\n filename.to_string_lossy()\n ))\n .into()),\n }\n}\n```"}], "func_name": "get_input_file", "docstring": "Returns a reader to the list of checksums", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "79b14a8ebc7c1034577d5ee24e6b9ea171d00c7fc79951cdf9d0f44fc4e8f3f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: identify_algo_name_and_length\n\nDocumentation:\nGets the algorithm name and length from the `LineInfo` if the algo-based format is matched.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn identify_algo_name_and_length(\n line_info: &LineInfo,\n algo_name_input: Option<&str>,\n last_algo: &mut Option,\n) -> Result<(String, Option), LineCheckError> {\n let algo_from_line = line_info.algo_name.clone().unwrap_or_default();\n let algorithm = algo_from_line.to_lowercase();\n *last_algo = Some(algo_from_line);\n\n // check if we are called with XXXsum (example: md5sum) but we detected a different algo parsing the file\n // (for example SHA1 (f) = d...)\n // Also handle the case cksum -s sm3 but the file contains other formats\n if algo_name_input.is_some() && algo_name_input != Some(&algorithm) {\n return Err(LineCheckError::ImproperlyFormatted);\n }\n\n if !SUPPORTED_ALGORITHMS.contains(&algorithm.as_str()) {\n // Not supported algo, leave early\n return Err(LineCheckError::ImproperlyFormatted);\n }\n\n let bytes = if let Some(bitlen) = line_info.algo_bit_len {\n if algorithm != ALGORITHM_OPTIONS_BLAKE2B || bitlen % 8 != 0 {\n // Either\n // the algo based line is provided with a bit length\n // with an algorithm that does not support it (only Blake2B does).\n //\n // eg: MD5-128 (foo.txt) = fffffffff\n // ^ This is illegal\n // OR\n // the given length is wrong because it's not a multiple of 8.\n return Err(LineCheckError::ImproperlyFormatted);\n }\n Some(bitlen / 8)\n } else if algorithm == ALGORITHM_OPTIONS_BLAKE2B {\n // Default length with BLAKE2b,\n Some(64)\n } else {\n None\n };\n\n Ok((algorithm, bytes))\n}\n```"}], "func_name": "identify_algo_name_and_length", "docstring": "Gets the algorithm name and length from the `LineInfo` if the algo-based format is matched.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6c912204398c9f92ac9518cfb0b65a271961ec8f0f7762b6c68bcfba4526b5f1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compute_and_check_digest_from_file\n\nDocumentation:\nGiven a filename and an algorithm, compute the digest and compare it with\nthe expected one.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compute_and_check_digest_from_file(\n filename: &[u8],\n expected_checksum: &str,\n mut algo: HashAlgorithm,\n opts: ChecksumOptions,\n) -> Result<(), LineCheckError> {\n let (filename_to_check_unescaped, prefix) = unescape_filename(filename);\n let real_filename_to_check = os_str_from_bytes(&filename_to_check_unescaped)?;\n\n // Open the input file\n let file_to_check = get_file_to_check(&real_filename_to_check, opts)?;\n let mut file_reader = BufReader::new(file_to_check);\n\n // Read the file and calculate the checksum\n let create_fn = &mut algo.create_fn;\n let mut digest = create_fn();\n let (calculated_checksum, _) =\n digest_reader(&mut digest, &mut file_reader, opts.binary, algo.bits).unwrap();\n\n // Do the checksum validation\n let checksum_correct = expected_checksum == calculated_checksum;\n print_file_report(\n std::io::stdout(),\n filename,\n FileChecksumResult::from_bool(checksum_correct),\n prefix,\n opts.verbose,\n );\n\n if checksum_correct {\n Ok(())\n } else {\n Err(LineCheckError::DigestMismatch)\n }\n}\n```"}], "func_name": "compute_and_check_digest_from_file", "docstring": "Given a filename and an algorithm, compute the digest and compare it with\nthe expected one.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "febfb98e5f15ee816c1ab1c1eb446cc8aca2cae1869087e61d3e463c4e13ecdc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_algo_based_line\n\nDocumentation:\nCheck a digest checksum with non-algo based pre-treatment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_algo_based_line(\n line_info: &LineInfo,\n cli_algo_name: Option<&str>,\n opts: ChecksumOptions,\n last_algo: &mut Option,\n) -> Result<(), LineCheckError> {\n let filename_to_check = line_info.filename.as_slice();\n\n let (algo_name, algo_byte_len) =\n identify_algo_name_and_length(line_info, cli_algo_name, last_algo)?;\n\n // If the digest bitlen is known, we can check the format of the expected\n // checksum with it.\n let digest_char_length_hint = match (algo_name.as_str(), algo_byte_len) {\n (ALGORITHM_OPTIONS_BLAKE2B, Some(bytelen)) => Some(bytelen * 2),\n _ => None,\n };\n\n let expected_checksum = get_expected_digest_as_hex_string(line_info, digest_char_length_hint)\n .ok_or(LineCheckError::ImproperlyFormatted)?;\n\n let algo = detect_algo(&algo_name, algo_byte_len)?;\n\n compute_and_check_digest_from_file(filename_to_check, &expected_checksum, algo, opts)\n}\n```"}], "func_name": "process_algo_based_line", "docstring": "Check a digest checksum with non-algo based pre-treatment.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f93daec4bf56fcde527710b5e1328b7807c3f0b63ac43f6be1df0dbfc29103e3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_checksum_line\n\nDocumentation:\nParses a checksum line, detect the algorithm to use, read the file and produce\nits digest, and compare it to the expected value.\n\nReturns `Ok(bool)` if the comparison happened, bool indicates if the digest\nmatched the expected.\nIf the comparison didn't happen, return a `LineChecksumError`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_checksum_line(\n line: &OsStr,\n i: usize,\n cli_algo_name: Option<&str>,\n cli_algo_length: Option,\n opts: ChecksumOptions,\n cached_line_format: &mut Option,\n last_algo: &mut Option,\n) -> Result<(), LineCheckError> {\n let line_bytes = os_str_as_bytes(line)?;\n\n // Early return on empty or commented lines.\n if line.is_empty() || line_bytes.starts_with(b\"#\") {\n return Err(LineCheckError::Skipped);\n }\n\n // Use `LineInfo` to extract the data of a line.\n // Then, depending on its format, apply a different pre-treatment.\n let Some(line_info) = LineInfo::parse(line, cached_line_format) else {\n return Err(LineCheckError::ImproperlyFormatted);\n };\n\n if line_info.format == LineFormat::AlgoBased {\n process_algo_based_line(&line_info, cli_algo_name, opts, last_algo)\n } else if let Some(cli_algo) = cli_algo_name {\n // If we match a non-algo based parser, we expect a cli argument\n // to give us the algorithm to use\n process_non_algo_based_line(i, &line_info, cli_algo, cli_algo_length, opts)\n } else {\n // We have no clue of what algorithm to use\n return Err(LineCheckError::ImproperlyFormatted);\n }\n}\n```"}], "func_name": "process_checksum_line", "docstring": "Parses a checksum line, detect the algorithm to use, read the file and produce\nits digest, and compare it to the expected value.\n\nReturns `Ok(bool)` if the comparison happened, bool indicates if the digest\nmatched the expected.\nIf the comparison didn't happen, return a `LineChecksumError`.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d118dd0e73ebbaf1562e653873f743a179edfc1067c91f00b16c0979b344fbc4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: calculate_blake2b_length\n\nDocumentation:\nCalculates the length of the digest.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn calculate_blake2b_length(length: usize) -> UResult> {\n match length {\n 0 => Ok(None),\n n if n % 8 != 0 => {\n show_error!(\"invalid length: \\u{2018}{length}\\u{2019}\");\n Err(io::Error::new(io::ErrorKind::InvalidInput, \"length is not a multiple of 8\").into())\n }\n n if n > 512 => {\n show_error!(\"invalid length: \\u{2018}{length}\\u{2019}\");\n Err(io::Error::new(\n io::ErrorKind::InvalidInput,\n \"maximum digest length for \\u{2018}BLAKE2b\\u{2019} is 512 bits\",\n )\n .into())\n }\n n => {\n // Divide by 8, as our blake2b implementation expects bytes instead of bits.\n if n == 512 {\n // When length is 512, it is blake2b's default.\n // So, don't show it\n Ok(None)\n } else {\n Ok(Some(n / 8))\n }\n }\n }\n}\n```"}], "func_name": "calculate_blake2b_length", "docstring": "Calculates the length of the digest.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/checksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/checksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7d9ea2f528f7015b634bec1f959f3d875475438e67c704a5ea75883fa5e8e5fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cstr2string\n\nDocumentation:\n# Safety\nptr must point to a valid C string.\n\nReturns None if ptr is null.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn cstr2string(ptr: *const c_char) -> Option {\n if ptr.is_null() {\n None\n } else {\n Some(unsafe { CStr::from_ptr(ptr).to_string_lossy().into_owned() })\n }\n}\n```"}], "func_name": "cstr2string", "docstring": "# Safety\nptr must point to a valid C string.\n\nReturns None if ptr is null.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/entries.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/entries.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cee6dac6b6110f8bbb5ead9cb2e95596396901e12cdf0185a6441e74aa6de775"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_raw\n\nDocumentation:\n# Safety\nAll the pointed-to strings must be valid and not change while\nthe function runs. That means PW_LOCK must be held.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn from_raw(raw: passwd) -> Self {\n Self {\n name: cstr2string(raw.pw_name).expect(\"passwd without name\"),\n uid: raw.pw_uid,\n gid: raw.pw_gid,\n #[cfg(not(all(\n target_os = \"android\",\n any(target_arch = \"x86\", target_arch = \"arm\")\n )))]\n user_info: cstr2string(raw.pw_gecos),\n #[cfg(all(target_os = \"android\", any(target_arch = \"x86\", target_arch = \"arm\")))]\n user_info: None,\n user_shell: cstr2string(raw.pw_shell),\n user_dir: cstr2string(raw.pw_dir),\n user_passwd: cstr2string(raw.pw_passwd),\n #[cfg(any(target_os = \"freebsd\", target_vendor = \"apple\"))]\n user_access_class: cstr2string(raw.pw_class),\n #[cfg(any(target_os = \"freebsd\", target_vendor = \"apple\"))]\n passwd_change_time: raw.pw_change,\n #[cfg(any(target_os = \"freebsd\", target_vendor = \"apple\"))]\n expiration: raw.pw_expire,\n }\n }\n```"}], "func_name": "from_raw", "docstring": "# Safety\nAll the pointed-to strings must be valid and not change while\nthe function runs. That means PW_LOCK must be held.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/entries.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/entries.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "36d3a721b502528e917bcf92773641f423e6907ad43543835832df79c8d0caca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: belongs_to\n\nDocumentation:\nThis is a wrapper function for `libc::getgrouplist`.\n\nFrom: ``\n> If the number of groups of which user is a member is less than or\n> equal to *ngroups, then the value *ngroups is returned.\n> If the user is a member of more than *ngroups groups, then\n> getgrouplist() returns -1. In this case, the value returned in\n> *ngroups can be used to resize the buffer passed to a further\n> call getgrouplist().\n\nHowever, on macOS/darwin (and maybe others?) `getgrouplist` does\nnot update `ngroups` if `ngroups` is too small. Therefore, if not\nupdated by `getgrouplist`, `ngroups` needs to be increased in a\nloop until `getgrouplist` stops returning -1.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn belongs_to(&self) -> Vec {\n let mut ngroups: c_int = 8;\n let mut ngroups_old: c_int;\n let mut groups = vec![0; ngroups.try_into().unwrap()];\n let name = CString::new(self.name.as_bytes()).unwrap();\n loop {\n ngroups_old = ngroups;\n if unsafe { getgrouplist(name.as_ptr(), self.gid, groups.as_mut_ptr(), &mut ngroups) }\n == -1\n {\n if ngroups == ngroups_old {\n ngroups *= 2;\n }\n groups.resize(ngroups.try_into().unwrap(), 0);\n } else {\n break;\n }\n }\n let ngroups = ngroups.try_into().unwrap();\n assert!(ngroups <= groups.len());\n groups.truncate(ngroups);\n groups\n }\n```"}], "func_name": "belongs_to", "docstring": "This is a wrapper function for `libc::getgrouplist`.\n\nFrom: ``\n> If the number of groups of which user is a member is less than or\n> equal to *ngroups, then the value *ngroups is returned.\n> If the user is a member of more than *ngroups groups, then\n> getgrouplist() returns -1. In this case, the value returned in\n> *ngroups can be used to resize the buffer passed to a further\n> call getgrouplist().\n\nHowever, on macOS/darwin (and maybe others?) `getgrouplist` does\nnot update `ngroups` if `ngroups` is too small. Therefore, if not\nupdated by `getgrouplist`, `ngroups` needs to be increased in a\nloop until `getgrouplist` stops returning -1.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/entries.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/entries.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "01c24ba90eac5aa988006f6a0d778673d00e7ecfb0280844bde8ea9ed5973dc7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_raw\n\nDocumentation:\n# Safety\ngr_name must be valid and not change while\nthe function runs. That means PW_LOCK must be held.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn from_raw(raw: group) -> Self {\n Self {\n name: cstr2string(raw.gr_name).expect(\"group without name\"),\n gid: raw.gr_gid,\n }\n }\n```"}], "func_name": "from_raw", "docstring": "# Safety\ngr_name must be valid and not change while\nthe function runs. That means PW_LOCK must be held.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/entries.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/entries.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6191f88d61a5de51e449e5bfc157427f74fbd0953276e6eeb1879fb431a8652f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_path\n\nDocumentation:\nGet information for a given path.\n\nIf `path` points to a symlink and `dereference` is true, information about\nthe link's target will be returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_path(path: impl AsRef, dereference: bool) -> IOResult {\n #[cfg(unix)]\n {\n let stat = if dereference {\n nix::sys::stat::stat(path.as_ref())\n } else {\n nix::sys::stat::lstat(path.as_ref())\n };\n Ok(Self(stat?))\n }\n #[cfg(target_os = \"windows\")]\n {\n use std::fs::OpenOptions;\n use std::os::windows::prelude::*;\n let mut open_options = OpenOptions::new();\n let mut custom_flags = 0;\n if !dereference {\n custom_flags |=\n windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;\n }\n custom_flags |= windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;\n open_options.custom_flags(custom_flags);\n let file = open_options.read(true).open(path.as_ref())?;\n Self::from_file(&file)\n }\n }\n```"}], "func_name": "from_path", "docstring": "Get information for a given path.\n\nIf `path` points to a symlink and `dereference` is true, information about\nthe link's target will be returned.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "785d58a4adb1a5e0b29fb1fd4f9f4d48917388babb06041ad8d79ce2961ae134"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: display_permissions_unix\n\nDocumentation:\nDisplay the permissions of a file on a unix like system\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn display_permissions_unix(mode: mode_t, display_file_type: bool) -> String {\n let mut result;\n if display_file_type {\n result = String::with_capacity(10);\n result.push(get_file_display(mode));\n } else {\n result = String::with_capacity(9);\n }\n\n result.push(if has!(mode, S_IRUSR) { 'r' } else { '-' });\n result.push(if has!(mode, S_IWUSR) { 'w' } else { '-' });\n result.push(if has!(mode, S_ISUID as mode_t) {\n if has!(mode, S_IXUSR) { 's' } else { 'S' }\n } else if has!(mode, S_IXUSR) {\n 'x'\n } else {\n '-'\n });\n\n result.push(if has!(mode, S_IRGRP) { 'r' } else { '-' });\n result.push(if has!(mode, S_IWGRP) { 'w' } else { '-' });\n result.push(if has!(mode, S_ISGID as mode_t) {\n if has!(mode, S_IXGRP) { 's' } else { 'S' }\n } else if has!(mode, S_IXGRP) {\n 'x'\n } else {\n '-'\n });\n\n result.push(if has!(mode, S_IROTH) { 'r' } else { '-' });\n result.push(if has!(mode, S_IWOTH) { 'w' } else { '-' });\n result.push(if has!(mode, S_ISVTX as mode_t) {\n if has!(mode, S_IXOTH) { 't' } else { 'T' }\n } else if has!(mode, S_IXOTH) {\n 'x'\n } else {\n '-'\n });\n\n result\n}\n```"}], "func_name": "display_permissions_unix", "docstring": "Display the permissions of a file on a unix like system", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f6efafd33fc5fbd9b2bdec565a4ec00b74c35469e6eaa586ccaa8ed88d572974"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dir_strip_dot_for_creation\n\nDocumentation:\nFor some programs like install or mkdir, dir/. can be provided\nSpecial case to match GNU's behavior:\ninstall -d foo/. should work and just create foo/\nstd::fs::create_dir(\"foo/.\"); fails in pure Rust\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn dir_strip_dot_for_creation(path: &Path) -> PathBuf {\n if path.to_string_lossy().ends_with(\"/.\") {\n // Do a simple dance to strip the \"/.\"\n Path::new(&path).components().collect::()\n } else {\n path.to_path_buf()\n }\n}\n```"}], "func_name": "dir_strip_dot_for_creation", "docstring": "For some programs like install or mkdir, dir/. can be provided\nSpecial case to match GNU's behavior:\ninstall -d foo/. should work and just create foo/\nstd::fs::create_dir(\"foo/.\"); fails in pure Rust", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9732e0b16e3443e6f927115b3a21e5dcd2bb805c827cce33d37215a0993e96ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: paths_refer_to_same_file\n\nDocumentation:\nChecks if `p1` and `p2` are the same file.\nIf error happens when trying to get files' metadata, returns false\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn paths_refer_to_same_file>(p1: P, p2: P, dereference: bool) -> bool {\n infos_refer_to_same_file(\n FileInformation::from_path(p1, dereference),\n FileInformation::from_path(p2, dereference),\n )\n}\n```"}], "func_name": "paths_refer_to_same_file", "docstring": "Checks if `p1` and `p2` are the same file.\nIf error happens when trying to get files' metadata, returns false", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0d9762aa663f62c902b9856e0f874ba13e0a0ba52f6507dc344d3156c8a404c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: infos_refer_to_same_file\n\nDocumentation:\nChecks if `p1` and `p2` are the same file information.\nIf error happens when trying to get files' metadata, returns false\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn infos_refer_to_same_file(\n info1: IOResult,\n info2: IOResult,\n) -> bool {\n if let Ok(info1) = info1 {\n if let Ok(info2) = info2 {\n return info1 == info2;\n }\n }\n false\n}\n```"}], "func_name": "infos_refer_to_same_file", "docstring": "Checks if `p1` and `p2` are the same file information.\nIf error happens when trying to get files' metadata, returns false", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "071cbf4dbc9718ccea8e59be585f65d195bd48b05c2d88e8aad2ba5a090e2059"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_path_relative_to\n\nDocumentation:\nConverts absolute `path` to be relative to absolute `to` path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn make_path_relative_to, P2: AsRef>(path: P1, to: P2) -> PathBuf {\n let path = path.as_ref();\n let to = to.as_ref();\n let common_prefix_size = path\n .components()\n .zip(to.components())\n .take_while(|(first, second)| first == second)\n .count();\n let path_suffix = path\n .components()\n .skip(common_prefix_size)\n .map(|x| x.as_os_str());\n let mut components: Vec<_> = to\n .components()\n .skip(common_prefix_size)\n .map(|_| Component::ParentDir.as_os_str())\n .chain(path_suffix)\n .collect();\n if components.is_empty() {\n components.push(Component::CurDir.as_os_str());\n }\n components.iter().collect()\n}\n```"}], "func_name": "make_path_relative_to", "docstring": "Converts absolute `path` to be relative to absolute `to` path.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6a4600f6cafa9cb019bc130e447ccb8b585fd05989402f0f13c6707e5102caf2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_symlink_loop\n\nDocumentation:\nChecks if there is a symlink loop in the given path.\n\nA symlink loop is a chain of symlinks where the last symlink points back to one of the previous symlinks in the chain.\n\n# Arguments\n\n* `path` - A reference to a `Path` representing the starting path to check for symlink loops.\n\n# Returns\n\n* `bool` - Returns `true` if a symlink loop is detected, `false` otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_symlink_loop(path: &Path) -> bool {\n let mut visited_symlinks = HashSet::new();\n let mut current_path = path.to_path_buf();\n\n while let (Ok(metadata), Ok(link)) = (\n current_path.symlink_metadata(),\n fs::read_link(¤t_path),\n ) {\n if !metadata.file_type().is_symlink() {\n return false;\n }\n if !visited_symlinks.insert(current_path.clone()) {\n return true;\n }\n current_path = link;\n }\n\n false\n}\n```"}], "func_name": "is_symlink_loop", "docstring": "Checks if there is a symlink loop in the given path.\n\nA symlink loop is a chain of symlinks where the last symlink points back to one of the previous symlinks in the chain.\n\n# Arguments\n\n* `path` - A reference to a `Path` representing the starting path to check for symlink loops.\n\n# Returns\n\n* `bool` - Returns `true` if a symlink loop is detected, `false` otherwise.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "019fcb9294f72704648c2116ac422672d41b4231dbadb7587d5022fe7b9d87f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_stdin_directory\n\nDocumentation:\nChecks if the standard input (stdin) is a directory.\n\n# Arguments\n\n* `stdin` - A reference to the standard input handle.\n\n# Returns\n\n* `bool` - Returns `true` if stdin is a directory, `false` otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_stdin_directory(stdin: &Stdin) -> bool {\n #[cfg(unix)]\n {\n use nix::sys::stat::fstat;\n let mode = fstat(stdin.as_fd()).unwrap().st_mode as mode_t;\n has!(mode, S_IFDIR)\n }\n\n #[cfg(windows)]\n {\n use std::os::windows::io::AsRawHandle;\n let handle = stdin.as_raw_handle();\n if let Ok(metadata) = fs::metadata(format!(\"{}\", handle as usize)) {\n return metadata.is_dir();\n }\n false\n }\n}\n```"}], "func_name": "is_stdin_directory", "docstring": "Checks if the standard input (stdin) is a directory.\n\n# Arguments\n\n* `stdin` - A reference to the standard input handle.\n\n# Returns\n\n* `bool` - Returns `true` if stdin is a directory, `false` otherwise.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "039d47285dbe6beb2e3972b08215c57e369e5944557666c8663828ebc08e3a02"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sane_blksize\n\nDocumentation:\nProvides sanity checked blksize value from the provided value.\n\nIf the provided value is a invalid values a meaningful adaption\nof that value is done.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sane_blksize(st_blksize: u64) -> u64 {\n match st_blksize {\n 0 => DEFAULT,\n 1..=MAX => st_blksize,\n _ => DEFAULT,\n }\n }\n```"}], "func_name": "sane_blksize", "docstring": "Provides sanity checked blksize value from the provided value.\n\nIf the provided value is a invalid values a meaningful adaption\nof that value is done.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ae7c19a0937d8e6e7dad18ed678435535734fec3a025ac1fd8a07758778a8376"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sane_blksize_from_metadata\n\nDocumentation:\nProvides the blksize information from the provided metadata.\n\nIf the metadata contain invalid values a meaningful adaption\nof that value is done.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sane_blksize_from_metadata(_metadata: &std::fs::Metadata) -> u64 {\n #[cfg(not(target_os = \"windows\"))]\n {\n sane_blksize(_metadata.blksize())\n }\n\n #[cfg(target_os = \"windows\")]\n {\n DEFAULT\n }\n }\n```"}], "func_name": "sane_blksize_from_metadata", "docstring": "Provides the blksize information from the provided metadata.\n\nIf the metadata contain invalid values a meaningful adaption\nof that value is done.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "65ad2de6471d28deb98e9b5e8f997778eaae38ab6397c2c10fb1065d94220b01"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sane_blksize_from_path\n\nDocumentation:\nProvides the blksize information from given file path's filesystem.\n\nIf the metadata can't be fetched or contain invalid values a\nmeaningful adaption of that value is done.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sane_blksize_from_path(path: &Path) -> u64 {\n match metadata(path) {\n Ok(metadata) => sane_blksize_from_metadata(&metadata),\n Err(_) => DEFAULT,\n }\n }\n```"}], "func_name": "sane_blksize_from_path", "docstring": "Provides the blksize information from given file path's filesystem.\n\nIf the metadata can't be fetched or contain invalid values a\nmeaningful adaption of that value is done.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fd9c4340874f91cf9e68c6e37555c12497e926f0722f3ffb533b4ab97f3dbd08"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_filename\n\nDocumentation:\nExtracts the filename component from the given `file` path and returns it as an `Option<&str>`.\n\nIf the `file` path contains a filename, this function returns `Some(filename)` where `filename` is\nthe extracted filename as a string slice (`&str`). If the `file` path does not have a filename\ncomponent or if the filename is not valid UTF-8, it returns `None`.\n\n# Arguments\n\n* `file`: A reference to a `Path` representing the file path from which to extract the filename.\n\n# Returns\n\n* `Some(filename)`: If a valid filename exists in the `file` path, where `filename` is the\nextracted filename as a string slice (`&str`).\n* `None`: If the `file` path does not contain a valid filename or if the filename is not valid UTF-8.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_filename(file: &Path) -> Option<&str> {\n file.file_name().and_then(|filename| filename.to_str())\n}\n```"}], "func_name": "get_filename", "docstring": "Extracts the filename component from the given `file` path and returns it as an `Option<&str>`.\n\nIf the `file` path contains a filename, this function returns `Some(filename)` where `filename` is\nthe extracted filename as a string slice (`&str`). If the `file` path does not have a filename\ncomponent or if the filename is not valid UTF-8, it returns `None`.\n\n# Arguments\n\n* `file`: A reference to a `Path` representing the file path from which to extract the filename.\n\n# Returns\n\n* `Some(filename)`: If a valid filename exists in the `file` path, where `filename` is the\nextracted filename as a string slice (`&str`).\n* `None`: If the `file` path does not contain a valid filename or if the filename is not valid UTF-8.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fs.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "56fa096f7c555b769b7701badb20b67a67161fa97d988ac16deeb4d9fbeb7385"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_xattrs\n\nDocumentation:\nCopies extended attributes (xattrs) from one file or directory to another.\n\n# Arguments\n\n* `source` - A reference to the source path.\n* `dest` - A reference to the destination path.\n\n# Returns\n\nA result indicating success or failure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn copy_xattrs>(source: P, dest: P) -> std::io::Result<()> {\n for attr_name in xattr::list(&source)? {\n if let Some(value) = xattr::get(&source, &attr_name)? {\n xattr::set(&dest, &attr_name, &value)?;\n }\n }\n Ok(())\n}\n```"}], "func_name": "copy_xattrs", "docstring": "Copies extended attributes (xattrs) from one file or directory to another.\n\n# Arguments\n\n* `source` - A reference to the source path.\n* `dest` - A reference to the destination path.\n\n# Returns\n\nA result indicating success or failure.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fsxattr.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fsxattr.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc60a811bfdfd15a972cc5cab6232a289392f8b8668fd456b3dbb2090f7c1089"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: retrieve_xattrs\n\nDocumentation:\nRetrieves the extended attributes (xattrs) of a given file or directory.\n\n# Arguments\n\n* `source` - A reference to the path of the file or directory.\n\n# Returns\n\nA result containing a HashMap of attributes names and values, or an error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn retrieve_xattrs>(source: P) -> std::io::Result>> {\n let mut attrs = HashMap::new();\n for attr_name in xattr::list(&source)? {\n if let Some(value) = xattr::get(&source, &attr_name)? {\n attrs.insert(attr_name, value);\n }\n }\n Ok(attrs)\n}\n```"}], "func_name": "retrieve_xattrs", "docstring": "Retrieves the extended attributes (xattrs) of a given file or directory.\n\n# Arguments\n\n* `source` - A reference to the path of the file or directory.\n\n# Returns\n\nA result containing a HashMap of attributes names and values, or an error.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fsxattr.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fsxattr.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "775a30ab754f23cccd153c436e1cec4942e05c5930e7eb4c3b9ece7046755fb0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: apply_xattrs\n\nDocumentation:\nApplies extended attributes (xattrs) to a given file or directory.\n\n# Arguments\n\n* `dest` - A reference to the path of the file or directory.\n* `xattrs` - A HashMap containing attribute names and their corresponding values.\n\n# Returns\n\nA result indicating success or failure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn apply_xattrs>(\n dest: P,\n xattrs: HashMap>,\n) -> std::io::Result<()> {\n for (attr, value) in xattrs {\n xattr::set(&dest, &attr, &value)?;\n }\n Ok(())\n}\n```"}], "func_name": "apply_xattrs", "docstring": "Applies extended attributes (xattrs) to a given file or directory.\n\n# Arguments\n\n* `dest` - A reference to the path of the file or directory.\n* `xattrs` - A HashMap containing attribute names and their corresponding values.\n\n# Returns\n\nA result indicating success or failure.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fsxattr.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fsxattr.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5cc7fa96323c3aa0db043e4d3c211d2300e423114ec8ddebce6b82fbb777e063"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_acl\n\nDocumentation:\nChecks if a file has an Access Control List (ACL) based on its extended attributes.\n\n# Arguments\n\n* `file` - A reference to the path of the file.\n\n# Returns\n\n`true` if the file has extended attributes (indicating an ACL), `false` otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn has_acl>(file: P) -> bool {\n // don't use exacl here, it is doing more getxattr call then needed\n xattr::list(file).is_ok_and(|acl| {\n // if we have extra attributes, we have an acl\n acl.count() > 0\n })\n}\n```"}], "func_name": "has_acl", "docstring": "Checks if a file has an Access Control List (ACL) based on its extended attributes.\n\n# Arguments\n\n* `file` - A reference to the path of the file.\n\n# Returns\n\n`true` if the file has extended attributes (indicating an ACL), `false` otherwise.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fsxattr.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fsxattr.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d8a9444d016f5e91fc206b741273c18ef97cdb9203e6853dbbd2497ab71e28a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_acl_perm_bits_from_xattr\n\nDocumentation:\nReturns the permissions bits of a file or directory which has Access Control List (ACL) entries based on its\nextended attributes (Only works for linux)\n\n# Arguments\n\n* `source` - A reference to the path of the file.\n\n# Returns\n\n`u32` the perm bits of a file having extended attributes of type 'system.posix_acl_default' with permissions\notherwise returns a 0 if perm bits are 0 or the file has no extended attributes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_acl_perm_bits_from_xattr>(source: P) -> u32 {\n // TODO: Modify this to work on non linux unix systems.\n\n // Only default acl entries get inherited by objects under the path i.e. if child directories\n // will have their permissions modified.\n if let Ok(entries) = retrieve_xattrs(source) {\n let mut perm: u32 = 0;\n if let Some(value) = entries.get(&OsString::from(\"system.posix_acl_default\")) {\n // value is xattr byte vector\n // value follows a starts with a 4 byte header, and then has posix_acl_entries, each\n // posix_acl_entry is separated by a u32 sequence i.e. 0xFFFFFFFF\n //\n // struct posix_acl_entries {\n // e_tag: u16\n // e_perm: u16\n // e_id: u32\n // }\n //\n // Reference: `https://github.com/torvalds/linux/blob/master/include/uapi/linux/posix_acl_xattr.h`\n //\n // The value of the header is 0x0002, so we skip the first four bytes of the value and\n // process the rest\n\n let acl_entries = value\n .split_at(3)\n .1\n .iter()\n .filter(|&x| *x != 255)\n .copied()\n .collect::>();\n\n for entry in acl_entries.chunks_exact(4) {\n // Third byte and fourth byte will be the perm bits\n perm = (perm << 3) | u32::from(entry[2]) | u32::from(entry[3]);\n }\n return perm;\n }\n }\n 0\n}\n```"}], "func_name": "get_acl_perm_bits_from_xattr", "docstring": "Returns the permissions bits of a file or directory which has Access Control List (ACL) entries based on its\nextended attributes (Only works for linux)\n\n# Arguments\n\n* `source` - A reference to the path of the file.\n\n# Returns\n\n`u32` the perm bits of a file having extended attributes of type 'system.posix_acl_default' with permissions\notherwise returns a 0 if perm bits are 0 or the file has no extended attributes", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/fsxattr.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/fsxattr.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3467a8deee0fe3bf814e6edef7c15a6e705180d98672af7d48202ce14e05d198"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lines\n\nDocumentation:\nReturns an iterator over the lines, including line ending characters.\n\nThis function is just like [`BufRead::lines`], but it includes the\nline ending characters in each yielded [`String`] if the input\ndata has them. Set the `sep` parameter to the line ending\ncharacter; for Unix line endings, use `b'\\n'`.\n\n# Examples\n\nUse `sep` to specify an alternate character for line endings. For\nexample, if lines are terminated by the null character `b'\\0'`:\n\n```rust,ignore\nuse std::io::BufRead;\nuse std::io::Cursor;\n\nlet cursor = Cursor::new(b\"x\\0y\\0z\\0\");\nlet mut it = lines(cursor, b'\\0').map(|l| l.unwrap());\n\nassert_eq!(it.next(), Some(Vec::from(\"x\\0\")));\nassert_eq!(it.next(), Some(Vec::from(\"y\\0\")));\nassert_eq!(it.next(), Some(Vec::from(\"z\\0\")));\nassert_eq!(it.next(), None);\n```\n\nIf the input data does not end with a newline character (`'\\n'`),\nthen the last [`String`] yielded by this iterator also does not\nend with a newline:\n\n```rust,ignore\nlet cursor = Cursor::new(b\"x\\ny\\nz\");\nlet mut it = lines(cursor, b'\\n').map(|l| l.unwrap());\n\nassert_eq!(it.next(), Some(Vec::from(\"x\\n\")));\nassert_eq!(it.next(), Some(Vec::from(\"y\\n\")));\nassert_eq!(it.next(), Some(Vec::from(\"z\")));\nassert_eq!(it.next(), None);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn lines(reader: B, sep: u8) -> Lines\nwhere\n B: BufRead,\n{\n Lines { buf: reader, sep }\n}\n```"}], "func_name": "lines", "docstring": "Returns an iterator over the lines, including line ending characters.\n\nThis function is just like [`BufRead::lines`], but it includes the\nline ending characters in each yielded [`String`] if the input\ndata has them. Set the `sep` parameter to the line ending\ncharacter; for Unix line endings, use `b'\\n'`.\n\n# Examples\n\nUse `sep` to specify an alternate character for line endings. For\nexample, if lines are terminated by the null character `b'\\0'`:\n\n```rust,ignore\nuse std::io::BufRead;\nuse std::io::Cursor;\n\nlet cursor = Cursor::new(b\"x\\0y\\0z\\0\");\nlet mut it = lines(cursor, b'\\0').map(|l| l.unwrap());\n\nassert_eq!(it.next(), Some(Vec::from(\"x\\0\")));\nassert_eq!(it.next(), Some(Vec::from(\"y\\0\")));\nassert_eq!(it.next(), Some(Vec::from(\"z\\0\")));\nassert_eq!(it.next(), None);\n```\n\nIf the input data does not end with a newline character (`'\\n'`),\nthen the last [`String`] yielded by this iterator also does not\nend with a newline:\n\n```rust,ignore\nlet cursor = Cursor::new(b\"x\\ny\\nz\");\nlet mut it = lines(cursor, b'\\n').map(|l| l.unwrap());\n\nassert_eq!(it.next(), Some(Vec::from(\"x\\n\")));\nassert_eq!(it.next(), Some(Vec::from(\"y\\n\")));\nassert_eq!(it.next(), Some(Vec::from(\"z\")));\nassert_eq!(it.next(), None);\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/lines.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/lines.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7b0b29a84e1e1e28723bae32d6149cc90c984524ac9d8d9c90d0df813223940e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: chown\n\nDocumentation:\nActually perform the change of owner on a path\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn chown>(path: P, uid: uid_t, gid: gid_t, follow: bool) -> IOResult<()> {\n let path = path.as_ref();\n let s = CString::new(path.as_os_str().as_bytes()).unwrap();\n let ret = unsafe {\n if follow {\n libc::chown(s.as_ptr(), uid, gid)\n } else {\n libc::lchown(s.as_ptr(), uid, gid)\n }\n };\n if ret == 0 {\n Ok(())\n } else {\n Err(IOError::last_os_error())\n }\n}\n```"}], "func_name": "chown", "docstring": "Actually perform the change of owner on a path", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/perms.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/perms.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6afbe654e8966f70426cae428559af59614fa339d716bde8fb4b5fe2ae1d73e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wrap_chown\n\nDocumentation:\nPerform the change of owner on a path\nwith the various options\nand error messages management\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn wrap_chown>(\n path: P,\n meta: &Metadata,\n dest_uid: Option,\n dest_gid: Option,\n follow: bool,\n verbosity: Verbosity,\n) -> Result {\n let dest_uid = dest_uid.unwrap_or_else(|| meta.uid());\n let dest_gid = dest_gid.unwrap_or_else(|| meta.gid());\n let path = path.as_ref();\n let mut out: String = String::new();\n\n if let Err(e) = chown(path, dest_uid, dest_gid, follow) {\n match verbosity.level {\n VerbosityLevel::Silent => (),\n level => {\n out = format!(\n \"changing {} of {}: {e}\",\n if verbosity.groups_only {\n \"group\"\n } else {\n \"ownership\"\n },\n path.quote(),\n );\n if level == VerbosityLevel::Verbose {\n out = if verbosity.groups_only {\n let gid = meta.gid();\n format!(\n \"{out}\\nfailed to change group of {} from {} to {}\",\n path.quote(),\n entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string()),\n entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())\n )\n } else {\n let uid = meta.uid();\n let gid = meta.gid();\n format!(\n \"{out}\\nfailed to change ownership of {} from {}:{} to {}:{}\",\n path.quote(),\n entries::uid2usr(uid).unwrap_or_else(|_| uid.to_string()),\n entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string()),\n entries::uid2usr(dest_uid).unwrap_or_else(|_| dest_uid.to_string()),\n entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())\n )\n };\n };\n }\n }\n return Err(out);\n } else {\n let changed = dest_uid != meta.uid() || dest_gid != meta.gid();\n if changed {\n match verbosity.level {\n VerbosityLevel::Changes | VerbosityLevel::Verbose => {\n let gid = meta.gid();\n out = if verbosity.groups_only {\n format!(\n \"changed group of {} from {} to {}\",\n path.quote(),\n entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string()),\n entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())\n )\n } else {\n let gid = meta.gid();\n let uid = meta.uid();\n format!(\n \"changed ownership of {} from {}:{} to {}:{}\",\n path.quote(),\n entries::uid2usr(uid).unwrap_or_else(|_| uid.to_string()),\n entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string()),\n entries::uid2usr(dest_uid).unwrap_or_else(|_| dest_uid.to_string()),\n entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())\n )\n };\n }\n _ => (),\n };\n } else if verbosity.level == VerbosityLevel::Verbose {\n out = if verbosity.groups_only {\n format!(\n \"group of {} retained as {}\",\n path.quote(),\n entries::gid2grp(dest_gid).unwrap_or_default()\n )\n } else {\n format!(\n \"ownership of {} retained as {}:{}\",\n path.quote(),\n entries::uid2usr(dest_uid).unwrap_or_else(|_| dest_uid.to_string()),\n entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())\n )\n };\n }\n }\n Ok(out)\n}\n```"}], "func_name": "wrap_chown", "docstring": "Perform the change of owner on a path\nwith the various options\nand error messages management", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/perms.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/perms.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5bbd8b30bcee5b37050e9c0a7dae72c71f828681c5cb9b397301fbae838dc910"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_root\n\nDocumentation:\nIn the context of chown and chgrp, check whether we are in a \"preserve-root\" scenario.\n\nIn particular, we want to prohibit further traversal only if:\n(--preserve-root and -R present) &&\n(path canonicalizes to \"/\") &&\n(\n(path is a symlink && would traverse/recurse this symlink) ||\n(path is not a symlink)\n)\nThe first clause is checked by the caller, the second and third clause is checked here.\nThe caller has to evaluate -P/-H/-L into 'would_recurse_symlink'.\nRecall that canonicalization resolves both relative paths (e.g. \"..\") and symlinks.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_root(path: &Path, would_traverse_symlink: bool) -> bool {\n // The third clause can be evaluated without any syscalls, so we do that first.\n // If we would_recurse_symlink, then the clause is true no matter whether the path is a symlink\n // or not. Otherwise, we only need to check here if the path can syntactically be a symlink:\n if !would_traverse_symlink {\n // We cannot check path.is_dir() here, as this would resolve symlinks,\n // which we need to avoid here.\n // All directory-ish paths match \"*/\", except \".\", \"..\", \"*/.\", and \"*/..\".\n let path_bytes = path.as_os_str().as_encoded_bytes();\n let looks_like_dir = path_bytes == [b'.']\n || path_bytes == [b'.', b'.']\n || path_bytes.ends_with(&[MAIN_SEPARATOR as u8])\n || path_bytes.ends_with(&[MAIN_SEPARATOR as u8, b'.'])\n || path_bytes.ends_with(&[MAIN_SEPARATOR as u8, b'.', b'.']);\n\n if !looks_like_dir {\n return false;\n }\n }\n\n // FIXME: TOCTOU bug! canonicalize() runs at a different time than WalkDir's recursion decision.\n // However, we're forced to make the decision whether to warn about --preserve-root\n // *before* even attempting to chown the path, let alone doing the stat inside WalkDir.\n if let Ok(p) = path.canonicalize() {\n let path_buf = path.to_path_buf();\n if p.parent().is_none() {\n if path_buf.as_os_str() == \"/\" {\n show_error!(\"it is dangerous to operate recursively on '/'\");\n } else {\n show_error!(\n \"it is dangerous to operate recursively on {} (same as '/')\",\n path_buf.quote()\n );\n }\n show_error!(\"use --no-preserve-root to override this failsafe\");\n return true;\n }\n }\n\n false\n}\n```"}], "func_name": "is_root", "docstring": "In the context of chown and chgrp, check whether we are in a \"preserve-root\" scenario.\n\nIn particular, we want to prohibit further traversal only if:\n(--preserve-root and -R present) &&\n(path canonicalizes to \"/\") &&\n(\n(path is a symlink && would traverse/recurse this symlink) ||\n(path is not a symlink)\n)\nThe first clause is checked by the caller, the second and third clause is checked here.\nThe caller has to evaluate -P/-H/-L into 'would_recurse_symlink'.\nRecall that canonicalization resolves both relative paths (e.g. \"..\") and symlinks.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/perms.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/perms.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6cd9807339afa0b0dfc1ff654b48738a4b36584d6e84c7cf1d26f3faa9f2ddee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: configure_symlink_and_recursion\n\nDocumentation:\nDetermines symbolic link traversal and recursion settings based on flags.\nReturns the updated `dereference` and `traverse_symlinks` values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn configure_symlink_and_recursion(\n matches: &ArgMatches,\n default_traverse_symlinks: TraverseSymlinks,\n) -> Result<(bool, bool, TraverseSymlinks), Box> {\n let mut dereference = if matches.get_flag(options::dereference::DEREFERENCE) {\n Some(true) // Follow symlinks\n } else if matches.get_flag(options::dereference::NO_DEREFERENCE) {\n Some(false) // Do not follow symlinks\n } else {\n None // Default behavior\n };\n\n let mut traverse_symlinks = default_traverse_symlinks;\n if matches.get_flag(\"L\") {\n traverse_symlinks = TraverseSymlinks::All\n } else if matches.get_flag(\"H\") {\n traverse_symlinks = TraverseSymlinks::First\n } else if matches.get_flag(\"P\") {\n traverse_symlinks = TraverseSymlinks::None\n };\n\n let recursive = matches.get_flag(options::RECURSIVE);\n if recursive {\n if traverse_symlinks == TraverseSymlinks::None {\n if dereference == Some(true) {\n return Err(USimpleError::new(\n 1,\n \"-R --dereference requires -H or -L\".to_string(),\n ));\n }\n dereference = Some(false);\n }\n } else {\n traverse_symlinks = TraverseSymlinks::None;\n }\n\n Ok((recursive, dereference.unwrap_or(true), traverse_symlinks))\n}\n```"}], "func_name": "configure_symlink_and_recursion", "docstring": "Determines symbolic link traversal and recursion settings based on flags.\nReturns the updated `dereference` and `traverse_symlinks` values.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/perms.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/perms.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7fde4bd585e497ba32e2430c27ee51a84d109328173ab72b823ee882cca9c70d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pipe\n\nDocumentation:\nA wrapper around [`nix::unistd::pipe`] that ensures the pipe is cleaned up.\n\nReturns two `File` objects: everything written to the second can be read\nfrom the first.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pipe() -> Result<(File, File)> {\n let (read, write) = nix::unistd::pipe()?;\n Ok((File::from(read), File::from(write)))\n}\n```"}], "func_name": "pipe", "docstring": "A wrapper around [`nix::unistd::pipe`] that ensures the pipe is cleaned up.\n\nReturns two `File` objects: everything written to the second can be read\nfrom the first.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/pipes.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/pipes.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9c31fa22cb6f89b942a480769128d514c6e75b1ce9d57cd1284091e015d66da2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: geteuid\n\nDocumentation:\n`geteuid()` returns the effective user ID of the calling process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn geteuid() -> uid_t {\n unsafe { libc::geteuid() }\n}\n```"}], "func_name": "geteuid", "docstring": "`geteuid()` returns the effective user ID of the calling process.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/process.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/process.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c64ffcb58c6f102ed6c0395aed367b72b050e0a337f90fbc20234240a760f47"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: getpgrp\n\nDocumentation:\n`getpgrp()` returns the process group ID of the calling process.\nIt is a trivial wrapper over libc::getpgrp to \"hide\" the unsafe\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn getpgrp() -> pid_t {\n unsafe { libc::getpgrp() }\n}\n```"}], "func_name": "getpgrp", "docstring": "`getpgrp()` returns the process group ID of the calling process.\nIt is a trivial wrapper over libc::getpgrp to \"hide\" the unsafe", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/process.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/process.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6d3b1db3a53954a6d39054d0537d756af5cd54d5ea8d22f19a9364faf9214386"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: getegid\n\nDocumentation:\n`getegid()` returns the effective group ID of the calling process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn getegid() -> gid_t {\n unsafe { libc::getegid() }\n}\n```"}], "func_name": "getegid", "docstring": "`getegid()` returns the effective group ID of the calling process.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/process.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/process.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "adceec608274ebc317de9d10bb4b6047da0d4c1ceb732567f7fca9b3bd20eb67"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: getgid\n\nDocumentation:\n`getgid()` returns the real group ID of the calling process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn getgid() -> gid_t {\n unsafe { libc::getgid() }\n}\n```"}], "func_name": "getgid", "docstring": "`getgid()` returns the real group ID of the calling process.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/process.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/process.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b68644d629231165f6bdff7a84173815a59a9c40995b7a5f33f4a9da4b493a2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: getuid\n\nDocumentation:\n`getuid()` returns the real user ID of the calling process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn getuid() -> uid_t {\n unsafe { libc::getuid() }\n}\n```"}], "func_name": "getuid", "docstring": "`getuid()` returns the real user ID of the calling process.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/process.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/process.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "787d3fd611bfe2f15463d4180a6a2df1d0c6ed29e3c17a1daf627dbf22e54735"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: getpid\n\nDocumentation:\n`getpid()` returns the pid of the calling process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn getpid() -> pid_t {\n unsafe { libc::getpid() }\n}\n```"}], "func_name": "getpid", "docstring": "`getpid()` returns the pid of the calling process.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/process.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/process.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5175afdb006384b0c8c37f63cdbfe766e7a4845ecae547af841e6f13bcd16878"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_new\n\nDocumentation:\nTry new with pid path such as `/proc/self`\n\n# Error\n\nIf the files in path cannot be parsed into [ProcessInformation],\nit almost caused by wrong filesystem structure.\n\n- [The /proc Filesystem](https://docs.kernel.org/filesystems/proc.html#process-specific-subdirectories)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_new(value: PathBuf) -> Result {\n let dir_append = |mut path: PathBuf, str: String| {\n path.push(str);\n path\n };\n\n let value = if value.is_symlink() {\n fs::read_link(value)?\n } else {\n value\n };\n\n let pid = {\n value\n .iter()\n .next_back()\n .ok_or(io::ErrorKind::Other)?\n .to_str()\n .ok_or(io::ErrorKind::InvalidData)?\n .parse::()\n .map_err(|_| io::ErrorKind::InvalidData)?\n };\n let cmdline = fs::read_to_string(dir_append(value.clone(), \"cmdline\".into()))?\n .replace('\\0', \" \")\n .trim_end()\n .into();\n\n Ok(Self {\n pid,\n cmdline,\n inner_status: fs::read_to_string(dir_append(value.clone(), \"status\".into()))?,\n inner_stat: fs::read_to_string(dir_append(value, \"stat\".into()))?,\n ..Default::default()\n })\n }\n```"}], "func_name": "try_new", "docstring": "Try new with pid path such as `/proc/self`\n\n# Error\n\nIf the files in path cannot be parsed into [ProcessInformation],\nit almost caused by wrong filesystem structure.\n\n- [The /proc Filesystem](https://docs.kernel.org/filesystems/proc.html#process-specific-subdirectories)", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/proc_info.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/proc_info.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1255254ec5bbc5b2ba976a9c6ff684932a843266833ba91e8901a8f766499a58"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: status\n\nDocumentation:\nCollect information from `/proc//status` file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn status(&mut self) -> Rc> {\n if let Some(c) = &self.cached_status {\n return Rc::clone(c);\n }\n\n let result = self\n .inner_status\n .lines()\n .filter_map(|it| it.split_once(':'))\n .map(|it| (it.0.to_string(), it.1.trim_start().to_string()))\n .collect::>();\n\n let result = Rc::new(result);\n self.cached_status = Some(Rc::clone(&result));\n Rc::clone(&result)\n }\n```"}], "func_name": "status", "docstring": "Collect information from `/proc//status` file", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/proc_info.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/proc_info.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1710110a9e303f85861445d9867b567979dc2b8672a07a669272517024aa00d1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stat\n\nDocumentation:\nCollect information from `/proc//stat` file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stat(&mut self) -> Rc> {\n if let Some(c) = &self.cached_stat {\n return Rc::clone(c);\n }\n\n let result: Vec<_> = stat_split(&self.inner_stat);\n\n let result = Rc::new(result);\n self.cached_stat = Some(Rc::clone(&result));\n Rc::clone(&result)\n }\n```"}], "func_name": "stat", "docstring": "Collect information from `/proc//stat` file", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/proc_info.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/proc_info.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f74b2b8e4ffaee3f14b0f5372c3ec886afdda6798f96f46d4c9484d249a5f279"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_time\n\nDocumentation:\nFetch start time from [ProcessInformation::cached_stat]\n\n- [The /proc Filesystem: Table 1-4](https://docs.kernel.org/filesystems/proc.html#id10)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start_time(&mut self) -> Result {\n if let Some(time) = self.cached_start_time {\n return Ok(time);\n }\n\n // Kernel doc: https://docs.kernel.org/filesystems/proc.html#process-specific-subdirectories\n // Table 1-4\n let time = self\n .stat()\n .get(21)\n .ok_or(io::ErrorKind::InvalidData)?\n .parse::()\n .map_err(|_| io::ErrorKind::InvalidData)?;\n\n self.cached_start_time = Some(time);\n\n Ok(time)\n }\n```"}], "func_name": "start_time", "docstring": "Fetch start time from [ProcessInformation::cached_stat]\n\n- [The /proc Filesystem: Table 1-4](https://docs.kernel.org/filesystems/proc.html#id10)", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/proc_info.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/proc_info.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f2afe43d2be82874c372a306ed30c6554c5a91ce1c232ce7e44c936b4acef6db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tty\n\nDocumentation:\nThis function will scan the `/proc//fd` directory\n\nIf the process does not belong to any terminal and mismatched permission,\nthe result will contain [TerminalType::Unknown].\n\nOtherwise [TerminalType::Unknown] does not appear in the result.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn tty(&self) -> Teletype {\n let path = PathBuf::from(format!(\"/proc/{}/fd\", self.pid));\n\n let Ok(result) = fs::read_dir(path) else {\n return Teletype::Unknown;\n };\n\n for dir in result.flatten().filter(|it| it.path().is_symlink()) {\n if let Ok(path) = fs::read_link(dir.path()) {\n if let Ok(tty) = Teletype::try_from(path) {\n return tty;\n }\n }\n }\n\n Teletype::Unknown\n }\n```"}], "func_name": "tty", "docstring": "This function will scan the `/proc//fd` directory\n\nIf the process does not belong to any terminal and mismatched permission,\nthe result will contain [TerminalType::Unknown].\n\nOtherwise [TerminalType::Unknown] does not appear in the result.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/proc_info.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/proc_info.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fe65da10c8cc04e03680cec084fa3c17c500fe92ca7c3d5b878172caa145cad2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stat_split\n\nDocumentation:\nParsing `/proc/self/stat` file.\n\nIn some case, the first pair (and the only one pair) will contains whitespace,\nso if we want to parse it, we have to write new algorithm.\n\nTODO: If possible, test and use regex to replace this algorithm.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn stat_split(stat: &str) -> Vec {\n let stat = String::from(stat);\n\n let mut buf = String::with_capacity(stat.len());\n\n let l = stat.find('(');\n let r = stat.find(')');\n let content = if let (Some(l), Some(r)) = (l, r) {\n let replaced = stat[(l + 1)..r].replace(' ', \"$$\");\n\n buf.push_str(&stat[..l]);\n buf.push_str(&replaced);\n buf.push_str(&stat[(r + 1)..stat.len()]);\n\n &buf\n } else {\n &stat\n };\n\n content\n .split_whitespace()\n .map(|it| it.replace(\"$$\", \" \"))\n .collect()\n}\n```"}], "func_name": "stat_split", "docstring": "Parsing `/proc/self/stat` file.\n\nIn some case, the first pair (and the only one pair) will contains whitespace,\nso if we want to parse it, we have to write new algorithm.\n\nTODO: If possible, test and use regex to replace this algorithm.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/proc_info.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/proc_info.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "612ec0a3824478154bf2c35a8ac675014b5caa9b732bf3941a81b15c3a899c35"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bytes_start_with\n\nDocumentation:\nCheck whether `bytes` starts with any byte in `pattern`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn bytes_start_with(bytes: &[u8], pattern: &[u8]) -> bool {\n !bytes.is_empty() && pattern.contains(&bytes[0])\n}\n```"}], "func_name": "bytes_start_with", "docstring": "Check whether `bytes` starts with any byte in `pattern`.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/quoting_style.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/quoting_style.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b85727d2f9bae63855196ac85c8450cc6a2eaa4b6d0c461b8ca9dda3587c33eb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shell_escaped_char_set\n\nDocumentation:\nReturn a set of characters that implies quoting of the word in\nshell-quoting mode.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn shell_escaped_char_set(is_dirname: bool) -> &'static [u8] {\n const ESCAPED_CHARS: &[u8] = b\":\\\"`$\\\\^\\n\\t\\r=\";\n // the ':' colon character only induce quoting in the\n // context of ls displaying a directory name before listing its content.\n // (e.g. with the recursive flag -R)\n let start_index = if is_dirname { 0 } else { 1 };\n &ESCAPED_CHARS[start_index..]\n}\n```"}], "func_name": "shell_escaped_char_set", "docstring": "Return a set of characters that implies quoting of the word in\nshell-quoting mode.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/quoting_style.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/quoting_style.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2918050ab0c6adcc0876a2b422783ea7ff94449a04eb97f6e56a77ab2b8b6031"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: escape_name_inner\n\nDocumentation:\nEscape a name according to the given quoting style.\n\nThis inner function provides an additional flag `dirname` which\nis meant for ls' directory name display.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn escape_name_inner(name: &[u8], style: &QuotingStyle, dirname: bool) -> Vec {\n match style {\n QuotingStyle::Literal { show_control } => {\n if *show_control {\n name.to_owned()\n } else {\n name.utf8_chunks()\n .map(|s| {\n let valid: String = s\n .valid()\n .chars()\n .flat_map(|c| EscapedChar::new_literal(c).hide_control())\n .collect();\n let invalid = \"?\".repeat(s.invalid().len());\n valid + &invalid\n })\n .collect::()\n .into()\n }\n }\n QuotingStyle::C { quotes } => {\n let escaped_str: String = name\n .utf8_chunks()\n .flat_map(|s| {\n let valid = s\n .valid()\n .chars()\n .flat_map(|c| EscapedChar::new_c(c, *quotes, dirname));\n let invalid = s.invalid().iter().flat_map(|b| EscapedChar::new_octal(*b));\n valid.chain(invalid)\n })\n .collect::();\n\n match quotes {\n Quotes::Single => format!(\"'{escaped_str}'\"),\n Quotes::Double => format!(\"\\\"{escaped_str}\\\"\"),\n Quotes::None => escaped_str,\n }\n .into()\n }\n QuotingStyle::Shell {\n escape,\n always_quote,\n show_control,\n } => {\n let (quotes, must_quote) = if name\n .iter()\n .any(|c| shell_escaped_char_set(dirname).contains(c))\n {\n (Quotes::Single, true)\n } else if name.contains(&b'\\'') {\n (Quotes::Double, true)\n } else if *always_quote || name.is_empty() {\n (Quotes::Single, true)\n } else {\n (Quotes::Single, false)\n };\n\n let (escaped_str, contains_quote_chars) = if *escape {\n shell_with_escape(name, quotes)\n } else {\n shell_without_escape(name, quotes, *show_control)\n };\n\n if must_quote | contains_quote_chars && quotes != Quotes::None {\n let mut quoted_str = Vec::::with_capacity(escaped_str.len() + 2);\n let quote = if quotes == Quotes::Single {\n b'\\''\n } else {\n b'\"'\n };\n quoted_str.push(quote);\n quoted_str.extend(escaped_str);\n quoted_str.push(quote);\n quoted_str\n } else {\n escaped_str\n }\n }\n }\n}\n```"}], "func_name": "escape_name_inner", "docstring": "Escape a name according to the given quoting style.\n\nThis inner function provides an additional flag `dirname` which\nis meant for ls' directory name display.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/quoting_style.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/quoting_style.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0713ab95f4d12509f13669558c86d89a2751f80ef53b1777e9639462cc949803"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: escape_name\n\nDocumentation:\nEscape a filename with respect to the given style.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn escape_name(name: &OsStr, style: &QuotingStyle) -> OsString {\n let name = crate::os_str_as_bytes_lossy(name);\n crate::os_string_from_vec(escape_name_inner(&name, style, false))\n .expect(\"all byte sequences should be valid for platform, or already replaced in name\")\n}\n```"}], "func_name": "escape_name", "docstring": "Escape a filename with respect to the given style.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/quoting_style.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/quoting_style.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1970b9bd1e75e3ccd1a29bfb95cf10987600853fd3b907d044ebfb6ad8845a78"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: escape_dir_name\n\nDocumentation:\nEscape a directory name with respect to the given style.\nThis is mainly meant to be used for ls' directory name printing and is not\nlikely to be used elsewhere.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn escape_dir_name(dir_name: &OsStr, style: &QuotingStyle) -> OsString {\n let name = crate::os_str_as_bytes_lossy(dir_name);\n crate::os_string_from_vec(escape_name_inner(&name, style, true))\n .expect(\"all byte sequences should be valid for platform, or already replaced in name\")\n}\n```"}], "func_name": "escape_dir_name", "docstring": "Escape a directory name with respect to the given style.\nThis is mainly meant to be used for ls' directory name printing and is not\nlikely to be used elsewhere.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/quoting_style.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/quoting_style.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ec5361b446b2bccb15fc21936b1b6b5268bf79d81f24f68c7dee0331f9c47f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_str\n\nDocumentation:\nParse a string of the form `a-b` into a `Range`\n\n```\nuse std::str::FromStr;\nuse uucore::ranges::Range;\nassert_eq!(Range::from_str(\"5\"), Ok(Range { low: 5, high: 5 }));\nassert_eq!(Range::from_str(\"4-\"), Ok(Range { low: 4, high: usize::MAX - 1 }));\nassert_eq!(Range::from_str(\"-4\"), Ok(Range { low: 1, high: 4 }));\nassert_eq!(Range::from_str(\"2-4\"), Ok(Range { low: 2, high: 4 }));\nassert!(Range::from_str(\"0-4\").is_err());\nassert!(Range::from_str(\"4-2\").is_err());\nassert!(Range::from_str(\"-\").is_err());\nassert!(Range::from_str(\"a\").is_err());\nassert!(Range::from_str(\"a-b\").is_err());\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_str(s: &str) -> Result {\n fn parse(s: &str) -> Result {\n match s.parse::() {\n Ok(0) => Err(\"fields and positions are numbered from 1\"),\n // GNU fails when we are at the limit. Match their behavior\n Ok(n) if n == usize::MAX => Err(\"byte/character offset is too large\"),\n Ok(n) => Ok(n),\n Err(_) => Err(\"failed to parse range\"),\n }\n }\n\n Ok(match s.split_once('-') {\n None => {\n let n = parse(s)?;\n Self { low: n, high: n }\n }\n Some((\"\", \"\")) => return Err(\"invalid range with no endpoint\"),\n Some((low, \"\")) => Self {\n low: parse(low)?,\n high: usize::MAX - 1,\n },\n Some((\"\", high)) => Self {\n low: 1,\n high: parse(high)?,\n },\n Some((low, high)) => {\n let (low, high) = (parse(low)?, parse(high)?);\n if low <= high {\n Self { low, high }\n } else {\n return Err(\"high end of range less than low end\");\n }\n }\n })\n }\n```"}], "func_name": "from_str", "docstring": "Parse a string of the form `a-b` into a `Range`\n\n```\nuse std::str::FromStr;\nuse uucore::ranges::Range;\nassert_eq!(Range::from_str(\"5\"), Ok(Range { low: 5, high: 5 }));\nassert_eq!(Range::from_str(\"4-\"), Ok(Range { low: 4, high: usize::MAX - 1 }));\nassert_eq!(Range::from_str(\"-4\"), Ok(Range { low: 1, high: 4 }));\nassert_eq!(Range::from_str(\"2-4\"), Ok(Range { low: 2, high: 4 }));\nassert!(Range::from_str(\"0-4\").is_err());\nassert!(Range::from_str(\"4-2\").is_err());\nassert!(Range::from_str(\"-\").is_err());\nassert!(Range::from_str(\"a\").is_err());\nassert!(Range::from_str(\"a-b\").is_err());\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/ranges.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/ranges.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f0a2798286f306ae551ad155a7a3338d57a713ecf0b4e01237976c56fceed80"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_list\n\nDocumentation:\nParse a list of ranges separated by commas and/or spaces\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_list(list: &str) -> Result, String> {\n let mut ranges = Vec::new();\n\n for item in list.split(&[',', ' ']) {\n let range_item = FromStr::from_str(item)\n .map_err(|e| format!(\"range {} was invalid: {e}\", item.quote()))?;\n ranges.push(range_item);\n }\n\n Ok(Self::merge(ranges))\n }\n```"}], "func_name": "from_list", "docstring": "Parse a list of ranges separated by commas and/or spaces", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/ranges.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/ranges.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "128816bbf0db7a7cc9bafc9031636749b4ba1b2b33e40bb8975ba3552678a5c7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: merge\n\nDocumentation:\nMerge any overlapping ranges. Adjacent ranges are *NOT* merged.\n\nIs guaranteed to return only disjoint ranges in a sorted order.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn merge(mut ranges: Vec) -> Vec {\n ranges.sort();\n\n // merge overlapping ranges\n for i in 0..ranges.len() {\n let j = i + 1;\n\n while j < ranges.len() && ranges[j].low <= ranges[i].high {\n let j_high = ranges.remove(j).high;\n ranges[i].high = max(ranges[i].high, j_high);\n }\n }\n ranges\n }\n```"}], "func_name": "merge", "docstring": "Merge any overlapping ranges. Adjacent ranges are *NOT* merged.\n\nIs guaranteed to return only disjoint ranges in a sorted order.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/ranges.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/ranges.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d849e28c4b77cd2d362714cc2b14fab087a93b6bfe465b0811037dfa60cb0d83"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: complement\n\nDocumentation:\nCalculate the complement of the given ranges.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn complement(ranges: &[Range]) -> Vec {\n let mut prev_high = 0;\n let mut complements = Vec::with_capacity(ranges.len() + 1);\n\n for range in ranges {\n if range.low > prev_high + 1 {\n complements.push(Range {\n low: prev_high + 1,\n high: range.low - 1,\n });\n }\n prev_high = range.high;\n }\n\n if prev_high < usize::MAX - 1 {\n complements.push(Range {\n low: prev_high + 1,\n high: usize::MAX - 1,\n });\n }\n\n complements\n}\n```"}], "func_name": "complement", "docstring": "Calculate the complement of the given ranges.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/ranges.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/ranges.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ffc32aedf9c07995f90dda3643bc84c21c0116dde303c6feb2184cd11803792"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: contain\n\nDocumentation:\nTest if at least one of the given Ranges contain the supplied value.\n\nExamples:\n\n```\nlet ranges = uucore::ranges::Range::from_list(\"11,2,6-8\").unwrap();\n\nassert!(!uucore::ranges::contain(&ranges, 0));\nassert!(!uucore::ranges::contain(&ranges, 1));\nassert!(!uucore::ranges::contain(&ranges, 5));\nassert!(!uucore::ranges::contain(&ranges, 10));\n\nassert!(uucore::ranges::contain(&ranges, 2));\nassert!(uucore::ranges::contain(&ranges, 6));\nassert!(uucore::ranges::contain(&ranges, 7));\nassert!(uucore::ranges::contain(&ranges, 8));\nassert!(uucore::ranges::contain(&ranges, 11));\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn contain(ranges: &[Range], n: usize) -> bool {\n for range in ranges {\n if n >= range.low && n <= range.high {\n return true;\n }\n }\n\n false\n}\n```"}], "func_name": "contain", "docstring": "Test if at least one of the given Ranges contain the supplied value.\n\nExamples:\n\n```\nlet ranges = uucore::ranges::Range::from_list(\"11,2,6-8\").unwrap();\n\nassert!(!uucore::ranges::contain(&ranges, 0));\nassert!(!uucore::ranges::contain(&ranges, 1));\nassert!(!uucore::ranges::contain(&ranges, 5));\nassert!(!uucore::ranges::contain(&ranges, 10));\n\nassert!(uucore::ranges::contain(&ranges, 2));\nassert!(uucore::ranges::contain(&ranges, 6));\nassert!(uucore::ranges::contain(&ranges, 7));\nassert!(uucore::ranges::contain(&ranges, 8));\nassert!(uucore::ranges::contain(&ranges, 11));\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/ranges.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/ranges.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f6b1763a1b14c4cc25f94d63b122f781e072d583cd20fb31e584d77a8c90c36"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new ring buffer with a maximum size of `size`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(size: usize) -> Self {\n Self {\n data: VecDeque::new(),\n size,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new ring buffer with a maximum size of `size`.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/ringbuffer.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/ringbuffer.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f2fa9084833699b91f32e2b9b8fcbda4f329db0989575483b61f6decb77d90f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_iter\n\nDocumentation:\nCreate a new ring buffer from an iterator.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_iter(iter: impl Iterator, size: usize) -> Self {\n let mut ring_buffer = Self::new(size);\n for value in iter {\n ring_buffer.push_back(value);\n }\n ring_buffer\n }\n```"}], "func_name": "from_iter", "docstring": "Create a new ring buffer from an iterator.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/ringbuffer.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/ringbuffer.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aaaa8fd8efa2d5a42d8718a4cf8d85b6fde8a5ad266873495dfaac0c4bad1a71"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_selinux_enabled\n\nDocumentation:\nChecks if SELinux is enabled on the system.\n\nThis function verifies whether the kernel has SELinux support enabled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_selinux_enabled() -> bool {\n selinux::kernel_support() != selinux::KernelSupport::Unsupported\n}\n```"}], "func_name": "is_selinux_enabled", "docstring": "Checks if SELinux is enabled on the system.\n\nThis function verifies whether the kernel has SELinux support enabled.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/selinux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/selinux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "68d5a04d0fb9d9289bfe168f8f6a8e72490c51af3bfdc012b3491389561f5eaf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: selinux_error_description\n\nDocumentation:\nReturns a string describing the error and its causes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn selinux_error_description(mut error: &dyn Error) -> String {\n let mut description = String::new();\n while let Some(source) = error.source() {\n let error_text = source.to_string();\n // Check if this is an OS error and trim it\n if let Some(idx) = error_text.find(\" (os error \") {\n description.push_str(&error_text[..idx]);\n } else {\n description.push_str(&error_text);\n }\n error = source;\n }\n description\n}\n```"}], "func_name": "selinux_error_description", "docstring": "Returns a string describing the error and its causes.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/selinux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/selinux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4bb5e574d66ff459c2a32caffdd05ba5e808e034c229c9e197b3925d60898e52"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_selinux_security_context\n\nDocumentation:\nSets the SELinux security context for the given filesystem path.\n\nIf a specific context is provided, it attempts to set this context explicitly.\nOtherwise, it applies the default SELinux context for the provided path.\n\n# Arguments\n\n* `path` - Filesystem path on which to set the SELinux context.\n* `context` - Optional SELinux context string to explicitly set.\n\n# Errors\n\nReturns an error if:\n- SELinux is not enabled on the system.\n- The provided context is invalid or cannot be applied.\n- The default SELinux context cannot be set.\n\n# Examples\n\nSetting default context:\n```\nuse std::path::Path;\nuse uucore::selinux::set_selinux_security_context;\n\n// Set the default SELinux context for a file\nlet result = set_selinux_security_context(Path::new(\"/path/to/file\"), None);\nif let Err(err) = result {\neprintln!(\"Failed to set default context: {}\", err);\n}\n```\n\nSetting specific context:\n```\nuse std::path::Path;\nuse uucore::selinux::set_selinux_security_context;\n\n// Set a specific SELinux context for a file\nlet context = String::from(\"unconfined_u:object_r:user_home_t:s0\");\nlet result = set_selinux_security_context(Path::new(\"/path/to/file\"), Some(&context));\nif let Err(err) = result {\neprintln!(\"Failed to set context: {}\", err);\n}\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_selinux_security_context(\n path: &Path,\n context: Option<&String>,\n) -> Result<(), SeLinuxError> {\n if !is_selinux_enabled() {\n return Err(SeLinuxError::SELinuxNotEnabled);\n }\n\n if let Some(ctx_str) = context {\n // Create a CString from the provided context string\n let c_context = std::ffi::CString::new(ctx_str.as_str()).map_err(|e| {\n SeLinuxError::ContextConversionFailure(\n ctx_str.to_string(),\n selinux_error_description(&e),\n )\n })?;\n\n // Convert the CString into an SELinux security context\n let security_context =\n selinux::OpaqueSecurityContext::from_c_str(&c_context).map_err(|e| {\n SeLinuxError::ContextConversionFailure(\n ctx_str.to_string(),\n selinux_error_description(&e),\n )\n })?;\n\n // Set the provided security context on the specified path\n SecurityContext::from_c_str(\n &security_context.to_c_string().map_err(|e| {\n SeLinuxError::ContextConversionFailure(\n ctx_str.to_string(),\n selinux_error_description(&e),\n )\n })?,\n false,\n )\n .set_for_path(path, false, false)\n .map_err(|e| {\n SeLinuxError::ContextSetFailure(ctx_str.to_string(), selinux_error_description(&e))\n })\n } else {\n // If no context provided, set the default SELinux context for the path\n SecurityContext::set_default_for_path(path).map_err(|e| {\n SeLinuxError::ContextSetFailure(String::new(), selinux_error_description(&e))\n })\n }\n}\n```"}], "func_name": "set_selinux_security_context", "docstring": "Sets the SELinux security context for the given filesystem path.\n\nIf a specific context is provided, it attempts to set this context explicitly.\nOtherwise, it applies the default SELinux context for the provided path.\n\n# Arguments\n\n* `path` - Filesystem path on which to set the SELinux context.\n* `context` - Optional SELinux context string to explicitly set.\n\n# Errors\n\nReturns an error if:\n- SELinux is not enabled on the system.\n- The provided context is invalid or cannot be applied.\n- The default SELinux context cannot be set.\n\n# Examples\n\nSetting default context:\n```\nuse std::path::Path;\nuse uucore::selinux::set_selinux_security_context;\n\n// Set the default SELinux context for a file\nlet result = set_selinux_security_context(Path::new(\"/path/to/file\"), None);\nif let Err(err) = result {\neprintln!(\"Failed to set default context: {}\", err);\n}\n```\n\nSetting specific context:\n```\nuse std::path::Path;\nuse uucore::selinux::set_selinux_security_context;\n\n// Set a specific SELinux context for a file\nlet context = String::from(\"unconfined_u:object_r:user_home_t:s0\");\nlet result = set_selinux_security_context(Path::new(\"/path/to/file\"), Some(&context));\nif let Err(err) = result {\neprintln!(\"Failed to set context: {}\", err);\n}\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/selinux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/selinux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eba2767774a2f959e4e8ff54ef62213103471bae8a41eae3847d69f1562e9c77"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_selinux_security_context\n\nDocumentation:\nGets the SELinux security context for the given filesystem path.\n\nRetrieves the security context of the specified filesystem path if SELinux is enabled\non the system.\n\n# Arguments\n\n* `path` - Filesystem path for which to retrieve the SELinux context.\n\n# Returns\n\n* `Ok(String)` - The SELinux context string if successfully retrieved. Returns an empty\nstring if no context was found.\n* `Err(SeLinuxError)` - An error variant indicating the type of failure:\n- `SeLinuxError::SELinuxNotEnabled` - SELinux is not enabled on the system.\n- `SeLinuxError::FileOpenFailure` - Failed to open the specified file.\n- `SeLinuxError::ContextRetrievalFailure` - Failed to retrieve the security context.\n- `SeLinuxError::ContextConversionFailure` - Failed to convert the security context to a string.\n- `SeLinuxError::ContextSetFailure` - Failed to set the security context.\n\n# Examples\n\n```\nuse std::path::Path;\nuse uucore::selinux::{get_selinux_security_context, SeLinuxError};\n\n// Get the SELinux context for a file\nmatch get_selinux_security_context(Path::new(\"/path/to/file\")) {\nOk(context) => {\nif context.is_empty() {\nprintln!(\"No SELinux context found for the file\");\n} else {\nprintln!(\"SELinux context: {}\", context);\n}\n},\nErr(SeLinuxError::SELinuxNotEnabled) => println!(\"SELinux is not enabled on this system\"),\nErr(SeLinuxError::FileOpenFailure(e)) => println!(\"Failed to open the file: {}\", e),\nErr(SeLinuxError::ContextRetrievalFailure(e)) => println!(\"Failed to retrieve the security context: {}\", e),\nErr(SeLinuxError::ContextConversionFailure(ctx, e)) => println!(\"Failed to convert context '{}': {}\", ctx, e),\nErr(SeLinuxError::ContextSetFailure(ctx, e)) => println!(\"Failed to set context '{}': {}\", ctx, e),\n}\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_selinux_security_context(path: &Path) -> Result {\n if !is_selinux_enabled() {\n return Err(SeLinuxError::SELinuxNotEnabled);\n }\n\n let f = std::fs::File::open(path)\n .map_err(|e| SeLinuxError::FileOpenFailure(selinux_error_description(&e)))?;\n\n // Get the security context of the file\n let context = match SecurityContext::of_file(&f, false) {\n Ok(Some(ctx)) => ctx,\n Ok(None) => return Ok(String::new()), // No context found, return empty string\n Err(e) => {\n return Err(SeLinuxError::ContextRetrievalFailure(\n selinux_error_description(&e),\n ));\n }\n };\n\n let context_c_string = context.to_c_string().map_err(|e| {\n SeLinuxError::ContextConversionFailure(String::new(), selinux_error_description(&e))\n })?;\n\n if let Some(c_str) = context_c_string {\n // Convert the C string to a Rust String\n Ok(c_str.to_string_lossy().to_string())\n } else {\n Ok(String::new())\n }\n}\n```"}], "func_name": "get_selinux_security_context", "docstring": "Gets the SELinux security context for the given filesystem path.\n\nRetrieves the security context of the specified filesystem path if SELinux is enabled\non the system.\n\n# Arguments\n\n* `path` - Filesystem path for which to retrieve the SELinux context.\n\n# Returns\n\n* `Ok(String)` - The SELinux context string if successfully retrieved. Returns an empty\nstring if no context was found.\n* `Err(SeLinuxError)` - An error variant indicating the type of failure:\n- `SeLinuxError::SELinuxNotEnabled` - SELinux is not enabled on the system.\n- `SeLinuxError::FileOpenFailure` - Failed to open the specified file.\n- `SeLinuxError::ContextRetrievalFailure` - Failed to retrieve the security context.\n- `SeLinuxError::ContextConversionFailure` - Failed to convert the security context to a string.\n- `SeLinuxError::ContextSetFailure` - Failed to set the security context.\n\n# Examples\n\n```\nuse std::path::Path;\nuse uucore::selinux::{get_selinux_security_context, SeLinuxError};\n\n// Get the SELinux context for a file\nmatch get_selinux_security_context(Path::new(\"/path/to/file\")) {\nOk(context) => {\nif context.is_empty() {\nprintln!(\"No SELinux context found for the file\");\n} else {\nprintln!(\"SELinux context: {}\", context);\n}\n},\nErr(SeLinuxError::SELinuxNotEnabled) => println!(\"SELinux is not enabled on this system\"),\nErr(SeLinuxError::FileOpenFailure(e)) => println!(\"Failed to open the file: {}\", e),\nErr(SeLinuxError::ContextRetrievalFailure(e)) => println!(\"Failed to retrieve the security context: {}\", e),\nErr(SeLinuxError::ContextConversionFailure(ctx, e)) => println!(\"Failed to convert context '{}': {}\", ctx, e),\nErr(SeLinuxError::ContextSetFailure(ctx, e)) => println!(\"Failed to set context '{}': {}\", ctx, e),\n}\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/selinux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/selinux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a6ab7bd9f590fbd248fd3f3bd5235ad4815e0e3ffe632a5cf6599611b54542a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: contexts_differ\n\nDocumentation:\nCompares SELinux security contexts of two filesystem paths.\n\nThis function retrieves and compares the SELinux security contexts of two paths.\nIf the contexts differ or an error occurs during retrieval, it returns true.\n\n# Arguments\n\n* `from_path` - Source filesystem path.\n* `to_path` - Destination filesystem path.\n\n# Returns\n\n* `true` - If contexts differ, cannot be retrieved, or if SELinux is not enabled.\n* `false` - If contexts are the same.\n\n# Examples\n\n```\nuse std::path::Path;\nuse uucore::selinux::contexts_differ;\n\n// Check if contexts differ between two files\nlet differ = contexts_differ(Path::new(\"/path/to/source\"), Path::new(\"/path/to/destination\"));\nif differ {\nprintln!(\"Files have different SELinux contexts\");\n} else {\nprintln!(\"Files have the same SELinux context\");\n}\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn contexts_differ(from_path: &Path, to_path: &Path) -> bool {\n if !is_selinux_enabled() {\n return true;\n }\n\n // Check if SELinux contexts differ\n match (\n selinux::SecurityContext::of_path(from_path, false, false),\n selinux::SecurityContext::of_path(to_path, false, false),\n ) {\n (Ok(Some(from_ctx)), Ok(Some(to_ctx))) => {\n // Convert contexts to CString and compare\n match (from_ctx.to_c_string(), to_ctx.to_c_string()) {\n (Ok(Some(from_c_str)), Ok(Some(to_c_str))) => {\n from_c_str.to_string_lossy() != to_c_str.to_string_lossy()\n }\n // If contexts couldn't be converted to CString or were None, consider them different\n _ => true,\n }\n }\n // If either context is None or an error occurred, assume contexts differ\n _ => true,\n }\n}\n```"}], "func_name": "contexts_differ", "docstring": "Compares SELinux security contexts of two filesystem paths.\n\nThis function retrieves and compares the SELinux security contexts of two paths.\nIf the contexts differ or an error occurs during retrieval, it returns true.\n\n# Arguments\n\n* `from_path` - Source filesystem path.\n* `to_path` - Destination filesystem path.\n\n# Returns\n\n* `true` - If contexts differ, cannot be retrieved, or if SELinux is not enabled.\n* `false` - If contexts are the same.\n\n# Examples\n\n```\nuse std::path::Path;\nuse uucore::selinux::contexts_differ;\n\n// Check if contexts differ between two files\nlet differ = contexts_differ(Path::new(\"/path/to/source\"), Path::new(\"/path/to/destination\"));\nif differ {\nprintln!(\"Files have different SELinux contexts\");\n} else {\nprintln!(\"Files have the same SELinux context\");\n}\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/selinux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/selinux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0035d02b25b26500a03922998cf37fe7a9237eb6db4f46217723ebd015982a4c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: preserve_security_context\n\nDocumentation:\nPreserves the SELinux security context from one filesystem path to another.\n\nThis function copies the security context from the source path to the destination path.\nIf SELinux is not enabled, or if the source has no context, the function returns success\nwithout making any changes.\n\n# Arguments\n\n* `from_path` - Source filesystem path from which to copy the SELinux context.\n* `to_path` - Destination filesystem path to which the context should be applied.\n\n# Returns\n\n* `Ok(())` - If the context was successfully preserved or if SELinux is not enabled.\n* `Err(SeLinuxError)` - If an error occurred during context retrieval or application.\n\n# Examples\n\n```\nuse std::path::Path;\nuse uucore::selinux::preserve_security_context;\n\n// Preserve the SELinux context from source to destination\nmatch preserve_security_context(Path::new(\"/path/to/source\"), Path::new(\"/path/to/destination\")) {\nOk(_) => println!(\"Context preserved successfully (or SELinux is not enabled)\"),\nErr(err) => eprintln!(\"Failed to preserve context: {}\", err),\n}\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn preserve_security_context(from_path: &Path, to_path: &Path) -> Result<(), SeLinuxError> {\n // If SELinux is not enabled, return success without doing anything\n if !is_selinux_enabled() {\n return Err(SeLinuxError::SELinuxNotEnabled);\n }\n\n // Get context from the source path\n let context = get_selinux_security_context(from_path)?;\n\n // If no context was found, just return success (nothing to preserve)\n if context.is_empty() {\n return Ok(());\n }\n\n // Apply the context to the destination path\n set_selinux_security_context(to_path, Some(&context))\n}\n```"}], "func_name": "preserve_security_context", "docstring": "Preserves the SELinux security context from one filesystem path to another.\n\nThis function copies the security context from the source path to the destination path.\nIf SELinux is not enabled, or if the source has no context, the function returns success\nwithout making any changes.\n\n# Arguments\n\n* `from_path` - Source filesystem path from which to copy the SELinux context.\n* `to_path` - Destination filesystem path to which the context should be applied.\n\n# Returns\n\n* `Ok(())` - If the context was successfully preserved or if SELinux is not enabled.\n* `Err(SeLinuxError)` - If an error occurred during context retrieval or application.\n\n# Examples\n\n```\nuse std::path::Path;\nuse uucore::selinux::preserve_security_context;\n\n// Preserve the SELinux context from source to destination\nmatch preserve_security_context(Path::new(\"/path/to/source\"), Path::new(\"/path/to/destination\")) {\nOk(_) => println!(\"Context preserved successfully (or SELinux is not enabled)\"),\nErr(err) => eprintln!(\"Failed to preserve context: {}\", err),\n}\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/selinux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/selinux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "38f1e6697b83215a2cd6435636a70992491ed10f820fb87be1aa3beda66968f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: signal_by_name_or_value\n\nDocumentation:\nReturns the signal number for a given signal name or value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn signal_by_name_or_value(signal_name_or_value: &str) -> Option {\n let signal_name_upcase = signal_name_or_value.to_uppercase();\n if let Ok(value) = signal_name_upcase.parse() {\n return if is_signal(value) { Some(value) } else { None };\n }\n let signal_name = signal_name_upcase.trim_start_matches(\"SIG\");\n\n ALL_SIGNALS.iter().position(|&s| s == signal_name)\n}\n```"}], "func_name": "signal_by_name_or_value", "docstring": "Returns the signal number for a given signal name or value.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/signals.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/signals.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "148cebfc4b80f3e8abb01aaa445a69c980684ccfcabeab65191a96f2dbaa7b3d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_signal\n\nDocumentation:\nReturns true if the given number is a valid signal number.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_signal(num: usize) -> bool {\n num < ALL_SIGNALS.len()\n}\n```"}], "func_name": "is_signal", "docstring": "Returns true if the given number is a valid signal number.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/signals.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/signals.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e1fdf492b78cb7eafffb1580dc4575d82a983ab0132cabab60f632b326a890fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_output_bytes\n\nDocumentation:\nReturn a new Blake2b instance with a custom output bytes length\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_output_bytes(output_bytes: usize) -> Self {\n let mut params = blake2b_simd::Params::new();\n params.hash_length(output_bytes);\n\n let state = params.to_state();\n Self(state, output_bytes * 8)\n }\n```"}], "func_name": "with_output_bytes", "docstring": "Return a new Blake2b instance with a custom output bytes length", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/sum.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/sum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "47e723cc5afb2fa15b45ee258c396191fcf3c198167e4d9dd6ecda1ab7e969ef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update\n\nDocumentation:\n`--update` argument, defaults to `older` if no values are provided\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn update() -> clap::Arg {\n clap::Arg::new(OPT_UPDATE)\n .long(\"update\")\n .help(\"move only when the SOURCE file is newer than the destination file or when the destination file is missing\")\n .value_parser(ShortcutValueParser::new([\"none\", \"all\", \"older\",\"none-fail\"]))\n .num_args(0..=1)\n .default_missing_value(\"older\")\n .require_equals(true)\n .overrides_with(\"update\")\n .action(clap::ArgAction::Set)\n }\n```"}], "func_name": "update", "docstring": "`--update` argument, defaults to `older` if no values are provided", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/update_control.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/update_control.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "018fe3f18716a2dbeaf7c4911621c0890ae89703fcc01836328791b5ffe3b3f9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: determine_update_mode\n\nDocumentation:\nDetermine the \"mode\" for the update operation to perform, if any.\n\nParses the backup options and converts them to an instance of\n`UpdateMode` for further processing.\n\nTakes [`clap::ArgMatches`] as argument which **must** contain the options\nfrom [`arguments::update()`] or [`arguments::update_no_args()`]. Otherwise\nthe `ReplaceAll` mode is returned unconditionally.\n\n# Examples\n\nHere's how one would integrate the update mode determination into an\napplication.\n\n```\n#[macro_use]\nextern crate uucore;\nuse uucore::update_control::{self, UpdateMode};\nuse clap::{Command, Arg, ArgMatches};\n\nfn main() {\nlet matches = Command::new(\"command\")\n.arg(update_control::arguments::update())\n.arg(update_control::arguments::update_no_args())\n.get_matches_from(vec![\n\"command\", \"--update=all\"\n]);\n\nlet update_mode = update_control::determine_update_mode(&matches);\nassert_eq!(update_mode, UpdateMode::All)\n}\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn determine_update_mode(matches: &ArgMatches) -> UpdateMode {\n if let Some(mode) = matches.get_one::(arguments::OPT_UPDATE) {\n match mode.as_str() {\n \"all\" => UpdateMode::All,\n \"none\" => UpdateMode::None,\n \"older\" => UpdateMode::IfOlder,\n \"none-fail\" => UpdateMode::NoneFail,\n _ => unreachable!(\"other args restricted by clap\"),\n }\n } else if matches.get_flag(arguments::OPT_UPDATE_NO_ARG) {\n // short form of this option is equivalent to using --update=older\n UpdateMode::IfOlder\n } else {\n // no option was present\n UpdateMode::All\n }\n}\n```"}], "func_name": "determine_update_mode", "docstring": "Determine the \"mode\" for the update operation to perform, if any.\n\nParses the backup options and converts them to an instance of\n`UpdateMode` for further processing.\n\nTakes [`clap::ArgMatches`] as argument which **must** contain the options\nfrom [`arguments::update()`] or [`arguments::update_no_args()`]. Otherwise\nthe `ReplaceAll` mode is returned unconditionally.\n\n# Examples\n\nHere's how one would integrate the update mode determination into an\napplication.\n\n```\n#[macro_use]\nextern crate uucore;\nuse uucore::update_control::{self, UpdateMode};\nuse clap::{Command, Arg, ArgMatches};\n\nfn main() {\nlet matches = Command::new(\"command\")\n.arg(update_control::arguments::update())\n.arg(update_control::arguments::update_no_args())\n.get_matches_from(vec![\n\"command\", \"--update=all\"\n]);\n\nlet update_mode = update_control::determine_update_mode(&matches);\nassert_eq!(update_mode, UpdateMode::All)\n}", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/update_control.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/update_control.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "28b3cdc6b9ec24ace6addb4f0dcff09b8a82a761a5e15751bdde69d9e5d858c9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_user_process\n\nDocumentation:\ncheck if the record is a user process\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_user_process(&self) -> bool {\n !self.user().is_empty() && self.record_type() == USER_PROCESS\n }\n```"}], "func_name": "is_user_process", "docstring": "check if the record is a user process", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/utmpx.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/utmpx.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb5232e3d7bd49bac992cad22004a0eaa7f088ab483cf9c0416bcc50986ea673"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: iter_all_records\n\nDocumentation:\nIterate through all the utmp records.\n\nThis will use the default location, or the path [`Utmpx::iter_all_records_from`]\nwas most recently called with.\n\nOnly one instance of [`UtmpxIter`] may be active at a time. This\nfunction will block as long as one is still active. Beware!\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn iter_all_records() -> UtmpxIter {\n let iter = UtmpxIter::new();\n unsafe {\n // This can technically fail, and it would be nice to detect that,\n // but it doesn't return anything so we'd have to do nasty things\n // with errno.\n #[cfg_attr(target_env = \"musl\", allow(deprecated))]\n setutxent();\n }\n iter\n }\n```"}], "func_name": "iter_all_records", "docstring": "Iterate through all the utmp records.\n\nThis will use the default location, or the path [`Utmpx::iter_all_records_from`]\nwas most recently called with.\n\nOnly one instance of [`UtmpxIter`] may be active at a time. This\nfunction will block as long as one is still active. Beware!", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/utmpx.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/utmpx.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "905a7c36056ea366f9d8641d8a5c78fac867136de0f60d290271d4274c0c675f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: iter_all_records_from\n\nDocumentation:\nIterate through all the utmp records from a specific file.\n\nNo failure is reported or detected.\n\nThis function affects subsequent calls to [`Utmpx::iter_all_records`].\n\nThe same caveats as for [`Utmpx::iter_all_records`] apply.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn iter_all_records_from>(path: P) -> UtmpxIter {\n let iter = UtmpxIter::new();\n let path = CString::new(path.as_ref().as_os_str().as_bytes()).unwrap();\n unsafe {\n // In glibc, utmpxname() only fails if there's not enough memory\n // to copy the string.\n // Solaris returns 1 on success instead of 0. Supposedly there also\n // exist systems where it returns void.\n // GNU who on Debian seems to output nothing if an invalid filename\n // is specified, no warning or anything.\n // So this function is pretty crazy and we don't try to detect errors.\n // Not much we can do besides pray.\n #[cfg_attr(target_env = \"musl\", allow(deprecated))]\n utmpxname(path.as_ptr());\n #[cfg_attr(target_env = \"musl\", allow(deprecated))]\n setutxent();\n }\n iter\n }\n```"}], "func_name": "iter_all_records_from", "docstring": "Iterate through all the utmp records from a specific file.\n\nNo failure is reported or detected.\n\nThis function affects subsequent calls to [`Utmpx::iter_all_records`].\n\nThe same caveats as for [`Utmpx::iter_all_records`] apply.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/utmpx.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/utmpx.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fe8fcfc5ef159c1268cc06112aa5521c99bef8b513d617a97f909b99529baea2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: version_non_digit_cmp\n\nDocumentation:\nCompares the non-digit parts of a version.\nSpecial cases: ~ are before everything else, even ends (\"a~\" < \"a\")\nLetters are before non-letters\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn version_non_digit_cmp(a: &str, b: &str) -> Ordering {\n let mut a_chars = a.chars();\n let mut b_chars = b.chars();\n loop {\n match (a_chars.next(), b_chars.next()) {\n (Some(c1), Some(c2)) if c1 == c2 => {}\n (None, None) => return Ordering::Equal,\n (_, Some('~')) => return Ordering::Greater,\n (Some('~'), _) => return Ordering::Less,\n (None, Some(_)) => return Ordering::Less,\n (Some(_), None) => return Ordering::Greater,\n (Some(c1), Some(c2)) if c1.is_ascii_alphabetic() && !c2.is_ascii_alphabetic() => {\n return Ordering::Less;\n }\n (Some(c1), Some(c2)) if !c1.is_ascii_alphabetic() && c2.is_ascii_alphabetic() => {\n return Ordering::Greater;\n }\n (Some(c1), Some(c2)) => return c1.cmp(&c2),\n }\n }\n}\n```"}], "func_name": "version_non_digit_cmp", "docstring": "Compares the non-digit parts of a version.\nSpecial cases: ~ are before everything else, even ends (\"a~\" < \"a\")\nLetters are before non-letters", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/version_cmp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/version_cmp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ae327fb245adec40e0724845f1c7142c96a1a75e60da190f3ed11097550d008b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_file_ending\n\nDocumentation:\nRemove file endings matching the regex (\\.[A-Za-z~][A-Za-z0-9~]*)*$\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn remove_file_ending(a: &str) -> &str {\n let mut ending_start = None;\n let mut prev_was_dot = false;\n for (idx, char) in a.char_indices() {\n if char == '.' {\n if ending_start.is_none() || prev_was_dot {\n ending_start = Some(idx);\n }\n prev_was_dot = true;\n } else if prev_was_dot {\n prev_was_dot = false;\n if !char.is_ascii_alphabetic() && char != '~' {\n ending_start = None;\n }\n } else if !char.is_ascii_alphanumeric() && char != '~' {\n ending_start = None;\n }\n }\n if prev_was_dot {\n ending_start = None;\n }\n if let Some(ending_start) = ending_start {\n &a[..ending_start]\n } else {\n a\n }\n}\n```"}], "func_name": "remove_file_ending", "docstring": "Remove file endings matching the regex (\\.[A-Za-z~][A-Za-z0-9~]*)*$", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/version_cmp.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/version_cmp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b343fdf932151b69d46e04889a066cb1a2684bb9a3ca1033f5947c6f77caacd2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_stream\n\nDocumentation:\nCopy data from `Read` implementor `source` into a `Write` implementor\n`dest`. This works by reading a chunk of data from `source` and writing the\ndata to `dest` in a loop.\n\nThis function uses the Linux-specific `splice` call when possible which does\nnot use any intermediate user-space buffer. It falls backs to\n`std::io::copy` when the call fails and is still recoverable.\n\n# Arguments\n* `source` - `Read` implementor to copy data from.\n* `dest` - `Write` implementor to copy data to.\n\n# Returns\n\nResult of operation and bytes successfully written (as a `u64`) when\noperation is successful.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn copy_stream(src: &mut R, dest: &mut S) -> UResult\nwhere\n R: Read + AsFd + AsRawFd,\n S: Write + AsFd + AsRawFd,\n{\n // If we're on Linux or Android, try to use the splice() system call\n // for faster writing. If it works, we're done.\n let result = splice_write(src, &dest.as_fd())?;\n if !result.1 {\n return Ok(result.0);\n }\n\n // If the splice() call failed, fall back on slower writing.\n let result = std::io::copy(src, dest)?;\n\n // If the splice() call failed and there has been some data written to\n // stdout via while loop above AND there will be second splice() call\n // that will succeed, data pushed through splice will be output before\n // the data buffered in stdout.lock. Therefore additional explicit flush\n // is required here.\n dest.flush()?;\n Ok(result)\n}\n```"}], "func_name": "copy_stream", "docstring": "Copy data from `Read` implementor `source` into a `Write` implementor\n`dest`. This works by reading a chunk of data from `source` and writing the\ndata to `dest` in a loop.\n\nThis function uses the Linux-specific `splice` call when possible which does\nnot use any intermediate user-space buffer. It falls backs to\n`std::io::copy` when the call fails and is still recoverable.\n\n# Arguments\n* `source` - `Read` implementor to copy data from.\n* `dest` - `Write` implementor to copy data to.\n\n# Returns\n\nResult of operation and bytes successfully written (as a `u64`) when\noperation is successful.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/buf_copy/linux.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/buf_copy/linux.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "65385672cd865d29a45a71879dd64ec0b71c3f0ce24e42374b2d9a58e706f1ec"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_stream\n\nDocumentation:\nCopy data from `Read` implementor `source` into a `Write` implementor\n`dest`. This works by reading a chunk of data from `source` and writing the\ndata to `dest` in a loop, using std::io::copy. This is implemented for\nnon-Linux platforms.\n\n# Arguments\n* `source` - `Read` implementor to copy data from.\n* `dest` - `Write` implementor to copy data to.\n\n# Returns\n\nResult of operation and bytes successfully written (as a `u64`) when\noperation is successful.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn copy_stream(src: &mut R, dest: &mut S) -> UResult\nwhere\n R: Read,\n S: Write,\n{\n let result = std::io::copy(src, dest)?;\n Ok(result)\n}\n```"}], "func_name": "copy_stream", "docstring": "Copy data from `Read` implementor `source` into a `Write` implementor\n`dest`. This works by reading a chunk of data from `source` and writing the\ndata to `dest` in a loop, using std::io::copy. This is implemented for\nnon-Linux platforms.\n\n# Arguments\n* `source` - `Read` implementor to copy data from.\n* `dest` - `Write` implementor to copy data to.\n\n# Returns\n\nResult of operation and bytes successfully written (as a `u64`) when\noperation is successful.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/buf_copy/other.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/buf_copy/other.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e2062d2bfc7183434ef2edfa73bac4d44bc2568ba345ed030d3ba92530d2c098"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new FormatArguments from a slice of FormatArgument\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(args: &'a [FormatArgument]) -> Self {\n Self {\n args,\n next_arg_position: 0,\n highest_arg_position: None,\n current_offset: 0,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new FormatArguments from a slice of FormatArgument", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/format/argument.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/format/argument.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2212faaf38d5c18322c2dbf199db96713a57010761649d18b6cd85e0ab65242c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_exhausted\n\nDocumentation:\nCheck if all arguments have been consumed\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_exhausted(&self) -> bool {\n self.current_offset >= self.args.len()\n }\n```"}], "func_name": "is_exhausted", "docstring": "Check if all arguments have been consumed", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/format/argument.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/format/argument.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e2e7b33f06e1e1a7cdb83f02cf8162941a41649a7d2963ac3197efa64c84f62d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_code\n\nDocumentation:\nParse the numeric part of the `\\xHHH` and `\\0NNN` escape sequences\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_code(input: &mut &[u8], base: Base) -> Option {\n // All arithmetic on `ret` needs to be wrapping, because octal input can\n // take 3 digits, which is 9 bits, and therefore more than what fits in a\n // `u8`. GNU just seems to wrap these values.\n // Note that if we instead make `ret` a `u32` and use `char::from_u32` will\n // yield incorrect results because it will interpret values larger than\n // `u8::MAX` as unicode.\n let [c, rest @ ..] = input else { return None };\n let mut ret = base.convert_digit(*c)?;\n *input = rest;\n\n for _ in 1..base.max_digits() {\n let [c, rest @ ..] = input else { break };\n let Some(n) = base.convert_digit(*c) else {\n break;\n };\n ret = ret.wrapping_mul(base.as_base()).wrapping_add(n);\n *input = rest;\n }\n\n Some(ret)\n}\n```"}], "func_name": "parse_code", "docstring": "Parse the numeric part of the `\\xHHH` and `\\0NNN` escape sequences", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/format/escape.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/format/escape.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca410b866c0378b9674661023a0c8283964f70baa984d3e3ea7a40f34a6a42d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_escape_code\n\nDocumentation:\nParse an escape sequence, like `\\n` or `\\xff`, etc.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_escape_code(\n rest: &mut &[u8],\n zero_octal_parsing: OctalParsing,\n) -> Result {\n if let [c, new_rest @ ..] = rest {\n // This is for the \\NNN syntax for octal sequences.\n // Note that '0' is intentionally omitted because that\n // would be the \\0NNN syntax.\n if let b'1'..=b'7' = c {\n if let Some(parsed) = parse_code(rest, Base::Oct(OctalParsing::ThreeDigits)) {\n return Ok(EscapedChar::Byte(parsed));\n }\n }\n\n *rest = new_rest;\n match c {\n b'\\\\' => Ok(EscapedChar::Byte(b'\\\\')),\n b'\"' => Ok(EscapedChar::Byte(b'\"')),\n b'a' => Ok(EscapedChar::Byte(b'\\x07')),\n b'b' => Ok(EscapedChar::Byte(b'\\x08')),\n b'c' => Ok(EscapedChar::End),\n b'e' => Ok(EscapedChar::Byte(b'\\x1b')),\n b'f' => Ok(EscapedChar::Byte(b'\\x0c')),\n b'n' => Ok(EscapedChar::Byte(b'\\n')),\n b'r' => Ok(EscapedChar::Byte(b'\\r')),\n b't' => Ok(EscapedChar::Byte(b'\\t')),\n b'v' => Ok(EscapedChar::Byte(b'\\x0b')),\n b'x' => {\n if let Some(c) = parse_code(rest, Base::Hex) {\n Ok(EscapedChar::Byte(c))\n } else {\n Err(FormatError::MissingHex)\n }\n }\n b'0' => Ok(EscapedChar::Byte(\n parse_code(rest, Base::Oct(zero_octal_parsing)).unwrap_or(b'\\0'),\n )),\n b'u' => match parse_unicode(rest, 4) {\n Ok(c) => Ok(EscapedChar::Char(c)),\n Err(EscapeError::MissingHexadecimalNumber) => Err(FormatError::MissingHex),\n Err(EscapeError::InvalidCharacters(chars)) => {\n Err(FormatError::InvalidCharacter('u', chars))\n }\n },\n b'U' => match parse_unicode(rest, 8) {\n Ok(c) => Ok(EscapedChar::Char(c)),\n Err(EscapeError::MissingHexadecimalNumber) => Err(FormatError::MissingHex),\n Err(EscapeError::InvalidCharacters(chars)) => {\n Err(FormatError::InvalidCharacter('U', chars))\n }\n },\n c => Ok(EscapedChar::Backslash(*c)),\n }\n } else {\n Ok(EscapedChar::Byte(b'\\\\'))\n }\n}\n```"}], "func_name": "parse_escape_code", "docstring": "Parse an escape sequence, like `\\n` or `\\xff`, etc.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/format/escape.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/format/escape.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "012700e9eb8f3c4772883ea928230df3c1dbc2abdae864cbf76a90a8f765073e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_spec_and_escape\n\nDocumentation:\nParse a format string containing % directives and escape sequences\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_spec_and_escape(\n fmt: &[u8],\n) -> impl Iterator, FormatError>> + '_ {\n let mut current = fmt;\n std::iter::from_fn(move || match current {\n [] => None,\n [b'%', b'%', rest @ ..] => {\n current = rest;\n Some(Ok(FormatItem::Char(EscapedChar::Byte(b'%'))))\n }\n [b'%', rest @ ..] => {\n current = rest;\n let spec = match Spec::parse(&mut current) {\n Ok(spec) => spec,\n Err(slice) => return Some(Err(FormatError::SpecError(slice.to_vec()))),\n };\n Some(Ok(FormatItem::Spec(spec)))\n }\n [b'\\\\', rest @ ..] => {\n current = rest;\n Some(parse_escape_code(&mut current, OctalParsing::default()).map(FormatItem::Char))\n }\n [c, rest @ ..] => {\n current = rest;\n Some(Ok(FormatItem::Char(EscapedChar::Byte(*c))))\n }\n })\n}\n```"}], "func_name": "parse_spec_and_escape", "docstring": "Parse a format string containing % directives and escape sequences", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/format/mod.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/format/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e7ac67bd4c3fafa63b0f2607e146b4e90c696948a7eb2a3c7414543dec08383"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_escape_only\n\nDocumentation:\nParse a format string containing escape sequences\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_escape_only(\n fmt: &[u8],\n zero_octal_parsing: OctalParsing,\n) -> impl Iterator + '_ {\n let mut current = fmt;\n std::iter::from_fn(move || match current {\n [] => None,\n [b'\\\\', rest @ ..] => {\n current = rest;\n Some(\n parse_escape_code(&mut current, zero_octal_parsing)\n .unwrap_or(EscapedChar::Backslash(b'x')),\n )\n }\n [c, rest @ ..] => {\n current = rest;\n Some(EscapedChar::Byte(*c))\n }\n })\n}\n```"}], "func_name": "parse_escape_only", "docstring": "Parse a format string containing escape sequences", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/format/mod.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/format/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "262921600326539484481f007dc4a2857d10941a24d9389d5704d91f52677881"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: printf\n\nDocumentation:\nWrite a formatted string to stdout.\n\n`format_string` contains the template and `args` contains the\narguments to render into the template.\n\nSee also [`sprintf`], which creates a new formatted [`String`].\n\n# Examples\n\n```rust\nuse uucore::format::{printf, FormatArgument};\n\nprintf(\"hello %s\", &[FormatArgument::String(\"world\".into())]).unwrap();\n// prints \"hello world\"\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn printf<'a>(\n format_string: impl AsRef<[u8]>,\n arguments: impl IntoIterator,\n) -> Result<(), FormatError> {\n printf_writer(stdout(), format_string, arguments)\n}\n```"}], "func_name": "printf", "docstring": "Write a formatted string to stdout.\n\n`format_string` contains the template and `args` contains the\narguments to render into the template.\n\nSee also [`sprintf`], which creates a new formatted [`String`].\n\n# Examples\n\n```rust\nuse uucore::format::{printf, FormatArgument};\n\nprintf(\"hello %s\", &[FormatArgument::String(\"world\".into())]).unwrap();\n// prints \"hello world\"\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/format/mod.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/format/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25720efae17b14b2f104f49babb7115763fffb15b6954fd371f98b272cae28f9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sprintf\n\nDocumentation:\nCreate a new formatted string.\n\n`format_string` contains the template and `args` contains the\narguments to render into the template.\n\nSee also [`printf`], which prints to stdout.\n\n# Examples\n\n```rust\nuse uucore::format::{sprintf, FormatArgument};\n\nlet s = sprintf(\"hello %s\", &[FormatArgument::String(\"world\".into())]).unwrap();\nlet s = std::str::from_utf8(&s).unwrap();\nassert_eq!(s, \"hello world\");\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sprintf<'a>(\n format_string: impl AsRef<[u8]>,\n arguments: impl IntoIterator,\n) -> Result, FormatError> {\n let mut writer = Vec::new();\n printf_writer(&mut writer, format_string, arguments)?;\n Ok(writer)\n}\n```"}], "func_name": "sprintf", "docstring": "Create a new formatted string.\n\n`format_string` contains the template and `args` contains the\narguments to render into the template.\n\nSee also [`printf`], which prints to stdout.\n\n# Examples\n\n```rust\nuse uucore::format::{sprintf, FormatArgument};\n\nlet s = sprintf(\"hello %s\", &[FormatArgument::String(\"world\".into())]).unwrap();\nlet s = std::str::from_utf8(&s).unwrap();\nassert_eq!(s, \"hello world\");\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/format/mod.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/format/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9ca34f5198d9c167a6f80546a35dbb74c8716e12e17c6af5b9462804269a6e1d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: any\n\nDocumentation:\nWhether any of the flags is set to true\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn any(&self) -> bool {\n self != &Self::default()\n }\n```"}], "func_name": "any", "docstring": "Whether any of the flags is set to true", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/format/spec.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/format/spec.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "56b91bb42c4eae95ffa4b3ddc34790858d91548466bbdfa8464d69c77c0e77fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: digit\n\nDocumentation:\nReturn the digit value of a character in the given base\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn digit(&self, c: char) -> Option {\n fn from_decimal(c: char) -> u64 {\n u64::from(c) - u64::from('0')\n }\n match self {\n Self::Binary => ('0'..='1').contains(&c).then(|| from_decimal(c)),\n Self::Octal => ('0'..='7').contains(&c).then(|| from_decimal(c)),\n Self::Decimal => c.is_ascii_digit().then(|| from_decimal(c)),\n Self::Hexadecimal => match c.to_ascii_lowercase() {\n '0'..='9' => Some(from_decimal(c)),\n c @ 'a'..='f' => Some(u64::from(c) - u64::from('a') + 10),\n _ => None,\n },\n }\n }\n```"}], "func_name": "digit", "docstring": "Return the digit value of a character in the given base", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/num_parser.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/num_parser.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a72a1e8fdb750bf04d69cd69ed936b8239c9721fc85e53e8900aa4589c986a11"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_digits\n\nDocumentation:\nGreedily parse as many digits as possible from the string\nReturns parsed digits (if any), and the rest of the string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_digits<'a>(&self, str: &'a str) -> (Option, &'a str) {\n let (digits, _, rest) = self.parse_digits_count(str, None);\n (digits, rest)\n }\n```"}], "func_name": "parse_digits", "docstring": "Greedily parse as many digits as possible from the string\nReturns parsed digits (if any), and the rest of the string.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/num_parser.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/num_parser.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "799baf27837cb6d9587d6342a531ca14485d813185a0926f091b98a2e58008c6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_digits_count\n\nDocumentation:\nGreedily parse as many digits as possible from the string, adding to already parsed digits.\nThis is meant to be used (directly) for the part after a decimal point.\nReturns parsed digits (if any), the number of parsed digits, and the rest of the string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn parse_digits_count<'a>(\n &self,\n str: &'a str,\n digits: Option,\n ) -> (Option, i64, &'a str) {\n let mut digits: Option = digits;\n let mut count: i64 = 0;\n let mut rest = str;\n\n // Doing operations on BigUint is really expensive, so we do as much as we\n // can on u64, then add them to the BigUint.\n let mut digits_tmp: u64 = 0;\n let mut count_tmp: i64 = 0;\n let mut mul_tmp: u64 = 1;\n while let Some(d) = rest.chars().next().and_then(|c| self.digit(c)) {\n (digits_tmp, count_tmp, mul_tmp) = (\n digits_tmp * *self as u64 + d,\n count_tmp + 1,\n mul_tmp * *self as u64,\n );\n rest = &rest[1..];\n // In base 16, we parse 4 bits at a time, so we can parse 16 digits at most in a u64.\n if count_tmp >= 15 {\n // Accumulate what we have so far\n (digits, count) = (\n Some(digits.unwrap_or_default() * mul_tmp + digits_tmp),\n count + count_tmp,\n );\n // Reset state\n (digits_tmp, count_tmp, mul_tmp) = (0, 0, 1);\n }\n }\n\n // Accumulate the leftovers (if any)\n if mul_tmp > 1 {\n (digits, count) = (\n Some(digits.unwrap_or_default() * mul_tmp + digits_tmp),\n count + count_tmp,\n );\n }\n (digits, count, rest)\n }\n```"}], "func_name": "parse_digits_count", "docstring": "Greedily parse as many digits as possible from the string, adding to already parsed digits.\nThis is meant to be used (directly) for the part after a decimal point.\nReturns parsed digits (if any), the number of parsed digits, and the rest of the string.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/num_parser.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/num_parser.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00927098a45737866cf0416b84b32ed0c01f727d6c5dd5969bc16c1072e4ba51"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extended_parse\n\nDocumentation:\nParse a number as i64. No fractional part is allowed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extended_parse(input: &str) -> Result> {\n fn into_i64<'a>(ebd: ExtendedBigDecimal) -> Result> {\n match ebd {\n ExtendedBigDecimal::BigDecimal(bd) => {\n let (digits, scale) = bd.into_bigint_and_scale();\n if scale == 0 {\n let negative = digits.sign() == Sign::Minus;\n match i64::try_from(digits) {\n Ok(i) => Ok(i),\n _ => Err(ExtendedParserError::Overflow(if negative {\n i64::MIN\n } else {\n i64::MAX\n })),\n }\n } else {\n // Should not happen.\n Err(ExtendedParserError::NotNumeric)\n }\n }\n ExtendedBigDecimal::MinusZero => Ok(0),\n // No other case should not happen.\n _ => Err(ExtendedParserError::NotNumeric),\n }\n }\n\n match parse(input, ParseTarget::Integral, &[]) {\n Ok(v) => into_i64(v),\n Err(e) => Err(e.map(into_i64)),\n }\n }\n```"}], "func_name": "extended_parse", "docstring": "Parse a number as i64. No fractional part is allowed.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/num_parser.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/num_parser.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "56c9aa63d9000b98ccffbb489a8ee0f3249912db236e8523d2aa536429c0e9c9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extended_parse\n\nDocumentation:\nParse a number as u64. No fractional part is allowed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extended_parse(input: &str) -> Result> {\n fn into_u64<'a>(ebd: ExtendedBigDecimal) -> Result> {\n match ebd {\n ExtendedBigDecimal::BigDecimal(bd) => {\n let (digits, scale) = bd.into_bigint_and_scale();\n if scale == 0 {\n let (sign, digits) = digits.into_parts();\n\n match u64::try_from(digits) {\n Ok(i) => {\n if sign == Sign::Minus {\n Ok(!i + 1)\n } else {\n Ok(i)\n }\n }\n _ => Err(ExtendedParserError::Overflow(u64::MAX)),\n }\n } else {\n // Should not happen.\n Err(ExtendedParserError::NotNumeric)\n }\n }\n ExtendedBigDecimal::MinusZero => Ok(0),\n _ => Err(ExtendedParserError::NotNumeric),\n }\n }\n\n match parse(input, ParseTarget::Integral, &[]) {\n Ok(v) => into_u64(v),\n Err(e) => Err(e.map(into_u64)),\n }\n }\n```"}], "func_name": "extended_parse", "docstring": "Parse a number as u64. No fractional part is allowed.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/num_parser.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/num_parser.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f89b3e1378a41559f6203c5df4f2013be4a5ac3427838fedfd73a518b3ccb5e1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_allow_list\n\nDocumentation:\nChange allow_list of the parser - whitelist for the suffix\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_allow_list(&mut self, allow_list: &'parser [&str]) -> &mut Self {\n self.allow_list = Some(allow_list);\n self\n }\n```"}], "func_name": "with_allow_list", "docstring": "Change allow_list of the parser - whitelist for the suffix", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/parse_size.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/parse_size.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6c0de42ab3ad2285798f7152db11599828dd6037f5271024cc6f8a5dfbc9ca95"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_default_unit\n\nDocumentation:\nChange default_unit of the parser - when no suffix is provided\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_default_unit(&mut self, default_unit: &'parser str) -> &mut Self {\n self.default_unit = Some(default_unit);\n self\n }\n```"}], "func_name": "with_default_unit", "docstring": "Change default_unit of the parser - when no suffix is provided", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/parse_size.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/parse_size.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "abcfa54bcdc1eb87070d745fafb90225619e6160253b05a757ce3922ca3d90ec"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_b_byte_count\n\nDocumentation:\nChange b_byte_count of the parser - to treat \"b\" as a \"byte count\" instead of \"block\"\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_b_byte_count(&mut self, value: bool) -> &mut Self {\n self.b_byte_count = value;\n self\n }\n```"}], "func_name": "with_b_byte_count", "docstring": "Change b_byte_count of the parser - to treat \"b\" as a \"byte count\" instead of \"block\"", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/parse_size.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/parse_size.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f822aaf1d45e1d8e7b854a63b17b8050b5fcdfa26d7e09dc9160cb452b9784c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_allow_empty_numeric\n\nDocumentation:\nChange no_empty_numeric of the parser - to allow empty numeric strings\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_allow_empty_numeric(&mut self, value: bool) -> &mut Self {\n self.no_empty_numeric = value;\n self\n }\n```"}], "func_name": "with_allow_empty_numeric", "docstring": "Change no_empty_numeric of the parser - to allow empty numeric strings", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/parse_size.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/parse_size.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4893d4d30a27f457c92ff6e8af5965c041538382b5f3d274be0a233c3f672585"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse\n\nDocumentation:\nParse a size string into a number of bytes.\n\nA size string comprises an integer and an optional unit. The unit\nmay be K, M, G, T, P, E, Z, Y, R or Q (powers of 1024), or KB, MB,\netc. (powers of 1000), or b which is 512.\nBinary prefixes can be used, too: KiB=K, MiB=M, and so on.\n\n# Errors\n\nWill return `ParseSizeError` if it's not possible to parse this\nstring into a number, e.g. if the string does not begin with a\nnumeral, or if the unit is not one of the supported units described\nin the preceding section.\n\n# Examples\n\n```rust\nuse uucore::parser::parse_size::Parser;\nlet parser = Parser {\ndefault_unit: Some(\"M\"),\n..Default::default()\n};\nassert_eq!(Ok(123 * 1024 * 1024), parser.parse(\"123M\")); // M is 1024^2\nassert_eq!(Ok(123 * 1024 * 1024), parser.parse(\"123\")); // default unit set to \"M\" on parser instance\nassert_eq!(Ok(9 * 1000), parser.parse(\"9kB\")); // kB is 1000\nassert_eq!(Ok(2 * 1024), parser.parse(\"2K\")); // K is 1024\nassert_eq!(Ok(44251 * 1024), parser.parse(\"0xACDBK\")); // 0xACDB is 44251 in decimal\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse(&self, size: &str) -> Result {\n if size.is_empty() {\n return Err(ParseSizeError::parse_failure(size));\n }\n\n let number_system = Self::determine_number_system(size);\n\n // Split the size argument into numeric and unit parts\n // For example, if the argument is \"123K\", the numeric part is \"123\", and\n // the unit is \"K\"\n let numeric_string: String = match number_system {\n NumberSystem::Hexadecimal => size\n .chars()\n .take(2)\n .chain(size.chars().skip(2).take_while(char::is_ascii_hexdigit))\n .collect(),\n _ => size.chars().take_while(char::is_ascii_digit).collect(),\n };\n let mut unit: &str = &size[numeric_string.len()..];\n\n if let Some(default_unit) = self.default_unit {\n // Check if `unit` is empty then assigns `default_unit` to `unit`\n if unit.is_empty() {\n unit = default_unit;\n }\n }\n\n // Check if `b` is a byte count and remove `b`\n if self.b_byte_count && unit.ends_with('b') {\n // If `unit` = 'b' then return error\n if numeric_string.is_empty() {\n return Err(ParseSizeError::parse_failure(size));\n }\n unit = &unit[0..unit.len() - 1];\n }\n\n if let Some(allow_list) = self.allow_list {\n // Check if `unit` appears in `allow_list`, if not return error\n if !allow_list.contains(&unit) && !unit.is_empty() {\n if numeric_string.is_empty() {\n return Err(ParseSizeError::parse_failure(size));\n }\n return Err(ParseSizeError::invalid_suffix(size));\n }\n }\n\n // Special case: for percentage, just compute the given fraction\n // of the total physical memory on the machine, if possible.\n if unit == \"%\" {\n let number: u128 = Self::parse_number(&numeric_string, 10, size)?;\n return match total_physical_memory() {\n Ok(total) => Ok((number / 100) * total),\n Err(_) => Err(ParseSizeError::PhysicalMem(size.to_string())),\n };\n }\n\n // Compute the factor the unit represents.\n // empty string means the factor is 1.\n //\n // The lowercase \"b\" (used by `od`, `head`, `tail`, etc.) means\n // \"block\" and the Posix block size is 512. The uppercase \"B\"\n // means \"byte\".\n let (base, exponent): (u128, u32) = match unit {\n \"\" => (1, 0),\n \"B\" if self.capital_b_bytes => (1, 0),\n \"b\" => (512, 1),\n \"KiB\" | \"kiB\" | \"K\" | \"k\" => (1024, 1),\n \"MiB\" | \"miB\" | \"M\" | \"m\" => (1024, 2),\n \"GiB\" | \"giB\" | \"G\" | \"g\" => (1024, 3),\n \"TiB\" | \"tiB\" | \"T\" | \"t\" => (1024, 4),\n \"PiB\" | \"piB\" | \"P\" | \"p\" => (1024, 5),\n \"EiB\" | \"eiB\" | \"E\" | \"e\" => (1024, 6),\n \"ZiB\" | \"ziB\" | \"Z\" | \"z\" => (1024, 7),\n \"YiB\" | \"yiB\" | \"Y\" | \"y\" => (1024, 8),\n \"RiB\" | \"riB\" | \"R\" | \"r\" => (1024, 9),\n \"QiB\" | \"qiB\" | \"Q\" | \"q\" => (1024, 10),\n \"KB\" | \"kB\" => (1000, 1),\n \"MB\" | \"mB\" => (1000, 2),\n \"GB\" | \"gB\" => (1000, 3),\n \"TB\" | \"tB\" => (1000, 4),\n \"PB\" | \"pB\" => (1000, 5),\n \"EB\" | \"eB\" => (1000, 6),\n \"ZB\" | \"zB\" => (1000, 7),\n \"YB\" | \"yB\" => (1000, 8),\n \"RB\" | \"rB\" => (1000, 9),\n \"QB\" | \"qB\" => (1000, 10),\n _ if numeric_string.is_empty() => return Err(ParseSizeError::parse_failure(size)),\n _ => return Err(ParseSizeError::invalid_suffix(size)),\n };\n let factor = base.pow(exponent);\n\n // parse string into u128\n let number: u128 = match number_system {\n NumberSystem::Decimal => {\n if numeric_string.is_empty() && !self.no_empty_numeric {\n 1\n } else {\n Self::parse_number(&numeric_string, 10, size)?\n }\n }\n NumberSystem::Octal => {\n let trimmed_string = numeric_string.trim_start_matches('0');\n Self::parse_number(trimmed_string, 8, size)?\n }\n NumberSystem::Hexadecimal => {\n let trimmed_string = numeric_string.trim_start_matches(\"0x\");\n Self::parse_number(trimmed_string, 16, size)?\n }\n };\n\n number\n .checked_mul(factor)\n .ok_or_else(|| ParseSizeError::size_too_big(size))\n }\n```"}], "func_name": "parse", "docstring": "Parse a size string into a number of bytes.\n\nA size string comprises an integer and an optional unit. The unit\nmay be K, M, G, T, P, E, Z, Y, R or Q (powers of 1024), or KB, MB,\netc. (powers of 1000), or b which is 512.\nBinary prefixes can be used, too: KiB=K, MiB=M, and so on.\n\n# Errors\n\nWill return `ParseSizeError` if it's not possible to parse this\nstring into a number, e.g. if the string does not begin with a\nnumeral, or if the unit is not one of the supported units described\nin the preceding section.\n\n# Examples\n\n```rust\nuse uucore::parser::parse_size::Parser;\nlet parser = Parser {\ndefault_unit: Some(\"M\"),\n..Default::default()\n};\nassert_eq!(Ok(123 * 1024 * 1024), parser.parse(\"123M\")); // M is 1024^2\nassert_eq!(Ok(123 * 1024 * 1024), parser.parse(\"123\")); // default unit set to \"M\" on parser instance\nassert_eq!(Ok(9 * 1000), parser.parse(\"9kB\")); // kB is 1000\nassert_eq!(Ok(2 * 1024), parser.parse(\"2K\")); // K is 1024\nassert_eq!(Ok(44251 * 1024), parser.parse(\"0xACDBK\")); // 0xACDB is 44251 in decimal\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/parse_size.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/parse_size.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca7bdbbecad2ca07c8ab367954c39aca95f77996f05606b2f94f1901d7889c6c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_u64\n\nDocumentation:\nSame as `parse()` but tries to return u64\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_u64(&self, size: &str) -> Result {\n self.parse(size).and_then(|num_u128| {\n u64::try_from(num_u128).map_err(|_| ParseSizeError::size_too_big(size))\n })\n }\n```"}], "func_name": "parse_u64", "docstring": "Same as `parse()` but tries to return u64", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/parse_size.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/parse_size.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b51dae9b1d92bf327741e7ad58248ef990f5fd4e1ed0162c8c1c7fcca29ea5c6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_u64_max\n\nDocumentation:\nSame as `parse_u64()`, except returns `u64::MAX` on overflow\nGNU lib/coreutils include similar functionality\nand GNU test suite checks this behavior for some utils (`split` for example)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_u64_max(&self, size: &str) -> Result {\n let result = self.parse_u64(size);\n match result {\n Ok(_) => result,\n Err(error) => {\n if let ParseSizeError::SizeTooBig(_) = error {\n Ok(u64::MAX)\n } else {\n Err(error)\n }\n }\n }\n }\n```"}], "func_name": "parse_u64_max", "docstring": "Same as `parse_u64()`, except returns `u64::MAX` on overflow\nGNU lib/coreutils include similar functionality\nand GNU test suite checks this behavior for some utils (`split` for example)", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/parse_size.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/parse_size.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "245b3872b8a71cc79135743453b3749a33c408be3edc4f84a66c867b30ac5c75"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_u128_max\n\nDocumentation:\nSame as `parse_u64_max()`, except for u128, i.e. returns `u128::MAX` on overflow\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_u128_max(&self, size: &str) -> Result {\n let result = self.parse_u128(size);\n match result {\n Ok(_) => result,\n Err(error) => {\n if let ParseSizeError::SizeTooBig(_) = error {\n Ok(u128::MAX)\n } else {\n Err(error)\n }\n }\n }\n }\n```"}], "func_name": "parse_u128_max", "docstring": "Same as `parse_u64_max()`, except for u128, i.e. returns `u128::MAX` on overflow", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/parse_size.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/parse_size.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f72ab4aad3d31aa3332a4914bb37da726f73da58d077e7bf246066f6ec13429"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_str\n\nDocumentation:\nParse a duration from a string.\n\nThe string may contain only a number, like \"123\" or \"4.5\", or it\nmay contain a number with a unit specifier, like \"123s\" meaning\none hundred twenty three seconds or \"4.5d\" meaning four and a half\ndays. If no unit is specified, the unit is assumed to be seconds.\n\nIf `allow_suffixes` is true, the allowed suffixes are\n\n* \"s\" for seconds,\n* \"m\" for minutes,\n* \"h\" for hours,\n* \"d\" for days.\n\nThis function does not overflow if large values are provided. If\noverflow would have occurred, [`Duration::MAX`] is returned instead.\n\nIf the value is smaller than 1 nanosecond, we return 1 nanosecond.\n\n# Errors\n\nThis function returns an error if the input string is empty, the\ninput is not a valid number, or the unit specifier is invalid or\nunknown.\n\n# Examples\n\n```rust\nuse std::time::Duration;\nuse uucore::parser::parse_time::from_str;\nassert_eq!(from_str(\"123\", true), Ok(Duration::from_secs(123)));\nassert_eq!(from_str(\"123\", false), Ok(Duration::from_secs(123)));\nassert_eq!(from_str(\"2d\", true), Ok(Duration::from_secs(60 * 60 * 24 * 2)));\nassert!(from_str(\"2d\", false).is_err());\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_str(string: &str, allow_suffixes: bool) -> Result {\n // TODO: Switch to Duration::NANOSECOND if that ever becomes stable\n // https://github.com/rust-lang/rust/issues/57391\n const NANOSECOND_DURATION: Duration = Duration::from_nanos(1);\n\n let len = string.len();\n if len == 0 {\n return Err(format!(\"invalid time interval {}\", string.quote()));\n }\n let num = match num_parser::parse(\n string,\n ParseTarget::Duration,\n if allow_suffixes {\n &[('s', 1), ('m', 60), ('h', 60 * 60), ('d', 60 * 60 * 24)]\n } else {\n &[]\n },\n ) {\n Ok(ebd) | Err(ExtendedParserError::Overflow(ebd)) => ebd,\n Err(ExtendedParserError::Underflow(_)) => return Ok(NANOSECOND_DURATION),\n _ => {\n return Err(format!(\"invalid time interval {}\", string.quote()));\n }\n };\n\n // Allow non-negative durations (-0 is fine), and infinity.\n let num = match num {\n ExtendedBigDecimal::BigDecimal(bd) if !bd.is_negative() => bd,\n ExtendedBigDecimal::MinusZero => 0.into(),\n ExtendedBigDecimal::Infinity => return Ok(Duration::MAX),\n _ => return Err(format!(\"invalid time interval {}\", string.quote())),\n };\n\n // Transform to nanoseconds (9 digits after decimal point)\n let (nanos_bi, _) = num.with_scale(9).into_bigint_and_scale();\n\n // If the value is smaller than a nanosecond, just return that.\n if nanos_bi.is_zero() && !num.is_zero() {\n return Ok(NANOSECOND_DURATION);\n }\n\n const NANOS_PER_SEC: u32 = 1_000_000_000;\n let whole_secs: u64 = match (&nanos_bi / NANOS_PER_SEC).try_into() {\n Ok(whole_secs) => whole_secs,\n Err(_) => return Ok(Duration::MAX),\n };\n let nanos: u32 = (&nanos_bi % NANOS_PER_SEC).to_u32().unwrap();\n Ok(Duration::new(whole_secs, nanos))\n}\n```"}], "func_name": "from_str", "docstring": "Parse a duration from a string.\n\nThe string may contain only a number, like \"123\" or \"4.5\", or it\nmay contain a number with a unit specifier, like \"123s\" meaning\none hundred twenty three seconds or \"4.5d\" meaning four and a half\ndays. If no unit is specified, the unit is assumed to be seconds.\n\nIf `allow_suffixes` is true, the allowed suffixes are\n\n* \"s\" for seconds,\n* \"m\" for minutes,\n* \"h\" for hours,\n* \"d\" for days.\n\nThis function does not overflow if large values are provided. If\noverflow would have occurred, [`Duration::MAX`] is returned instead.\n\nIf the value is smaller than 1 nanosecond, we return 1 nanosecond.\n\n# Errors\n\nThis function returns an error if the input string is empty, the\ninput is not a valid number, or the unit specifier is invalid or\nunknown.\n\n# Examples\n\n```rust\nuse std::time::Duration;\nuse uucore::parser::parse_time::from_str;\nassert_eq!(from_str(\"123\", true), Ok(Duration::from_secs(123)));\nassert_eq!(from_str(\"123\", false), Ok(Duration::from_secs(123)));\nassert_eq!(from_str(\"2d\", true), Ok(Duration::from_secs(60 * 60 * 24 * 2)));\nassert!(from_str(\"2d\", false).is_err());\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/parse_time.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/parse_time.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "78f08145ffafb2174cbb1469ca8875b88be0131c43842e20ea9191643fd42d32"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_ambiguous_value_tip\n\nDocumentation:\nAdds a suggestion when error is because of ambiguous values based on the provided possible values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_ambiguous_value_tip(\n possible_values: &[&PossibleValue],\n err: &mut clap::error::Error,\n value: &str,\n) {\n let mut formatted_possible_values = String::new();\n for (i, s) in possible_values.iter().enumerate() {\n formatted_possible_values.push_str(&format!(\"'{}'\", s.get_name()));\n if i < possible_values.len() - 2 {\n formatted_possible_values.push_str(\", \");\n } else if i < possible_values.len() - 1 {\n formatted_possible_values.push_str(\" or \");\n }\n }\n err.insert(\n ContextKind::Suggested,\n ContextValue::StyledStrs(vec![format!(\n \"It looks like '{value}' could match several values. Did you mean {formatted_possible_values}?\"\n )\n .into()]),\n );\n}\n```"}], "func_name": "add_ambiguous_value_tip", "docstring": "Adds a suggestion when error is because of ambiguous values based on the provided possible values.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/features/parser/shortcut_value_parser.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/features/parser/shortcut_value_parser.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2312de231fd39e850a73ff650ae4d6da7c63814d61afc3658feb96d61295de4c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: println_verbatim\n\nDocumentation:\nPrint a path (or `OsStr`-like object) directly to stdout, with a trailing newline,\nwithout losing any information if its encoding is invalid.\n\nThis function is appropriate for commands where printing paths is the point and the\noutput is likely to be captured, like `pwd` and `basename`. For informational output\nuse `Quotable::quote`.\n\nFIXME: Invalid Unicode will produce an error on Windows. That could be fixed by\nusing low-level library calls and bypassing `io::Write`. This is not a big priority\nbecause broken filenames are much rarer on Windows than on Unix.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn println_verbatim>(text: S) -> io::Result<()> {\n let mut stdout = io::stdout().lock();\n stdout.write_all_os(text.as_ref())?;\n stdout.write_all(b\"\\n\")?;\n Ok(())\n}\n```"}], "func_name": "println_verbatim", "docstring": "Print a path (or `OsStr`-like object) directly to stdout, with a trailing newline,\nwithout losing any information if its encoding is invalid.\n\nThis function is appropriate for commands where printing paths is the point and the\noutput is likely to be captured, like `pwd` and `basename`. For informational output\nuse `Quotable::quote`.\n\nFIXME: Invalid Unicode will produce an error on Windows. That could be fixed by\nusing low-level library calls and bypassing `io::Write`. This is not a big priority\nbecause broken filenames are much rarer on Windows than on Unix.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/display.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/display.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e1f20f8eb5a67b3e161f4ec95a18b1ec782e2b9838a1ea6cb7c5ad3910dbbe81"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_all_os\n\nDocumentation:\nWrite the entire OS string into this writer.\n\n# Errors\n\nAn error is returned if the underlying I/O operation fails.\n\nOn Windows, if the OS string is not valid Unicode, an error of kind\n[`io::ErrorKind::InvalidData`] is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_all_os(&mut self, buf: &OsStr) -> io::Result<()> {\n #[cfg(any(unix, target_os = \"wasi\"))]\n {\n self.write_all(buf.as_bytes())\n }\n\n #[cfg(not(any(unix, target_os = \"wasi\")))]\n {\n // It's possible to write a better OsWrite impl for Windows consoles (e.g. Stdout)\n // as those are fundamentally 16-bit. If the OS string is invalid then it can be\n // encoded to 16-bit and written using raw windows_sys calls. But this is quite involved\n // (see `sys/pal/windows/stdio.rs` in the stdlib) and the value-add is small.\n //\n // There's no way to write invalid OS strings to Windows files, as those are 8-bit.\n\n match buf.to_str() {\n Some(text) => self.write_all(text.as_bytes()),\n // We could output replacement characters instead, but the\n // stdlib errors when sending invalid UTF-8 to the console,\n // so let's follow that.\n None => Err(io::Error::new(\n io::ErrorKind::InvalidData,\n \"OS string cannot be converted to bytes\",\n )),\n }\n }\n }\n```"}], "func_name": "write_all_os", "docstring": "Write the entire OS string into this writer.\n\n# Errors\n\nAn error is returned if the underlying I/O operation fails.\n\nOn Windows, if the OS string is not valid Unicode, an error of kind\n[`io::ErrorKind::InvalidData`] is returned.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/display.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/display.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e7faf9c59f5b3b34d2485714308d643cdc3277644f25aea2a99eb833d121930a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_exit_code\n\nDocumentation:\nSet the exit code for the program if `uumain` returns `Ok(())`.\n\nThis function is most useful for non-fatal errors, for example when applying an operation to\nmultiple files:\n```ignore\nuse uucore::error::{UResult, set_exit_code};\n\nfn uumain(args: impl uucore::Args) -> UResult<()> {\n...\nfor file in files {\nlet res = some_operation_that_might_fail(file);\nmatch res {\nOk() => {},\nErr(_) => set_exit_code(1),\n}\n}\nOk(()) // If any of the operations failed, 1 is returned.\n}\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_exit_code(code: i32) {\n EXIT_CODE.store(code, Ordering::SeqCst);\n}\n```"}], "func_name": "set_exit_code", "docstring": "Set the exit code for the program if `uumain` returns `Ok(())`.\n\nThis function is most useful for non-fatal errors, for example when applying an operation to\nmultiple files:\n```ignore\nuse uucore::error::{UResult, set_exit_code};\n\nfn uumain(args: impl uucore::Args) -> UResult<()> {\n...\nfor file in files {\nlet res = some_operation_that_might_fail(file);\nmatch res {\nOk() => {},\nErr(_) => set_exit_code(1),\n}\n}\nOk(()) // If any of the operations failed, 1 is returned.\n}\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/error.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/error.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ce153c680603d271a5cacfd8bca6b38e0826f38bd2ad73e4e512aaeb5536e0a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new `UUsageError` with a given exit code and message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new>(code: i32, message: S) -> Box {\n Box::new(Self {\n code,\n message: message.into(),\n })\n }\n```"}], "func_name": "new", "docstring": "Create a new `UUsageError` with a given exit code and message.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/error.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/error.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25f2ce503c91b0048c6b8214504bf695146e2039dd206cb96c582e276fc12961"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new `UIoError` with a given exit code and message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new>(kind: std::io::ErrorKind, context: S) -> Box {\n Box::new(Self {\n context: Some(context.into()),\n inner: kind.into(),\n })\n }\n```"}], "func_name": "new", "docstring": "Create a new `UIoError` with a given exit code and message.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/error.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/error.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "861847afd9908eac79aef4e805c1e466491571902c7a434f19ae3d77cdefd5aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: strip_errno\n\nDocumentation:\nStrip the trailing \" (os error XX)\" from io error strings.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn strip_errno(err: &std::io::Error) -> String {\n let mut msg = err.to_string();\n if let Some(pos) = msg.find(\" (os error \") {\n msg.truncate(pos);\n }\n msg\n}\n```"}], "func_name": "strip_errno", "docstring": "Strip the trailing \" (os error XX)\" from io error strings.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/error.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/error.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f9e8f7bd5014c454e65d1855be0c27a7c8dcac16cc844b3074c5b384f2535361"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_zero_flag\n\nDocumentation:\nCreate a [`LineEnding`] from a `-z`/`--zero` flag\n\nIf `is_zero_terminated` is true, [`LineEnding::Nul`] is returned,\notherwise [`LineEnding::Newline`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_zero_flag(is_zero_terminated: bool) -> Self {\n if is_zero_terminated {\n Self::Nul\n } else {\n Self::Newline\n }\n }\n```"}], "func_name": "from_zero_flag", "docstring": "Create a [`LineEnding`] from a `-z`/`--zero` flag\n\nIf `is_zero_terminated` is true, [`LineEnding::Nul`] is returned,\notherwise [`LineEnding::Newline`].", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/line_ending.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/line_ending.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a34c197e427a2620a71fe4dc773e535215beef267e53f9203d8af7b3116c9d95"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_message\n\nDocumentation:\nRetrieves a localized message by its identifier.\n\nLooks up a message with the given ID in the current locale bundle and returns\nthe localized text. If the message ID is not found in the current locale,\nit will fall back to English. If the message is not found in English either,\nreturns the message ID itself.\n\n# Arguments\n\n* `id` - The message identifier in the Fluent resources\n\n# Returns\n\nA `String` containing the localized message, or the message ID if not found\n\n# Examples\n\n```\nuse uucore::locale::get_message;\n\n// Get a localized greeting (from .ftl files)\nlet greeting = get_message(\"greeting\");\nprintln!(\"{}\", greeting);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_message(id: &str) -> String {\n get_message_internal(id, None)\n}\n```"}], "func_name": "get_message", "docstring": "Retrieves a localized message by its identifier.\n\nLooks up a message with the given ID in the current locale bundle and returns\nthe localized text. If the message ID is not found in the current locale,\nit will fall back to English. If the message is not found in English either,\nreturns the message ID itself.\n\n# Arguments\n\n* `id` - The message identifier in the Fluent resources\n\n# Returns\n\nA `String` containing the localized message, or the message ID if not found\n\n# Examples\n\n```\nuse uucore::locale::get_message;\n\n// Get a localized greeting (from .ftl files)\nlet greeting = get_message(\"greeting\");\nprintln!(\"{}\", greeting);\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/locale.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/locale.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bd0ba81c0b9b43e25e2acade4b8483d8d5ab101d60afe9a88e349bcb071f0960"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_message_with_args\n\nDocumentation:\nRetrieves a localized message with variable substitution.\n\nLooks up a message with the given ID in the current locale bundle,\nsubstitutes variables from the provided arguments map, and returns the\nlocalized text. If the message ID is not found in the current locale,\nit will fall back to English. If the message is not found in English either,\nreturns the message ID itself.\n\n# Arguments\n\n* `id` - The message identifier in the Fluent resources\n* `ftl_args` - Key-value pairs for variable substitution in the message\n\n# Returns\n\nA `String` containing the localized message with variable substitution, or the message ID if not found\n\n# Examples\n\n```\nuse uucore::locale::get_message_with_args;\nuse std::collections::HashMap;\n\n// For a Fluent message like: \"Hello, { $name }! You have { $count } notifications.\"\nlet mut args = HashMap::new();\nargs.insert(\"name\".to_string(), \"Alice\".to_string());\nargs.insert(\"count\".to_string(), \"3\".to_string());\n\nlet message = get_message_with_args(\"notification\", args);\nprintln!(\"{}\", message);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_message_with_args(id: &str, ftl_args: HashMap) -> String {\n let mut args = FluentArgs::new();\n\n for (key, value) in ftl_args {\n // Try to parse as number first for proper pluralization support\n if let Ok(num_val) = value.parse::() {\n args.set(key, num_val);\n } else if let Ok(float_val) = value.parse::() {\n args.set(key, float_val);\n } else {\n // Keep as string if not a number\n args.set(key, value);\n }\n }\n\n get_message_internal(id, Some(args))\n}\n```"}], "func_name": "get_message_with_args", "docstring": "Retrieves a localized message with variable substitution.\n\nLooks up a message with the given ID in the current locale bundle,\nsubstitutes variables from the provided arguments map, and returns the\nlocalized text. If the message ID is not found in the current locale,\nit will fall back to English. If the message is not found in English either,\nreturns the message ID itself.\n\n# Arguments\n\n* `id` - The message identifier in the Fluent resources\n* `ftl_args` - Key-value pairs for variable substitution in the message\n\n# Returns\n\nA `String` containing the localized message with variable substitution, or the message ID if not found\n\n# Examples\n\n```\nuse uucore::locale::get_message_with_args;\nuse std::collections::HashMap;\n\n// For a Fluent message like: \"Hello, { $name }! You have { $count } notifications.\"\nlet mut args = HashMap::new();\nargs.insert(\"name\".to_string(), \"Alice\".to_string());\nargs.insert(\"count\".to_string(), \"3\".to_string());\n\nlet message = get_message_with_args(\"notification\", args);\nprintln!(\"{}\", message);\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/locale.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/locale.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dc512b9fb6a39a77074d51770110a70d14ede461efc886ab3d44701466c8166d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: setup_localization\n\nDocumentation:\nSets up localization using the system locale with English fallback.\n\nThis function initializes the localization system based on the system's locale\npreferences (via the LANG environment variable) or falls back to English\nif the system locale cannot be determined or the locale file doesn't exist.\nEnglish is always loaded as a fallback.\n\n# Arguments\n\n* `p` - Path to the directory containing localization (.ftl) files\n\n# Returns\n\n* `Ok(())` if initialization succeeds\n* `Err(LocalizationError)` if initialization fails\n\n# Errors\n\nReturns a `LocalizationError` if:\n* The en-US.ftl file cannot be read (English is required)\n* The files contain invalid Fluent syntax\n* The bundle cannot be initialized properly\n\n# Examples\n\n```\nuse uucore::locale::setup_localization;\n\n// Initialize localization using files in the \"locales\" directory\n// Make sure you have at least an \"en-US.ftl\" file in this directory\n// Other locale files like \"fr-FR.ftl\" are optional\nmatch setup_localization(\"./locales\") {\nOk(_) => println!(\"Localization initialized successfully\"),\nErr(e) => eprintln!(\"Failed to initialize localization: {}\", e),\n}\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn setup_localization(p: &str) -> Result<(), LocalizationError> {\n let locale = detect_system_locale().unwrap_or_else(|_| {\n LanguageIdentifier::from_str(DEFAULT_LOCALE).expect(\"Default locale should always be valid\")\n });\n\n let locales_dir = get_locales_dir(p)?;\n init_localization(&locale, &locales_dir)\n}\n```"}], "func_name": "setup_localization", "docstring": "Sets up localization using the system locale with English fallback.\n\nThis function initializes the localization system based on the system's locale\npreferences (via the LANG environment variable) or falls back to English\nif the system locale cannot be determined or the locale file doesn't exist.\nEnglish is always loaded as a fallback.\n\n# Arguments\n\n* `p` - Path to the directory containing localization (.ftl) files\n\n# Returns\n\n* `Ok(())` if initialization succeeds\n* `Err(LocalizationError)` if initialization fails\n\n# Errors\n\nReturns a `LocalizationError` if:\n* The en-US.ftl file cannot be read (English is required)\n* The files contain invalid Fluent syntax\n* The bundle cannot be initialized properly\n\n# Examples\n\n```\nuse uucore::locale::setup_localization;\n\n// Initialize localization using files in the \"locales\" directory\n// Make sure you have at least an \"en-US.ftl\" file in this directory\n// Other locale files like \"fr-FR.ftl\" are optional\nmatch setup_localization(\"./locales\") {\nOk(_) => println!(\"Localization initialized successfully\"),\nErr(e) => eprintln!(\"Failed to initialize localization: {}\", e),\n}\n```", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/locale.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/locale.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad37a3779626d0da94fa96534986254825586cd21cbbd2c18f5e80aed083fbd2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_locales_dir\n\nDocumentation:\nHelper function to get the locales directory based on the build configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_locales_dir(p: &str) -> Result {\n #[cfg(debug_assertions)]\n {\n // During development, use the project's locales directory\n let manifest_dir = env!(\"CARGO_MANIFEST_DIR\");\n // from uucore path, load the locales directory from the program directory\n let dev_path = PathBuf::from(manifest_dir)\n .join(\"../uu\")\n .join(p)\n .join(\"locales\");\n\n if dev_path.exists() {\n return Ok(dev_path);\n }\n\n // Fallback for development if the expected path doesn't exist\n let fallback_dev_path = PathBuf::from(manifest_dir).join(p);\n if fallback_dev_path.exists() {\n return Ok(fallback_dev_path);\n }\n\n Err(LocalizationError::LocalesDirNotFound(format!(\n \"Development locales directory not found at {} or {}\",\n dev_path.display(),\n fallback_dev_path.display()\n )))\n }\n\n #[cfg(not(debug_assertions))]\n {\n use std::env;\n // In release builds, look relative to executable\n let exe_path = env::current_exe().map_err(|e| {\n LocalizationError::PathResolution(format!(\"Failed to get executable path: {}\", e))\n })?;\n\n let exe_dir = exe_path.parent().ok_or_else(|| {\n LocalizationError::PathResolution(\"Failed to get executable directory\".to_string())\n })?;\n\n // Try the coreutils-style path first\n let coreutils_path = exe_dir.join(\"locales\").join(p);\n if coreutils_path.exists() {\n return Ok(coreutils_path);\n }\n\n // Fallback to just the parameter as a relative path\n let fallback_path = exe_dir.join(p);\n if fallback_path.exists() {\n return Ok(fallback_path);\n }\n\n return Err(LocalizationError::LocalesDirNotFound(format!(\n \"Release locales directory not found at {} or {}\",\n coreutils_path.display(),\n fallback_path.display()\n )));\n }\n}\n```"}], "func_name": "get_locales_dir", "docstring": "Helper function to get the locales directory based on the build configuration", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/locale.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/locale.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ccf765368024de8537f27edf27e5fefd17effd19740a490e35234e9e019f6b8d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_wsl_1\n\nDocumentation:\nTest if the program is running under WSL version 1\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_wsl_1() -> bool {\n #[cfg(target_os = \"linux\")]\n {\n if is_wsl_2() {\n return false;\n }\n if let Ok(b) = std::fs::read(\"/proc/sys/kernel/osrelease\") {\n if let Ok(s) = std::str::from_utf8(&b) {\n let a = s.to_ascii_lowercase();\n return a.contains(\"microsoft\") || a.contains(\"wsl\");\n }\n }\n }\n false\n}\n```"}], "func_name": "is_wsl_1", "docstring": "Test if the program is running under WSL version 1", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/os.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/os.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "10f716e8b16faba70372e3384f220e71ccefa4ae90ae1060320682901fbe195e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_wsl_2\n\nDocumentation:\nTest if the program is running under WSL version 2\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_wsl_2() -> bool {\n #[cfg(target_os = \"linux\")]\n {\n if let Ok(b) = std::fs::read(\"/proc/sys/kernel/osrelease\") {\n if let Ok(s) = std::str::from_utf8(&b) {\n let a = s.to_ascii_lowercase();\n return a.contains(\"wsl2\");\n }\n }\n }\n false\n}\n```"}], "func_name": "is_wsl_2", "docstring": "Test if the program is running under WSL version 2", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/os.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/os.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5328924e97aef9a69605825bbc753038a7ddeca5e08809f0c3738cc7cbb7ab63"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_broken_pipe\n\nDocumentation:\nDecide whether a panic was caused by a broken pipe (SIGPIPE) error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_broken_pipe(info: &PanicHookInfo) -> bool {\n if let Some(res) = info.payload().downcast_ref::() {\n if res.contains(\"BrokenPipe\") || res.contains(\"Broken pipe\") {\n return true;\n }\n }\n false\n}\n```"}], "func_name": "is_broken_pipe", "docstring": "Decide whether a panic was caused by a broken pipe (SIGPIPE) error.", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/panic.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/panic.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18d8c7c9118270ab63ebbdd32039f475f8a7a7833d8c5c1af8dd73a224b7eb14"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mute_sigpipe_panic\n\nDocumentation:\nTerminate without error on panics that occur due to broken pipe errors.\n\nFor background discussions on `SIGPIPE` handling, see\n\n* ``\n* ``\n* ``\n* ``\n* ``\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn mute_sigpipe_panic() {\n let hook = panic::take_hook();\n panic::set_hook(Box::new(move |info| {\n if !is_broken_pipe(info) {\n hook(info);\n }\n }));\n}\n```"}], "func_name": "mute_sigpipe_panic", "docstring": "Terminate without error on panics that occur due to broken pipe errors.\n\nFor background discussions on `SIGPIPE` handling, see\n\n* ``\n* ``\n* ``\n* ``\n* ``", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/panic.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/panic.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b2210f89a0cd4de45ebfd26b6da6634de88613f6af03b81df827092b0cf8c26"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: posix_version\n\nDocumentation:\nReturns the value of the `_POSIX2_VERSION` environment variable if it is defined\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn posix_version() -> Option {\n env::var(\"_POSIX2_VERSION\")\n .ok()\n .and_then(|v| v.parse::().ok())\n}\n```"}], "func_name": "posix_version", "docstring": "Returns the value of the `_POSIX2_VERSION` environment variable if it is defined", "repo": "uutils/coreutils", "path": "src/uucore/src/lib/mods/posix.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore/src/lib/mods/posix.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94c803722c5591888d2c84f2d0ca9f9ff29953f1e6892685909e73b11033e863"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: render_markdown\n\nDocumentation:\nRender markdown into a format that's easier to read in the terminal.\n\nFor now, all this function does is remove backticks.\nSome ideas for future improvement:\n- Render headings as bold\n- Convert triple backticks to indented\n- Printing tables in a nice format\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn render_markdown(s: &str) -> String {\n s.replace('`', \"\")\n}\n```"}], "func_name": "render_markdown", "docstring": "Render markdown into a format that's easier to read in the terminal.\n\nFor now, all this function does is remove backticks.\nSome ideas for future improvement:\n- Render headings as bold\n- Convert triple backticks to indented\n- Printing tables in a nice format", "repo": "uutils/coreutils", "path": "src/uucore_procs/src/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore_procs/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b4b2558fe1a3f935a5eb72cb93c100cf50552e4a025f897f71a4e43965b3a2a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_argument\n\nDocumentation:\nGet an argument from the input vector of `TokenTree`.\n\nAsserts that the argument is a string literal and returns the string value,\notherwise it panics with an error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_argument(input: &[TokenTree], index: usize, name: &str) -> String {\n // Multiply by two to ignore the `','` in between the arguments\n let string = match &input.get(index * 2) {\n Some(TokenTree::Literal(lit)) => lit.to_string(),\n Some(_) => panic!(\"Argument {index} should be a string literal.\"),\n None => panic!(\"Missing argument at index {index} for {name}\"),\n };\n\n string\n .parse::()\n .unwrap()\n .strip_prefix('\"')\n .unwrap()\n .strip_suffix('\"')\n .unwrap()\n .to_string()\n}\n```"}], "func_name": "get_argument", "docstring": "Get an argument from the input vector of `TokenTree`.\n\nAsserts that the argument is a string literal and returns the string value,\notherwise it panics with an error.", "repo": "uutils/coreutils", "path": "src/uucore_procs/src/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uucore_procs/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "afae9d45fda8cde379d5842d2c108ec14538c5c94da78e05346a80f7cf1fbf03"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_about\n\nDocumentation:\nParses the text between the first markdown code block and the next header, if any,\ninto an about string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_about(content: &str) -> String {\n content\n .lines()\n .skip_while(|l| !l.starts_with(MARKDOWN_CODE_FENCES))\n .skip(1)\n .skip_while(|l| !l.starts_with(MARKDOWN_CODE_FENCES))\n .skip(1)\n .take_while(|l| !l.starts_with('#'))\n .collect::>()\n .join(\"\\n\")\n .trim()\n .to_string()\n}\n```"}], "func_name": "parse_about", "docstring": "Parses the text between the first markdown code block and the next header, if any,\ninto an about string.", "repo": "uutils/coreutils", "path": "src/uuhelp_parser/src/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uuhelp_parser/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7a11a69b4206b6b9a3910968469ee3d008ce0dc5a02a10fed70495c2196a9248"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_usage\n\nDocumentation:\nParses the first markdown code block into a usage string\n\nThe code fences are removed and the name of the util is replaced\nwith `{}` so that it can be replaced with the appropriate name\nat runtime.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_usage(content: &str) -> String {\n content\n .lines()\n .skip_while(|l| !l.starts_with(MARKDOWN_CODE_FENCES))\n .skip(1)\n .take_while(|l| !l.starts_with(MARKDOWN_CODE_FENCES))\n .map(|l| {\n // Replace the util name (assumed to be the first word) with \"{}\"\n // to be replaced with the runtime value later.\n if let Some((_util, args)) = l.split_once(' ') {\n format!(\"{{}} {args}\\n\")\n } else {\n \"{}\\n\".to_string()\n }\n })\n .collect::()\n .trim()\n .to_string()\n}\n```"}], "func_name": "parse_usage", "docstring": "Parses the first markdown code block into a usage string\n\nThe code fences are removed and the name of the util is replaced\nwith `{}` so that it can be replaced with the appropriate name\nat runtime.", "repo": "uutils/coreutils", "path": "src/uuhelp_parser/src/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uuhelp_parser/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3c5b42b7dfea4c562a657bc9cd49c50914f383e7352f556943abb84615515d54"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_section\n\nDocumentation:\nGet a single section from content\n\nThe section must be a second level section (i.e. start with `##`).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_section(section: &str, content: &str) -> Option {\n fn is_section_header(line: &str, section: &str) -> bool {\n line.strip_prefix(\"##\")\n .is_some_and(|l| l.trim().to_lowercase() == section)\n }\n\n let section = §ion.to_lowercase();\n\n // We cannot distinguish between an empty or non-existing section below,\n // so we do a quick test to check whether the section exists\n if content.lines().all(|l| !is_section_header(l, section)) {\n return None;\n }\n\n // Prefix includes space to allow processing of section with level 3-6 headers\n let section_header_prefix = \"## \";\n\n Some(\n content\n .lines()\n .skip_while(|&l| !is_section_header(l, section))\n .skip(1)\n .take_while(|l| !l.starts_with(section_header_prefix))\n .collect::>()\n .join(\"\\n\")\n .trim()\n .to_string(),\n )\n}\n```"}], "func_name": "parse_section", "docstring": "Get a single section from content\n\nThe section must be a second level section (i.e. start with `##`).", "repo": "uutils/coreutils", "path": "src/uuhelp_parser/src/lib.rs", "url": "https://github.com/uutils/coreutils/blob/master/src/uuhelp_parser/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "041d827b0bb57cba43fb8024e17a7f6306b8d270d5969abbc45168316c534a89"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_scene\n\nDocumentation:\nMake a simple scene with foo and bar empty files\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn make_scene() -> TestScenario {\n let scene = TestScenario::new(util_name!());\n let at = &scene.fixtures;\n\n at.touch(\"foo\");\n at.touch(\"bar\");\n\n scene\n }\n```"}], "func_name": "make_scene", "docstring": "Make a simple scene with foo and bar empty files", "repo": "uutils/coreutils", "path": "tests/by-util/test_cksum.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/by-util/test_cksum.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4dba9d9df0eda7fd549bc9f8f030f0427546d7e81d5fd87dd341d6ff2fd92cc9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate\n\nDocumentation:\nReturns a string of numbers with the given range, each on a new line.\nThe upper bound is not included.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate(from: u32, to: u32) -> String {\n (from..to).fold(String::new(), |acc, v| format!(\"{acc}{v}\\n\"))\n}\n```"}], "func_name": "generate", "docstring": "Returns a string of numbers with the given range, each on a new line.\nThe upper bound is not included.", "repo": "uutils/coreutils", "path": "tests/by-util/test_csplit.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/by-util/test_csplit.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b76fe44dff9a4d52960ffcf469b1fbf0d2d3bbf1076c4ce5b8dfa491bbc42b63"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: test_date_set_valid_2\n\nDocumentation:\nTODO: expected to fail currently; change to `succeeds()` when required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn test_date_set_valid_2() {\n if geteuid() == 0 {\n let result = new_ucmd!()\n .arg(\"--set\")\n .arg(\"Sat 20 Mar 2021 14:53:01 AWST\") // spell-checker:disable-line\n .fails();\n result.no_stdout();\n assert!(result.stderr_str().starts_with(\"date: invalid date \"));\n }\n}\n```"}], "func_name": "test_date_set_valid_2", "docstring": "TODO: expected to fail currently; change to `succeeds()` when required.", "repo": "uutils/coreutils", "path": "tests/by-util/test_date.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/by-util/test_date.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a0dd05c1a29aab4fdec2ef0c95e3e186bddbc153797e85ba847e5ba9b0bdf65"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: matches_template\n\nDocumentation:\nDecide whether a string matches a given template.\n\nIn the template, the character `'X'` is treated as a wildcard,\nthat is, it matches anything. All other characters in `template`\nand `s` must match exactly.\n\n# Examples\n\n```rust,ignore\n# These all match.\nassert!(matches_template(\"abc\", \"abc\"));\nassert!(matches_template(\"aXc\", \"abc\"));\nassert!(matches_template(\"XXX\", \"abc\"));\n\n# None of these match\nassert!(matches_template(\"abc\", \"abcd\"));\nassert!(matches_template(\"abc\", \"ab\"));\nassert!(matches_template(\"aXc\", \"abd\"));\nassert!(matches_template(\"XXX\", \"abcd\"));\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn matches_template(template: &str, s: &str) -> bool {\n if template.len() != s.len() {\n return false;\n }\n for (a, b) in template.chars().zip(s.chars()) {\n if !(a == 'X' || a == b) {\n return false;\n }\n }\n true\n}\n```"}], "func_name": "matches_template", "docstring": "Decide whether a string matches a given template.\n\nIn the template, the character `'X'` is treated as a wildcard,\nthat is, it matches anything. All other characters in `template`\nand `s` must match exactly.\n\n# Examples\n\n```rust,ignore\n# These all match.\nassert!(matches_template(\"abc\", \"abc\"));\nassert!(matches_template(\"aXc\", \"abc\"));\nassert!(matches_template(\"XXX\", \"abc\"));\n\n# None of these match\nassert!(matches_template(\"abc\", \"abcd\"));\nassert!(matches_template(\"abc\", \"ab\"));\nassert!(matches_template(\"aXc\", \"abd\"));\nassert!(matches_template(\"XXX\", \"abcd\"));\n```", "repo": "uutils/coreutils", "path": "tests/by-util/test_mktemp.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/by-util/test_mktemp.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ada1d1cdd0576daa13cc837bd001c6a42bff629719370d98673ac1276725e377"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: collect\n\nDocumentation:\nGet all files in `self.directory` that match `self.regex`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn collect(&self) -> Vec {\n read_dir(Path::new(&self.directory.subdir))\n .unwrap()\n .filter_map(|entry| {\n let path = entry.unwrap().path();\n let name = self\n .directory\n .minus_as_string(path.as_path().to_str().unwrap_or(\"\"));\n if self.regex.is_match(&name) {\n Some(name)\n } else {\n None\n }\n })\n .collect()\n }\n```"}], "func_name": "collect", "docstring": "Get all files in `self.directory` that match `self.regex`", "repo": "uutils/coreutils", "path": "tests/by-util/test_split.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/by-util/test_split.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0c5bc77e16b347e8b07b93ec57b88267a0c35285f66d067a6907b1d6967c516"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: collate\n\nDocumentation:\nAccumulate bytes of all files in `self.collect()`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn collate(&self) -> Vec {\n let mut files = self.collect();\n files.sort();\n let mut data: Vec = vec![];\n for name in &files {\n data.extend(self.directory.read_bytes(name));\n }\n data\n }\n```"}], "func_name": "collate", "docstring": "Accumulate bytes of all files in `self.collect()`", "repo": "uutils/coreutils", "path": "tests/by-util/test_split.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/by-util/test_split.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e6ce7f974d9e46bbcf6108ac4465fd80a4faaef07e5774d3902aba2a7dda24c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\n`create()` file handle located at `at` / `name`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(at: &AtPath, name: &str) -> Self {\n Self {\n inner: File::create(at.plus(name)).unwrap(),\n }\n }\n```"}], "func_name": "new", "docstring": "`create()` file handle located at `at` / `name`", "repo": "uutils/coreutils", "path": "tests/by-util/test_split.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/by-util/test_split.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a044bbc0639e279f202bbbe160697fa1c0f07b4e69f985378cecc78e79dba6d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_lines\n\nDocumentation:\nAdd n lines each of size `RandomFile::LINESIZE`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_lines(&mut self, lines: usize) {\n self.add_lines_with_line_size(lines, Self::LINESIZE);\n }\n```"}], "func_name": "add_lines", "docstring": "Add n lines each of size `RandomFile::LINESIZE`", "repo": "uutils/coreutils", "path": "tests/by-util/test_split.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/by-util/test_split.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ed9ba960b4eb9f5d0febf2be5a5ed073613b18b8d33b31e35ff91246f5cbbad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_lines_with_line_size\n\nDocumentation:\nAdd n lines each of the given size.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_lines_with_line_size(&mut self, lines: usize, line_size: usize) {\n let mut n = lines;\n while n > 0 {\n writeln!(self.inner, \"{}\", random_chars(line_size)).unwrap();\n n -= 1;\n }\n }\n```"}], "func_name": "add_lines_with_line_size", "docstring": "Add n lines each of the given size.", "repo": "uutils/coreutils", "path": "tests/by-util/test_split.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/by-util/test_split.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9621b935c3438a3d0e859d9ae24a21131baf6b04f68be2fe814a9599fcb41e14"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRun `yes`, capture some of the output, then check exit status.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn run(args: &[impl AsRef], expected: &[u8]) {\n let result = new_ucmd!().args(args).run_stdout_starts_with(expected);\n check_termination(result.exit_status());\n}\n```"}], "func_name": "run", "docstring": "Run `yes`, capture some of the output, then check exit status.", "repo": "uutils/coreutils", "path": "tests/by-util/test_yes.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/by-util/test_yes.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d2c16e9a456193d51dc7bae639924849df72abc1e1fa7a937652d127fe993329"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: random\n\nDocumentation:\nGenerate a random byte from [`Self::CHARSET`] and return it as `u8`.\n\n# Arguments\n\n* `rng`: A [`rand::Rng`]\n\nreturns: u8\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn random(rng: &mut R) -> u8\n where\n R: Rng + ?Sized,\n {\n let idx = rng.random_range(0..Self::CHARSET.len());\n Self::CHARSET[idx]\n }\n```"}], "func_name": "random", "docstring": "Generate a random byte from [`Self::CHARSET`] and return it as `u8`.\n\n# Arguments\n\n* `rng`: A [`rand::Rng`]\n\nreturns: u8", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/random.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/random.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "49c4ef91b1bda76a28adb686725c82882f243354153c810052afb643a32cc9ac"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate\n\nDocumentation:\nGenerate a random string from the given [`Distribution`] with the given `length` in bytes.\n\n# Arguments\n\n* `dist`: A u8 [`Distribution`]\n* `length`: the length of the resulting string in bytes\n\nreturns: String\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate(dist: D, length: usize) -> String\n where\n D: Distribution,\n {\n rng()\n .sample_iter(dist)\n .take(length)\n .map(|b| b as char)\n .collect()\n }\n```"}], "func_name": "generate", "docstring": "Generate a random string from the given [`Distribution`] with the given `length` in bytes.\n\n# Arguments\n\n* `dist`: A u8 [`Distribution`]\n* `length`: the length of the resulting string in bytes\n\nreturns: String", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/random.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/random.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "908be2640b728d9afc0e0d3132896d70bd5e4a02c89051bc15b5919498f7cf4c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_tests_binary\n\nDocumentation:\nThis function needs the env variable UUTESTS_BINARY_PATH\nwhich will very probably be env!(\"`CARGO_BIN_EXE_`\")\nbecause here, we are in a crate but we need the name of the final binary\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_tests_binary() -> &'static str {\n TESTS_BINARY_PATH.get_or_init(|| {\n if let Ok(path) = env::var(\"UUTESTS_BINARY_PATH\") {\n return PathBuf::from(path);\n }\n panic!(\"Could not determine coreutils binary path. Please set UUTESTS_BINARY_PATH environment variable\");\n })\n .to_str()\n .unwrap()\n}\n```"}], "func_name": "get_tests_binary", "docstring": "This function needs the env variable UUTESTS_BINARY_PATH\nwhich will very probably be env!(\"`CARGO_BIN_EXE_`\")\nbecause here, we are in a crate but we need the name of the final binary", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82d640b8b26b46f448f8309eb01ed50215f660366d7d98ef12e37b39a6d6f0f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_ci\n\nDocumentation:\nTest if the program is running under CI\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_ci() -> bool {\n std::env::var(\"CI\").is_ok_and(|s| s.eq_ignore_ascii_case(\"true\"))\n}\n```"}], "func_name": "is_ci", "docstring": "Test if the program is running under CI", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6b7d1caf5e7e91743396697bd72e64dea51b405c18fc7df3346efd381999f12e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_scenario_fixture\n\nDocumentation:\nRead a test scenario fixture, returning its bytes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_scenario_fixture>(tmpd: Option<&Rc>, file_rel_path: S) -> Vec {\n let tmpdir_path = tmpd.as_ref().unwrap().as_ref().path();\n AtPath::new(tmpdir_path).read_bytes(file_rel_path.as_ref().to_str().unwrap())\n}\n```"}], "func_name": "read_scenario_fixture", "docstring": "Read a test scenario fixture, returning its bytes", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d3d47ecd7c15bfbcb30d4a867f0bfca8ea8720534c781fa2655bac64319d908"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stdout_apply\n\nDocumentation:\nApply a function to `stdout` as bytes and return a new [`CmdResult`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stdout_apply<'a, F, R>(&'a self, function: F) -> Self\n where\n F: Fn(&'a [u8]) -> R,\n R: Into>,\n {\n Self::new(\n self.bin_path.clone(),\n self.util_name.clone(),\n self.tmpd.clone(),\n self.exit_status,\n function(&self.stdout),\n self.stderr.as_slice(),\n )\n }\n```"}], "func_name": "stdout_apply", "docstring": "Apply a function to `stdout` as bytes and return a new [`CmdResult`]", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "892552784828e61d28341e75a0fc64d554ed2b5e8c01d89d73989a0399ffa1e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stdout_str_apply\n\nDocumentation:\nApply a function to `stdout` as `&str` and return a new [`CmdResult`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stdout_str_apply<'a, F, R>(&'a self, function: F) -> Self\n where\n F: Fn(&'a str) -> R,\n R: Into>,\n {\n Self::new(\n self.bin_path.clone(),\n self.util_name.clone(),\n self.tmpd.clone(),\n self.exit_status,\n function(self.stdout_str()),\n self.stderr.as_slice(),\n )\n }\n```"}], "func_name": "stdout_str_apply", "docstring": "Apply a function to `stdout` as `&str` and return a new [`CmdResult`]", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d4320de35dec6874dc70bcd2317688b7bbd0ac50b43aeb4513bde2cc4d3974cd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stderr_apply\n\nDocumentation:\nApply a function to `stderr` as bytes and return a new [`CmdResult`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stderr_apply<'a, F, R>(&'a self, function: F) -> Self\n where\n F: Fn(&'a [u8]) -> R,\n R: Into>,\n {\n Self::new(\n self.bin_path.clone(),\n self.util_name.clone(),\n self.tmpd.clone(),\n self.exit_status,\n self.stdout.as_slice(),\n function(&self.stderr),\n )\n }\n```"}], "func_name": "stderr_apply", "docstring": "Apply a function to `stderr` as bytes and return a new [`CmdResult`]", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a57f180b5698d2b7a7c14ee8b7fcd0c6b32d3139c382a10166ab95b8ccf2e8c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stderr_str_apply\n\nDocumentation:\nApply a function to `stderr` as `&str` and return a new [`CmdResult`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stderr_str_apply<'a, F, R>(&'a self, function: F) -> Self\n where\n F: Fn(&'a str) -> R,\n R: Into>,\n {\n Self::new(\n self.bin_path.clone(),\n self.util_name.clone(),\n self.tmpd.clone(),\n self.exit_status,\n self.stdout.as_slice(),\n function(self.stderr_str()),\n )\n }\n```"}], "func_name": "stderr_str_apply", "docstring": "Apply a function to `stderr` as `&str` and return a new [`CmdResult`]", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8d9bdf0e662aee2e130d149147822410dce3940132ba18df23ecb9f6d5a3338c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exit_status\n\nDocumentation:\nReturn the exit status of the child process.\n\n# Panics\n\nIf the child process is still running or hasn't been started.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exit_status(&self) -> ExitStatus {\n self.try_exit_status()\n .expect(\"Program must be run first or has not finished, yet\")\n }\n```"}], "func_name": "exit_status", "docstring": "Return the exit status of the child process.\n\n# Panics\n\nIf the child process is still running or hasn't been started.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa47b6d640a06d778ad2bea250a0c22889c080b1e1f1ed22a39779f5cf53e450"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tmpd\n\nDocumentation:\nReturns the program's `TempDir`\nPanics if not present\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn tmpd(&self) -> Rc {\n match &self.tmpd {\n Some(ptr) => ptr.clone(),\n None => panic!(\"Command not associated with a TempDir\"),\n }\n }\n```"}], "func_name": "tmpd", "docstring": "Returns the program's `TempDir`\nPanics if not present", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8eb67629bb0c844bd0afd84400c04ce45b4e8bcd69f3125bd9a1ef775f1993d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: symlink_exists\n\nDocumentation:\nDecide whether the named symbolic link exists in the test directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn symlink_exists(&self, path: &str) -> bool {\n match fs::symlink_metadata(self.plus(path)) {\n Ok(m) => m.file_type().is_symlink(),\n Err(_) => false,\n }\n }\n```"}], "func_name": "symlink_exists", "docstring": "Decide whether the named symbolic link exists in the test directory.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a636282386d86b0c6be8fa4774fb68c6f7913ab8ec4156f0e52991f00cb8669"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cmd\n\nDocumentation:\nReturns builder for invoking any system command. Paths given are treated\nrelative to the environment's unique temporary test directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn cmd>(&self, bin_path: S) -> UCommand {\n let mut command = UCommand::new();\n command.bin_path(bin_path);\n command.temp_dir(self.tmpd.clone());\n command\n }\n```"}], "func_name": "cmd", "docstring": "Returns builder for invoking any system command. Paths given are treated\nrelative to the environment's unique temporary test directory.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "02d9653c828df6546d8b6b044f9605758c9e3dbae35609403a90dc487b43719c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cmd_shell\n\nDocumentation:\nReturns builder for invoking a command in shell (e.g. sh -c 'cmd').\nPaths given are treated relative to the environment's unique temporary\ntest directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn cmd_shell>(&self, cmd: S) -> UCommand {\n let mut command = UCommand::new();\n // Intentionally leave bin_path unset.\n command.arg(cmd);\n command.temp_dir(self.tmpd.clone());\n command\n }\n```"}], "func_name": "cmd_shell", "docstring": "Returns builder for invoking a command in shell (e.g. sh -c 'cmd').\nPaths given are treated relative to the environment's unique temporary\ntest directory.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c090e0b5033640dcea84b540ee01d76deba23303ba8f129912c0695498318cd6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ccmd\n\nDocumentation:\nReturns builder for invoking any uutils command. Paths given are treated\nrelative to the environment's unique temporary test directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ccmd>(&self, util_name: S) -> UCommand {\n UCommand::with_util(util_name, self.tmpd.clone())\n }\n```"}], "func_name": "ccmd", "docstring": "Returns builder for invoking any uutils command. Paths given are treated\nrelative to the environment's unique temporary test directory.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e0e6ffe051bd84683ad819504bcb8717a9ccaea132f5b49e001e967849c8cf82"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: umount_temp_fs\n\nDocumentation:\nUnmounts the temporary filesystem if it is currently mounted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn umount_temp_fs(&mut self) {\n if let Some(mount_point) = self.tmp_fs_mountpoint.as_ref() {\n self.cmd(\"umount\").arg(mount_point).succeeds();\n self.tmp_fs_mountpoint = None;\n }\n }\n```"}], "func_name": "umount_temp_fs", "docstring": "Unmounts the temporary filesystem if it is currently mounted.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80f40f36777eb9204eb69bd208944482a424047a6df610d31bd350b97e2dc16f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_util\n\nDocumentation:\nCreate a [`UCommand`] for a specific uutils utility.\n\nSets the temporary directory to `tmpd` and the execution binary to the path where\n`coreutils` is found.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_util(util_name: T, tmpd: Rc) -> Self\n where\n T: AsRef,\n {\n let mut ucmd = Self::new();\n ucmd.util_name = Some(util_name.as_ref().into());\n ucmd.bin_path(&*get_tests_binary!()).temp_dir(tmpd);\n ucmd\n }\n```"}], "func_name": "with_util", "docstring": "Create a [`UCommand`] for a specific uutils utility.\n\nSets the temporary directory to `tmpd` and the execution binary to the path where\n`coreutils` is found.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6cff20380d55dfaa63b67903848f7b2613a8533587460ad994bd1671fd5fa390"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_test_scenario\n\nDocumentation:\nCreate a [`UCommand`] from a [`TestScenario`].\n\nThe temporary directory and uutils utility are inherited from the [`TestScenario`] and the\nexecution binary is set to `coreutils`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_test_scenario(scene: &TestScenario) -> Self {\n Self::with_util(&scene.util_name, scene.tmpd.clone())\n }\n```"}], "func_name": "from_test_scenario", "docstring": "Create a [`UCommand`] from a [`TestScenario`].\n\nThe temporary directory and uutils utility are inherited from the [`TestScenario`] and the\nexecution binary is set to `coreutils`.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea2f249c810378fc019f0f31e52b2e7bb795d80a083af89b5429e422972d2700"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bin_path\n\nDocumentation:\nSet the execution binary.\n\nMake sure the binary found at this path is executable. It's safest to provide the\ncanonicalized path instead of just the name of the executable, since path resolution is not\nguaranteed to work on all platforms.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn bin_path(&mut self, bin_path: T) -> &mut Self\n where\n T: Into,\n {\n self.bin_path = Some(bin_path.into());\n self\n }\n```"}], "func_name": "bin_path", "docstring": "Set the execution binary.\n\nMake sure the binary found at this path is executable. It's safest to provide the\ncanonicalized path instead of just the name of the executable, since path resolution is not\nguaranteed to work on all platforms.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "db12bef06ff10cc49085c32b05c1c9521e7720f59c9d5b5777779dbbf1a92dc5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: temp_dir\n\nDocumentation:\nSet the temporary directory.\n\nPer default an individual temporary directory is created for every [`UCommand`]. If not\nspecified otherwise with [`UCommand::current_dir`] the working directory is set to this\ntemporary directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn temp_dir(&mut self, temp_dir: Rc) -> &mut Self {\n self.tmpd = Some(temp_dir);\n self\n }\n```"}], "func_name": "temp_dir", "docstring": "Set the temporary directory.\n\nPer default an individual temporary directory is created for every [`UCommand`]. If not\nspecified otherwise with [`UCommand::current_dir`] the working directory is set to this\ntemporary directory.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4bc93c082403b0e7660b0741ce80886c6f6e7f31dfd80c6403627127394c525c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: current_dir\n\nDocumentation:\nSet the working directory for this [`UCommand`]\n\nPer default the working directory is set to the [`UCommand`] temporary directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn current_dir(&mut self, current_dir: T) -> &mut Self\n where\n T: Into,\n {\n self.current_dir = Some(current_dir.into());\n self\n }\n```"}], "func_name": "current_dir", "docstring": "Set the working directory for this [`UCommand`]\n\nPer default the working directory is set to the [`UCommand`] temporary directory.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a67ff2cd7e48a00340fdd8ab7ae6fd248252b3d966774ed9dc43a8eb0383200"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: arg\n\nDocumentation:\nAdd a parameter to the invocation. Path arguments are treated relative\nto the test environment directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn arg>(&mut self, arg: S) -> &mut Self {\n self.args.push_back(arg.as_ref().into());\n self\n }\n```"}], "func_name": "arg", "docstring": "Add a parameter to the invocation. Path arguments are treated relative\nto the test environment directory.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "426f1724206d6566daf6dbc7dc4f6c7bd5118b9618117225761dec8b79de6a35"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: args\n\nDocumentation:\nAdd multiple parameters to the invocation. Path arguments are treated relative\nto the test environment directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn args>(&mut self, args: &[S]) -> &mut Self {\n self.args.extend(args.iter().map(|s| s.as_ref().into()));\n self\n }\n```"}], "func_name": "args", "docstring": "Add multiple parameters to the invocation. Path arguments are treated relative\nto the test environment directory.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "74cbf1fd7c4be9af5847c4b6745abf28f5e6c0d8009c343da2a788fabafc102c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pipe_in\n\nDocumentation:\nprovides standard input to feed in to the command when spawned\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pipe_in>>(&mut self, input: T) -> &mut Self {\n assert!(\n self.bytes_into_stdin.is_none(),\n \"{MULTIPLE_STDIN_MEANINGLESS}\",\n );\n self.set_stdin(Stdio::piped());\n self.bytes_into_stdin = Some(input.into());\n self\n }\n```"}], "func_name": "pipe_in", "docstring": "provides standard input to feed in to the command when spawned", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25f866015c3dea4b39e6a9b465c9bf664fd29b98045b2d1f3304fb79b24c17f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pipe_in_fixture\n\nDocumentation:\nlike `pipe_in()`, but uses the contents of the file at the provided relative path as the piped in data\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pipe_in_fixture>(&mut self, file_rel_path: S) -> &mut Self {\n let contents = read_scenario_fixture(self.tmpd.as_ref(), file_rel_path);\n self.pipe_in(contents)\n }\n```"}], "func_name": "pipe_in_fixture", "docstring": "like `pipe_in()`, but uses the contents of the file at the provided relative path as the piped in data", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d814bc583a47e7529dd81b2af99a837ac2c15f07f54786826b7ab4b689c636cd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ignore_stdin_write_error\n\nDocumentation:\nIgnores error caused by feeding stdin to the command.\nThis is typically useful to test non-standard workflows\nlike feeding something to a command that does not read it\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ignore_stdin_write_error(&mut self) -> &mut Self {\n self.ignore_stdin_write_error = true;\n self\n }\n```"}], "func_name": "ignore_stdin_write_error", "docstring": "Ignores error caused by feeding stdin to the command.\nThis is typically useful to test non-standard workflows\nlike feeding something to a command that does not read it", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "761428827a04a403160ace827435d5b8917ca4e520a06d7ad9083984bd8091d8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: umask\n\nDocumentation:\nThe umask is a value that restricts the permissions of newly created files and directories.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn umask(&mut self, umask: mode_t) -> &mut Self {\n self.umask = Some(umask);\n self\n }\n```"}], "func_name": "umask", "docstring": "The umask is a value that restricts the permissions of newly created files and directories.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5dfe1ee498b553e26de255d6baecd0bf20781b4dc59b5bdec2239c88ae3650b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_no_wait\n\nDocumentation:\nSpawns the command, feeds the stdin if any, and returns the\nchild process immediately.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn run_no_wait(&mut self) -> UChild {\n assert!(!self.has_run, \"{ALREADY_RUN}\");\n self.has_run = true;\n\n let (mut command, captured_stdout, captured_stderr, stdin_pty) = self.build();\n log_info(\"run\", self.to_string());\n let child = command.spawn().unwrap();\n\n let mut child = UChild::from(self, child, captured_stdout, captured_stderr, stdin_pty);\n\n if let Some(input) = self.bytes_into_stdin.take() {\n child.pipe_in(input);\n }\n\n child\n }\n```"}], "func_name": "run_no_wait", "docstring": "Spawns the command, feeds the stdin if any, and returns the\nchild process immediately.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "10af473598a1c6370207bd6d2881225aeb748b4df54cefaf587c7553045a8885"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: output_bytes\n\nDocumentation:\nReturn the captured output as bytes.\n\nSubsequent calls to any of the other output methods will operate on the subsequent output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn output_bytes(&mut self) -> Vec {\n let mut buffer = Vec::::new();\n self.current_file.read_to_end(&mut buffer).unwrap();\n buffer\n }\n```"}], "func_name": "output_bytes", "docstring": "Return the captured output as bytes.\n\nSubsequent calls to any of the other output methods will operate on the subsequent output.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "95774071e15fbbe3e49ca2b0fa13d1249b709748825f6df169ae75999f5c2376"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: output_all_bytes\n\nDocumentation:\nReturn all captured output, so far.\n\nSubsequent calls to any of the other output methods will operate on the subsequent output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn output_all_bytes(&mut self) -> Vec {\n let mut buffer = Vec::::new();\n let mut file = self.output.reopen().unwrap();\n\n file.read_to_end(&mut buffer).unwrap();\n self.current_file = file;\n\n buffer\n }\n```"}], "func_name": "output_all_bytes", "docstring": "Return all captured output, so far.\n\nSubsequent calls to any of the other output methods will operate on the subsequent output.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "762119c74cebf59dc652b99510b9363ac0de59b10160bb249ee8b3e2dd0f2398"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: output_exact_bytes\n\nDocumentation:\nReturn the exact amount of bytes.\n\nSubsequent calls to any of the other output methods will operate on the subsequent output.\n\n# Important\n\nThis method blocks indefinitely if the amount of bytes given by `size` cannot be read\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn output_exact_bytes(&mut self, size: usize) -> Vec {\n let mut buffer = vec![0; size];\n self.current_file.read_exact(&mut buffer).unwrap();\n buffer\n }\n```"}], "func_name": "output_exact_bytes", "docstring": "Return the exact amount of bytes.\n\nSubsequent calls to any of the other output methods will operate on the subsequent output.\n\n# Important\n\nThis method blocks indefinitely if the amount of bytes given by `size` cannot be read", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b8d614fd37287185d8d855fa2372146178f15a96f34212cf6dc307a9ec2ae515"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delay\n\nDocumentation:\nConvenience method for `sleep(Duration::from_millis(millis))`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn delay(&mut self, millis: u64) -> &mut Self {\n sleep(Duration::from_millis(millis));\n self\n }\n```"}], "func_name": "delay", "docstring": "Convenience method for `sleep(Duration::from_millis(millis))`", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "77bc38f813d569a6752a6301fec2711aab38ec2a92648a917de6e2096767f40d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_kill\n\nDocumentation:\nTry to kill the child process and wait for its termination.\n\nThis method blocks until the child process is killed, but returns an error if `self.timeout`\nor the default of 60s was reached. If no such error happened, the process resources are\nreleased, so there is usually no need to call `wait` or alike on unix systems although it's\nstill possible to do so.\n\n# Platform specific behavior\n\nOn unix systems the child process resources will be released like a call to [`Child::wait`]\nor alike would do.\n\n# Error\n\nIf [`Child::kill`] returned an error or if the child process could not be terminated within\n`self.timeout` or the default of 60s.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_kill(&mut self) -> io::Result<()> {\n let start = Instant::now();\n self.raw.kill()?;\n\n let timeout = self.timeout.unwrap_or(Duration::from_secs(60));\n // As a side effect, we're cleaning up the killed child process with the implicit call to\n // `Child::try_wait` in `self.is_alive`, which reaps the process id on unix systems. We\n // always fail with error on timeout if `self.timeout` is set to zero.\n while self.is_alive() || timeout == Duration::ZERO {\n if start.elapsed() < timeout {\n self.delay(10);\n } else {\n return Err(io::Error::other(format!(\n \"kill: Timeout of '{}s' reached\",\n timeout.as_secs_f64()\n )));\n }\n hint::spin_loop();\n }\n\n Ok(())\n }\n```"}], "func_name": "try_kill", "docstring": "Try to kill the child process and wait for its termination.\n\nThis method blocks until the child process is killed, but returns an error if `self.timeout`\nor the default of 60s was reached. If no such error happened, the process resources are\nreleased, so there is usually no need to call `wait` or alike on unix systems although it's\nstill possible to do so.\n\n# Platform specific behavior\n\nOn unix systems the child process resources will be released like a call to [`Child::wait`]\nor alike would do.\n\n# Error\n\nIf [`Child::kill`] returned an error or if the child process could not be terminated within\n`self.timeout` or the default of 60s.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "baad82b8ce910da6242f224d39e5752b4487edf9326d35493fd8b37be0bef667"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: kill\n\nDocumentation:\nTerminate the child process unconditionally and wait for the termination.\n\nIgnores any errors happening during [`Child::kill`] (i.e. child process already exited) but\nstill panics on timeout.\n\n# Panics\nIf the child process could not be terminated within `self.timeout` or the default of 60s.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn kill(&mut self) -> &mut Self {\n self.try_kill()\n .or_else(|error| {\n // We still throw the error on timeout in the `try_kill` function\n if error.kind() == io::ErrorKind::Other {\n Err(error)\n } else {\n Ok(())\n }\n })\n .unwrap();\n self\n }\n```"}], "func_name": "kill", "docstring": "Terminate the child process unconditionally and wait for the termination.\n\nIgnores any errors happening during [`Child::kill`] (i.e. child process already exited) but\nstill panics on timeout.\n\n# Panics\nIf the child process could not be terminated within `self.timeout` or the default of 60s.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7db9a2472a16fb7612931805d0afaeb76ef48999da77807a359a2870237a8c03"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait\n\nDocumentation:\nWait for the child process to terminate and return a [`CmdResult`].\n\nSee `wait_with_output` for details on timeouts etc. This method can also be run if\nthe child process was killed with [`UChild::kill`].\n\n# Errors\n\nReturns the error from the call to `wait_with_output` if any\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn wait(self) -> io::Result {\n let (bin_path, util_name, tmpd) = (\n self.bin_path.clone(),\n self.util_name.clone(),\n self.tmpd.clone(),\n );\n\n let output = self.wait_with_output()?;\n\n Ok(CmdResult {\n bin_path,\n util_name,\n tmpd,\n exit_status: Some(output.status),\n stdout: output.stdout,\n stderr: output.stderr,\n })\n }\n```"}], "func_name": "wait", "docstring": "Wait for the child process to terminate and return a [`CmdResult`].\n\nSee `wait_with_output` for details on timeouts etc. This method can also be run if\nthe child process was killed with [`UChild::kill`].\n\n# Errors\n\nReturns the error from the call to `wait_with_output` if any", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2e3ac1821d0521b01e2821cc924d0be11d03b826d9a4aad5980b8534aa522ca9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait_with_output\n\nDocumentation:\nWait for the child process to terminate and return an instance of [`Output`].\n\nIf `self.timeout` is reached while waiting, a [`io::ErrorKind::Other`] representing a\ntimeout error is returned. If no errors happened, we join with the thread created by\n[`UChild::pipe_in`] if any.\n\n# Error\n\nIf `self.timeout` is reached while waiting or [`Child::wait_with_output`] returned an\nerror.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn wait_with_output(mut self) -> io::Result {\n // some apps do not stop execution until their stdin gets closed.\n // to prevent a endless waiting here, we close the stdin.\n self.join(); // ensure that all pending async input is piped in\n self.close_stdin();\n\n let output = if let Some(timeout) = self.timeout {\n let child = self.raw;\n\n let (sender, receiver) = mpsc::channel();\n let handle = thread::Builder::new()\n .name(\"wait_with_output\".to_string())\n .spawn(move || sender.send(child.wait_with_output()))\n .unwrap();\n\n match receiver.recv_timeout(timeout) {\n Ok(result) => {\n // unwraps are safe here because we got a result from the sender and there was no panic\n // causing a disconnect.\n handle.join().unwrap().unwrap();\n result\n }\n Err(RecvTimeoutError::Timeout) => Err(io::Error::other(format!(\n \"wait: Timeout of '{}s' reached\",\n timeout.as_secs_f64()\n ))),\n Err(RecvTimeoutError::Disconnected) => {\n handle.join().expect(\"Panic caused disconnect\").unwrap();\n panic!(\"Error receiving from waiting thread because of unexpected disconnect\");\n }\n }\n } else {\n self.raw.wait_with_output()\n };\n\n let mut output = output?;\n\n if let Some(join_handle) = self.join_handle.take() {\n join_handle\n .join()\n .expect(\"Error joining with the piping stdin thread\")\n .unwrap();\n };\n\n if let Some(stdout) = self.captured_stdout.as_mut() {\n if let Some(handle) = stdout.reader_thread_handle.take() {\n handle.join().unwrap();\n }\n output.stdout = stdout.output_bytes();\n }\n if let Some(stderr) = self.captured_stderr.as_mut() {\n if let Some(handle) = stderr.reader_thread_handle.take() {\n handle.join().unwrap();\n }\n output.stderr = stderr.output_bytes();\n }\n\n Ok(output)\n }\n```"}], "func_name": "wait_with_output", "docstring": "Wait for the child process to terminate and return an instance of [`Output`].\n\nIf `self.timeout` is reached while waiting, a [`io::ErrorKind::Other`] representing a\ntimeout error is returned. If no errors happened, we join with the thread created by\n[`UChild::pipe_in`] if any.\n\n# Error\n\nIf `self.timeout` is reached while waiting or [`Child::wait_with_output`] returned an\nerror.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "678c01bc91046b1595de946eb8abc6d55c2067dc85217298e240917de3624bb5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stdout_bytes\n\nDocumentation:\nRead, consume and return the output as bytes from [`Child`]'s stdout.\n\nEach subsequent call to any of the functions below will operate on the subsequent output of\nthe child process:\n\n* [`UChild::stdout`]\n* [`UChild::stdout_exact_bytes`]\n* and the call to itself [`UChild::stdout_bytes`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stdout_bytes(&mut self) -> Vec {\n match self.captured_stdout.as_mut() {\n Some(output) => output.output_bytes(),\n None if self.raw.stdout.is_some() => {\n let mut buffer: Vec = vec![];\n let stdout = self.raw.stdout.as_mut().unwrap();\n stdout.read_to_end(&mut buffer).unwrap();\n buffer\n }\n None => vec![],\n }\n }\n```"}], "func_name": "stdout_bytes", "docstring": "Read, consume and return the output as bytes from [`Child`]'s stdout.\n\nEach subsequent call to any of the functions below will operate on the subsequent output of\nthe child process:\n\n* [`UChild::stdout`]\n* [`UChild::stdout_exact_bytes`]\n* and the call to itself [`UChild::stdout_bytes`]", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ec45f4cb54919f6b4f5575102c58f3418b3af603e0a0533f0e800f015a77e880"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stdout_all_bytes\n\nDocumentation:\nRead and return all output from start of the child process until now.\n\nEach subsequent call of any of the methods below will operate on the subsequent output of\nthe child process. This method will panic if the output wasn't captured (for example if\n[`UCommand::set_stdout`] was used).\n\n* [`UChild::stdout`]\n* [`UChild::stdout_bytes`]\n* [`UChild::stdout_exact_bytes`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stdout_all_bytes(&mut self) -> Vec {\n match self.captured_stdout.as_mut() {\n Some(output) => output.output_all_bytes(),\n None => {\n panic!(\"Usage error: This method cannot be used if the output wasn't captured.\")\n }\n }\n }\n```"}], "func_name": "stdout_all_bytes", "docstring": "Read and return all output from start of the child process until now.\n\nEach subsequent call of any of the methods below will operate on the subsequent output of\nthe child process. This method will panic if the output wasn't captured (for example if\n[`UCommand::set_stdout`] was used).\n\n* [`UChild::stdout`]\n* [`UChild::stdout_bytes`]\n* [`UChild::stdout_exact_bytes`]", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "52dc4e0e140a92b7e455202cbcd988e0d9c9d42961c6d5e665af9dc508034612"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stdout_exact_bytes\n\nDocumentation:\nRead, consume and return the exact amount of bytes from `stdout`.\n\nThis method may block indefinitely if the `size` amount of bytes exceeds the amount of bytes\nthat can be read. See also [`UChild::stdout_bytes`] for side effects.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stdout_exact_bytes(&mut self, size: usize) -> Vec {\n match self.captured_stdout.as_mut() {\n Some(output) => output.output_exact_bytes(size),\n None if self.raw.stdout.is_some() => {\n let mut buffer = vec![0; size];\n let stdout = self.raw.stdout.as_mut().unwrap();\n stdout.read_exact(&mut buffer).unwrap();\n buffer\n }\n None => vec![],\n }\n }\n```"}], "func_name": "stdout_exact_bytes", "docstring": "Read, consume and return the exact amount of bytes from `stdout`.\n\nThis method may block indefinitely if the `size` amount of bytes exceeds the amount of bytes\nthat can be read. See also [`UChild::stdout_bytes`] for side effects.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "73bb867e2650688ab3a1c5c08c92a6b05e1a96356c05ddc453b0386be6ae5f36"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stderr_bytes\n\nDocumentation:\nRead, consume and return the currently available bytes from child's stderr.\n\nIf stderr is redirected to stdout with [`UCommand::stderr_to_stdout`] then always zero bytes\nare returned. See also [`UChild::stdout_bytes`] for side effects.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stderr_bytes(&mut self) -> Vec {\n match self.captured_stderr.as_mut() {\n Some(output) => output.output_bytes(),\n None if self.raw.stderr.is_some() => {\n let mut buffer: Vec = vec![];\n let stderr = self.raw.stderr.as_mut().unwrap();\n stderr.read_to_end(&mut buffer).unwrap();\n buffer\n }\n None => vec![],\n }\n }\n```"}], "func_name": "stderr_bytes", "docstring": "Read, consume and return the currently available bytes from child's stderr.\n\nIf stderr is redirected to stdout with [`UCommand::stderr_to_stdout`] then always zero bytes\nare returned. See also [`UChild::stdout_bytes`] for side effects.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dc3483f78dc083e3bbba963425184e360ca7906a4d2a44b86a02d0294247eb4d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stderr_all_bytes\n\nDocumentation:\nRead and return all output from start of the child process until now.\n\nEach subsequent call of any of the methods below will operate on the subsequent output of\nthe child process. This method will panic if the output wasn't captured (for example if\n[`UCommand::set_stderr`] was used). If [`UCommand::stderr_to_stdout`] was used always zero\nbytes are returned.\n\n* [`UChild::stderr`]\n* [`UChild::stderr_bytes`]\n* [`UChild::stderr_exact_bytes`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stderr_all_bytes(&mut self) -> Vec {\n match self.captured_stderr.as_mut() {\n Some(output) => output.output_all_bytes(),\n None if self.stderr_to_stdout => vec![],\n None => {\n panic!(\"Usage error: This method cannot be used if the output wasn't captured.\")\n }\n }\n }\n```"}], "func_name": "stderr_all_bytes", "docstring": "Read and return all output from start of the child process until now.\n\nEach subsequent call of any of the methods below will operate on the subsequent output of\nthe child process. This method will panic if the output wasn't captured (for example if\n[`UCommand::set_stderr`] was used). If [`UCommand::stderr_to_stdout`] was used always zero\nbytes are returned.\n\n* [`UChild::stderr`]\n* [`UChild::stderr_bytes`]\n* [`UChild::stderr_exact_bytes`]", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "688092907fb323939b9c758a39957630bff64f2072b5db036f26d4aa6d563ce0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stderr_exact_bytes\n\nDocumentation:\nRead, consume and return the exact amount of bytes from stderr.\n\nIf stderr is redirect to stdout with [`UCommand::stderr_to_stdout`] then always zero bytes\nare returned.\n\n# Important\nThis method blocks indefinitely if the `size` amount of bytes cannot be read.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stderr_exact_bytes(&mut self, size: usize) -> Vec {\n match self.captured_stderr.as_mut() {\n Some(output) => output.output_exact_bytes(size),\n None if self.raw.stderr.is_some() => {\n let stderr = self.raw.stderr.as_mut().unwrap();\n let mut buffer = vec![0; size];\n stderr.read_exact(&mut buffer).unwrap();\n buffer\n }\n None => vec![],\n }\n }\n```"}], "func_name": "stderr_exact_bytes", "docstring": "Read, consume and return the exact amount of bytes from stderr.\n\nIf stderr is redirect to stdout with [`UCommand::stderr_to_stdout`] then always zero bytes\nare returned.\n\n# Important\nThis method blocks indefinitely if the `size` amount of bytes cannot be read.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b4972a6bd71935d6cc13a7359dad07beb274cd2ee722c8f50fd1d19649a9ae47"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pipe_in\n\nDocumentation:\nPipe data into [`Child`] stdin in a separate thread to avoid deadlocks.\n\nIn contrast to [`UChild::write_in`], this method is designed to simulate a pipe on the\ncommand line and can be used only once or else panics. Note, that [`UCommand::set_stdin`]\nmust be used together with [`Stdio::piped`] or else this method doesn't work as expected.\n`Stdio::piped` is the current default when using [`UCommand::run_no_wait`]) without calling\n`set_stdin`. This method stores a [`JoinHandle`] of the thread in which the writing to the\nchild processes' stdin is running. The associated thread is joined with the main process in\nthe methods below when exiting the child process.\n\n* [`UChild::wait`]\n* [`UChild::pipe_in_and_wait`]\n\nUsually, there's no need to join manually but if needed, the [`UChild::join`] method can be\nused .\n\n[`JoinHandle`]: std::thread::JoinHandle\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pipe_in>>(&mut self, content: T) -> &mut Self {\n let ignore_stdin_write_error = self.ignore_stdin_write_error;\n let mut content: Vec = content.into();\n if self.stdin_pty.is_some() {\n content.append(&mut END_OF_TRANSMISSION_SEQUENCE.to_vec());\n }\n let mut writer = self.take_stdin_as_writer();\n\n let join_handle = std::thread::Builder::new()\n .name(\"pipe_in\".to_string())\n .spawn(\n move || match writer.write_all(&content).and_then(|()| writer.flush()) {\n Err(error) if !ignore_stdin_write_error => Err(io::Error::other(format!(\n \"failed to write to stdin of child: {error}\"\n ))),\n Ok(()) | Err(_) => Ok(()),\n },\n )\n .unwrap();\n\n self.join_handle = Some(join_handle);\n self\n }\n```"}], "func_name": "pipe_in", "docstring": "Pipe data into [`Child`] stdin in a separate thread to avoid deadlocks.\n\nIn contrast to [`UChild::write_in`], this method is designed to simulate a pipe on the\ncommand line and can be used only once or else panics. Note, that [`UCommand::set_stdin`]\nmust be used together with [`Stdio::piped`] or else this method doesn't work as expected.\n`Stdio::piped` is the current default when using [`UCommand::run_no_wait`]) without calling\n`set_stdin`. This method stores a [`JoinHandle`] of the thread in which the writing to the\nchild processes' stdin is running. The associated thread is joined with the main process in\nthe methods below when exiting the child process.\n\n* [`UChild::wait`]\n* [`UChild::pipe_in_and_wait`]\n\nUsually, there's no need to join manually but if needed, the [`UChild::join`] method can be\nused .\n\n[`JoinHandle`]: std::thread::JoinHandle", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "66cbbf98912d0004107c44d5f73026e0b32249b0f821095953d92ce8fa457cd4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: join\n\nDocumentation:\nCall join on the thread created by [`UChild::pipe_in`] and if the thread is still running.\n\nThis method can be called multiple times but is a noop if already joined.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn join(&mut self) -> &mut Self {\n if let Some(join_handle) = self.join_handle.take() {\n join_handle\n .join()\n .expect(\"Error joining with the piping stdin thread\")\n .unwrap();\n }\n self\n }\n```"}], "func_name": "join", "docstring": "Call join on the thread created by [`UChild::pipe_in`] and if the thread is still running.\n\nThis method can be called multiple times but is a noop if already joined.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "50ef57d30b8ef5b910e290ba10ca64bc28d7f7707f82b4c55cae14c9923e809a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pipe_in_and_wait\n\nDocumentation:\nConvenience method for [`UChild::pipe_in`] and then [`UChild::wait`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pipe_in_and_wait>>(mut self, content: T) -> CmdResult {\n self.pipe_in(content);\n self.wait().unwrap()\n }\n```"}], "func_name": "pipe_in_and_wait", "docstring": "Convenience method for [`UChild::pipe_in`] and then [`UChild::wait`]", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0093aeaeb7ceddc11d1a8278e73908223b31bd57e44b2b57ac59a32e05fb8681"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_write_in\n\nDocumentation:\nWrite some bytes to the child process stdin.\n\nThis function is meant for small data and faking user input like typing a `yes` or `no`.\nThis function blocks until all data is written but can be used multiple times in contrast to\n[`UChild::pipe_in`].\n\n# Errors\nIf [`std::process::ChildStdin::write_all`] or [`std::process::ChildStdin::flush`] returned an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_write_in>>(&mut self, data: T) -> io::Result<()> {\n let ignore_stdin_write_error = self.ignore_stdin_write_error;\n let mut writer = self.access_stdin_as_writer();\n\n match writer.write_all(&data.into()).and_then(|()| writer.flush()) {\n Err(error) if !ignore_stdin_write_error => Err(io::Error::other(format!(\n \"failed to write to stdin of child: {error}\"\n ))),\n Ok(()) | Err(_) => Ok(()),\n }\n }\n```"}], "func_name": "try_write_in", "docstring": "Write some bytes to the child process stdin.\n\nThis function is meant for small data and faking user input like typing a `yes` or `no`.\nThis function blocks until all data is written but can be used multiple times in contrast to\n[`UChild::pipe_in`].\n\n# Errors\nIf [`std::process::ChildStdin::write_all`] or [`std::process::ChildStdin::flush`] returned an error", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "65f9a7cfd6ae5d2b8014ee949de7b6b52810e826fc8105850d49827ed75d8667"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_in\n\nDocumentation:\nConvenience function for [`UChild::try_write_in`] and a following `unwrap`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_in>>(&mut self, data: T) -> &mut Self {\n self.try_write_in(data).unwrap();\n self\n }\n```"}], "func_name": "write_in", "docstring": "Convenience function for [`UChild::try_write_in`] and a following `unwrap`.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2860d3e7bf3763edefb1050de3ed210222cc2443dae3a2e80de43ec44869ede4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: close_stdout\n\nDocumentation:\nClose the child process stdout.\n\nNote this will have no effect if the output was captured with CapturedOutput which is the\ndefault if [`UCommand::set_stdout`] wasn't called.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn close_stdout(&mut self) -> &mut Self {\n self.raw.stdout.take();\n self\n }\n```"}], "func_name": "close_stdout", "docstring": "Close the child process stdout.\n\nNote this will have no effect if the output was captured with CapturedOutput which is the\ndefault if [`UCommand::set_stdout`] wasn't called.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7d4c103cdffa2a22017a71a265d802c0c600c4c60482a544cd360ad2eeca68f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: close_stderr\n\nDocumentation:\nClose the child process stderr.\n\nNote this will have no effect if the output was captured with CapturedOutput which is the\ndefault if [`UCommand::set_stderr`] wasn't called.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn close_stderr(&mut self) -> &mut Self {\n self.raw.stderr.take();\n self\n }\n```"}], "func_name": "close_stderr", "docstring": "Close the child process stderr.\n\nNote this will have no effect if the output was captured with CapturedOutput which is the\ndefault if [`UCommand::set_stderr`] wasn't called.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d9229501b79e2f897ee57d333aa20c269748810fd9f92b9a0dc68acb9df66ed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: close_stdin\n\nDocumentation:\nClose the child process stdin.\n\nNote, this does not have any effect if using the [`UChild::pipe_in`] method.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn close_stdin(&mut self) -> &mut Self {\n self.raw.stdin.take();\n if self.stdin_pty.is_some() {\n // a pty can not be closed. We need to send a EOT:\n let _ = self.try_write_in(END_OF_TRANSMISSION_SEQUENCE);\n self.stdin_pty.take();\n }\n self\n }\n```"}], "func_name": "close_stdin", "docstring": "Close the child process stdin.\n\nNote, this does not have any effect if using the [`UChild::pipe_in`] method.", "repo": "uutils/coreutils", "path": "tests/uutests/src/lib/util.rs", "url": "https://github.com/uutils/coreutils/blob/master/tests/uutests/src/lib/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a3d99e65c8d09d7ca1081e5bfaee40e0d2e191ba420d47a7b89d7ec72baa6e35"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: execute\n\nDocumentation:\nSigns the request before calling `oauth2::reqwest::http_client`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn execute(&self, mut request: HttpRequest) -> Result {\n let signed_url = self.sign_url(\n Url::parse(&request.uri().to_string()).expect(\"http::Uri should be a valid url::Url\"),\n request.method(),\n request.body(),\n );\n *request.uri_mut() = signed_url\n .as_str()\n .try_into()\n .expect(\"url::Url should be a valid http::Uri\");\n self.inner.call(request)\n }\n```"}], "func_name": "execute", "docstring": "Signs the request before calling `oauth2::reqwest::http_client`.", "repo": "ramosbugs/oauth2-rs", "path": "examples/letterboxd.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/examples/letterboxd.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8be29fec595cbfc523cddda125b257d3ed6e781ac21ddc8a61a5d5dccc644c1e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sign_url\n\nDocumentation:\nSigns the request based on a random and unique nonce, timestamp, and\nclient id and secret.\n\nThe client id, nonce, timestamp and signature are added to the url's\nquery.\n\nSee http://api-docs.letterboxd.com/#signing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn sign_url(&self, mut url: Url, method: &http::method::Method, body: &[u8]) -> Url {\n let nonce = uuid::Uuid::new_v4(); // use UUID as random and unique nonce\n\n let timestamp = time::SystemTime::now()\n .duration_since(time::UNIX_EPOCH)\n .expect(\"SystemTime::duration_since failed\")\n .as_secs();\n\n url.query_pairs_mut()\n .append_pair(\"apikey\", &self.client_id)\n .append_pair(\"nonce\", &format!(\"{}\", nonce))\n .append_pair(\"timestamp\", &format!(\"{}\", timestamp));\n\n // create signature\n let mut hmac = Hmac::::new_from_slice(self.client_secret.secret().as_bytes())\n .expect(\"HMAC can take key of any size\");\n hmac.update(method.as_str().as_bytes());\n hmac.update(&[b'\\0']);\n hmac.update(url.as_str().as_bytes());\n hmac.update(&[b'\\0']);\n hmac.update(body);\n let signature: String = hmac.finalize().into_bytes().encode_hex();\n\n url.query_pairs_mut().append_pair(\"signature\", &signature);\n\n url\n }\n```"}], "func_name": "sign_url", "docstring": "Signs the request based on a random and unique nonce, timestamp, and\nclient id and secret.\n\nThe client id, nonce, timestamp and signature are added to the url's\nquery.\n\nSee http://api-docs.letterboxd.com/#signing.", "repo": "ramosbugs/oauth2-rs", "path": "examples/letterboxd.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/examples/letterboxd.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "72f5bf1373ab37041928780a620f1f62951bd96a0665e06db8bc2115b169d760"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: token_type\n\nDocumentation:\nREQUIRED. The type of the token issued as described in\n[Section 7.1](https://tools.ietf.org/html/rfc6749#section-7.1).\nValue is case insensitive and deserialized to the generic `TokenType` parameter.\nBut in this particular case as the service is non compliant, it has a default value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn token_type(&self) -> &BasicTokenType {\n match &self.token_type {\n Some(t) => t,\n None => &BasicTokenType::Bearer,\n }\n }\n```"}], "func_name": "token_type", "docstring": "REQUIRED. The type of the token issued as described in\n[Section 7.1](https://tools.ietf.org/html/rfc6749#section-7.1).\nValue is case insensitive and deserialized to the generic `TokenType` parameter.\nBut in this particular case as the service is non compliant, it has a default value", "repo": "ramosbugs/oauth2-rs", "path": "examples/wunderlist.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/examples/wunderlist.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "da4695c8cc9e61543bf85636a0e89af08603418066cac0bc590f3d258bed0f2b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nInitializes an OAuth2 client with the specified client ID.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(client_id: ClientId) -> Self {\n Self {\n client_id,\n client_secret: None,\n auth_url: None,\n auth_type: AuthType::BasicAuth,\n token_url: None,\n redirect_url: None,\n introspection_url: None,\n revocation_url: None,\n device_authorization_url: None,\n phantom: PhantomData,\n }\n }\n```"}], "func_name": "new", "docstring": "Initializes an OAuth2 client with the specified client ID.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6871686eac1f9c312e09339b91dfe1bd10db4d4e4467ef028eeda8627e011a76"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_auth_uri\n\nDocumentation:\nSet the authorization endpoint.\n\nThe client uses the authorization endpoint to obtain authorization from the resource owner\nvia user-agent redirection. This URL is used in all standard OAuth2 flows except the\n[Resource Owner Password Credentials Grant](https://tools.ietf.org/html/rfc6749#section-4.3)\nand the [Client Credentials Grant](https://tools.ietf.org/html/rfc6749#section-4.4).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_auth_uri(\n self,\n auth_url: AuthUrl,\n ) -> Client<\n TE,\n TR,\n TIR,\n RT,\n TRE,\n EndpointSet,\n HasDeviceAuthUrl,\n HasIntrospectionUrl,\n HasRevocationUrl,\n HasTokenUrl,\n > {\n Client {\n client_id: self.client_id,\n client_secret: self.client_secret,\n auth_url: Some(auth_url),\n auth_type: self.auth_type,\n token_url: self.token_url,\n redirect_url: self.redirect_url,\n introspection_url: self.introspection_url,\n revocation_url: self.revocation_url,\n device_authorization_url: self.device_authorization_url,\n phantom: PhantomData,\n }\n }\n```"}], "func_name": "set_auth_uri", "docstring": "Set the authorization endpoint.\n\nThe client uses the authorization endpoint to obtain authorization from the resource owner\nvia user-agent redirection. This URL is used in all standard OAuth2 flows except the\n[Resource Owner Password Credentials Grant](https://tools.ietf.org/html/rfc6749#section-4.3)\nand the [Client Credentials Grant](https://tools.ietf.org/html/rfc6749#section-4.4).", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "db559eb6ec9f609a8b583c3f4496b153dfe4db0c62dc81f43a10d3e63ab07c43"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_auth_uri_option\n\nDocumentation:\nConditionally set the authorization endpoint.\n\nThe client uses the authorization endpoint to obtain authorization from the resource owner\nvia user-agent redirection. This URL is used in all standard OAuth2 flows except the\n[Resource Owner Password Credentials Grant](https://tools.ietf.org/html/rfc6749#section-4.3)\nand the [Client Credentials Grant](https://tools.ietf.org/html/rfc6749#section-4.4).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_auth_uri_option(\n self,\n auth_url: Option,\n ) -> Client<\n TE,\n TR,\n TIR,\n RT,\n TRE,\n EndpointMaybeSet,\n HasDeviceAuthUrl,\n HasIntrospectionUrl,\n HasRevocationUrl,\n HasTokenUrl,\n > {\n Client {\n client_id: self.client_id,\n client_secret: self.client_secret,\n auth_url,\n auth_type: self.auth_type,\n token_url: self.token_url,\n redirect_url: self.redirect_url,\n introspection_url: self.introspection_url,\n revocation_url: self.revocation_url,\n device_authorization_url: self.device_authorization_url,\n phantom: PhantomData,\n }\n }\n```"}], "func_name": "set_auth_uri_option", "docstring": "Conditionally set the authorization endpoint.\n\nThe client uses the authorization endpoint to obtain authorization from the resource owner\nvia user-agent redirection. This URL is used in all standard OAuth2 flows except the\n[Resource Owner Password Credentials Grant](https://tools.ietf.org/html/rfc6749#section-4.3)\nand the [Client Credentials Grant](https://tools.ietf.org/html/rfc6749#section-4.4).", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "20d75ce02fd5439e732eaec3acbbc3e800616933dbc3c12a17b94220eab69051"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_device_authorization_url\n\nDocumentation:\nSet the [RFC 8628](https://tools.ietf.org/html/rfc8628) device authorization endpoint used\nfor the Device Authorization Flow.\n\nSee [`exchange_device_code()`](Self::exchange_device_code).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_device_authorization_url(\n self,\n device_authorization_url: DeviceAuthorizationUrl,\n ) -> Client<\n TE,\n TR,\n TIR,\n RT,\n TRE,\n HasAuthUrl,\n EndpointSet,\n HasIntrospectionUrl,\n HasRevocationUrl,\n HasTokenUrl,\n > {\n Client {\n client_id: self.client_id,\n client_secret: self.client_secret,\n auth_url: self.auth_url,\n auth_type: self.auth_type,\n token_url: self.token_url,\n redirect_url: self.redirect_url,\n introspection_url: self.introspection_url,\n revocation_url: self.revocation_url,\n device_authorization_url: Some(device_authorization_url),\n phantom: PhantomData,\n }\n }\n```"}], "func_name": "set_device_authorization_url", "docstring": "Set the [RFC 8628](https://tools.ietf.org/html/rfc8628) device authorization endpoint used\nfor the Device Authorization Flow.\n\nSee [`exchange_device_code()`](Self::exchange_device_code).", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb779745e5602e328561bdcdedf368e03a8feaa242d119eac262c6395ea7f8d5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_device_authorization_url_option\n\nDocumentation:\nConditionally set the [RFC 8628](https://tools.ietf.org/html/rfc8628) device authorization\nendpoint used for the Device Authorization Flow.\n\nSee [`exchange_device_code()`](Self::exchange_device_code).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_device_authorization_url_option(\n self,\n device_authorization_url: Option,\n ) -> Client<\n TE,\n TR,\n TIR,\n RT,\n TRE,\n HasAuthUrl,\n EndpointMaybeSet,\n HasIntrospectionUrl,\n HasRevocationUrl,\n HasTokenUrl,\n > {\n Client {\n client_id: self.client_id,\n client_secret: self.client_secret,\n auth_url: self.auth_url,\n auth_type: self.auth_type,\n token_url: self.token_url,\n redirect_url: self.redirect_url,\n introspection_url: self.introspection_url,\n revocation_url: self.revocation_url,\n device_authorization_url,\n phantom: PhantomData,\n }\n }\n```"}], "func_name": "set_device_authorization_url_option", "docstring": "Conditionally set the [RFC 8628](https://tools.ietf.org/html/rfc8628) device authorization\nendpoint used for the Device Authorization Flow.\n\nSee [`exchange_device_code()`](Self::exchange_device_code).", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5a83932467fcf422ddc1e83eac2412bd4f2ed6b34f8cd09fd02157a955630751"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_introspection_url\n\nDocumentation:\nSet the [RFC 7662](https://tools.ietf.org/html/rfc7662) introspection endpoint.\n\nSee [`introspect()`](Self::introspect).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_introspection_url(\n self,\n introspection_url: IntrospectionUrl,\n ) -> Client<\n TE,\n TR,\n TIR,\n RT,\n TRE,\n HasAuthUrl,\n HasDeviceAuthUrl,\n EndpointSet,\n HasRevocationUrl,\n HasTokenUrl,\n > {\n Client {\n client_id: self.client_id,\n client_secret: self.client_secret,\n auth_url: self.auth_url,\n auth_type: self.auth_type,\n token_url: self.token_url,\n redirect_url: self.redirect_url,\n introspection_url: Some(introspection_url),\n revocation_url: self.revocation_url,\n device_authorization_url: self.device_authorization_url,\n phantom: PhantomData,\n }\n }\n```"}], "func_name": "set_introspection_url", "docstring": "Set the [RFC 7662](https://tools.ietf.org/html/rfc7662) introspection endpoint.\n\nSee [`introspect()`](Self::introspect).", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "364959e0bb9e6d6c1f58e5688bd10df98d32c4e3ebd1048a843b46a3e3a1c99f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_introspection_url_option\n\nDocumentation:\nConditionally set the [RFC 7662](https://tools.ietf.org/html/rfc7662) introspection\nendpoint.\n\nSee [`introspect()`](Self::introspect).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_introspection_url_option(\n self,\n introspection_url: Option,\n ) -> Client<\n TE,\n TR,\n TIR,\n RT,\n TRE,\n HasAuthUrl,\n HasDeviceAuthUrl,\n EndpointMaybeSet,\n HasRevocationUrl,\n HasTokenUrl,\n > {\n Client {\n client_id: self.client_id,\n client_secret: self.client_secret,\n auth_url: self.auth_url,\n auth_type: self.auth_type,\n token_url: self.token_url,\n redirect_url: self.redirect_url,\n introspection_url,\n revocation_url: self.revocation_url,\n device_authorization_url: self.device_authorization_url,\n phantom: PhantomData,\n }\n }\n```"}], "func_name": "set_introspection_url_option", "docstring": "Conditionally set the [RFC 7662](https://tools.ietf.org/html/rfc7662) introspection\nendpoint.\n\nSee [`introspect()`](Self::introspect).", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "382d02a6c7524f2396ccbfc10a4d329a06ede305b73c2c0b9e071bfb626f09cd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_redirect_uri\n\nDocumentation:\nSet the redirect URL used by the authorization endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_redirect_uri(mut self, redirect_url: RedirectUrl) -> Self {\n self.redirect_url = Some(redirect_url);\n\n self\n }\n```"}], "func_name": "set_redirect_uri", "docstring": "Set the redirect URL used by the authorization endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ec1b9c41e702a1d57771dd2fe142c9e6f9f7634efa027faa93b7b4ca0872dbe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_revocation_url\n\nDocumentation:\nSet the [RFC 7009](https://tools.ietf.org/html/rfc7009) revocation endpoint.\n\nSee [`revoke_token()`](Self::revoke_token()).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_revocation_url(\n self,\n revocation_url: RevocationUrl,\n ) -> Client<\n TE,\n TR,\n TIR,\n RT,\n TRE,\n HasAuthUrl,\n HasDeviceAuthUrl,\n HasIntrospectionUrl,\n EndpointSet,\n HasTokenUrl,\n > {\n Client {\n client_id: self.client_id,\n client_secret: self.client_secret,\n auth_url: self.auth_url,\n auth_type: self.auth_type,\n token_url: self.token_url,\n redirect_url: self.redirect_url,\n introspection_url: self.introspection_url,\n revocation_url: Some(revocation_url),\n device_authorization_url: self.device_authorization_url,\n phantom: PhantomData,\n }\n }\n```"}], "func_name": "set_revocation_url", "docstring": "Set the [RFC 7009](https://tools.ietf.org/html/rfc7009) revocation endpoint.\n\nSee [`revoke_token()`](Self::revoke_token()).", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "454911f257a7753c2ba61f8613421ad4ad772379b04d5a457b6383183d523a9d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_revocation_url_option\n\nDocumentation:\nConditionally set the [RFC 7009](https://tools.ietf.org/html/rfc7009) revocation\nendpoint.\n\nSee [`revoke_token()`](Self::revoke_token()).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_revocation_url_option(\n self,\n revocation_url: Option,\n ) -> Client<\n TE,\n TR,\n TIR,\n RT,\n TRE,\n HasAuthUrl,\n HasDeviceAuthUrl,\n HasIntrospectionUrl,\n EndpointMaybeSet,\n HasTokenUrl,\n > {\n Client {\n client_id: self.client_id,\n client_secret: self.client_secret,\n auth_url: self.auth_url,\n auth_type: self.auth_type,\n token_url: self.token_url,\n redirect_url: self.redirect_url,\n introspection_url: self.introspection_url,\n revocation_url,\n device_authorization_url: self.device_authorization_url,\n phantom: PhantomData,\n }\n }\n```"}], "func_name": "set_revocation_url_option", "docstring": "Conditionally set the [RFC 7009](https://tools.ietf.org/html/rfc7009) revocation\nendpoint.\n\nSee [`revoke_token()`](Self::revoke_token()).", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "52d6fc42557e87e0e113e5a75ebceeb184ad2e3881f98b85e5288f5107954ff9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_token_uri\n\nDocumentation:\nSet the token endpoint.\n\nThe client uses the token endpoint to exchange an authorization code for an access token,\ntypically with client authentication. This URL is used in\nall standard OAuth2 flows except the\n[Implicit Grant](https://tools.ietf.org/html/rfc6749#section-4.2).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_token_uri(\n self,\n token_url: TokenUrl,\n ) -> Client<\n TE,\n TR,\n TIR,\n RT,\n TRE,\n HasAuthUrl,\n HasDeviceAuthUrl,\n HasIntrospectionUrl,\n HasRevocationUrl,\n EndpointSet,\n > {\n Client {\n client_id: self.client_id,\n client_secret: self.client_secret,\n auth_url: self.auth_url,\n auth_type: self.auth_type,\n token_url: Some(token_url),\n redirect_url: self.redirect_url,\n introspection_url: self.introspection_url,\n revocation_url: self.revocation_url,\n device_authorization_url: self.device_authorization_url,\n phantom: PhantomData,\n }\n }\n```"}], "func_name": "set_token_uri", "docstring": "Set the token endpoint.\n\nThe client uses the token endpoint to exchange an authorization code for an access token,\ntypically with client authentication. This URL is used in\nall standard OAuth2 flows except the\n[Implicit Grant](https://tools.ietf.org/html/rfc6749#section-4.2).", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "461815544d3c6cf2fccb2682cbbed637de985dbc901933a8c6c21f50b7d3451d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_token_uri_option\n\nDocumentation:\nConditionally set the token endpoint.\n\nThe client uses the token endpoint to exchange an authorization code for an access token,\ntypically with client authentication. This URL is used in\nall standard OAuth2 flows except the\n[Implicit Grant](https://tools.ietf.org/html/rfc6749#section-4.2).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_token_uri_option(\n self,\n token_url: Option,\n ) -> Client<\n TE,\n TR,\n TIR,\n RT,\n TRE,\n HasAuthUrl,\n HasDeviceAuthUrl,\n HasIntrospectionUrl,\n HasRevocationUrl,\n EndpointMaybeSet,\n > {\n Client {\n client_id: self.client_id,\n client_secret: self.client_secret,\n auth_url: self.auth_url,\n auth_type: self.auth_type,\n token_url,\n redirect_url: self.redirect_url,\n introspection_url: self.introspection_url,\n revocation_url: self.revocation_url,\n device_authorization_url: self.device_authorization_url,\n phantom: PhantomData,\n }\n }\n```"}], "func_name": "set_token_uri_option", "docstring": "Conditionally set the token endpoint.\n\nThe client uses the token endpoint to exchange an authorization code for an access token,\ntypically with client authentication. This URL is used in\nall standard OAuth2 flows except the\n[Implicit Grant](https://tools.ietf.org/html/rfc6749#section-4.2).", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e64d33ce1cb742b7ba43ee175c6cf2444ff6d1cebca2f91b82e17bc7f1b753d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exchange_code\n\nDocumentation:\nExchange a code returned during the\n[Authorization Code Flow](https://datatracker.ietf.org/doc/html/rfc6749#section-4.1)\nfor an access token.\n\nAcquires ownership of the `code` because authorization codes may only be used once to\nretrieve an access token from the authorization server.\n\nRequires [`set_token_uri()`](Self::set_token_uri) to have been previously\ncalled to set the token endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exchange_code(&self, code: AuthorizationCode) -> CodeTokenRequest {\n self.exchange_code_impl(self.token_uri(), code)\n }\n```"}], "func_name": "exchange_code", "docstring": "Exchange a code returned during the\n[Authorization Code Flow](https://datatracker.ietf.org/doc/html/rfc6749#section-4.1)\nfor an access token.\n\nAcquires ownership of the `code` because authorization codes may only be used once to\nretrieve an access token from the authorization server.\n\nRequires [`set_token_uri()`](Self::set_token_uri) to have been previously\ncalled to set the token endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a6e2901f34c59add8ad52e646287eb091d8fa058cbfb1a5b5094bda639c9accf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exchange_device_access_token\n\nDocumentation:\nExchange an [RFC 8628](https://tools.ietf.org/html/rfc8628#section-3.2) Device Authorization\nResponse returned by [`exchange_device_code()`](Self::exchange_device_code) for an access\ntoken.\n\nRequires [`set_token_uri()`](Self::set_token_uri) to have been previously\ncalled to set the token endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exchange_device_access_token<'a, EF>(\n &'a self,\n auth_response: &'a DeviceAuthorizationResponse,\n ) -> DeviceAccessTokenRequest<'a, 'static, TR, EF>\n where\n EF: ExtraDeviceAuthorizationFields,\n {\n self.exchange_device_access_token_impl(self.token_uri(), auth_response)\n }\n```"}], "func_name": "exchange_device_access_token", "docstring": "Exchange an [RFC 8628](https://tools.ietf.org/html/rfc8628#section-3.2) Device Authorization\nResponse returned by [`exchange_device_code()`](Self::exchange_device_code) for an access\ntoken.\n\nRequires [`set_token_uri()`](Self::set_token_uri) to have been previously\ncalled to set the token endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "97cd389a5630b65c7fdb744e49626e5909d2f1cf35387a4a9be54fd4a2116336"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exchange_password\n\nDocumentation:\nRequest an access token using the\n[Resource Owner Password Credentials Flow](https://datatracker.ietf.org/doc/html/rfc6749#section-4.3).\n\nRequires\n[`set_token_uri()`](Self::set_token_uri) to have\nbeen previously called to set the token endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exchange_password<'a>(\n &'a self,\n username: &'a ResourceOwnerUsername,\n password: &'a ResourceOwnerPassword,\n ) -> PasswordTokenRequest<'a, TE, TR> {\n self.exchange_password_impl(self.token_uri(), username, password)\n }\n```"}], "func_name": "exchange_password", "docstring": "Request an access token using the\n[Resource Owner Password Credentials Flow](https://datatracker.ietf.org/doc/html/rfc6749#section-4.3).\n\nRequires\n[`set_token_uri()`](Self::set_token_uri) to have\nbeen previously called to set the token endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e3dbff05b4e3aec355690643357bf2240463f06dd9e630c2aed95f91abdb0c9f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exchange_refresh_token\n\nDocumentation:\nExchange a refresh token for an access token.\n\nSee .\n\nRequires\n[`set_token_uri()`](Self::set_token_uri) to have\nbeen previously called to set the token endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exchange_refresh_token<'a>(\n &'a self,\n refresh_token: &'a RefreshToken,\n ) -> RefreshTokenRequest<'a, TE, TR> {\n self.exchange_refresh_token_impl(self.token_uri(), refresh_token)\n }\n```"}], "func_name": "exchange_refresh_token", "docstring": "Exchange a refresh token for an access token.\n\nSee .\n\nRequires\n[`set_token_uri()`](Self::set_token_uri) to have\nbeen previously called to set the token endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "31633f2996c89d468415fe93782b110b7b12e8a13da651556397a23db05a7528"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exchange_client_credentials\n\nDocumentation:\nRequest an access token using the\n[Client Credentials Flow](https://datatracker.ietf.org/doc/html/rfc6749#section-4.4).\n\nRequires [`set_token_uri_option()`](Self::set_token_uri_option) to have been previously\ncalled to set the token endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exchange_client_credentials(\n &self,\n ) -> Result, ConfigurationError> {\n Ok(self.exchange_client_credentials_impl(\n self.token_url\n .as_ref()\n .ok_or(ConfigurationError::MissingUrl(\"token\"))?,\n ))\n }\n```"}], "func_name": "exchange_client_credentials", "docstring": "Request an access token using the\n[Client Credentials Flow](https://datatracker.ietf.org/doc/html/rfc6749#section-4.4).\n\nRequires [`set_token_uri_option()`](Self::set_token_uri_option) to have been previously\ncalled to set the token endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fe783b197ff450efc884506cae57bc0d32f413200426e237cc8c3c82fabf03ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exchange_code\n\nDocumentation:\nExchange a code returned during the\n[Authorization Code Flow](https://datatracker.ietf.org/doc/html/rfc6749#section-4.1)\nfor an access token.\n\nAcquires ownership of the `code` because authorization codes may only be used once to\nretrieve an access token from the authorization server.\n\nRequires [`set_token_uri_option()`](Self::set_token_uri_option) to have been previously\ncalled to set the token endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exchange_code(\n &self,\n code: AuthorizationCode,\n ) -> Result, ConfigurationError> {\n Ok(self.exchange_code_impl(\n self.token_url\n .as_ref()\n .ok_or(ConfigurationError::MissingUrl(\"token\"))?,\n code,\n ))\n }\n```"}], "func_name": "exchange_code", "docstring": "Exchange a code returned during the\n[Authorization Code Flow](https://datatracker.ietf.org/doc/html/rfc6749#section-4.1)\nfor an access token.\n\nAcquires ownership of the `code` because authorization codes may only be used once to\nretrieve an access token from the authorization server.\n\nRequires [`set_token_uri_option()`](Self::set_token_uri_option) to have been previously\ncalled to set the token endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b8cd0bc3c832989d27ff8b1a4cd05cdf64c4efdab1a72b384a63b51c8df4d0d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exchange_device_access_token\n\nDocumentation:\nExchange an [RFC 8628](https://tools.ietf.org/html/rfc8628#section-3.2) Device Authorization\nResponse returned by [`exchange_device_code()`](Self::exchange_device_code) for an access\ntoken.\n\nRequires [`set_token_uri_option()`](Self::set_token_uri_option) to have been previously\ncalled to set the token endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exchange_device_access_token<'a, EF>(\n &'a self,\n auth_response: &'a DeviceAuthorizationResponse,\n ) -> Result, ConfigurationError>\n where\n EF: ExtraDeviceAuthorizationFields,\n {\n Ok(self.exchange_device_access_token_impl(\n self.token_url\n .as_ref()\n .ok_or(ConfigurationError::MissingUrl(\"token\"))?,\n auth_response,\n ))\n }\n```"}], "func_name": "exchange_device_access_token", "docstring": "Exchange an [RFC 8628](https://tools.ietf.org/html/rfc8628#section-3.2) Device Authorization\nResponse returned by [`exchange_device_code()`](Self::exchange_device_code) for an access\ntoken.\n\nRequires [`set_token_uri_option()`](Self::set_token_uri_option) to have been previously\ncalled to set the token endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "73c800ec9fc40cc0c415ca40fadb974a8f9a7ba26b10b5a766127ebca935abe6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exchange_password\n\nDocumentation:\nRequest an access token using the\n[Resource Owner Password Credentials Flow](https://datatracker.ietf.org/doc/html/rfc6749#section-4.3).\n\nRequires\n[`set_token_uri_option()`](Self::set_token_uri_option) to have\nbeen previously called to set the token endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exchange_password<'a>(\n &'a self,\n username: &'a ResourceOwnerUsername,\n password: &'a ResourceOwnerPassword,\n ) -> Result, ConfigurationError> {\n Ok(self.exchange_password_impl(\n self.token_url\n .as_ref()\n .ok_or(ConfigurationError::MissingUrl(\"token\"))?,\n username,\n password,\n ))\n }\n```"}], "func_name": "exchange_password", "docstring": "Request an access token using the\n[Resource Owner Password Credentials Flow](https://datatracker.ietf.org/doc/html/rfc6749#section-4.3).\n\nRequires\n[`set_token_uri_option()`](Self::set_token_uri_option) to have\nbeen previously called to set the token endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "19045f1e92371e482639fe7b9932b8625f1828dd3907d2e62c1e1d1008d455be"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exchange_refresh_token\n\nDocumentation:\nExchange a refresh token for an access token.\n\nSee .\n\nRequires\n[`set_token_uri_option()`](Self::set_token_uri_option) to have\nbeen previously called to set the token endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exchange_refresh_token<'a>(\n &'a self,\n refresh_token: &'a RefreshToken,\n ) -> Result, ConfigurationError> {\n Ok(self.exchange_refresh_token_impl(\n self.token_url\n .as_ref()\n .ok_or(ConfigurationError::MissingUrl(\"token\"))?,\n refresh_token,\n ))\n }\n```"}], "func_name": "exchange_refresh_token", "docstring": "Exchange a refresh token for an access token.\n\nSee .\n\nRequires\n[`set_token_uri_option()`](Self::set_token_uri_option) to have\nbeen previously called to set the token endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "330b1c9ff98b0656f06aef8881aa28a27c52b42466cb73fc1b9510fc6e5155b5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: device_authorization_url\n\nDocumentation:\nReturn the [RFC 8628](https://tools.ietf.org/html/rfc8628) device authorization endpoint\nused for the Device Authorization Flow.\n\nSee [`exchange_device_code()`](Self::exchange_device_code).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn device_authorization_url(&self) -> &DeviceAuthorizationUrl {\n // This is enforced statically via the HasDeviceAuthUrl generic type.\n self.device_authorization_url\n .as_ref()\n .expect(\"should have device_authorization_url\")\n }\n```"}], "func_name": "device_authorization_url", "docstring": "Return the [RFC 8628](https://tools.ietf.org/html/rfc8628) device authorization endpoint\nused for the Device Authorization Flow.\n\nSee [`exchange_device_code()`](Self::exchange_device_code).", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad3622c9c0e5db942a4fdb60228fdff5149c74f89022c61e70ccf3886d4e2e3b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exchange_device_code\n\nDocumentation:\nBegin the [RFC 8628](https://tools.ietf.org/html/rfc8628) Device Authorization Flow.\n\nRequires\n[`set_device_authorization_url_option()`](Self::set_device_authorization_url_option) to have\nbeen previously called to set the device authorization endpoint.\n\nSee [`exchange_device_access_token()`](Self::exchange_device_access_token).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exchange_device_code(\n &self,\n ) -> Result, ConfigurationError> {\n Ok(self.exchange_device_code_impl(\n self.device_authorization_url\n .as_ref()\n .ok_or(ConfigurationError::MissingUrl(\"device authorization\"))?,\n ))\n }\n```"}], "func_name": "exchange_device_code", "docstring": "Begin the [RFC 8628](https://tools.ietf.org/html/rfc8628) Device Authorization Flow.\n\nRequires\n[`set_device_authorization_url_option()`](Self::set_device_authorization_url_option) to have\nbeen previously called to set the device authorization endpoint.\n\nSee [`exchange_device_access_token()`](Self::exchange_device_access_token).", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9382b1dfca2cda7e4b9472bb5956884c1c9784579f1f102a92a984a597bbb05"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: introspect\n\nDocumentation:\nRetrieve metadata for an access token using the\n[`RFC 7662`](https://tools.ietf.org/html/rfc7662) introspection endpoint.\n\nRequires [`set_introspection_url()`](Self::set_introspection_url) to have been previously\ncalled to set the introspection endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn introspect<'a>(&'a self, token: &'a AccessToken) -> IntrospectionRequest<'a, TE, TIR> {\n self.introspect_impl(self.introspection_url(), token)\n }\n```"}], "func_name": "introspect", "docstring": "Retrieve metadata for an access token using the\n[`RFC 7662`](https://tools.ietf.org/html/rfc7662) introspection endpoint.\n\nRequires [`set_introspection_url()`](Self::set_introspection_url) to have been previously\ncalled to set the introspection endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3cc0692f9c0472756dbae8fb7172d39720aee6463b90e91ebd0651e5127c878f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: introspection_url\n\nDocumentation:\nReturn the [RFC 7662](https://tools.ietf.org/html/rfc7662) introspection endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn introspection_url(&self) -> &IntrospectionUrl {\n // This is enforced statically via the HasIntrospectionUrl generic type.\n self.introspection_url\n .as_ref()\n .expect(\"should have introspection_url\")\n }\n```"}], "func_name": "introspection_url", "docstring": "Return the [RFC 7662](https://tools.ietf.org/html/rfc7662) introspection endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fe32fdaa2b2a1cd40dbcaa5565490d0243660620bda1d594f2a2ccd6d676fcc3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: introspect\n\nDocumentation:\nRetrieve metadata for an access token using the\n[`RFC 7662`](https://tools.ietf.org/html/rfc7662) introspection endpoint.\n\nRequires [`set_introspection_url_option()`](Self::set_introspection_url_option) to have been\npreviously called to set the introspection endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn introspect<'a>(\n &'a self,\n token: &'a AccessToken,\n ) -> Result, ConfigurationError> {\n Ok(self.introspect_impl(\n self.introspection_url\n .as_ref()\n .ok_or(ConfigurationError::MissingUrl(\"introspection\"))?,\n token,\n ))\n }\n```"}], "func_name": "introspect", "docstring": "Retrieve metadata for an access token using the\n[`RFC 7662`](https://tools.ietf.org/html/rfc7662) introspection endpoint.\n\nRequires [`set_introspection_url_option()`](Self::set_introspection_url_option) to have been\npreviously called to set the introspection endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "50b18fb5e38196396643b273dd34f9f3aa55eaf9f6bba0d44b706b491be29bba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: revoke_token\n\nDocumentation:\nRevoke an access or refresh token using the [RFC 7009](https://tools.ietf.org/html/rfc7009)\nrevocation endpoint.\n\nRequires [`set_revocation_url()`](Self::set_revocation_url) to have been previously\ncalled to set the revocation endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn revoke_token(\n &self,\n token: RT,\n ) -> Result, ConfigurationError> {\n self.revoke_token_impl(self.revocation_url(), token)\n }\n```"}], "func_name": "revoke_token", "docstring": "Revoke an access or refresh token using the [RFC 7009](https://tools.ietf.org/html/rfc7009)\nrevocation endpoint.\n\nRequires [`set_revocation_url()`](Self::set_revocation_url) to have been previously\ncalled to set the revocation endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "79bf61ac33d4def5e28329ef6d11a1ceed2663560835f37bcdc4e1f9532268dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: revocation_url\n\nDocumentation:\nReturn the [RFC 7009](https://tools.ietf.org/html/rfc7009) revocation endpoint.\n\nSee [`revoke_token()`](Self::revoke_token()).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn revocation_url(&self) -> &RevocationUrl {\n // This is enforced statically via the HasRevocationUrl generic type.\n self.revocation_url\n .as_ref()\n .expect(\"should have revocation_url\")\n }\n```"}], "func_name": "revocation_url", "docstring": "Return the [RFC 7009](https://tools.ietf.org/html/rfc7009) revocation endpoint.\n\nSee [`revoke_token()`](Self::revoke_token()).", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ddef434e19e147e741cc12a2392b98041e5e735329b3276ac4f2b68b0c744148"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: revoke_token\n\nDocumentation:\nRevoke an access or refresh token using the [RFC 7009](https://tools.ietf.org/html/rfc7009)\nrevocation endpoint.\n\nRequires [`set_revocation_url_option()`](Self::set_revocation_url_option) to have been\npreviously called to set the revocation endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn revoke_token(\n &self,\n token: RT,\n ) -> Result, ConfigurationError> {\n self.revoke_token_impl(\n self.revocation_url\n .as_ref()\n .ok_or(ConfigurationError::MissingUrl(\"revocation\"))?,\n token,\n )\n }\n```"}], "func_name": "revoke_token", "docstring": "Revoke an access or refresh token using the [RFC 7009](https://tools.ietf.org/html/rfc7009)\nrevocation endpoint.\n\nRequires [`set_revocation_url_option()`](Self::set_revocation_url_option) to have been\npreviously called to set the revocation endpoint.", "repo": "ramosbugs/oauth2-rs", "path": "src/client.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9dd3eff064ab04711a52b95280cc5aa38eb3520b3aae29988fbb20c4ed2dfd08"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_scope\n\nDocumentation:\nAppends a new scope to the authorization URL.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_scope(mut self, scope: Scope) -> Self {\n self.scopes.push(Cow::Owned(scope));\n self\n }\n```"}], "func_name": "add_scope", "docstring": "Appends a new scope to the authorization URL.", "repo": "ramosbugs/oauth2-rs", "path": "src/code.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2034388299b44efa7919fbf5d88f1718b479197ecfd84e10f67e8a0de19be4d9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_scopes\n\nDocumentation:\nAppends a collection of scopes to the token request.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_scopes(mut self, scopes: I) -> Self\n where\n I: IntoIterator,\n {\n self.scopes.extend(scopes.into_iter().map(Cow::Owned));\n self\n }\n```"}], "func_name": "add_scopes", "docstring": "Appends a collection of scopes to the token request.", "repo": "ramosbugs/oauth2-rs", "path": "src/code.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5ff85418fa8243d26b717fc2fbdfc29e964233425e5695ad2246e2dbcb747fac"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_extra_param\n\nDocumentation:\nAppends an extra param to the authorization URL.\n\nThis method allows extensions to be used without direct support from\nthis crate. If `name` conflicts with a parameter managed by this crate, the\nbehavior is undefined. In particular, do not set parameters defined by\n[RFC 6749](https://tools.ietf.org/html/rfc6749) or\n[RFC 7636](https://tools.ietf.org/html/rfc7636).\n\n# Security Warning\n\nCallers should follow the security recommendations for any OAuth2 extensions used with\nthis function, which are beyond the scope of\n[RFC 6749](https://tools.ietf.org/html/rfc6749).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_extra_param(mut self, name: N, value: V) -> Self\n where\n N: Into>,\n V: Into>,\n {\n self.extra_params.push((name.into(), value.into()));\n self\n }\n```"}], "func_name": "add_extra_param", "docstring": "Appends an extra param to the authorization URL.\n\nThis method allows extensions to be used without direct support from\nthis crate. If `name` conflicts with a parameter managed by this crate, the\nbehavior is undefined. In particular, do not set parameters defined by\n[RFC 6749](https://tools.ietf.org/html/rfc6749) or\n[RFC 7636](https://tools.ietf.org/html/rfc7636).\n\n# Security Warning\n\nCallers should follow the security recommendations for any OAuth2 extensions used with\nthis function, which are beyond the scope of\n[RFC 6749](https://tools.ietf.org/html/rfc6749).", "repo": "ramosbugs/oauth2-rs", "path": "src/code.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fb415237666b820195d8e8795bea79dc007726ca5a33a5b6c87bf6ea27019a54"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: use_implicit_flow\n\nDocumentation:\nEnables the [Implicit Grant](https://tools.ietf.org/html/rfc6749#section-4.2) flow.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn use_implicit_flow(mut self) -> Self {\n self.response_type = \"token\".into();\n self\n }\n```"}], "func_name": "use_implicit_flow", "docstring": "Enables the [Implicit Grant](https://tools.ietf.org/html/rfc6749#section-4.2) flow.", "repo": "ramosbugs/oauth2-rs", "path": "src/code.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a330abba5fb1a6431bda9bae6c3201bc01cd8e93e657c6a2ae74a1c9c9309eb5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_response_type\n\nDocumentation:\nEnables custom flows other than the `code` and `token` (implicit flow) grant.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_response_type(mut self, response_type: &ResponseType) -> Self {\n self.response_type = (**response_type).to_owned().into();\n self\n }\n```"}], "func_name": "set_response_type", "docstring": "Enables custom flows other than the `code` and `token` (implicit flow) grant.", "repo": "ramosbugs/oauth2-rs", "path": "src/code.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a4da4ab2f695b3f0dc255cd76baf6c674928e5d7b00226f05e2faa41f774af4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_pkce_challenge\n\nDocumentation:\nEnables the use of [Proof Key for Code Exchange](https://tools.ietf.org/html/rfc7636)\n(PKCE).\n\nPKCE is *highly recommended* for all public clients (i.e., those for which there\nis no client secret or for which the client secret is distributed with the client,\nsuch as in a native, mobile app, or browser app).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_pkce_challenge(mut self, pkce_code_challenge: PkceCodeChallenge) -> Self {\n self.pkce_challenge = Some(pkce_code_challenge);\n self\n }\n```"}], "func_name": "set_pkce_challenge", "docstring": "Enables the use of [Proof Key for Code Exchange](https://tools.ietf.org/html/rfc7636)\n(PKCE).\n\nPKCE is *highly recommended* for all public clients (i.e., those for which there\nis no client secret or for which the client secret is distributed with the client,\nsuch as in a native, mobile app, or browser app).", "repo": "ramosbugs/oauth2-rs", "path": "src/code.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2c58265a84838e291b5245b8525645e9584de12d74b8efd635b5d4edf9e93360"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_redirect_uri\n\nDocumentation:\nOverrides the `redirect_url` to the one specified.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_redirect_uri(mut self, redirect_url: Cow<'a, RedirectUrl>) -> Self {\n self.redirect_url = Some(redirect_url);\n self\n }\n```"}], "func_name": "set_redirect_uri", "docstring": "Overrides the `redirect_url` to the one specified.", "repo": "ramosbugs/oauth2-rs", "path": "src/code.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b8d71b5f26f2b074437065f897b1b40439dafd086d73fc86366e67bb27e7fd0c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: url\n\nDocumentation:\nReturns the full authorization URL and CSRF state for this authorization\nrequest.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn url(self) -> (Url, CsrfToken) {\n let scopes = self\n .scopes\n .iter()\n .map(|s| s.to_string())\n .collect::>()\n .join(\" \");\n\n let url = {\n let mut pairs: Vec<(&str, &str)> = vec![\n (\"response_type\", self.response_type.as_ref()),\n (\"client_id\", self.client_id),\n (\"state\", self.state.secret()),\n ];\n\n if let Some(ref pkce_challenge) = self.pkce_challenge {\n pairs.push((\"code_challenge\", pkce_challenge.as_str()));\n pairs.push((\"code_challenge_method\", pkce_challenge.method().as_str()));\n }\n\n if let Some(ref redirect_url) = self.redirect_url {\n pairs.push((\"redirect_uri\", redirect_url.as_str()));\n }\n\n if !scopes.is_empty() {\n pairs.push((\"scope\", &scopes));\n }\n\n let mut url: Url = self.auth_url.url().to_owned();\n\n url.query_pairs_mut()\n .extend_pairs(pairs.iter().map(|&(k, v)| (k, v)));\n\n url.query_pairs_mut()\n .extend_pairs(self.extra_params.iter().cloned());\n url\n };\n\n (url, self.state)\n }\n```"}], "func_name": "url", "docstring": "Returns the full authorization URL and CSRF state for this authorization\nrequest.", "repo": "ramosbugs/oauth2-rs", "path": "src/code.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8bcd4d67d5b43efeca30e3c9984d6ba1b73ee9285f8627f6c36778742127175c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: request\n\nDocumentation:\nSynchronously sends the request to the authorization server and awaits a response.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn request(\n self,\n http_client: &C,\n ) -> Result, RequestTokenError<::Error, TE>>\n where\n C: SyncHttpClient,\n EF: ExtraDeviceAuthorizationFields,\n {\n endpoint_response(http_client.call(self.prepare_request()?)?)\n }\n```"}], "func_name": "request", "docstring": "Synchronously sends the request to the authorization server and awaits a response.", "repo": "ramosbugs/oauth2-rs", "path": "src/devicecode.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/devicecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca6e39a4acff373d49ee3254e2d708956e3def824edeff5e129228c6196036ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: request_async\n\nDocumentation:\nAsynchronously sends the request to the authorization server and returns a Future.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn request_async<'c, C, EF>(\n self,\n http_client: &'c C,\n ) -> impl Future<\n Output = Result<\n DeviceAuthorizationResponse,\n RequestTokenError<>::Error, TE>,\n >,\n > + 'c\n where\n Self: 'c,\n C: AsyncHttpClient<'c>,\n EF: ExtraDeviceAuthorizationFields,\n {\n Box::pin(async move { endpoint_response(http_client.call(self.prepare_request()?).await?) })\n }\n```"}], "func_name": "request_async", "docstring": "Asynchronously sends the request to the authorization server and returns a Future.", "repo": "ramosbugs/oauth2-rs", "path": "src/devicecode.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/devicecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac3c4ee50e4324bef17a6f24e53fa9e99930ee3051e43c0883e4cfdcd4fce84e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_time_fn\n\nDocumentation:\nSpecifies a function for returning the current time.\n\nThis function is used while polling the authorization server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_time_fn<'t, T>(self, time_fn: T) -> DeviceAccessTokenRequest<'a, 't, TR, EF>\n where\n T: Fn() -> DateTime + Send + Sync + 't,\n {\n DeviceAccessTokenRequest {\n auth_type: self.auth_type,\n client_id: self.client_id,\n client_secret: self.client_secret,\n extra_params: self.extra_params,\n token_url: self.token_url,\n dev_auth_resp: self.dev_auth_resp,\n time_fn: Arc::new(time_fn),\n max_backoff_interval: self.max_backoff_interval,\n _phantom: PhantomData,\n }\n }\n```"}], "func_name": "set_time_fn", "docstring": "Specifies a function for returning the current time.\n\nThis function is used while polling the authorization server.", "repo": "ramosbugs/oauth2-rs", "path": "src/devicecode.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/devicecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0d15effdc660ba662c57c2440bc0051db1b715e4d72428a7aab43166cf0518f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: request\n\nDocumentation:\nSynchronously polls the authorization server for a response, waiting\nusing a user defined sleep function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn request(\n self,\n http_client: &C,\n sleep_fn: S,\n timeout: Option,\n ) -> Result::Error, DeviceCodeErrorResponse>>\n where\n C: SyncHttpClient,\n S: Fn(Duration),\n {\n // Get the request timeout and starting interval\n let timeout_dt = self.compute_timeout(timeout)?;\n let mut interval = self.dev_auth_resp.interval();\n\n // Loop while requesting a token.\n loop {\n let now = (*self.time_fn)();\n if now > timeout_dt {\n break Err(RequestTokenError::ServerResponse(\n DeviceCodeErrorResponse::new(\n DeviceCodeErrorResponseType::ExpiredToken,\n Some(String::from(\"This device code has expired.\")),\n None,\n ),\n ));\n }\n\n match self.process_response(http_client.call(self.prepare_request()?), interval) {\n DeviceAccessTokenPollResult::ContinueWithNewPollInterval(new_interval) => {\n interval = new_interval\n }\n DeviceAccessTokenPollResult::Done(res) => break res,\n }\n\n // Sleep here using the provided sleep function.\n sleep_fn(interval);\n }\n }\n```"}], "func_name": "request", "docstring": "Synchronously polls the authorization server for a response, waiting\nusing a user defined sleep function.", "repo": "ramosbugs/oauth2-rs", "path": "src/devicecode.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/devicecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c33d5ce261b96c047811ed7638eacad52d1327cce2ddc53acd8eac14963aa85d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: request_async\n\nDocumentation:\nAsynchronously sends the request to the authorization server and awaits a response.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn request_async<'c, C, S, SF>(\n self,\n http_client: &'c C,\n sleep_fn: S,\n timeout: Option,\n ) -> impl Future<\n Output = Result<\n TR,\n RequestTokenError<>::Error, DeviceCodeErrorResponse>,\n >,\n > + 'c\n where\n Self: 'c,\n C: AsyncHttpClient<'c>,\n S: Fn(Duration) -> SF + 'c,\n SF: Future,\n {\n Box::pin(async move {\n // Get the request timeout and starting interval\n let timeout_dt = self.compute_timeout(timeout)?;\n let mut interval = self.dev_auth_resp.interval();\n\n // Loop while requesting a token.\n loop {\n let now = (*self.time_fn)();\n if now > timeout_dt {\n break Err(RequestTokenError::ServerResponse(\n DeviceCodeErrorResponse::new(\n DeviceCodeErrorResponseType::ExpiredToken,\n Some(String::from(\"This device code has expired.\")),\n None,\n ),\n ));\n }\n\n match self\n .process_response(http_client.call(self.prepare_request()?).await, interval)\n {\n DeviceAccessTokenPollResult::ContinueWithNewPollInterval(new_interval) => {\n interval = new_interval\n }\n DeviceAccessTokenPollResult::Done(res) => break res,\n }\n\n // Sleep here using the provided sleep function.\n sleep_fn(interval).await;\n }\n })\n }\n```"}], "func_name": "request_async", "docstring": "Asynchronously sends the request to the authorization server and awaits a response.", "repo": "ramosbugs/oauth2-rs", "path": "src/devicecode.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/devicecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dfcf410b68654921693a8a53c68d735ee841cbcc19819e950120d9983b769c13"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mock_time_fn\n\nDocumentation:\nCreates a time function that increments by one second each time.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn mock_time_fn() -> impl Fn() -> DateTime + Send + Sync {\n let timer = std::sync::Mutex::new(IncreasingTime::new());\n move || timer.lock().unwrap().next()\n }\n```"}], "func_name": "mock_time_fn", "docstring": "Creates a time function that increments by one second each time.", "repo": "ramosbugs/oauth2-rs", "path": "src/devicecode.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/devicecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bab2a90f3eda0ed46020fc85559594702b611fb35105366b635b7cb58b68ec70"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nInstantiate a new `ErrorResponse`.\n\n# Arguments\n\n* `error` - REQUIRED. A single ASCII error code deserialized to the generic parameter.\n`ErrorResponseType`.\n* `error_description` - OPTIONAL. Human-readable ASCII text providing additional\ninformation, used to assist the client developer in understanding the error that\noccurred. Values for this parameter MUST NOT include characters outside the set\n`%x20-21 / %x23-5B / %x5D-7E`.\n* `error_uri` - OPTIONAL. A URI identifying a human-readable web page with information\nabout the error used to provide the client developer with additional information about\nthe error. Values for the \"error_uri\" parameter MUST conform to the URI-reference\nsyntax and thus MUST NOT include characters outside the set `%x21 / %x23-5B / %x5D-7E`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(error: T, error_description: Option, error_uri: Option) -> Self {\n Self {\n error,\n error_description,\n error_uri,\n }\n }\n```"}], "func_name": "new", "docstring": "Instantiate a new `ErrorResponse`.\n\n# Arguments\n\n* `error` - REQUIRED. A single ASCII error code deserialized to the generic parameter.\n`ErrorResponseType`.\n* `error_description` - OPTIONAL. Human-readable ASCII text providing additional\ninformation, used to assist the client developer in understanding the error that\noccurred. Values for this parameter MUST NOT include characters outside the set\n`%x20-21 / %x23-5B / %x5D-7E`.\n* `error_uri` - OPTIONAL. A URI identifying a human-readable web page with information\nabout the error used to provide the client developer with additional information about\nthe error. Values for the \"error_uri\" parameter MUST conform to the URI-reference\nsyntax and thus MUST NOT include characters outside the set `%x21 / %x23-5B / %x5D-7E`.", "repo": "ramosbugs/oauth2-rs", "path": "src/error.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/error.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9bf5593538e406d58151e554ff47d8bd0dcf54f0c96146212af8a8f389c70af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: deserialize_untagged_enum_case_insensitive\n\nDocumentation:\nSerde case-insensitive deserializer for an untagged `enum`.\n\nThis function converts values to lowercase before deserializing as the `enum`. Requires the\n`#[serde(rename_all = \"lowercase\")]` attribute to be set on the `enum`.\n\n# Example\n\nIn example below, the following JSON values all deserialize to\n`GroceryBasket { fruit_item: Fruit::Banana }`:\n\n* `{\"fruit_item\": \"banana\"}`\n* `{\"fruit_item\": \"BANANA\"}`\n* `{\"fruit_item\": \"Banana\"}`\n\nNote: this example does not compile automatically due to\n[Rust issue #29286](https://github.com/rust-lang/rust/issues/29286).\n\n```\n# /*\nuse serde::Deserialize;\n\n#[derive(Deserialize)]\n#[serde(rename_all = \"lowercase\")]\nenum Fruit {\nApple,\nBanana,\nOrange,\n}\n\n#[derive(Deserialize)]\nstruct GroceryBasket {\n#[serde(deserialize_with = \"helpers::deserialize_untagged_enum_case_insensitive\")]\nfruit_item: Fruit,\n}\n# */\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn deserialize_untagged_enum_case_insensitive<'de, T, D>(deserializer: D) -> Result\nwhere\n T: Deserialize<'de>,\n D: Deserializer<'de>,\n{\n T::deserialize(Value::String(\n String::deserialize(deserializer)?.to_lowercase(),\n ))\n .map_err(serde::de::Error::custom)\n}\n```"}], "func_name": "deserialize_untagged_enum_case_insensitive", "docstring": "Serde case-insensitive deserializer for an untagged `enum`.\n\nThis function converts values to lowercase before deserializing as the `enum`. Requires the\n`#[serde(rename_all = \"lowercase\")]` attribute to be set on the `enum`.\n\n# Example\n\nIn example below, the following JSON values all deserialize to\n`GroceryBasket { fruit_item: Fruit::Banana }`:\n\n* `{\"fruit_item\": \"banana\"}`\n* `{\"fruit_item\": \"BANANA\"}`\n* `{\"fruit_item\": \"Banana\"}`\n\nNote: this example does not compile automatically due to\n[Rust issue #29286](https://github.com/rust-lang/rust/issues/29286).\n\n```\n# /*\nuse serde::Deserialize;\n\n#[derive(Deserialize)]\n#[serde(rename_all = \"lowercase\")]\nenum Fruit {\nApple,\nBanana,\nOrange,\n}\n\n#[derive(Deserialize)]\nstruct GroceryBasket {\n#[serde(deserialize_with = \"helpers::deserialize_untagged_enum_case_insensitive\")]\nfruit_item: Fruit,\n}\n# */\n```", "repo": "ramosbugs/oauth2-rs", "path": "src/helpers.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/helpers.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f1629fe3c1cb72e731e43c0dbcdb358aeb6764bf2cfe8ae7abc004532d6081c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: deserialize_optional_string_or_vec_string\n\nDocumentation:\nDeserializes a string or array of strings into an array of strings\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn deserialize_optional_string_or_vec_string<'de, D>(\n deserializer: D,\n) -> Result>, D::Error>\nwhere\n D: Deserializer<'de>,\n{\n struct StringOrVec(PhantomData>);\n\n impl<'de> serde::de::Visitor<'de> for StringOrVec {\n type Value = Option>;\n\n fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {\n formatter.write_str(\"string or list of strings\")\n }\n\n fn visit_str(self, value: &str) -> Result\n where\n E: serde::de::Error,\n {\n Ok(Some(vec![value.to_owned()]))\n }\n\n fn visit_none(self) -> Result\n where\n E: serde::de::Error,\n {\n Ok(None)\n }\n\n fn visit_unit(self) -> Result\n where\n E: serde::de::Error,\n {\n Ok(None)\n }\n\n fn visit_seq(self, visitor: S) -> Result\n where\n S: serde::de::SeqAccess<'de>,\n {\n Deserialize::deserialize(SeqAccessDeserializer::new(visitor)).map(Some)\n }\n }\n\n deserializer.deserialize_any(StringOrVec(PhantomData))\n}\n```"}], "func_name": "deserialize_optional_string_or_vec_string", "docstring": "Deserializes a string or array of strings into an array of strings", "repo": "ramosbugs/oauth2-rs", "path": "src/helpers.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/helpers.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "23a99dbfbbc8c638c5031cea4e3641a60185c891e285b3d49efae215cd48f062"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: variant_name\n\nDocumentation:\nSerde string serializer for an enum.\n\nSource:\n[https://github.com/serde-rs/serde/issues/553](https://github.com/serde-rs/serde/issues/553)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn variant_name(t: &T) -> &'static str {\n #[derive(Debug)]\n struct NotEnum;\n type Result = std::result::Result;\n impl Error for NotEnum {\n fn description(&self) -> &str {\n \"not struct\"\n }\n }\n impl Display for NotEnum {\n fn fmt(&self, _f: &mut Formatter) -> std::fmt::Result {\n unimplemented!()\n }\n }\n impl serde::ser::Error for NotEnum {\n fn custom(_msg: T) -> Self {\n NotEnum\n }\n }\n\n struct VariantName;\n impl Serializer for VariantName {\n type Ok = &'static str;\n type Error = NotEnum;\n type SerializeSeq = Impossible;\n type SerializeTuple = Impossible;\n type SerializeTupleStruct = Impossible;\n type SerializeTupleVariant = Enum;\n type SerializeMap = Impossible;\n type SerializeStruct = Impossible;\n type SerializeStructVariant = Enum;\n fn serialize_bool(self, _v: bool) -> Result {\n Err(NotEnum)\n }\n fn serialize_i8(self, _v: i8) -> Result {\n Err(NotEnum)\n }\n fn serialize_i16(self, _v: i16) -> Result {\n Err(NotEnum)\n }\n fn serialize_i32(self, _v: i32) -> Result {\n Err(NotEnum)\n }\n fn serialize_i64(self, _v: i64) -> Result {\n Err(NotEnum)\n }\n fn serialize_u8(self, _v: u8) -> Result {\n Err(NotEnum)\n }\n fn serialize_u16(self, _v: u16) -> Result {\n Err(NotEnum)\n }\n fn serialize_u32(self, _v: u32) -> Result {\n Err(NotEnum)\n }\n fn serialize_u64(self, _v: u64) -> Result {\n Err(NotEnum)\n }\n fn serialize_f32(self, _v: f32) -> Result {\n Err(NotEnum)\n }\n fn serialize_f64(self, _v: f64) -> Result {\n Err(NotEnum)\n }\n fn serialize_char(self, _v: char) -> Result {\n Err(NotEnum)\n }\n fn serialize_str(self, _v: &str) -> Result {\n Err(NotEnum)\n }\n fn serialize_bytes(self, _v: &[u8]) -> Result {\n Err(NotEnum)\n }\n fn serialize_none(self) -> Result {\n Err(NotEnum)\n }\n fn serialize_some(self, _value: &T) -> Result {\n Err(NotEnum)\n }\n fn serialize_unit(self) -> Result {\n Err(NotEnum)\n }\n fn serialize_unit_struct(self, _name: &'static str) -> Result {\n Err(NotEnum)\n }\n fn serialize_unit_variant(\n self,\n _name: &'static str,\n _variant_index: u32,\n variant: &'static str,\n ) -> Result {\n Ok(variant)\n }\n fn serialize_newtype_struct(\n self,\n _name: &'static str,\n _value: &T,\n ) -> Result {\n Err(NotEnum)\n }\n fn serialize_newtype_variant(\n self,\n _name: &'static str,\n _variant_index: u32,\n variant: &'static str,\n _value: &T,\n ) -> Result {\n Ok(variant)\n }\n fn serialize_seq(self, _len: Option) -> Result {\n Err(NotEnum)\n }\n fn serialize_tuple(self, _len: usize) -> Result {\n Err(NotEnum)\n }\n fn serialize_tuple_struct(\n self,\n _name: &'static str,\n _len: usize,\n ) -> Result {\n Err(NotEnum)\n }\n fn serialize_tuple_variant(\n self,\n _name: &'static str,\n _variant_index: u32,\n variant: &'static str,\n _len: usize,\n ) -> Result {\n Ok(Enum(variant))\n }\n fn serialize_map(self, _len: Option) -> Result {\n Err(NotEnum)\n }\n fn serialize_struct(\n self,\n _name: &'static str,\n _len: usize,\n ) -> Result {\n Err(NotEnum)\n }\n fn serialize_struct_variant(\n self,\n _name: &'static str,\n _variant_index: u32,\n variant: &'static str,\n _len: usize,\n ) -> Result {\n Ok(Enum(variant))\n }\n }\n\n struct Enum(&'static str);\n impl SerializeStructVariant for Enum {\n type Ok = &'static str;\n type Error = NotEnum;\n fn serialize_field(\n &mut self,\n _key: &'static str,\n _value: &T,\n ) -> Result<()> {\n Ok(())\n }\n fn end(self) -> Result {\n Ok(self.0)\n }\n }\n impl SerializeTupleVariant for Enum {\n type Ok = &'static str;\n type Error = NotEnum;\n fn serialize_field(&mut self, _value: &T) -> Result<()> {\n Ok(())\n }\n fn end(self) -> Result {\n Ok(self.0)\n }\n }\n\n t.serialize(VariantName).unwrap()\n}\n```"}], "func_name": "variant_name", "docstring": "Serde string serializer for an enum.\n\nSource:\n[https://github.com/serde-rs/serde/issues/553](https://github.com/serde-rs/serde/issues/553)", "repo": "ramosbugs/oauth2-rs", "path": "src/helpers.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/helpers.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0ccbb209378b763c6999131a3021e0e044f111627d4997410f62e9ccd10340c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: type_hint\n\nDocumentation:\nIndicates the type of the token to be revoked, as defined by [RFC 7009, Section 2.1](https://tools.ietf.org/html/rfc7009#section-2.1), i.e.:\n\n* `access_token`: An access token as defined in [RFC 6749,\nSection 1.4](https://tools.ietf.org/html/rfc6749#section-1.4)\n\n* `refresh_token`: A refresh token as defined in [RFC 6749,\nSection 1.5](https://tools.ietf.org/html/rfc6749#section-1.5)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn type_hint(&self) -> Option<&str> {\n match self {\n StandardRevocableToken::AccessToken(_) => Some(\"access_token\"),\n StandardRevocableToken::RefreshToken(_) => Some(\"refresh_token\"),\n }\n }\n```"}], "func_name": "type_hint", "docstring": "Indicates the type of the token to be revoked, as defined by [RFC 7009, Section 2.1](https://tools.ietf.org/html/rfc7009#section-2.1), i.e.:\n\n* `access_token`: An access token as defined in [RFC 6749,\nSection 1.4](https://tools.ietf.org/html/rfc6749#section-1.4)\n\n* `refresh_token`: A refresh token as defined in [RFC 6749,\nSection 1.5](https://tools.ietf.org/html/rfc6749#section-1.5)", "repo": "ramosbugs/oauth2-rs", "path": "src/revocation.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/revocation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a7ed60991dd2eca5630b0e91546f29c80fe7583447e2fd02ed35246c46defe1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: request\n\nDocumentation:\nSynchronously sends the request to the authorization server and awaits a response.\n\nA successful response indicates that the server either revoked the token or the token was not known to the\nserver.\n\nError [`UnsupportedTokenType`](RevocationErrorResponseType::UnsupportedTokenType) will be returned if the\ntype of token type given is not supported by the server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn request(\n self,\n http_client: &C,\n ) -> Result<(), RequestTokenError<::Error, TE>>\n where\n C: SyncHttpClient,\n {\n // From https://tools.ietf.org/html/rfc7009#section-2.2:\n // \"The content of the response body is ignored by the client as all\n // necessary information is conveyed in the response code.\"\n endpoint_response_status_only(http_client.call(self.prepare_request()?)?)\n }\n```"}], "func_name": "request", "docstring": "Synchronously sends the request to the authorization server and awaits a response.\n\nA successful response indicates that the server either revoked the token or the token was not known to the\nserver.\n\nError [`UnsupportedTokenType`](RevocationErrorResponseType::UnsupportedTokenType) will be returned if the\ntype of token type given is not supported by the server.", "repo": "ramosbugs/oauth2-rs", "path": "src/revocation.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/revocation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "85a2fd5c0ce82d470b33df82f85c5253dcc195abd6e5e07a3bb99f33c3d89585"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_random_sha256_len\n\nDocumentation:\nGenerate a new random, base64-encoded SHA-256 PKCE challenge code and verifier.\n\n# Arguments\n\n* `num_bytes` - Number of random bytes to generate, prior to base64-encoding.\nThe value must be in the range 32 to 96 inclusive in order to generate a verifier\nwith a suitable length.\n\n# Panics\n\nThis method panics if the resulting PKCE code verifier is not of a suitable length\nto comply with [RFC 7636](https://tools.ietf.org/html/rfc7636).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_random_sha256_len(num_bytes: u32) -> (Self, PkceCodeVerifier) {\n let code_verifier = Self::new_random_len(num_bytes);\n (\n Self::from_code_verifier_sha256(&code_verifier),\n code_verifier,\n )\n }\n```"}], "func_name": "new_random_sha256_len", "docstring": "Generate a new random, base64-encoded SHA-256 PKCE challenge code and verifier.\n\n# Arguments\n\n* `num_bytes` - Number of random bytes to generate, prior to base64-encoding.\nThe value must be in the range 32 to 96 inclusive in order to generate a verifier\nwith a suitable length.\n\n# Panics\n\nThis method panics if the resulting PKCE code verifier is not of a suitable length\nto comply with [RFC 7636](https://tools.ietf.org/html/rfc7636).", "repo": "ramosbugs/oauth2-rs", "path": "src/types.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/types.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3cfafdc4d2ba141745e16dc6b699c4acc0382ad324cda73335cf1162f661ee38"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_random_len\n\nDocumentation:\nGenerate a new random, base64-encoded PKCE code verifier.\n\n# Arguments\n\n* `num_bytes` - Number of random bytes to generate, prior to base64-encoding.\nThe value must be in the range 32 to 96 inclusive in order to generate a verifier\nwith a suitable length.\n\n# Panics\n\nThis method panics if the resulting PKCE code verifier is not of a suitable length\nto comply with [RFC 7636](https://tools.ietf.org/html/rfc7636).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_random_len(num_bytes: u32) -> PkceCodeVerifier {\n // The RFC specifies that the code verifier must have \"a minimum length of 43\n // characters and a maximum length of 128 characters\".\n // This implies 32-96 octets of random data to be base64 encoded.\n assert!((32..=96).contains(&num_bytes));\n let random_bytes: Vec = (0..num_bytes).map(|_| thread_rng().gen::()).collect();\n PkceCodeVerifier::new(BASE64_URL_SAFE_NO_PAD.encode(random_bytes))\n }\n```"}], "func_name": "new_random_len", "docstring": "Generate a new random, base64-encoded PKCE code verifier.\n\n# Arguments\n\n* `num_bytes` - Number of random bytes to generate, prior to base64-encoding.\nThe value must be in the range 32 to 96 inclusive in order to generate a verifier\nwith a suitable length.\n\n# Panics\n\nThis method panics if the resulting PKCE code verifier is not of a suitable length\nto comply with [RFC 7636](https://tools.ietf.org/html/rfc7636).", "repo": "ramosbugs/oauth2-rs", "path": "src/types.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/types.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d3eb8dfb5afb1efdbf060ffb2f04dbdad24a0015c4242c369eb440469651625e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_code_verifier_sha256\n\nDocumentation:\nGenerate a SHA-256 PKCE code challenge from the supplied PKCE code verifier.\n\n# Panics\n\nThis method panics if the supplied PKCE code verifier is not of a suitable length\nto comply with [RFC 7636](https://tools.ietf.org/html/rfc7636).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_code_verifier_sha256(code_verifier: &PkceCodeVerifier) -> Self {\n // The RFC specifies that the code verifier must have \"a minimum length of 43\n // characters and a maximum length of 128 characters\".\n assert!(code_verifier.secret().len() >= 43 && code_verifier.secret().len() <= 128);\n\n let digest = Sha256::digest(code_verifier.secret().as_bytes());\n let code_challenge = BASE64_URL_SAFE_NO_PAD.encode(digest);\n\n Self {\n code_challenge,\n code_challenge_method: PkceCodeChallengeMethod::new(\"S256\".to_string()),\n }\n }\n```"}], "func_name": "from_code_verifier_sha256", "docstring": "Generate a SHA-256 PKCE code challenge from the supplied PKCE code verifier.\n\n# Panics\n\nThis method panics if the supplied PKCE code verifier is not of a suitable length\nto comply with [RFC 7636](https://tools.ietf.org/html/rfc7636).", "repo": "ramosbugs/oauth2-rs", "path": "src/types.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/types.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c1b3a0ae49882f441f84324d7c9e0578e8b89ca2ab456cd338a1036b1281ffb7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_pkce_verifier\n\nDocumentation:\nCompletes the [Proof Key for Code Exchange](https://tools.ietf.org/html/rfc7636)\n(PKCE) protocol flow.\n\nThis method must be called if [`crate::AuthorizationRequest::set_pkce_challenge`] was used\nduring the authorization request.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_pkce_verifier(mut self, pkce_verifier: PkceCodeVerifier) -> Self {\n self.pkce_verifier = Some(pkce_verifier);\n self\n }\n```"}], "func_name": "set_pkce_verifier", "docstring": "Completes the [Proof Key for Code Exchange](https://tools.ietf.org/html/rfc7636)\n(PKCE) protocol flow.\n\nThis method must be called if [`crate::AuthorizationRequest::set_pkce_challenge`] was used\nduring the authorization request.", "repo": "ramosbugs/oauth2-rs", "path": "src/token/mod.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/token/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ea1b861d10ae375cedeb30578039868034f1c5e3867ef008f8448b03a5e8b55"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_extra_fields\n\nDocumentation:\nSet the extra fields defined by the client application.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_extra_fields(&mut self, extra_fields: EF) {\n self.extra_fields = extra_fields;\n }\n```"}], "func_name": "set_extra_fields", "docstring": "Set the extra fields defined by the client application.", "repo": "ramosbugs/oauth2-rs", "path": "src/token/mod.rs", "url": "https://github.com/ramosbugs/oauth2-rs/blob/master/src/token/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a0dfb4594f9445a786a49302f2074f5e43510c42e620cfe3869f4d82488faf8c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: initialize\n\nDocumentation:\nCreates and invokes a [stable_swap_client::instruction::initialize] instruction.\n\n# Arguments\n\nSee [stable_swap_client::instruction::InitializeData].\n\n* `nonce` - The nonce used to generate the swap_authority.\n* `amp_factor` - Amplification factor.\n* `fees` - Initial fees.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn initialize<'a, 'b, 'c, 'info>(\n ctx: CpiContext<'a, 'b, 'c, 'info, Initialize<'info>>,\n nonce: u8,\n amp_factor: u64,\n fees: stable_swap_client::fees::Fees,\n) -> Result<()> {\n let ix = stable_swap_client::instruction::initialize(\n // token program ID is verified by the stable swap program\n ctx.accounts.token_program.key,\n ctx.accounts.swap.key,\n ctx.accounts.swap_authority.key,\n ctx.accounts.admin.key,\n ctx.accounts.token_a.fees.key,\n ctx.accounts.token_b.fees.key,\n ctx.accounts.token_a.mint.key,\n ctx.accounts.token_a.reserve.key,\n ctx.accounts.token_b.mint.key,\n ctx.accounts.token_b.reserve.key,\n ctx.accounts.pool_mint.key,\n ctx.accounts.output_lp.key,\n nonce,\n amp_factor,\n fees,\n )?;\n solana_program::program::invoke_signed(\n &ix,\n &[\n ctx.program,\n ctx.accounts.swap,\n ctx.accounts.swap_authority,\n ctx.accounts.admin,\n ctx.accounts.token_a.fees,\n ctx.accounts.token_b.fees,\n ctx.accounts.token_a.mint,\n ctx.accounts.token_a.reserve,\n ctx.accounts.token_b.mint,\n ctx.accounts.token_b.reserve,\n ctx.accounts.pool_mint,\n ctx.accounts.output_lp,\n ctx.accounts.token_program,\n ],\n ctx.signer_seeds,\n )?;\n Ok(())\n}\n```"}], "func_name": "initialize", "docstring": "Creates and invokes a [stable_swap_client::instruction::initialize] instruction.\n\n# Arguments\n\nSee [stable_swap_client::instruction::InitializeData].\n\n* `nonce` - The nonce used to generate the swap_authority.\n* `amp_factor` - Amplification factor.\n* `fees` - Initial fees.", "repo": "saber-hq/stable-swap", "path": "stable-swap-anchor/src/instructions.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-anchor/src/instructions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "89ed15c14651e9eb2da0c93cde54b556f61f0b21ed51debf3285bd3f5e737433"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: deposit\n\nDocumentation:\nCreates and invokes a [stable_swap_client::instruction::deposit] instruction.\n\n# Arguments\n\nSee [stable_swap_client::instruction::DepositData].\n\n* `token_a_amount` - Amount of tokens of [`Deposit::input_a`] to deposit.\n* `token_b_amount` - Amount of tokens of [`Deposit::input_b`] to deposit.\n* `min_mint_amount` - Minimum amount of LP tokens to mint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn deposit<'a, 'b, 'c, 'info>(\n ctx: CpiContext<'a, 'b, 'c, 'info, Deposit<'info>>,\n token_a_amount: u64,\n token_b_amount: u64,\n min_mint_amount: u64,\n) -> Result<()> {\n let ix = stable_swap_client::instruction::deposit(\n // token program ID is verified by the stable swap program\n ctx.accounts.user.token_program.key,\n ctx.accounts.user.swap.key,\n ctx.accounts.user.swap_authority.key,\n ctx.accounts.user.user_authority.key,\n ctx.accounts.input_a.user.key,\n ctx.accounts.input_b.user.key,\n ctx.accounts.input_a.reserve.key,\n ctx.accounts.input_b.reserve.key,\n ctx.accounts.pool_mint.key,\n ctx.accounts.output_lp.key,\n token_a_amount,\n token_b_amount,\n min_mint_amount,\n )?;\n solana_program::program::invoke_signed(\n &ix,\n &[\n ctx.program,\n ctx.accounts.user.token_program,\n ctx.accounts.user.swap,\n ctx.accounts.user.swap_authority,\n ctx.accounts.user.user_authority,\n // deposit\n ctx.accounts.input_a.user,\n ctx.accounts.input_b.user,\n ctx.accounts.input_a.reserve,\n ctx.accounts.input_b.reserve,\n ctx.accounts.pool_mint,\n ctx.accounts.output_lp,\n ],\n ctx.signer_seeds,\n )?;\n Ok(())\n}\n```"}], "func_name": "deposit", "docstring": "Creates and invokes a [stable_swap_client::instruction::deposit] instruction.\n\n# Arguments\n\nSee [stable_swap_client::instruction::DepositData].\n\n* `token_a_amount` - Amount of tokens of [`Deposit::input_a`] to deposit.\n* `token_b_amount` - Amount of tokens of [`Deposit::input_b`] to deposit.\n* `min_mint_amount` - Minimum amount of LP tokens to mint.", "repo": "saber-hq/stable-swap", "path": "stable-swap-anchor/src/instructions.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-anchor/src/instructions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bd8204eb97a999e699db02869a4c04718c2f5ba0cbcff03d94af04393d97af24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: swap\n\nDocumentation:\nCreates and invokes a [stable_swap_client::instruction::swap] instruction.\n\n# Arguments\n\nSee [stable_swap_client::instruction::SwapData].\n\n* `amount_in` - Amount of [`Swap::input`] tokens to swap.\n* `minimum_amount_out` - Minimum amount of [`Swap::output`] tokens to receive.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn swap<'a, 'b, 'c, 'info>(\n ctx: CpiContext<'a, 'b, 'c, 'info, Swap<'info>>,\n amount_in: u64,\n minimum_amount_out: u64,\n) -> Result<()> {\n let ix = stable_swap_client::instruction::swap(\n ctx.accounts.user.token_program.key,\n ctx.accounts.user.swap.key,\n ctx.accounts.user.swap_authority.key,\n ctx.accounts.user.user_authority.key,\n ctx.accounts.input.user.key,\n ctx.accounts.input.reserve.key,\n ctx.accounts.output.user_token.reserve.key,\n ctx.accounts.output.user_token.user.key,\n ctx.accounts.output.fees.key,\n amount_in,\n minimum_amount_out,\n )?;\n solana_program::program::invoke_signed(\n &ix,\n &[\n ctx.program,\n ctx.accounts.user.token_program,\n ctx.accounts.user.swap,\n ctx.accounts.user.swap_authority,\n ctx.accounts.user.user_authority,\n // swap\n ctx.accounts.input.user,\n ctx.accounts.input.reserve,\n ctx.accounts.output.user_token.reserve,\n ctx.accounts.output.user_token.user,\n ctx.accounts.output.fees,\n ],\n ctx.signer_seeds,\n )?;\n Ok(())\n}\n```"}], "func_name": "swap", "docstring": "Creates and invokes a [stable_swap_client::instruction::swap] instruction.\n\n# Arguments\n\nSee [stable_swap_client::instruction::SwapData].\n\n* `amount_in` - Amount of [`Swap::input`] tokens to swap.\n* `minimum_amount_out` - Minimum amount of [`Swap::output`] tokens to receive.", "repo": "saber-hq/stable-swap", "path": "stable-swap-anchor/src/instructions.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-anchor/src/instructions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c8c1f350d91dd998fe6035ae39a54313502052b995fc51705760c1aff032c1dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: withdraw_one\n\nDocumentation:\nCreates and invokes a [stable_swap_client::instruction::withdraw_one] instruction.\n\n# Arguments\n\nSee [stable_swap_client::instruction::WithdrawOneData].\n\n* `pool_token_amount` - Amount of LP tokens to withdraw.\n* `minimum_token_amount` - Minimum amount of tokens of [`WithdrawOne::output`] to withdraw.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn withdraw_one<'a, 'b, 'c, 'info>(\n ctx: CpiContext<'a, 'b, 'c, 'info, WithdrawOne<'info>>,\n pool_token_amount: u64,\n minimum_token_amount: u64,\n) -> Result<()> {\n let ix = stable_swap_client::instruction::withdraw_one(\n ctx.accounts.user.token_program.key,\n ctx.accounts.user.swap.key,\n ctx.accounts.user.swap_authority.key,\n ctx.accounts.user.user_authority.key,\n ctx.accounts.pool_mint.key,\n ctx.accounts.input_lp.key,\n ctx.accounts.output.user_token.reserve.key,\n ctx.accounts.quote_reserves.key,\n ctx.accounts.output.user_token.user.key,\n ctx.accounts.output.fees.key,\n pool_token_amount,\n minimum_token_amount,\n )?;\n solana_program::program::invoke_signed(\n &ix,\n &[\n ctx.program,\n ctx.accounts.user.token_program,\n ctx.accounts.user.swap,\n ctx.accounts.user.swap_authority,\n ctx.accounts.user.user_authority,\n // withdraw_one\n ctx.accounts.pool_mint,\n ctx.accounts.input_lp,\n ctx.accounts.output.user_token.reserve,\n ctx.accounts.quote_reserves,\n ctx.accounts.output.user_token.user,\n ctx.accounts.output.fees,\n ],\n ctx.signer_seeds,\n )?;\n Ok(())\n}\n```"}], "func_name": "withdraw_one", "docstring": "Creates and invokes a [stable_swap_client::instruction::withdraw_one] instruction.\n\n# Arguments\n\nSee [stable_swap_client::instruction::WithdrawOneData].\n\n* `pool_token_amount` - Amount of LP tokens to withdraw.\n* `minimum_token_amount` - Minimum amount of tokens of [`WithdrawOne::output`] to withdraw.", "repo": "saber-hq/stable-swap", "path": "stable-swap-anchor/src/instructions.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-anchor/src/instructions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "354e3d765dc2040771de0e1179983401a49914d44999dc8df5016414f4f35dc2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: withdraw\n\nDocumentation:\nCreates and invokes a [stable_swap_client::instruction::withdraw] instruction.\n\n# Arguments\n\nSee [stable_swap_client::instruction::WithdrawData].\n\n* `pool_token_amount` - Amount of LP tokens to withdraw.\n* `minimum_token_a_amount` - Minimum amount of tokens of [`Withdraw::output_a`] to withdraw.\n* `minimum_token_b_amount` - Minimum amount of tokens of [`Withdraw::output_b`] to withdraw.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn withdraw<'a, 'b, 'c, 'info>(\n ctx: CpiContext<'a, 'b, 'c, 'info, Withdraw<'info>>,\n pool_token_amount: u64,\n minimum_token_a_amount: u64,\n minimum_token_b_amount: u64,\n) -> Result<()> {\n let ix = stable_swap_client::instruction::withdraw(\n // token program ID is verified by the stable swap program\n ctx.accounts.user.token_program.key,\n ctx.accounts.user.swap.key,\n ctx.accounts.user.swap_authority.key,\n ctx.accounts.user.user_authority.key,\n // accounts\n ctx.accounts.pool_mint.key,\n ctx.accounts.input_lp.key,\n ctx.accounts.output_a.user_token.reserve.key,\n ctx.accounts.output_b.user_token.reserve.key,\n ctx.accounts.output_a.user_token.user.key,\n ctx.accounts.output_b.user_token.user.key,\n ctx.accounts.output_a.fees.key,\n ctx.accounts.output_b.fees.key,\n pool_token_amount,\n minimum_token_a_amount,\n minimum_token_b_amount,\n )?;\n solana_program::program::invoke_signed(&ix, &ctx.to_account_infos(), ctx.signer_seeds)?;\n Ok(())\n}\n```"}], "func_name": "withdraw", "docstring": "Creates and invokes a [stable_swap_client::instruction::withdraw] instruction.\n\n# Arguments\n\nSee [stable_swap_client::instruction::WithdrawData].\n\n* `pool_token_amount` - Amount of LP tokens to withdraw.\n* `minimum_token_a_amount` - Minimum amount of tokens of [`Withdraw::output_a`] to withdraw.\n* `minimum_token_b_amount` - Minimum amount of tokens of [`Withdraw::output_b`] to withdraw.", "repo": "saber-hq/stable-swap", "path": "stable-swap-anchor/src/instructions.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-anchor/src/instructions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e08570f7aaa80ee020b7391873b9170d9bc64c434065a351eddff76c564656be"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ramp_a\n\nDocumentation:\nCreates and invokes a [stable_swap_client::instruction::ramp_a] instruction.\n\n# Arguments\n\nSee [stable_swap_client::instruction::RampAData].\n\n* `target_amp` - Target amplification factor to ramp to.\n* `stop_ramp_ts` - Timestamp when ramp up/down should stop.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ramp_a<'a, 'b, 'c, 'info>(\n ctx: CpiContext<'a, 'b, 'c, 'info, AdminUserContext<'info>>,\n target_amp: u64,\n stop_ramp_ts: i64,\n) -> Result<()> {\n let ix = stable_swap_client::instruction::ramp_a(\n ctx.accounts.swap.key,\n ctx.accounts.admin.key,\n target_amp,\n stop_ramp_ts,\n )?;\n solana_program::program::invoke_signed(&ix, &ctx.to_account_infos(), ctx.signer_seeds)?;\n Ok(())\n}\n```"}], "func_name": "ramp_a", "docstring": "Creates and invokes a [stable_swap_client::instruction::ramp_a] instruction.\n\n# Arguments\n\nSee [stable_swap_client::instruction::RampAData].\n\n* `target_amp` - Target amplification factor to ramp to.\n* `stop_ramp_ts` - Timestamp when ramp up/down should stop.", "repo": "saber-hq/stable-swap", "path": "stable-swap-anchor/src/instructions.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-anchor/src/instructions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "36f75b56e436b9c20f277ea16ea960c54e26661cf433b860d6d4609d229aa207"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pause\n\nDocumentation:\nCreates and invokes a [stable_swap_client::instruction::pause] instruction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pause<'a, 'b, 'c, 'info>(\n ctx: CpiContext<'a, 'b, 'c, 'info, AdminUserContext<'info>>,\n) -> Result<()> {\n let ix = stable_swap_client::instruction::pause(ctx.accounts.swap.key, ctx.accounts.admin.key)?;\n solana_program::program::invoke_signed(&ix, &ctx.to_account_infos(), ctx.signer_seeds)?;\n Ok(())\n}\n```"}], "func_name": "pause", "docstring": "Creates and invokes a [stable_swap_client::instruction::pause] instruction.", "repo": "saber-hq/stable-swap", "path": "stable-swap-anchor/src/instructions.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-anchor/src/instructions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "15e84d4c41bfae46c1dc5fad14954a5358eb574df898e6a96f775e553a85ba56"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unpause\n\nDocumentation:\nCreates and invokes a [stable_swap_client::instruction::unpause] instruction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unpause<'a, 'b, 'c, 'info>(\n ctx: CpiContext<'a, 'b, 'c, 'info, AdminUserContext<'info>>,\n) -> Result<()> {\n let ix =\n stable_swap_client::instruction::unpause(ctx.accounts.swap.key, ctx.accounts.admin.key)?;\n solana_program::program::invoke_signed(&ix, &ctx.to_account_infos(), ctx.signer_seeds)?;\n Ok(())\n}\n```"}], "func_name": "unpause", "docstring": "Creates and invokes a [stable_swap_client::instruction::unpause] instruction.", "repo": "saber-hq/stable-swap", "path": "stable-swap-anchor/src/instructions.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-anchor/src/instructions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e7943d402fe14c250c846db6087414c322e9beaefcea9e4811e62b35cf825d7c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_new_fees\n\nDocumentation:\nCreates and invokes a [stable_swap_client::instruction::set_new_fees] instruction.\n\n# Arguments\n\n* `fees` - new [`stable_swap_client::fees::Fees`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_new_fees<'a, 'b, 'c, 'info>(\n ctx: CpiContext<'a, 'b, 'c, 'info, AdminUserContext<'info>>,\n fees: stable_swap_client::fees::Fees,\n) -> Result<()> {\n let ix = stable_swap_client::instruction::set_new_fees(\n ctx.accounts.swap.key,\n ctx.accounts.admin.key,\n fees,\n )?;\n solana_program::program::invoke_signed(&ix, &ctx.to_account_infos(), ctx.signer_seeds)?;\n Ok(())\n}\n```"}], "func_name": "set_new_fees", "docstring": "Creates and invokes a [stable_swap_client::instruction::set_new_fees] instruction.\n\n# Arguments\n\n* `fees` - new [`stable_swap_client::fees::Fees`].", "repo": "saber-hq/stable-swap", "path": "stable-swap-anchor/src/instructions.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-anchor/src/instructions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "832c7ecfda76538ceede907265894940eb20b3d237486f5ba98d745dfef2f49e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unpack\n\nDocumentation:\nUnpacks a byte buffer into a [AdminInstruction](enum.AdminInstruction.html).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unpack(input: &[u8]) -> Result, ProgramError> {\n let (&tag, rest) = input.split_first().ok_or(SwapError::InvalidInstruction)?;\n Ok(match tag {\n 100 => {\n let (target_amp, rest) = unpack_u64(rest)?;\n let (stop_ramp_ts, _rest) = unpack_i64(rest)?;\n Some(Self::RampA(RampAData {\n target_amp,\n stop_ramp_ts,\n }))\n }\n 101 => Some(Self::StopRampA),\n 102 => Some(Self::Pause),\n 103 => Some(Self::Unpause),\n 104 => Some(Self::SetFeeAccount),\n 105 => Some(Self::ApplyNewAdmin),\n 106 => Some(Self::CommitNewAdmin),\n 107 => {\n let fees = Fees::unpack_unchecked(rest)?;\n Some(Self::SetNewFees(fees))\n }\n _ => None,\n })\n }\n```"}], "func_name": "unpack", "docstring": "Unpacks a byte buffer into a [AdminInstruction](enum.AdminInstruction.html).", "repo": "saber-hq/stable-swap", "path": "stable-swap-client/src/instruction.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-client/src/instruction.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "23c167ff6b6b3b1605436388548958c325ab1badada27e56b4132efd0329035e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pack\n\nDocumentation:\nPacks a [AdminInstruction](enum.AdminInstruction.html) into a byte buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pack(&self) -> Vec {\n let mut buf = Vec::with_capacity(size_of::());\n match *self {\n Self::RampA(RampAData {\n target_amp,\n stop_ramp_ts,\n }) => {\n buf.push(100);\n buf.extend_from_slice(&target_amp.to_le_bytes());\n buf.extend_from_slice(&stop_ramp_ts.to_le_bytes());\n }\n Self::StopRampA => buf.push(101),\n Self::Pause => buf.push(102),\n Self::Unpause => buf.push(103),\n Self::SetFeeAccount => buf.push(104),\n Self::ApplyNewAdmin => buf.push(105),\n Self::CommitNewAdmin => buf.push(106),\n Self::SetNewFees(fees) => {\n buf.push(107);\n let mut fees_slice = [0u8; Fees::LEN];\n Pack::pack_into_slice(&fees, &mut fees_slice[..]);\n buf.extend_from_slice(&fees_slice);\n }\n }\n buf\n }\n```"}], "func_name": "pack", "docstring": "Packs a [AdminInstruction](enum.AdminInstruction.html) into a byte buffer.", "repo": "saber-hq/stable-swap", "path": "stable-swap-client/src/instruction.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-client/src/instruction.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7950409b87fcc9ae91dbfa6cf7250fe4747971064ab7dceab5707df407d7da47"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unpack\n\nDocumentation:\nUnpacks a byte buffer into a [SwapInstruction](enum.SwapInstruction.html).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unpack(input: &[u8]) -> Result {\n let (&tag, rest) = input.split_first().ok_or(SwapError::InvalidInstruction)?;\n Ok(match tag {\n 0 => {\n let (&nonce, rest) = rest.split_first().ok_or(SwapError::InvalidInstruction)?;\n let (amp_factor, rest) = unpack_u64(rest)?;\n let fees = Fees::unpack_unchecked(rest)?;\n Self::Initialize(InitializeData {\n nonce,\n amp_factor,\n fees,\n })\n }\n 1 => {\n let (amount_in, rest) = unpack_u64(rest)?;\n let (minimum_amount_out, _rest) = unpack_u64(rest)?;\n Self::Swap(SwapData {\n amount_in,\n minimum_amount_out,\n })\n }\n 2 => {\n let (token_a_amount, rest) = unpack_u64(rest)?;\n let (token_b_amount, rest) = unpack_u64(rest)?;\n let (min_mint_amount, _rest) = unpack_u64(rest)?;\n Self::Deposit(DepositData {\n token_a_amount,\n token_b_amount,\n min_mint_amount,\n })\n }\n 3 => {\n let (pool_token_amount, rest) = unpack_u64(rest)?;\n let (minimum_token_a_amount, rest) = unpack_u64(rest)?;\n let (minimum_token_b_amount, _rest) = unpack_u64(rest)?;\n Self::Withdraw(WithdrawData {\n pool_token_amount,\n minimum_token_a_amount,\n minimum_token_b_amount,\n })\n }\n 4 => {\n let (pool_token_amount, rest) = unpack_u64(rest)?;\n let (minimum_token_amount, _rest) = unpack_u64(rest)?;\n Self::WithdrawOne(WithdrawOneData {\n pool_token_amount,\n minimum_token_amount,\n })\n }\n _ => return Err(SwapError::InvalidInstruction.into()),\n })\n }\n```"}], "func_name": "unpack", "docstring": "Unpacks a byte buffer into a [SwapInstruction](enum.SwapInstruction.html).", "repo": "saber-hq/stable-swap", "path": "stable-swap-client/src/instruction.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-client/src/instruction.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "79000bf56e166eec8b419211d1064b081a549c9ec78df91cc6461f3d2268616a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pack\n\nDocumentation:\nPacks a [SwapInstruction](enum.SwapInstruction.html) into a byte buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pack(&self) -> Vec {\n let mut buf = Vec::with_capacity(size_of::());\n match *self {\n Self::Initialize(InitializeData {\n nonce,\n amp_factor,\n fees,\n }) => {\n buf.push(0);\n buf.push(nonce);\n buf.extend_from_slice(&_factor.to_le_bytes());\n let mut fees_slice = [0u8; Fees::LEN];\n Pack::pack_into_slice(&fees, &mut fees_slice[..]);\n buf.extend_from_slice(&fees_slice);\n }\n Self::Swap(SwapData {\n amount_in,\n minimum_amount_out,\n }) => {\n buf.push(1);\n buf.extend_from_slice(&amount_in.to_le_bytes());\n buf.extend_from_slice(&minimum_amount_out.to_le_bytes());\n }\n Self::Deposit(DepositData {\n token_a_amount,\n token_b_amount,\n min_mint_amount,\n }) => {\n buf.push(2);\n buf.extend_from_slice(&token_a_amount.to_le_bytes());\n buf.extend_from_slice(&token_b_amount.to_le_bytes());\n buf.extend_from_slice(&min_mint_amount.to_le_bytes());\n }\n Self::Withdraw(WithdrawData {\n pool_token_amount,\n minimum_token_a_amount,\n minimum_token_b_amount,\n }) => {\n buf.push(3);\n buf.extend_from_slice(&pool_token_amount.to_le_bytes());\n buf.extend_from_slice(&minimum_token_a_amount.to_le_bytes());\n buf.extend_from_slice(&minimum_token_b_amount.to_le_bytes());\n }\n Self::WithdrawOne(WithdrawOneData {\n pool_token_amount,\n minimum_token_amount,\n }) => {\n buf.push(4);\n buf.extend_from_slice(&pool_token_amount.to_le_bytes());\n buf.extend_from_slice(&minimum_token_amount.to_le_bytes());\n }\n }\n buf\n }\n```"}], "func_name": "pack", "docstring": "Packs a [SwapInstruction](enum.SwapInstruction.html) into a byte buffer.", "repo": "saber-hq/stable-swap", "path": "stable-swap-client/src/instruction.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-client/src/instruction.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9ef8ca0f9b395a1e2626e4cc3e1f58df553e6d9db714ca4002fc25436b2792b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unpack_from_slice\n\nDocumentation:\nUnpacks a byte buffer into a [SwapInfo](struct.SwapInfo.html).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn unpack_from_slice(input: &[u8]) -> Result {\n let input = array_ref![input, 0, 395];\n #[allow(clippy::ptr_offset_with_cast)]\n let (\n is_initialized,\n is_paused,\n nonce,\n initial_amp_factor,\n target_amp_factor,\n start_ramp_ts,\n stop_ramp_ts,\n future_admin_deadline,\n future_admin_key,\n admin_key,\n token_a,\n token_b,\n pool_mint,\n token_a_mint,\n token_b_mint,\n admin_fee_key_a,\n admin_fee_key_b,\n fees,\n ) = array_refs![input, 1, 1, 1, 8, 8, 8, 8, 8, 32, 32, 32, 32, 32, 32, 32, 32, 32, 64];\n Ok(Self {\n is_initialized: match is_initialized {\n [0] => false,\n [1] => true,\n _ => return Err(ProgramError::InvalidAccountData),\n },\n is_paused: match is_paused {\n [0] => false,\n [1] => true,\n _ => return Err(ProgramError::InvalidAccountData),\n },\n nonce: nonce[0],\n initial_amp_factor: u64::from_le_bytes(*initial_amp_factor),\n target_amp_factor: u64::from_le_bytes(*target_amp_factor),\n start_ramp_ts: i64::from_le_bytes(*start_ramp_ts),\n stop_ramp_ts: i64::from_le_bytes(*stop_ramp_ts),\n future_admin_deadline: i64::from_le_bytes(*future_admin_deadline),\n future_admin_key: Pubkey::new_from_array(*future_admin_key),\n admin_key: Pubkey::new_from_array(*admin_key),\n token_a: SwapTokenInfo {\n reserves: Pubkey::new_from_array(*token_a),\n mint: Pubkey::new_from_array(*token_a_mint),\n admin_fees: Pubkey::new_from_array(*admin_fee_key_a),\n index: 0,\n },\n token_b: SwapTokenInfo {\n reserves: Pubkey::new_from_array(*token_b),\n mint: Pubkey::new_from_array(*token_b_mint),\n admin_fees: Pubkey::new_from_array(*admin_fee_key_b),\n index: 1,\n },\n pool_mint: Pubkey::new_from_array(*pool_mint),\n fees: Fees::unpack_from_slice(fees)?,\n })\n }\n```"}], "func_name": "unpack_from_slice", "docstring": "Unpacks a byte buffer into a [SwapInfo](struct.SwapInfo.html).", "repo": "saber-hq/stable-swap", "path": "stable-swap-client/src/state.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-client/src/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "77f1db808990d080ab65f446c4bfd35dae1d698117d8a43fd53157c6dec1bcb7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compute_amp_factor\n\nDocumentation:\nCompute the amplification coefficient (A).\n\nThe amplification coefficient is used to determine the slippage incurred when\nperforming swaps. The lower it is, the closer the invariant is to the constant product[^stableswap].\n\nThe amplication coefficient linearly increases with respect to time,\nbased on the [`SwapInfo::start_ramp_ts`] and [`SwapInfo::stop_ramp_ts`] parameters.\n\n[^stableswap]: [Egorov, \"StableSwap,\" 2019.](https://curve.fi/files/stableswap-paper.pdf)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compute_amp_factor(&self) -> Option {\n if self.current_ts < self.stop_ramp_ts {\n let time_range = self.stop_ramp_ts.checked_sub(self.start_ramp_ts)?;\n let time_delta = self.current_ts.checked_sub(self.start_ramp_ts)?;\n\n // Compute amp factor based on ramp time\n if self.target_amp_factor >= self.initial_amp_factor {\n // Ramp up\n let amp_range = self\n .target_amp_factor\n .checked_sub(self.initial_amp_factor)?;\n let amp_delta = (amp_range as u128)\n .checked_mul(time_delta.to_u128()?)?\n .checked_div(time_range.to_u128()?)?\n .to_u64()?;\n self.initial_amp_factor.checked_add(amp_delta)\n } else {\n // Ramp down\n let amp_range = self\n .initial_amp_factor\n .checked_sub(self.target_amp_factor)?;\n let amp_delta = (amp_range as u128)\n .checked_mul(time_delta.to_u128()?)?\n .checked_div(time_range.to_u128()?)?\n .to_u64()?;\n self.initial_amp_factor.checked_sub(amp_delta)\n }\n } else {\n // when stop_ramp_ts == 0 or current_ts >= stop_ramp_ts\n Some(self.target_amp_factor)\n }\n }\n```"}], "func_name": "compute_amp_factor", "docstring": "Compute the amplification coefficient (A).\n\nThe amplification coefficient is used to determine the slippage incurred when\nperforming swaps. The lower it is, the closer the invariant is to the constant product[^stableswap].\n\nThe amplication coefficient linearly increases with respect to time,\nbased on the [`SwapInfo::start_ramp_ts`] and [`SwapInfo::stop_ramp_ts`] parameters.\n\n[^stableswap]: [Egorov, \"StableSwap,\" 2019.](https://curve.fi/files/stableswap-paper.pdf)", "repo": "saber-hq/stable-swap", "path": "stable-swap-math/src/curve.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-math/src/curve.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e7a92aec2cc814b411751e99139fab7ce1cc480d6dd503575f4060440c67d302"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compute_d\n\nDocumentation:\nComputes the Stable Swap invariant (D).\n\nThe invariant is defined as follows:\n\n```text\nA * sum(x_i) * n**n + D = A * D * n**n + D**(n+1) / (n**n * prod(x_i))\n```\n\n# Arguments\n\n- `amount_a` - The amount of token A owned by the LP pool. (i.e. token A reserves)\n- `amount_b` - The amount of token B owned by the LP pool. (i.e. token B reserves)\n\n*For more info on reserves, see [stable_swap_client::state::SwapTokenInfo::reserves].*\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compute_d(&self, amount_a: u64, amount_b: u64) -> Option {\n let sum_x = amount_a.checked_add(amount_b)?; // sum(x_i), a.k.a S\n if sum_x == 0 {\n Some(0.into())\n } else {\n let amp_factor = self.compute_amp_factor()?;\n let amount_a_times_coins = amount_a.checked_mul(N_COINS.into())?;\n let amount_b_times_coins = amount_b.checked_mul(N_COINS.into())?;\n\n // Newton's method to approximate D\n let mut d_prev: U192;\n let mut d: U192 = sum_x.into();\n for _ in 0..256 {\n let mut d_prod = d;\n d_prod = d_prod\n .checked_mul(d)?\n .checked_div(amount_a_times_coins.into())?;\n d_prod = d_prod\n .checked_mul(d)?\n .checked_div(amount_b_times_coins.into())?;\n d_prev = d;\n d = self.compute_next_d(amp_factor, d, d_prod, sum_x)?;\n // Equality with the precision of 1\n if d > d_prev {\n if d.checked_sub(d_prev)? <= 1.into() {\n break;\n }\n } else if d_prev.checked_sub(d)? <= 1.into() {\n break;\n }\n }\n\n Some(d)\n }\n }\n```"}], "func_name": "compute_d", "docstring": "Computes the Stable Swap invariant (D).\n\nThe invariant is defined as follows:\n\n```text\nA * sum(x_i) * n**n + D = A * D * n**n + D**(n+1) / (n**n * prod(x_i))\n```\n\n# Arguments\n\n- `amount_a` - The amount of token A owned by the LP pool. (i.e. token A reserves)\n- `amount_b` - The amount of token B owned by the LP pool. (i.e. token B reserves)\n\n*For more info on reserves, see [stable_swap_client::state::SwapTokenInfo::reserves].*", "repo": "saber-hq/stable-swap", "path": "stable-swap-math/src/curve.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-math/src/curve.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac2bbd560f319684c3ba60c648c642ec82109dddb46885dc81d8b1f4c8eb4a0b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compute_mint_amount_for_deposit\n\nDocumentation:\nComputes the amount of pool tokens to mint after a deposit.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compute_mint_amount_for_deposit(\n &self,\n deposit_amount_a: u64,\n deposit_amount_b: u64,\n swap_amount_a: u64,\n swap_amount_b: u64,\n pool_token_supply: u64,\n fees: &Fees,\n ) -> Option {\n // Initial invariant\n let d_0 = self.compute_d(swap_amount_a, swap_amount_b)?;\n let old_balances = [swap_amount_a, swap_amount_b];\n let mut new_balances = [\n swap_amount_a.checked_add(deposit_amount_a)?,\n swap_amount_b.checked_add(deposit_amount_b)?,\n ];\n // Invariant after change\n let d_1 = self.compute_d(new_balances[0], new_balances[1])?;\n if d_1 <= d_0 {\n None\n } else {\n // Recalculate the invariant accounting for fees\n for i in 0..new_balances.len() {\n let ideal_balance = d_1\n .checked_mul(old_balances[i].into())?\n .checked_div(d_0)?\n .to_u64()?;\n let difference = if ideal_balance > new_balances[i] {\n ideal_balance.checked_sub(new_balances[i])?\n } else {\n new_balances[i].checked_sub(ideal_balance)?\n };\n let fee = fees.normalized_trade_fee(N_COINS, difference)?;\n new_balances[i] = new_balances[i].checked_sub(fee)?;\n }\n\n let d_2 = self.compute_d(new_balances[0], new_balances[1])?;\n U192::from(pool_token_supply)\n .checked_mul(d_2.checked_sub(d_0)?)?\n .checked_div(d_0)?\n .to_u64()\n }\n }\n```"}], "func_name": "compute_mint_amount_for_deposit", "docstring": "Computes the amount of pool tokens to mint after a deposit.", "repo": "saber-hq/stable-swap", "path": "stable-swap-math/src/curve.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-math/src/curve.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b2f9d60771d6a8024659dcf77c693e7a28e71c21cbf68f745587d1fe1d7d429c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compute_y\n\nDocumentation:\nComputes the swap amount `y` in proportion to `x`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compute_y(&self, x: u64, d: U192) -> Option {\n self.compute_y_raw(x, d)?.to_u64()\n }\n```"}], "func_name": "compute_y", "docstring": "Computes the swap amount `y` in proportion to `x`.", "repo": "saber-hq/stable-swap", "path": "stable-swap-math/src/curve.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-math/src/curve.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a39e179e11259d96c853c64fec8d40283403d9309b460aa01a708bda2bebc0a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compute_withdraw_one\n\nDocumentation:\nCalculates the withdrawal amount when withdrawing only one type of token.\n\nCalculation:\n\n1. Get current D\n2. Solve Eqn against `y_i` for `D - _token_amount`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compute_withdraw_one(\n &self,\n pool_token_amount: u64,\n pool_token_supply: u64,\n swap_base_amount: u64, // Same denomination of token to be withdrawn\n swap_quote_amount: u64, // Counter denomination of token to be withdrawn\n fees: &Fees,\n ) -> Option<(u64, u64)> {\n let d_0 = self.compute_d(swap_base_amount, swap_quote_amount)?;\n let d_1 = d_0.checked_sub(\n U192::from(pool_token_amount)\n .checked_mul(d_0)?\n .checked_div(pool_token_supply.into())?,\n )?;\n let new_y = self.compute_y(swap_quote_amount, d_1)?;\n\n // expected_base_amount = swap_base_amount * d_1 / d_0 - new_y;\n let expected_base_amount = U192::from(swap_base_amount)\n .checked_mul(d_1)?\n .checked_div(d_0)?\n .to_u64()?\n .checked_sub(new_y)?;\n // expected_quote_amount = swap_quote_amount - swap_quote_amount * d_1 / d_0;\n let expected_quote_amount = swap_quote_amount.checked_sub(\n U192::from(swap_quote_amount)\n .checked_mul(d_1)?\n .checked_div(d_0)?\n .to_u64()?,\n )?;\n // new_base_amount = swap_base_amount - expected_base_amount * fee / fee_denominator;\n let new_base_amount = swap_base_amount\n .checked_sub(fees.normalized_trade_fee(N_COINS, expected_base_amount)?)?;\n // new_quote_amount = swap_quote_amount - expected_quote_amount * fee / fee_denominator;\n let new_quote_amount = swap_quote_amount\n .checked_sub(fees.normalized_trade_fee(N_COINS, expected_quote_amount)?)?;\n let dy = new_base_amount\n .checked_sub(self.compute_y(new_quote_amount, d_1)?)?\n .checked_sub(1)?; // Withdraw less to account for rounding errors\n let dy_0 = swap_base_amount.checked_sub(new_y)?;\n\n Some((dy, dy_0.checked_sub(dy)?))\n }\n```"}], "func_name": "compute_withdraw_one", "docstring": "Calculates the withdrawal amount when withdrawing only one type of token.\n\nCalculation:\n\n1. Get current D\n2. Solve Eqn against `y_i` for `D - _token_amount`", "repo": "saber-hq/stable-swap", "path": "stable-swap-math/src/curve.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-math/src/curve.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f063b948bda47b2e9f903db3da879f0bba5bf079e345c2a4260ac633023732f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: normalized_trade_fee\n\nDocumentation:\nCompute normalized fee for symmetric/asymmetric deposits/withdraws\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn normalized_trade_fee(&self, n_coins: u8, amount: u64) -> Option {\n // adjusted_fee_numerator: uint256 = self.fee * N_COINS / (4 * (N_COINS - 1))\n // The number 4 comes from Curve, originating from some sort of calculus\n // https://github.com/curvefi/curve-contract/blob/e5fb8c0e0bcd2fe2e03634135806c0f36b245511/tests/simulation.py#L124\n let adjusted_trade_fee_numerator = mul_div(\n self.trade_fee_numerator,\n n_coins.into(),\n (n_coins.checked_sub(1)?).checked_mul(4)?.into(),\n )?;\n\n mul_div(\n amount,\n adjusted_trade_fee_numerator,\n self.trade_fee_denominator,\n )\n }\n```"}], "func_name": "normalized_trade_fee", "docstring": "Compute normalized fee for symmetric/asymmetric deposits/withdraws", "repo": "saber-hq/stable-swap", "path": "stable-swap-math/src/math.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-math/src/math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b934db820d66a7b13ffd40333527cde645e38b011c124245f66b77eaca4f2ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: token_a_rate\n\nDocumentation:\nComputes the amount of token A backing the given amount of pool tokens.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn token_a_rate(&self, pool_tokens: u64) -> Option<(u64, u64, u64)> {\n let amount = (pool_tokens as u128)\n .checked_mul(self.token_a as u128)?\n .checked_div(self.supply as u128)?\n .to_u64()?;\n let fee = self.fees.withdraw_fee(amount)?;\n let admin_fee = self.fees.admin_withdraw_fee(fee)?;\n\n Some((amount.checked_sub(fee)?, fee, admin_fee))\n }\n```"}], "func_name": "token_a_rate", "docstring": "Computes the amount of token A backing the given amount of pool tokens.", "repo": "saber-hq/stable-swap", "path": "stable-swap-math/src/pool_converter.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-math/src/pool_converter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fe3b665ea910ed6d1886296ae5a9066ecc9d575e315ba61bc85df49b4eb96b36"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: token_b_rate\n\nDocumentation:\nComputes the amount of token B backing the given amount of pool tokens.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn token_b_rate(&self, pool_tokens: u64) -> Option<(u64, u64, u64)> {\n let amount = (pool_tokens as u128)\n .checked_mul(self.token_b as u128)?\n .checked_div(self.supply as u128)?\n .to_u64()?;\n let fee = self.fees.withdraw_fee(amount)?;\n let admin_fee = self.fees.admin_withdraw_fee(fee)?;\n\n Some((amount.checked_sub(fee)?, fee, admin_fee))\n }\n```"}], "func_name": "token_b_rate", "docstring": "Computes the amount of token B backing the given amount of pool tokens.", "repo": "saber-hq/stable-swap", "path": "stable-swap-math/src/pool_converter.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-math/src/pool_converter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b4c2f132b465e58ee50d4d1ac20d4c7ea237fbfcdbea201d90efb50c6c51e024"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lp_tokens_for_a_excluding_fees\n\nDocumentation:\nCalculates the number of LP tokens that correspond to an amount of token A.\nThis does not take withdraw fees into account.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn lp_tokens_for_a_excluding_fees(&self, token_a_amount: u64) -> Option {\n (token_a_amount as u128)\n .checked_mul(self.supply as u128)?\n .checked_div(self.token_a as u128)?\n .to_u64()\n }\n```"}], "func_name": "lp_tokens_for_a_excluding_fees", "docstring": "Calculates the number of LP tokens that correspond to an amount of token A.\nThis does not take withdraw fees into account.", "repo": "saber-hq/stable-swap", "path": "stable-swap-math/src/pool_converter.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-math/src/pool_converter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5e6f34a9d04baaf332543609c59516d0b8b39ee35de38f79c89713ff273b1d05"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lp_tokens_for_b_excluding_fees\n\nDocumentation:\nCalculates the number of LP tokens that correspond to an amount of token B.\nThis does not take withdraw fees into account.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn lp_tokens_for_b_excluding_fees(&self, token_b_amount: u64) -> Option {\n (token_b_amount as u128)\n .checked_mul(self.supply as u128)?\n .checked_div(self.token_b as u128)?\n .to_u64()\n }\n```"}], "func_name": "lp_tokens_for_b_excluding_fees", "docstring": "Calculates the number of LP tokens that correspond to an amount of token B.\nThis does not take withdraw fees into account.", "repo": "saber-hq/stable-swap", "path": "stable-swap-math/src/pool_converter.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-math/src/pool_converter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c617c1aefea1e853d99a543cc8413dd214cf1af38f4bf90e0380e6ca2b1807f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: calculate_pool_tokens_from_virtual_amount\n\nDocumentation:\nCalculates the amount of pool tokens represented by the given amount of virtual tokens.\n\nA virtual token is the denomination of virtual price. For example, if there is a virtual price of 1.04\non USDC-USDT LP, then 1 virtual token maps to 1/1.04 USDC-USDT LP tokens.\n\nThis is useful for building assets that are backed by LP tokens.\nAn example of this is [Cashio](https://github.com/CashioApp/cashio), which\nallows users to mint $CASH tokens based on the virtual price of underlying LP tokens.\n\n# Arguments\n\n- `virtual_amount` - The number of \"virtual\" underlying tokens.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn calculate_pool_tokens_from_virtual_amount(&self, virtual_amount: u64) -> Option {\n U192::from(virtual_amount)\n .checked_mul(self.lp_mint_supply.into())?\n .checked_div(self.compute_d()?)?\n .to_u64()\n }\n```"}], "func_name": "calculate_pool_tokens_from_virtual_amount", "docstring": "Calculates the amount of pool tokens represented by the given amount of virtual tokens.\n\nA virtual token is the denomination of virtual price. For example, if there is a virtual price of 1.04\non USDC-USDT LP, then 1 virtual token maps to 1/1.04 USDC-USDT LP tokens.\n\nThis is useful for building assets that are backed by LP tokens.\nAn example of this is [Cashio](https://github.com/CashioApp/cashio), which\nallows users to mint $CASH tokens based on the virtual price of underlying LP tokens.\n\n# Arguments\n\n- `virtual_amount` - The number of \"virtual\" underlying tokens.", "repo": "saber-hq/stable-swap", "path": "stable-swap-math/src/price.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-math/src/price.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0b9295b19425c24672765d72178eda09c8baf130cee2b6e0f32650a39786ee52"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: calculate_virtual_price_of_pool_tokens\n\nDocumentation:\nCalculates the virtual price of the given amount of pool tokens.\n\nThe virtual price is defined as the current price of the pool LP token\nrelative to the underlying pool assets.\n\nThe virtual price in the StableSwap algorithm is obtained through taking the invariance\nof the pool, which by default takes every token as valued at 1.00 of the underlying.\nYou can get the virtual price of each pool by calling this function\nfor it.[^chainlink]\n\n[^chainlink]: Source: \n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn calculate_virtual_price_of_pool_tokens(&self, pool_token_amount: u64) -> Option {\n self.compute_d()?\n .checked_mul(pool_token_amount.into())?\n .checked_div(self.lp_mint_supply.into())?\n .to_u64()\n }\n```"}], "func_name": "calculate_virtual_price_of_pool_tokens", "docstring": "Calculates the virtual price of the given amount of pool tokens.\n\nThe virtual price is defined as the current price of the pool LP token\nrelative to the underlying pool assets.\n\nThe virtual price in the StableSwap algorithm is obtained through taking the invariance\nof the pool, which by default takes every token as valued at 1.00 of the underlying.\nYou can get the virtual price of each pool by calling this function\nfor it.[^chainlink]\n\n[^chainlink]: Source: ", "repo": "saber-hq/stable-swap", "path": "stable-swap-math/src/price.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-math/src/price.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "49741f7ec2e3ea2db4b01723322029c4ac685fd41ee455e884792a951c80b4fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compute_d\n\nDocumentation:\nComputes D, which is the virtual price times the total supply of the pool.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compute_d(&self) -> Option {\n let calculator = StableSwap::from(self);\n calculator.compute_d(self.token_a_reserve, self.token_b_reserve)\n }\n```"}], "func_name": "compute_d", "docstring": "Computes D, which is the virtual price times the total supply of the pool.", "repo": "saber-hq/stable-swap", "path": "stable-swap-math/src/price.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-math/src/price.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e50e47dee025a07ef61295b32ef7c19a2b21f0b014f5d6dc28c05e74cce8775"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: apply_new_admin\n\nDocumentation:\nApply new admin (finalize admin transfer)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn apply_new_admin(token_swap: &mut SwapInfo) -> ProgramResult {\n if token_swap.future_admin_deadline == ZERO_TS {\n return Err(SwapError::NoActiveTransfer.into());\n }\n let clock = Clock::get()?;\n if clock.unix_timestamp > token_swap.future_admin_deadline {\n return Err(SwapError::AdminDeadlineExceeded.into());\n }\n\n msg!(\"Admin: old admin {}\", token_swap.admin_key);\n token_swap.admin_key = token_swap.future_admin_key;\n token_swap.future_admin_key = Pubkey::default();\n token_swap.future_admin_deadline = ZERO_TS;\n msg!(\"Admin: Finalized new admin {}\", token_swap.admin_key);\n Ok(())\n}\n```"}], "func_name": "apply_new_admin", "docstring": "Apply new admin (finalize admin transfer)", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/admin.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/admin.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "02544c2314372de2c5961114ff57ae0aaeeef6f2ed56a7113e451dec4695df7a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_reserves_match\n\nDocumentation:\nChecks if the reserve of the swap is the given key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_reserves_match(token: &SwapTokenInfo, reserves_info_key: &Pubkey) -> ProgramResult {\n check_token_keys_equal!(\n token,\n *reserves_info_key,\n token.reserves,\n \"Reserves\",\n SwapError::IncorrectSwapAccount\n );\n Ok(())\n}\n```"}], "func_name": "check_reserves_match", "docstring": "Checks if the reserve of the swap is the given key.", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/checks.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/checks.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "641784a2575d41fe246a2e81484d26f4d4eaaeed9c877c9bb35fc1fdbc50a3dd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_has_admin_signer\n\nDocumentation:\nAccess control for admin only instructions\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check_has_admin_signer(\n expected_admin_key: &Pubkey,\n admin_account_info: &AccountInfo,\n) -> ProgramResult {\n check_keys_equal!(\n *expected_admin_key,\n *admin_account_info.key,\n \"Admin signer\",\n SwapError::Unauthorized\n );\n if !admin_account_info.is_signer {\n return Err(ProgramError::MissingRequiredSignature);\n }\n Ok(())\n}\n```"}], "func_name": "check_has_admin_signer", "docstring": "Access control for admin only instructions", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/checks.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/checks.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48cc4380c85d90b7aed133366b0588267c579bc31d7ca4fd0e28272201454e73"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_withdraw_token_accounts\n\nDocumentation:\nChecks that the withdraw token accounts are correct.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check_withdraw_token_accounts(\n token: &SwapTokenInfo,\n reserves_info_key: &Pubkey,\n admin_fee_dest_key: &Pubkey,\n) -> ProgramResult {\n check_reserves_match(token, reserves_info_key)?;\n check_keys_equal!(\n *admin_fee_dest_key,\n token.admin_fees,\n \"Admin fee dest\",\n SwapError::InvalidAdmin\n );\n Ok(())\n}\n```"}], "func_name": "check_withdraw_token_accounts", "docstring": "Checks that the withdraw token accounts are correct.", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/checks.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/checks.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3730829337e108bd81d3f9bb8ccdbc2024715d163c357c027b073305356c2633"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_swap_token_destination_accounts\n\nDocumentation:\nChecks that the destination of the swap has the correct accounts.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check_swap_token_destination_accounts(\n token: &SwapTokenInfo,\n swap_destination_info_key: &Pubkey,\n admin_destination_info_key: &Pubkey,\n) -> ProgramResult {\n check_keys_equal!(\n *swap_destination_info_key,\n token.reserves,\n \"Incorrect destination, expected\",\n SwapError::IncorrectSwapAccount\n );\n check_keys_equal!(\n *admin_destination_info_key,\n token.admin_fees,\n \"Admin fee\",\n SwapError::InvalidAdmin\n );\n Ok(())\n}\n```"}], "func_name": "check_swap_token_destination_accounts", "docstring": "Checks that the destination of the swap has the correct accounts.", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/checks.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/checks.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94c1dc184208f202401c8e506a3db47457086d36f495aa706712d3751ca46277"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process\n\nDocumentation:\nProcesses an [Instruction](enum.Instruction.html).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn process(program_id: &Pubkey, accounts: &[AccountInfo], input: &[u8]) -> ProgramResult {\n let instruction = AdminInstruction::unpack(input)?;\n match instruction {\n None => swap::process_swap_instruction(program_id, accounts, input),\n Some(admin_instruction) => {\n admin::process_admin_instruction(&admin_instruction, accounts)\n }\n }\n }\n```"}], "func_name": "process", "docstring": "Processes an [Instruction](enum.Instruction.html).", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/mod.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3288b08b73ecd160ad59d26ec92865cb43fd0a44d462d7d9cdceb99e00b99218"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_initialize\n\nDocumentation:\nProcesses an [Initialize](enum.Instruction.html).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_initialize(\n program_id: &Pubkey,\n nonce: u8,\n amp_factor: u64,\n fees: Fees,\n accounts: &[AccountInfo],\n) -> ProgramResult {\n let account_info_iter = &mut accounts.iter();\n let swap_info = next_account_info(account_info_iter)?;\n let authority_info = next_account_info(account_info_iter)?;\n let admin_key_info = next_account_info(account_info_iter)?;\n let admin_fee_a_info = next_account_info(account_info_iter)?;\n let admin_fee_b_info = next_account_info(account_info_iter)?;\n let token_a_mint_info = next_account_info(account_info_iter)?;\n let token_a_info = next_account_info(account_info_iter)?;\n let token_b_mint_info = next_account_info(account_info_iter)?;\n let token_b_info = next_account_info(account_info_iter)?;\n let pool_mint_info = next_account_info(account_info_iter)?;\n let destination_info = next_account_info(account_info_iter)?; // Destination account to mint LP tokens to\n let token_program_info = next_account_info(account_info_iter)?;\n\n if !(MIN_AMP..=MAX_AMP).contains(&_factor) {\n msg!(\"Invalid amp factor: {}\", amp_factor);\n return Err(SwapError::InvalidInput.into());\n }\n\n let token_swap = SwapInfo::unpack_unchecked(&swap_info.data.borrow())?;\n if token_swap.is_initialized {\n return Err(SwapError::AlreadyInUse.into());\n }\n let swap_authority = utils::authority_id(program_id, swap_info.key, nonce)?;\n check_keys_equal!(\n *authority_info.key,\n swap_authority,\n \"Swap authority\",\n SwapError::InvalidProgramAddress\n );\n\n let destination = utils::unpack_token_account(&destination_info.data.borrow())?;\n let token_a = utils::unpack_token_account(&token_a_info.data.borrow())?;\n let token_b = utils::unpack_token_account(&token_b_info.data.borrow())?;\n\n check_keys_equal!(\n *authority_info.key,\n token_a.owner,\n \"Token A authority\",\n SwapError::InvalidOwner\n );\n check_keys_equal!(\n *authority_info.key,\n token_b.owner,\n \"Token B authority\",\n SwapError::InvalidOwner\n );\n check_keys_not_equal!(\n *authority_info.key,\n destination.owner,\n \"Initial LP destination authority\",\n SwapError::InvalidOutputOwner\n );\n\n if token_a.mint == token_b.mint {\n return Err(SwapError::RepeatedMint.into());\n }\n if token_b.amount == 0 {\n return Err(SwapError::EmptySupply.into());\n }\n if token_a.amount == 0 {\n return Err(SwapError::EmptySupply.into());\n }\n if token_a.delegate.is_some() {\n return Err(SwapError::InvalidDelegate.into());\n }\n if token_b.delegate.is_some() {\n return Err(SwapError::InvalidDelegate.into());\n }\n check_keys_equal!(\n token_a.mint,\n *token_a_mint_info.key,\n \"Mint A\",\n SwapError::IncorrectMint\n );\n check_keys_equal!(\n token_b.mint,\n *token_b_mint_info.key,\n \"Mint B\",\n SwapError::IncorrectMint\n );\n if token_a.close_authority.is_some() {\n return Err(SwapError::InvalidCloseAuthority.into());\n }\n if token_b.close_authority.is_some() {\n return Err(SwapError::InvalidCloseAuthority.into());\n }\n let pool_mint = utils::unpack_mint(&pool_mint_info.data.borrow())?;\n check_keys_equal_optional!(\n pool_mint.mint_authority,\n COption::Some(*authority_info.key),\n \"LP mint authority\",\n SwapError::InvalidOwner\n );\n if pool_mint.freeze_authority.is_some() {\n return Err(SwapError::InvalidFreezeAuthority.into());\n }\n if pool_mint.supply != 0 {\n return Err(SwapError::InvalidSupply.into());\n }\n let token_a_mint = utils::unpack_mint(&token_a_mint_info.data.borrow())?;\n let token_b_mint = utils::unpack_mint(&token_b_mint_info.data.borrow())?;\n if token_a_mint.decimals != token_b_mint.decimals {\n return Err(SwapError::MismatchedDecimals.into());\n }\n if pool_mint.decimals != token_a_mint.decimals {\n return Err(SwapError::MismatchedDecimals.into());\n }\n let admin_fee_key_a = utils::unpack_token_account(&admin_fee_a_info.data.borrow())?;\n let admin_fee_key_b = utils::unpack_token_account(&admin_fee_b_info.data.borrow())?;\n\n check_keys_equal!(\n token_a.mint,\n admin_fee_key_a.mint,\n \"Mint A\",\n SwapError::InvalidAdmin\n );\n check_keys_equal!(\n token_b.mint,\n admin_fee_key_b.mint,\n \"Mint B\",\n SwapError::InvalidAdmin\n );\n\n // amp_factor == initial_amp_factor == target_amp_factor on init\n let invariant = StableSwap::new(amp_factor, amp_factor, ZERO_TS, ZERO_TS, ZERO_TS);\n // Compute amount of LP tokens to mint for bootstrapper\n let mint_amount_u256 = invariant\n .compute_d(token_a.amount, token_b.amount)\n .ok_or(SwapError::CalculationFailure)?;\n let mint_amount = (mint_amount_u256.try_to_u64())?;\n token::mint_to(\n swap_info.key,\n token_program_info.clone(),\n pool_mint_info.clone(),\n destination_info.clone(),\n authority_info.clone(),\n nonce,\n mint_amount,\n )?;\n\n let obj = SwapInfo {\n is_initialized: true,\n is_paused: false,\n nonce,\n initial_amp_factor: amp_factor,\n target_amp_factor: amp_factor,\n start_ramp_ts: ZERO_TS,\n stop_ramp_ts: ZERO_TS,\n future_admin_deadline: ZERO_TS,\n future_admin_key: Pubkey::default(),\n admin_key: *admin_key_info.key,\n token_a: SwapTokenInfo {\n reserves: *token_a_info.key,\n mint: token_a.mint,\n admin_fees: *admin_fee_a_info.key,\n index: 0,\n },\n token_b: SwapTokenInfo {\n reserves: *token_b_info.key,\n mint: token_b.mint,\n admin_fees: *admin_fee_b_info.key,\n index: 1,\n },\n pool_mint: *pool_mint_info.key,\n fees,\n };\n SwapInfo::pack(obj, &mut swap_info.data.borrow_mut())?;\n\n log_event(\n Event::Deposit,\n token_a.amount,\n token_b.amount,\n mint_amount,\n 0,\n );\n Ok(())\n}\n```"}], "func_name": "process_initialize", "docstring": "Processes an [Initialize](enum.Instruction.html).", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/swap.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/swap.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f273ce6f24111511bfcef20c17a6eab16a7efcd43992a29b63d006c55037b0db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_swap\n\nDocumentation:\nProcesses an [Swap](enum.Instruction.html).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_swap(\n program_id: &Pubkey,\n amount_in: u64,\n minimum_amount_out: u64,\n accounts: &[AccountInfo],\n) -> ProgramResult {\n if amount_in == 0 {\n // noop\n return Ok(());\n }\n let account_info_iter = &mut accounts.iter();\n let swap_info = next_account_info(account_info_iter)?;\n let swap_authority_info = next_account_info(account_info_iter)?;\n let user_authority_info = next_account_info(account_info_iter)?;\n let source_info = next_account_info(account_info_iter)?;\n let swap_source_info = next_account_info(account_info_iter)?;\n let swap_destination_info = next_account_info(account_info_iter)?;\n let destination_info = next_account_info(account_info_iter)?;\n let admin_destination_info = next_account_info(account_info_iter)?;\n let token_program_info = next_account_info(account_info_iter)?;\n\n if *swap_source_info.key == *swap_destination_info.key {\n return Err(SwapError::InvalidInput.into());\n }\n\n let token_swap = SwapInfo::unpack(&swap_info.data.borrow())?;\n if token_swap.is_paused {\n return Err(SwapError::IsPaused.into());\n }\n\n check_token_keys_not_equal!(\n token_swap.token_a,\n *source_info.key,\n token_swap.token_a.reserves,\n \"Source account cannot be one of swap's token accounts for token\",\n SwapError::InvalidInput\n );\n\n check_token_keys_not_equal!(\n token_swap.token_b,\n *source_info.key,\n token_swap.token_b.reserves,\n \"Source account cannot be one of swap's token accounts for token\",\n SwapError::InvalidInput\n );\n\n check_swap_authority(\n &token_swap,\n swap_info.key,\n program_id,\n swap_authority_info.key,\n )?;\n\n if *swap_source_info.key == token_swap.token_a.reserves {\n // Swap A to B\n check_swap_token_destination_accounts(\n &token_swap.token_b,\n swap_destination_info.key,\n admin_destination_info.key,\n )?;\n } else if *swap_source_info.key == token_swap.token_b.reserves {\n // Swap B to A\n check_swap_token_destination_accounts(\n &token_swap.token_a,\n swap_destination_info.key,\n admin_destination_info.key,\n )?;\n } else {\n return Err(SwapError::IncorrectSwapAccount.into());\n }\n\n let clock = Clock::get()?;\n let swap_source_account = utils::unpack_token_account(&swap_source_info.data.borrow())?;\n let swap_destination_account =\n utils::unpack_token_account(&swap_destination_info.data.borrow())?;\n\n let invariant = StableSwap::new(\n token_swap.initial_amp_factor,\n token_swap.target_amp_factor,\n clock.unix_timestamp,\n token_swap.start_ramp_ts,\n token_swap.stop_ramp_ts,\n );\n let result = invariant\n .swap_to(\n amount_in,\n swap_source_account.amount,\n swap_destination_account.amount,\n &token_swap.fees,\n )\n .ok_or(SwapError::CalculationFailure)?;\n let amount_swapped = result.amount_swapped;\n if amount_swapped < minimum_amount_out {\n log_slippage_error(minimum_amount_out, amount_swapped);\n return Err(SwapError::ExceededSlippage.into());\n }\n\n // from user to swap\n token::transfer_as_user(\n token_program_info.clone(),\n source_info.clone(),\n swap_source_info.clone(),\n user_authority_info.clone(),\n amount_in,\n )?;\n // from swap to user\n token::transfer_as_swap(\n swap_info.key,\n token_program_info.clone(),\n swap_destination_info.clone(),\n destination_info.clone(),\n swap_authority_info.clone(),\n token_swap.nonce,\n amount_swapped,\n )?;\n // from swap to fees\n token::transfer_as_swap(\n swap_info.key,\n token_program_info.clone(),\n swap_destination_info.clone(),\n admin_destination_info.clone(),\n swap_authority_info.clone(),\n token_swap.nonce,\n result.admin_fee,\n )?;\n\n if *swap_source_info.key == token_swap.token_a.reserves {\n log_event(Event::SwapAToB, amount_in, amount_swapped, 0, result.fee);\n } else {\n log_event(Event::SwapBToA, amount_swapped, amount_in, 0, result.fee);\n };\n Ok(())\n}\n```"}], "func_name": "process_swap", "docstring": "Processes an [Swap](enum.Instruction.html).", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/swap.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/swap.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "34efe70226f38b755ef491e5633d349010fa9a00602c6f6468a735813d7c4e67"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_deposit\n\nDocumentation:\nProcesses an [Deposit](enum.Instruction.html).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_deposit(\n program_id: &Pubkey,\n token_a_amount: u64,\n token_b_amount: u64,\n min_mint_amount: u64,\n accounts: &[AccountInfo],\n) -> ProgramResult {\n if token_a_amount == 0 && token_b_amount == 0 {\n // noop\n return Ok(());\n }\n let account_info_iter = &mut accounts.iter();\n let swap_info = next_account_info(account_info_iter)?;\n let swap_authority_info = next_account_info(account_info_iter)?;\n let user_authority_info = next_account_info(account_info_iter)?;\n let source_a_info = next_account_info(account_info_iter)?;\n let source_b_info = next_account_info(account_info_iter)?;\n let token_a_info = next_account_info(account_info_iter)?;\n let token_b_info = next_account_info(account_info_iter)?;\n let pool_mint_info = next_account_info(account_info_iter)?;\n let dest_info = next_account_info(account_info_iter)?;\n let token_program_info = next_account_info(account_info_iter)?;\n\n let token_swap = SwapInfo::unpack(&swap_info.data.borrow())?;\n if token_swap.is_paused {\n return Err(SwapError::IsPaused.into());\n }\n check_swap_authority(\n &token_swap,\n swap_info.key,\n program_id,\n swap_authority_info.key,\n )?;\n\n check_deposit_token_accounts(&token_swap.token_a, source_a_info.key, token_a_info.key)?;\n check_deposit_token_accounts(&token_swap.token_b, source_b_info.key, token_b_info.key)?;\n\n check_keys_equal!(\n *pool_mint_info.key,\n token_swap.pool_mint,\n \"Mint A\",\n SwapError::IncorrectMint\n );\n\n let clock = Clock::get()?;\n let token_a = utils::unpack_token_account(&token_a_info.data.borrow())?;\n let token_b = utils::unpack_token_account(&token_b_info.data.borrow())?;\n let pool_mint = utils::unpack_mint(&pool_mint_info.data.borrow())?;\n\n let invariant = StableSwap::new(\n token_swap.initial_amp_factor,\n token_swap.target_amp_factor,\n clock.unix_timestamp,\n token_swap.start_ramp_ts,\n token_swap.stop_ramp_ts,\n );\n let mint_amount = invariant\n .compute_mint_amount_for_deposit(\n token_a_amount,\n token_b_amount,\n token_a.amount,\n token_b.amount,\n pool_mint.supply,\n &token_swap.fees,\n )\n .ok_or(SwapError::CalculationFailure)?;\n if mint_amount < min_mint_amount {\n log_slippage_error(min_mint_amount, mint_amount);\n return Err(SwapError::ExceededSlippage.into());\n }\n\n // from user to swap\n token::transfer_as_user(\n token_program_info.clone(),\n source_a_info.clone(),\n token_a_info.clone(),\n user_authority_info.clone(),\n token_a_amount,\n )?;\n // from user to swap\n token::transfer_as_user(\n token_program_info.clone(),\n source_b_info.clone(),\n token_b_info.clone(),\n user_authority_info.clone(),\n token_b_amount,\n )?;\n // mint lp to user\n token::mint_to(\n swap_info.key,\n token_program_info.clone(),\n pool_mint_info.clone(),\n dest_info.clone(),\n swap_authority_info.clone(),\n token_swap.nonce,\n mint_amount,\n )?;\n\n log_event(\n Event::Deposit,\n token_a_amount,\n token_b_amount,\n mint_amount,\n 0,\n );\n Ok(())\n}\n```"}], "func_name": "process_deposit", "docstring": "Processes an [Deposit](enum.Instruction.html).", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/swap.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/swap.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "946965f589612d6f7f4dfda25d425104e66c06a6ac14a2c76f6945d7ddf4ed39"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_withdraw\n\nDocumentation:\nProcesses an [Withdraw](enum.Instruction.html).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_withdraw(\n program_id: &Pubkey,\n pool_token_amount: u64,\n minimum_token_a_amount: u64,\n minimum_token_b_amount: u64,\n accounts: &[AccountInfo],\n) -> ProgramResult {\n if pool_token_amount == 0 {\n // noop\n return Ok(());\n }\n let account_info_iter = &mut accounts.iter();\n let swap_info = next_account_info(account_info_iter)?;\n let swap_authority_info = next_account_info(account_info_iter)?;\n let user_authority_info = next_account_info(account_info_iter)?;\n let pool_mint_info = next_account_info(account_info_iter)?;\n let source_info = next_account_info(account_info_iter)?;\n let token_a_info = next_account_info(account_info_iter)?;\n let token_b_info = next_account_info(account_info_iter)?;\n let dest_token_a_info = next_account_info(account_info_iter)?;\n let dest_token_b_info = next_account_info(account_info_iter)?;\n let admin_fee_dest_a_info = next_account_info(account_info_iter)?;\n let admin_fee_dest_b_info = next_account_info(account_info_iter)?;\n let token_program_info = next_account_info(account_info_iter)?;\n\n let token_swap = SwapInfo::unpack(&swap_info.data.borrow())?;\n check_swap_authority(\n &token_swap,\n swap_info.key,\n program_id,\n swap_authority_info.key,\n )?;\n\n check_withdraw_token_accounts(\n &token_swap.token_a,\n token_a_info.key,\n admin_fee_dest_a_info.key,\n )?;\n\n check_withdraw_token_accounts(\n &token_swap.token_b,\n token_b_info.key,\n admin_fee_dest_b_info.key,\n )?;\n\n check_keys_equal!(\n *pool_mint_info.key,\n token_swap.pool_mint,\n \"Pool mint\",\n SwapError::IncorrectMint\n );\n\n let pool_mint = utils::unpack_mint(&pool_mint_info.data.borrow())?;\n if pool_mint.supply == 0 {\n return Err(SwapError::EmptyPool.into());\n }\n\n let token_a = utils::unpack_token_account(&token_a_info.data.borrow())?;\n let token_b = utils::unpack_token_account(&token_b_info.data.borrow())?;\n\n let converter = PoolTokenConverter {\n supply: (pool_mint.supply),\n token_a: (token_a.amount),\n token_b: (token_b.amount),\n fees: &token_swap.fees,\n };\n let pool_token_amount_u256 = pool_token_amount;\n\n let ctx = WithdrawContext {\n token_swap,\n token_program_info,\n swap_authority_info,\n swap_info,\n };\n\n let (a_amount, a_fee, a_admin_fee) = check_can_withdraw_token(\n converter.token_a_rate(pool_token_amount_u256),\n minimum_token_a_amount,\n )?;\n let (b_amount, b_fee, b_admin_fee) = check_can_withdraw_token(\n converter.token_b_rate(pool_token_amount_u256),\n minimum_token_b_amount,\n )?;\n\n handle_token_withdraw(\n &ctx,\n (a_amount, a_admin_fee),\n token_a_info,\n dest_token_a_info,\n admin_fee_dest_a_info,\n )?;\n handle_token_withdraw(\n &ctx,\n (b_amount, b_admin_fee),\n token_b_info,\n dest_token_b_info,\n admin_fee_dest_b_info,\n )?;\n\n // burn LP tokens withdrawn\n token::burn(\n token_program_info.clone(),\n source_info.clone(),\n pool_mint_info.clone(),\n user_authority_info.clone(),\n pool_token_amount,\n )?;\n\n log_event(Event::WithdrawA, a_amount, 0, 0, a_fee);\n log_event(Event::WithdrawB, 0, b_amount, 0, b_fee);\n log_event(Event::Burn, 0, 0, pool_token_amount, 0);\n Ok(())\n}\n```"}], "func_name": "process_withdraw", "docstring": "Processes an [Withdraw](enum.Instruction.html).", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/swap.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/swap.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c6ae2aaf7a8c0e318bb21337d6ca01751ee9981c5c860bc0a1e0c75228362f8a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_withdraw_one\n\nDocumentation:\nProcesses an [WithdrawOne](enum.Instruction.html).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_withdraw_one(\n program_id: &Pubkey,\n pool_token_amount: u64,\n minimum_token_amount: u64,\n accounts: &[AccountInfo],\n) -> ProgramResult {\n if pool_token_amount == 0 {\n // noop\n return Ok(());\n }\n\n let account_info_iter = &mut accounts.iter();\n let swap_info = next_account_info(account_info_iter)?;\n let swap_authority_info = next_account_info(account_info_iter)?;\n let user_authority_info = next_account_info(account_info_iter)?;\n let pool_mint_info = next_account_info(account_info_iter)?;\n let source_info = next_account_info(account_info_iter)?;\n let base_token_info = next_account_info(account_info_iter)?;\n let quote_token_info = next_account_info(account_info_iter)?;\n let destination_info = next_account_info(account_info_iter)?;\n let admin_destination_info = next_account_info(account_info_iter)?;\n let token_program_info = next_account_info(account_info_iter)?;\n\n if *base_token_info.key == *quote_token_info.key {\n return Err(SwapError::InvalidInput.into());\n }\n\n let token_swap = SwapInfo::unpack(&swap_info.data.borrow())?;\n if token_swap.is_paused {\n return Err(SwapError::IsPaused.into());\n }\n check_swap_authority(\n &token_swap,\n swap_info.key,\n program_id,\n swap_authority_info.key,\n )?;\n\n if *base_token_info.key == token_swap.token_a.reserves {\n check_keys_equal!(\n *quote_token_info.key,\n token_swap.token_b.reserves,\n \"Swap A -> B reserves\",\n SwapError::IncorrectSwapAccount\n );\n check_keys_equal!(\n *admin_destination_info.key,\n token_swap.token_a.admin_fees,\n \"Swap A -> B admin fee destination\",\n SwapError::InvalidAdmin\n );\n } else if *base_token_info.key == token_swap.token_b.reserves {\n check_keys_equal!(\n *quote_token_info.key,\n token_swap.token_a.reserves,\n \"Swap B -> A reserves\",\n SwapError::IncorrectSwapAccount\n );\n check_keys_equal!(\n *admin_destination_info.key,\n token_swap.token_b.admin_fees,\n \"Swap B -> A admin fee destination\",\n SwapError::InvalidAdmin\n );\n } else {\n msg!(\"Unknown base token:\");\n base_token_info.key.log();\n return Err(SwapError::IncorrectSwapAccount.into());\n }\n\n check_keys_equal!(\n *pool_mint_info.key,\n token_swap.pool_mint,\n \"Pool mint\",\n SwapError::IncorrectMint\n );\n\n let pool_mint = utils::unpack_mint(&pool_mint_info.data.borrow())?;\n let clock = Clock::get()?;\n let base_token = utils::unpack_token_account(&base_token_info.data.borrow())?;\n let quote_token = utils::unpack_token_account("e_token_info.data.borrow())?;\n\n let invariant = StableSwap::new(\n token_swap.initial_amp_factor,\n token_swap.target_amp_factor,\n clock.unix_timestamp,\n token_swap.start_ramp_ts,\n token_swap.stop_ramp_ts,\n );\n let (dy, dy_fee) = invariant\n .compute_withdraw_one(\n pool_token_amount,\n pool_mint.supply,\n base_token.amount,\n quote_token.amount,\n &token_swap.fees,\n )\n .ok_or(SwapError::CalculationFailure)?;\n let withdraw_fee = token_swap\n .fees\n .withdraw_fee(dy)\n .ok_or(SwapError::CalculationFailure)?;\n let token_amount = dy\n .checked_sub(withdraw_fee)\n .ok_or(SwapError::CalculationFailure)?;\n if token_amount < minimum_token_amount {\n log_slippage_error(minimum_token_amount, token_amount);\n return Err(SwapError::ExceededSlippage.into());\n }\n\n let admin_trade_fee = token_swap\n .fees\n .admin_trade_fee(dy_fee)\n .ok_or(SwapError::CalculationFailure)?;\n let admin_withdraw_fee = token_swap\n .fees\n .admin_withdraw_fee(withdraw_fee)\n .ok_or(SwapError::CalculationFailure)?;\n let admin_fee = admin_trade_fee\n .checked_add(admin_withdraw_fee)\n .ok_or(SwapError::CalculationFailure)?;\n\n // from swap to user\n token::transfer_as_swap(\n swap_info.key,\n token_program_info.clone(),\n base_token_info.clone(),\n destination_info.clone(),\n swap_authority_info.clone(),\n token_swap.nonce,\n token_amount,\n )?;\n // from swap to fee\n token::transfer_as_swap(\n swap_info.key,\n token_program_info.clone(),\n base_token_info.clone(),\n admin_destination_info.clone(),\n swap_authority_info.clone(),\n token_swap.nonce,\n admin_fee,\n )?;\n token::burn(\n token_program_info.clone(),\n source_info.clone(),\n pool_mint_info.clone(),\n user_authority_info.clone(),\n pool_token_amount,\n )?;\n\n if *base_token_info.key == token_swap.token_a.reserves {\n log_event(Event::WithdrawA, token_amount, 0, 0, dy_fee);\n } else {\n log_event(Event::WithdrawB, 0, token_amount, 0, dy_fee);\n };\n log_event(Event::Burn, 0, 0, pool_token_amount, 0);\n Ok(())\n}\n```"}], "func_name": "process_withdraw_one", "docstring": "Processes an [WithdrawOne](enum.Instruction.html).", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/swap.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/swap.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b608781a7affd4438b8d886e5e1e1b2ea562f89e9a5f2e451eb61b4e54016f1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ramp_a\n\nDocumentation:\n//! Test utility methods\n#![allow(clippy::too_many_arguments)]\n\nuse crate::{curve::ZERO_TS, fees::Fees, instruction::*, processor::Processor, state::SwapInfo};\nuse solana_program::{\naccount_info::AccountInfo, entrypoint::ProgramResult, instruction::Instruction,\nprogram_error::ProgramError,\n};\nuse solana_program::{\nclock::Clock, msg, program_pack::Pack, program_stubs, pubkey::Pubkey, rent::Rent,\n};\nuse solana_sdk::account::{create_account_for_test, create_is_signer_account_infos, Account};\nuse spl_token::{\ninstruction::{initialize_account, initialize_mint, mint_to},\nstate::{Account as SplAccount, Mint as SplMint},\n};\n\nTest program id for the swap program.\npub static SWAP_PROGRAM_ID: Pubkey = crate::ID;\n\nFees for testing\npub const DEFAULT_TEST_FEES: Fees = Fees {\nadmin_trade_fee_numerator: 1,\nadmin_trade_fee_denominator: 2,\nadmin_withdraw_fee_numerator: 1,\nadmin_withdraw_fee_denominator: 2,\ntrade_fee_numerator: 6,\ntrade_fee_denominator: 100,\nwithdraw_fee_numerator: 6,\nwithdraw_fee_denominator: 100,\n};\n\nDefault token decimals\npub const DEFAULT_TOKEN_DECIMALS: u8 = 6;\n\npub fn pubkey_rand() -> Pubkey {\nPubkey::new_unique()\n}\n\npub struct SwapAccountInfo {\npub nonce: u8,\npub authority_key: Pubkey,\npub initial_amp_factor: u64,\npub target_amp_factor: u64,\npub swap_key: Pubkey,\npub swap_account: Account,\npub pool_mint_key: Pubkey,\npub pool_mint_account: Account,\npub pool_token_key: Pubkey,\npub pool_token_account: Account,\npub token_a_key: Pubkey,\npub token_a_account: Account,\npub token_a_mint_key: Pubkey,\npub token_a_mint_account: Account,\npub token_b_key: Pubkey,\npub token_b_account: Account,\npub token_b_mint_key: Pubkey,\npub token_b_mint_account: Account,\npub admin_key: Pubkey,\npub admin_account: Account,\npub admin_fee_a_key: Pubkey,\npub admin_fee_a_account: Account,\npub admin_fee_b_key: Pubkey,\npub admin_fee_b_account: Account,\npub fees: Fees,\n}\n\nimpl SwapAccountInfo {\npub fn new(\nuser_key: &Pubkey,\namp_factor: u64,\ntoken_a_amount: u64,\ntoken_b_amount: u64,\nfees: Fees,\n) -> Self {\nlet swap_key = pubkey_rand();\nlet swap_account = Account::new(0, SwapInfo::get_packed_len(), &SWAP_PROGRAM_ID);\nlet (authority_key, nonce) =\nPubkey::find_program_address(&[&swap_key.to_bytes()[..]], &SWAP_PROGRAM_ID);\n\nlet (pool_mint_key, mut pool_mint_account) = create_mint(\n&spl_token::id(),\n&authority_key,\nDEFAULT_TOKEN_DECIMALS,\nNone,\n);\nlet (pool_token_key, pool_token_account) = mint_token(\n&spl_token::id(),\n&pool_mint_key,\n&mut pool_mint_account,\n&authority_key,\nuser_key,\n0,\n);\nlet (token_a_mint_key, mut token_a_mint_account) =\ncreate_mint(&spl_token::id(), user_key, DEFAULT_TOKEN_DECIMALS, None);\nlet (token_a_key, token_a_account) = mint_token(\n&spl_token::id(),\n&token_a_mint_key,\n&mut token_a_mint_account,\nuser_key,\n&authority_key,\ntoken_a_amount,\n);\nlet (admin_fee_a_key, admin_fee_a_account) = mint_token(\n&spl_token::id(),\n&token_a_mint_key,\n&mut token_a_mint_account,\nuser_key,\n&authority_key,\n0,\n);\nlet (token_b_mint_key, mut token_b_mint_account) =\ncreate_mint(&spl_token::id(), user_key, DEFAULT_TOKEN_DECIMALS, None);\nlet (token_b_key, token_b_account) = mint_token(\n&spl_token::id(),\n&token_b_mint_key,\n&mut token_b_mint_account,\nuser_key,\n&authority_key,\ntoken_b_amount,\n);\nlet (admin_fee_b_key, admin_fee_b_account) = mint_token(\n&spl_token::id(),\n&token_b_mint_key,\n&mut token_b_mint_account,\nuser_key,\n&authority_key,\n0,\n);\n\nlet admin_account = Account::default();\n\nSwapAccountInfo {\nnonce,\nauthority_key,\ninitial_amp_factor: amp_factor,\ntarget_amp_factor: amp_factor,\nswap_key,\nswap_account,\npool_mint_key,\npool_mint_account,\npool_token_key,\npool_token_account,\ntoken_a_mint_key,\ntoken_a_mint_account,\ntoken_a_key,\ntoken_a_account,\ntoken_b_mint_key,\ntoken_b_mint_account,\ntoken_b_key,\ntoken_b_account,\nadmin_key: admin_account.owner,\nadmin_account,\nadmin_fee_a_key,\nadmin_fee_a_account,\nadmin_fee_b_key,\nadmin_fee_b_account,\nfees,\n}\n}\n\npub fn initialize_swap(&mut self) -> ProgramResult {\ndo_process_instruction(\ninitialize(\n&spl_token::id(),\n&self.swap_key,\n&self.authority_key,\n&self.admin_key,\n&self.admin_fee_a_key,\n&self.admin_fee_b_key,\n&self.token_a_mint_key,\n&self.token_a_key,\n&self.token_b_mint_key,\n&self.token_b_key,\n&self.pool_mint_key,\n&self.pool_token_key,\nself.nonce,\nself.initial_amp_factor,\nself.fees,\n)?,\nvec![\n&mut self.swap_account,\n&mut Account::default(),\n&mut self.admin_account,\n&mut self.admin_fee_a_account,\n&mut self.admin_fee_b_account,\n&mut self.token_a_mint_account,\n&mut self.token_a_account,\n&mut self.token_b_mint_account,\n&mut self.token_b_account,\n&mut self.pool_mint_account,\n&mut self.pool_token_account,\n&mut Account::default(),\n],\n)\n}\n\npub fn setup_token_accounts(\n&mut self,\nmint_owner: &Pubkey,\naccount_owner: &Pubkey,\na_amount: u64,\nb_amount: u64,\npool_amount: u64,\n) -> (Pubkey, Account, Pubkey, Account, Pubkey, Account) {\nlet (token_a_key, token_a_account) = mint_token(\n&spl_token::id(),\n&self.token_a_mint_key,\n&mut self.token_a_mint_account,\nmint_owner,\naccount_owner,\na_amount,\n);\nlet (token_b_key, token_b_account) = mint_token(\n&spl_token::id(),\n&self.token_b_mint_key,\n&mut self.token_b_mint_account,\nmint_owner,\naccount_owner,\nb_amount,\n);\nlet (pool_key, pool_account) = mint_token(\n&spl_token::id(),\n&self.pool_mint_key,\n&mut self.pool_mint_account,\n&self.authority_key,\naccount_owner,\npool_amount,\n);\n(\ntoken_a_key,\ntoken_a_account,\ntoken_b_key,\ntoken_b_account,\npool_key,\npool_account,\n)\n}\n\nfn get_admin_fee_key(&self, account_key: &Pubkey) -> Pubkey {\nif *account_key == self.token_a_key {\nreturn self.admin_fee_a_key;\n} else if *account_key == self.token_b_key {\nreturn self.admin_fee_b_key;\n}\npanic!(\"Could not find matching admin fee account\");\n}\n\nfn get_admin_fee_account(&self, account_key: &Pubkey) -> &Account {\nif *account_key == self.admin_fee_a_key {\nreturn &self.admin_fee_a_account;\n} else if *account_key == self.admin_fee_b_key {\nreturn &self.admin_fee_b_account;\n}\npanic!(\"Could not find matching admin fee account\");\n}\n\nfn set_admin_fee_account_(&mut self, account_key: &Pubkey, account: Account) {\nif *account_key == self.admin_fee_a_key {\nself.admin_fee_a_account = account;\nreturn;\n} else if *account_key == self.admin_fee_b_key {\nself.admin_fee_b_account = account;\nreturn;\n}\npanic!(\"Could not find matching admin fee account\");\n}\n\nfn get_token_account(&self, account_key: &Pubkey) -> &Account {\nif *account_key == self.token_a_key {\nreturn &self.token_a_account;\n} else if *account_key == self.token_b_key {\nreturn &self.token_b_account;\n}\npanic!(\"Could not find matching swap token account\");\n}\n\nfn set_token_account(&mut self, account_key: &Pubkey, account: Account) {\nif *account_key == self.token_a_key {\nself.token_a_account = account;\nreturn;\n} else if *account_key == self.token_b_key {\nself.token_b_account = account;\nreturn;\n}\npanic!(\"Could not find matching swap token account\");\n}\n\npub fn swap(\n&mut self,\nuser_key: &Pubkey,\nuser_source_key: &Pubkey,\nuser_source_account: &mut Account,\nswap_source_key: &Pubkey,\nswap_destination_key: &Pubkey,\nuser_destination_key: &Pubkey,\nuser_destination_account: &mut Account,\namount_in: u64,\nminimum_amount_out: u64,\n) -> ProgramResult {\nlet admin_destination_key = self.get_admin_fee_key(swap_destination_key);\nlet mut admin_destination_account =\nself.get_admin_fee_account(&admin_destination_key).clone();\nlet mut swap_source_account = self.get_token_account(swap_source_key).clone();\nlet mut swap_destination_account = self.get_token_account(swap_destination_key).clone();\n\n// perform the swap\ndo_process_instruction_at_time(\nswap(\n&spl_token::id(),\n&self.swap_key,\n&self.authority_key,\nuser_key,\nuser_source_key,\nswap_source_key,\nswap_destination_key,\nuser_destination_key,\n&admin_destination_key,\namount_in,\nminimum_amount_out,\n)\n.unwrap(),\nvec![\n&mut self.swap_account,\n&mut Account::default(),\n&mut Account::default(),\nuser_source_account,\n&mut swap_source_account,\n&mut swap_destination_account,\nuser_destination_account,\n&mut admin_destination_account,\n&mut Account::default(),\n],\nZERO_TS,\n)?;\n\nself.set_admin_fee_account_(&admin_destination_key, admin_destination_account);\nself.set_token_account(swap_source_key, swap_source_account);\nself.set_token_account(swap_destination_key, swap_destination_account);\n\nOk(())\n}\n\npub fn deposit(\n&mut self,\ndepositor_key: &Pubkey,\ndepositor_token_a_key: &Pubkey,\ndepositor_token_a_account: &mut Account,\ndepositor_token_b_key: &Pubkey,\ndepositor_token_b_account: &mut Account,\ndepositor_pool_key: &Pubkey,\ndepositor_pool_account: &mut Account,\namount_a: u64,\namount_b: u64,\nmin_mint_amount: u64,\n) -> ProgramResult {\n// perform deposit\ndo_process_instruction_at_time(\ndeposit(\n&spl_token::id(),\n&self.swap_key,\n&self.authority_key,\ndepositor_key,\ndepositor_token_a_key,\ndepositor_token_b_key,\n&self.token_a_key,\n&self.token_b_key,\n&self.pool_mint_key,\ndepositor_pool_key,\namount_a,\namount_b,\nmin_mint_amount,\n)\n.unwrap(),\nvec![\n&mut self.swap_account,\n&mut Account::default(),\n&mut Account::default(),\ndepositor_token_a_account,\ndepositor_token_b_account,\n&mut self.token_a_account,\n&mut self.token_b_account,\n&mut self.pool_mint_account,\ndepositor_pool_account,\n&mut Account::default(),\n],\nZERO_TS,\n)\n}\n\npub fn withdraw(\n&mut self,\nuser_key: &Pubkey,\npool_key: &Pubkey,\npool_account: &mut Account,\ntoken_a_key: &Pubkey,\ntoken_a_account: &mut Account,\ntoken_b_key: &Pubkey,\ntoken_b_account: &mut Account,\npool_amount: u64,\nminimum_a_amount: u64,\nminimum_b_amount: u64,\n) -> ProgramResult {\n// perform withdraw\ndo_process_instruction(\nwithdraw(\n&spl_token::id(),\n&self.swap_key,\n&self.authority_key,\nuser_key,\n&self.pool_mint_key,\npool_key,\n&self.token_a_key,\n&self.token_b_key,\ntoken_a_key,\ntoken_b_key,\n&self.admin_fee_a_key,\n&self.admin_fee_b_key,\npool_amount,\nminimum_a_amount,\nminimum_b_amount,\n)\n.unwrap(),\nvec![\n&mut self.swap_account,\n&mut Account::default(),\n&mut Account::default(),\n&mut self.pool_mint_account,\npool_account,\n&mut self.token_a_account,\n&mut self.token_b_account,\ntoken_a_account,\ntoken_b_account,\n&mut self.admin_fee_a_account,\n&mut self.admin_fee_b_account,\n&mut Account::default(),\n],\n)?;\n\nOk(())\n}\n\npub fn withdraw_one(\n&mut self,\nuser_key: &Pubkey,\npool_key: &Pubkey,\npool_account: &mut Account,\ndest_token_key: &Pubkey,\ndest_token_account: &mut Account,\npool_amount: u64,\nminimum_amount: u64,\n) -> ProgramResult {\n// perform withdraw_one\ndo_process_instruction_at_time(\nwithdraw_one(\n&spl_token::id(),\n&self.swap_key,\n&self.authority_key,\nuser_key,\n&self.pool_mint_key,\npool_key,\n&self.token_a_key,\n&self.token_b_key,\ndest_token_key,\n&self.admin_fee_a_key,\npool_amount,\nminimum_amount,\n)\n.unwrap(),\nvec![\n&mut self.swap_account,\n&mut Account::default(),\n&mut Account::default(),\n&mut self.pool_mint_account,\npool_account,\n&mut self.token_a_account,\n&mut self.token_b_account,\ndest_token_account,\n&mut self.admin_fee_a_account,\n&mut Account::default(),\n],\nZERO_TS,\n)\n}\n\nAdmin functions **/\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ramp_a(&mut self, target_amp: u64, current_ts: i64, stop_ramp_ts: i64) -> ProgramResult {\n do_process_instruction_at_time(\n ramp_a(&self.swap_key, &self.admin_key, target_amp, stop_ramp_ts).unwrap(),\n vec![&mut self.swap_account, &mut self.admin_account],\n current_ts,\n )\n }\n```"}], "func_name": "ramp_a", "docstring": "//! Test utility methods\n#![allow(clippy::too_many_arguments)]\n\nuse crate::{curve::ZERO_TS, fees::Fees, instruction::*, processor::Processor, state::SwapInfo};\nuse solana_program::{\naccount_info::AccountInfo, entrypoint::ProgramResult, instruction::Instruction,\nprogram_error::ProgramError,\n};\nuse solana_program::{\nclock::Clock, msg, program_pack::Pack, program_stubs, pubkey::Pubkey, rent::Rent,\n};\nuse solana_sdk::account::{create_account_for_test, create_is_signer_account_infos, Account};\nuse spl_token::{\ninstruction::{initialize_account, initialize_mint, mint_to},\nstate::{Account as SplAccount, Mint as SplMint},\n};\n\nTest program id for the swap program.\npub static SWAP_PROGRAM_ID: Pubkey = crate::ID;\n\nFees for testing\npub const DEFAULT_TEST_FEES: Fees = Fees {\nadmin_trade_fee_numerator: 1,\nadmin_trade_fee_denominator: 2,\nadmin_withdraw_fee_numerator: 1,\nadmin_withdraw_fee_denominator: 2,\ntrade_fee_numerator: 6,\ntrade_fee_denominator: 100,\nwithdraw_fee_numerator: 6,\nwithdraw_fee_denominator: 100,\n};\n\nDefault token decimals\npub const DEFAULT_TOKEN_DECIMALS: u8 = 6;\n\npub fn pubkey_rand() -> Pubkey {\nPubkey::new_unique()\n}\n\npub struct SwapAccountInfo {\npub nonce: u8,\npub authority_key: Pubkey,\npub initial_amp_factor: u64,\npub target_amp_factor: u64,\npub swap_key: Pubkey,\npub swap_account: Account,\npub pool_mint_key: Pubkey,\npub pool_mint_account: Account,\npub pool_token_key: Pubkey,\npub pool_token_account: Account,\npub token_a_key: Pubkey,\npub token_a_account: Account,\npub token_a_mint_key: Pubkey,\npub token_a_mint_account: Account,\npub token_b_key: Pubkey,\npub token_b_account: Account,\npub token_b_mint_key: Pubkey,\npub token_b_mint_account: Account,\npub admin_key: Pubkey,\npub admin_account: Account,\npub admin_fee_a_key: Pubkey,\npub admin_fee_a_account: Account,\npub admin_fee_b_key: Pubkey,\npub admin_fee_b_account: Account,\npub fees: Fees,\n}\n\nimpl SwapAccountInfo {\npub fn new(\nuser_key: &Pubkey,\namp_factor: u64,\ntoken_a_amount: u64,\ntoken_b_amount: u64,\nfees: Fees,\n) -> Self {\nlet swap_key = pubkey_rand();\nlet swap_account = Account::new(0, SwapInfo::get_packed_len(), &SWAP_PROGRAM_ID);\nlet (authority_key, nonce) =\nPubkey::find_program_address(&[&swap_key.to_bytes()[..]], &SWAP_PROGRAM_ID);\n\nlet (pool_mint_key, mut pool_mint_account) = create_mint(\n&spl_token::id(),\n&authority_key,\nDEFAULT_TOKEN_DECIMALS,\nNone,\n);\nlet (pool_token_key, pool_token_account) = mint_token(\n&spl_token::id(),\n&pool_mint_key,\n&mut pool_mint_account,\n&authority_key,\nuser_key,\n0,\n);\nlet (token_a_mint_key, mut token_a_mint_account) =\ncreate_mint(&spl_token::id(), user_key, DEFAULT_TOKEN_DECIMALS, None);\nlet (token_a_key, token_a_account) = mint_token(\n&spl_token::id(),\n&token_a_mint_key,\n&mut token_a_mint_account,\nuser_key,\n&authority_key,\ntoken_a_amount,\n);\nlet (admin_fee_a_key, admin_fee_a_account) = mint_token(\n&spl_token::id(),\n&token_a_mint_key,\n&mut token_a_mint_account,\nuser_key,\n&authority_key,\n0,\n);\nlet (token_b_mint_key, mut token_b_mint_account) =\ncreate_mint(&spl_token::id(), user_key, DEFAULT_TOKEN_DECIMALS, None);\nlet (token_b_key, token_b_account) = mint_token(\n&spl_token::id(),\n&token_b_mint_key,\n&mut token_b_mint_account,\nuser_key,\n&authority_key,\ntoken_b_amount,\n);\nlet (admin_fee_b_key, admin_fee_b_account) = mint_token(\n&spl_token::id(),\n&token_b_mint_key,\n&mut token_b_mint_account,\nuser_key,\n&authority_key,\n0,\n);\n\nlet admin_account = Account::default();\n\nSwapAccountInfo {\nnonce,\nauthority_key,\ninitial_amp_factor: amp_factor,\ntarget_amp_factor: amp_factor,\nswap_key,\nswap_account,\npool_mint_key,\npool_mint_account,\npool_token_key,\npool_token_account,\ntoken_a_mint_key,\ntoken_a_mint_account,\ntoken_a_key,\ntoken_a_account,\ntoken_b_mint_key,\ntoken_b_mint_account,\ntoken_b_key,\ntoken_b_account,\nadmin_key: admin_account.owner,\nadmin_account,\nadmin_fee_a_key,\nadmin_fee_a_account,\nadmin_fee_b_key,\nadmin_fee_b_account,\nfees,\n}\n}\n\npub fn initialize_swap(&mut self) -> ProgramResult {\ndo_process_instruction(\ninitialize(\n&spl_token::id(),\n&self.swap_key,\n&self.authority_key,\n&self.admin_key,\n&self.admin_fee_a_key,\n&self.admin_fee_b_key,\n&self.token_a_mint_key,\n&self.token_a_key,\n&self.token_b_mint_key,\n&self.token_b_key,\n&self.pool_mint_key,\n&self.pool_token_key,\nself.nonce,\nself.initial_amp_factor,\nself.fees,\n)?,\nvec![\n&mut self.swap_account,\n&mut Account::default(),\n&mut self.admin_account,\n&mut self.admin_fee_a_account,\n&mut self.admin_fee_b_account,\n&mut self.token_a_mint_account,\n&mut self.token_a_account,\n&mut self.token_b_mint_account,\n&mut self.token_b_account,\n&mut self.pool_mint_account,\n&mut self.pool_token_account,\n&mut Account::default(),\n],\n)\n}\n\npub fn setup_token_accounts(\n&mut self,\nmint_owner: &Pubkey,\naccount_owner: &Pubkey,\na_amount: u64,\nb_amount: u64,\npool_amount: u64,\n) -> (Pubkey, Account, Pubkey, Account, Pubkey, Account) {\nlet (token_a_key, token_a_account) = mint_token(\n&spl_token::id(),\n&self.token_a_mint_key,\n&mut self.token_a_mint_account,\nmint_owner,\naccount_owner,\na_amount,\n);\nlet (token_b_key, token_b_account) = mint_token(\n&spl_token::id(),\n&self.token_b_mint_key,\n&mut self.token_b_mint_account,\nmint_owner,\naccount_owner,\nb_amount,\n);\nlet (pool_key, pool_account) = mint_token(\n&spl_token::id(),\n&self.pool_mint_key,\n&mut self.pool_mint_account,\n&self.authority_key,\naccount_owner,\npool_amount,\n);\n(\ntoken_a_key,\ntoken_a_account,\ntoken_b_key,\ntoken_b_account,\npool_key,\npool_account,\n)\n}\n\nfn get_admin_fee_key(&self, account_key: &Pubkey) -> Pubkey {\nif *account_key == self.token_a_key {\nreturn self.admin_fee_a_key;\n} else if *account_key == self.token_b_key {\nreturn self.admin_fee_b_key;\n}\npanic!(\"Could not find matching admin fee account\");\n}\n\nfn get_admin_fee_account(&self, account_key: &Pubkey) -> &Account {\nif *account_key == self.admin_fee_a_key {\nreturn &self.admin_fee_a_account;\n} else if *account_key == self.admin_fee_b_key {\nreturn &self.admin_fee_b_account;\n}\npanic!(\"Could not find matching admin fee account\");\n}\n\nfn set_admin_fee_account_(&mut self, account_key: &Pubkey, account: Account) {\nif *account_key == self.admin_fee_a_key {\nself.admin_fee_a_account = account;\nreturn;\n} else if *account_key == self.admin_fee_b_key {\nself.admin_fee_b_account = account;\nreturn;\n}\npanic!(\"Could not find matching admin fee account\");\n}\n\nfn get_token_account(&self, account_key: &Pubkey) -> &Account {\nif *account_key == self.token_a_key {\nreturn &self.token_a_account;\n} else if *account_key == self.token_b_key {\nreturn &self.token_b_account;\n}\npanic!(\"Could not find matching swap token account\");\n}\n\nfn set_token_account(&mut self, account_key: &Pubkey, account: Account) {\nif *account_key == self.token_a_key {\nself.token_a_account = account;\nreturn;\n} else if *account_key == self.token_b_key {\nself.token_b_account = account;\nreturn;\n}\npanic!(\"Could not find matching swap token account\");\n}\n\npub fn swap(\n&mut self,\nuser_key: &Pubkey,\nuser_source_key: &Pubkey,\nuser_source_account: &mut Account,\nswap_source_key: &Pubkey,\nswap_destination_key: &Pubkey,\nuser_destination_key: &Pubkey,\nuser_destination_account: &mut Account,\namount_in: u64,\nminimum_amount_out: u64,\n) -> ProgramResult {\nlet admin_destination_key = self.get_admin_fee_key(swap_destination_key);\nlet mut admin_destination_account =\nself.get_admin_fee_account(&admin_destination_key).clone();\nlet mut swap_source_account = self.get_token_account(swap_source_key).clone();\nlet mut swap_destination_account = self.get_token_account(swap_destination_key).clone();\n\n// perform the swap\ndo_process_instruction_at_time(\nswap(\n&spl_token::id(),\n&self.swap_key,\n&self.authority_key,\nuser_key,\nuser_source_key,\nswap_source_key,\nswap_destination_key,\nuser_destination_key,\n&admin_destination_key,\namount_in,\nminimum_amount_out,\n)\n.unwrap(),\nvec![\n&mut self.swap_account,\n&mut Account::default(),\n&mut Account::default(),\nuser_source_account,\n&mut swap_source_account,\n&mut swap_destination_account,\nuser_destination_account,\n&mut admin_destination_account,\n&mut Account::default(),\n],\nZERO_TS,\n)?;\n\nself.set_admin_fee_account_(&admin_destination_key, admin_destination_account);\nself.set_token_account(swap_source_key, swap_source_account);\nself.set_token_account(swap_destination_key, swap_destination_account);\n\nOk(())\n}\n\npub fn deposit(\n&mut self,\ndepositor_key: &Pubkey,\ndepositor_token_a_key: &Pubkey,\ndepositor_token_a_account: &mut Account,\ndepositor_token_b_key: &Pubkey,\ndepositor_token_b_account: &mut Account,\ndepositor_pool_key: &Pubkey,\ndepositor_pool_account: &mut Account,\namount_a: u64,\namount_b: u64,\nmin_mint_amount: u64,\n) -> ProgramResult {\n// perform deposit\ndo_process_instruction_at_time(\ndeposit(\n&spl_token::id(),\n&self.swap_key,\n&self.authority_key,\ndepositor_key,\ndepositor_token_a_key,\ndepositor_token_b_key,\n&self.token_a_key,\n&self.token_b_key,\n&self.pool_mint_key,\ndepositor_pool_key,\namount_a,\namount_b,\nmin_mint_amount,\n)\n.unwrap(),\nvec![\n&mut self.swap_account,\n&mut Account::default(),\n&mut Account::default(),\ndepositor_token_a_account,\ndepositor_token_b_account,\n&mut self.token_a_account,\n&mut self.token_b_account,\n&mut self.pool_mint_account,\ndepositor_pool_account,\n&mut Account::default(),\n],\nZERO_TS,\n)\n}\n\npub fn withdraw(\n&mut self,\nuser_key: &Pubkey,\npool_key: &Pubkey,\npool_account: &mut Account,\ntoken_a_key: &Pubkey,\ntoken_a_account: &mut Account,\ntoken_b_key: &Pubkey,\ntoken_b_account: &mut Account,\npool_amount: u64,\nminimum_a_amount: u64,\nminimum_b_amount: u64,\n) -> ProgramResult {\n// perform withdraw\ndo_process_instruction(\nwithdraw(\n&spl_token::id(),\n&self.swap_key,\n&self.authority_key,\nuser_key,\n&self.pool_mint_key,\npool_key,\n&self.token_a_key,\n&self.token_b_key,\ntoken_a_key,\ntoken_b_key,\n&self.admin_fee_a_key,\n&self.admin_fee_b_key,\npool_amount,\nminimum_a_amount,\nminimum_b_amount,\n)\n.unwrap(),\nvec![\n&mut self.swap_account,\n&mut Account::default(),\n&mut Account::default(),\n&mut self.pool_mint_account,\npool_account,\n&mut self.token_a_account,\n&mut self.token_b_account,\ntoken_a_account,\ntoken_b_account,\n&mut self.admin_fee_a_account,\n&mut self.admin_fee_b_account,\n&mut Account::default(),\n],\n)?;\n\nOk(())\n}\n\npub fn withdraw_one(\n&mut self,\nuser_key: &Pubkey,\npool_key: &Pubkey,\npool_account: &mut Account,\ndest_token_key: &Pubkey,\ndest_token_account: &mut Account,\npool_amount: u64,\nminimum_amount: u64,\n) -> ProgramResult {\n// perform withdraw_one\ndo_process_instruction_at_time(\nwithdraw_one(\n&spl_token::id(),\n&self.swap_key,\n&self.authority_key,\nuser_key,\n&self.pool_mint_key,\npool_key,\n&self.token_a_key,\n&self.token_b_key,\ndest_token_key,\n&self.admin_fee_a_key,\npool_amount,\nminimum_amount,\n)\n.unwrap(),\nvec![\n&mut self.swap_account,\n&mut Account::default(),\n&mut Account::default(),\n&mut self.pool_mint_account,\npool_account,\n&mut self.token_a_account,\n&mut self.token_b_account,\ndest_token_account,\n&mut self.admin_fee_a_account,\n&mut Account::default(),\n],\nZERO_TS,\n)\n}\n\nAdmin functions **/", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/test_utils.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "154c3f4650efd4f6797baed0604f175b6578b90dde0061f805f7687dd92f6c29"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: transfer_as_swap\n\nDocumentation:\nIssue a spl_token `Transfer` instruction signed by the authority.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn transfer_as_swap<'a>(\n swap: &Pubkey,\n token_program: AccountInfo<'a>,\n source: AccountInfo<'a>,\n destination: AccountInfo<'a>,\n program_authority: AccountInfo<'a>,\n nonce: u8,\n amount: u64,\n) -> Result<(), ProgramError> {\n let swap_bytes = swap.to_bytes();\n let authority_signature_seeds = [&swap_bytes[..32], &[nonce]];\n let signers = &[&authority_signature_seeds[..]];\n let ix = spl_token::instruction::transfer(\n token_program.key,\n source.key,\n destination.key,\n program_authority.key,\n &[],\n amount,\n )?;\n\n invoke_signed(\n &ix,\n &[token_program, source, destination, program_authority],\n signers,\n )\n}\n```"}], "func_name": "transfer_as_swap", "docstring": "Issue a spl_token `Transfer` instruction signed by the authority.", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/token.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/token.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f087b17fd35dba45a606f2ebc652b929fb356e3c47abf73255f37b9d84c3dd0b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: transfer_as_user\n\nDocumentation:\nIssue a spl_token `Transfer` instruction as the user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn transfer_as_user<'a>(\n token_program: AccountInfo<'a>,\n source: AccountInfo<'a>,\n destination: AccountInfo<'a>,\n user_authority: AccountInfo<'a>,\n amount: u64,\n) -> Result<(), ProgramError> {\n let ix = spl_token::instruction::transfer(\n token_program.key,\n source.key,\n destination.key,\n user_authority.key,\n &[],\n amount,\n )?;\n solana_program::program::invoke(&ix, &[token_program, source, destination, user_authority])\n}\n```"}], "func_name": "transfer_as_user", "docstring": "Issue a spl_token `Transfer` instruction as the user.", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/token.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/token.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "423ccb3cb4e02d42d8f49ef0f6d8d8a2265616c2c8f10f2fee059de783c64aa1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: authority_id\n\nDocumentation:\nCalculates the authority id by generating a program address.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn authority_id(program_id: &Pubkey, my_info: &Pubkey, nonce: u8) -> Result {\n Pubkey::create_program_address(&[&my_info.to_bytes()[..32], &[nonce]], program_id)\n .or(Err(SwapError::InvalidProgramAddress))\n}\n```"}], "func_name": "authority_id", "docstring": "Calculates the authority id by generating a program address.", "repo": "saber-hq/stable-swap", "path": "stable-swap-program/program/src/processor/utils.rs", "url": "https://github.com/saber-hq/stable-swap/blob/master/stable-swap-program/program/src/processor/utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "384edf1d7933600e28def7bfd876dc08c5d47a4fce2cdb514fd1ee136c24c189"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: put\n\nDocumentation:\nStores the mapping \"key -> value\" in the database\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn put(&mut self, key: &[u8], value: &[u8]) {\n self.set_count(self.get_count() + 1);\n self.contents.push(ValueType::Value as u8);\n VarintU32::put_varint(&mut self.contents, key.len() as u32);\n self.contents.extend_from_slice(key);\n VarintU32::put_varint(&mut self.contents, value.len() as u32);\n self.contents.extend_from_slice(value);\n }\n```"}], "func_name": "put", "docstring": "Stores the mapping \"key -> value\" in the database", "repo": "Fullstop000/wickdb", "path": "src/batch.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/batch.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ffa2d59fe4dd554d4d9da23b4e8277679745b03ee3e6e341aba777fab56dd513"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete\n\nDocumentation:\nIf the database contains a mapping for \"key\", erase it. Else do nothing\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn delete(&mut self, key: &[u8]) {\n self.set_count(self.get_count() + 1);\n self.contents.push(ValueType::Deletion as u8);\n VarintU32::put_varint(&mut self.contents, key.len() as u32);\n self.contents.extend_from_slice(key);\n }\n```"}], "func_name": "delete", "docstring": "If the database contains a mapping for \"key\", erase it. Else do nothing", "repo": "Fullstop000/wickdb", "path": "src/batch.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/batch.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94178312ad11e2afdda06b89af81915cb90c4002af13be9449c71be42d96a456"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: append\n\nDocumentation:\nCopies the operations in \"source\" to this batch.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn append(&mut self, mut src: WriteBatch) {\n assert!(\n src.contents.len() >= HEADER_SIZE,\n \"[batch] malformed WriteBatch (too small) to append\"\n );\n self.set_count(self.get_count() + src.get_count());\n src.contents.drain(0..HEADER_SIZE);\n self.contents.append(&mut src.contents)\n }\n```"}], "func_name": "append", "docstring": "Copies the operations in \"source\" to this batch.", "repo": "Fullstop000/wickdb", "path": "src/batch.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/batch.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc65767424c175efbe2e911acb071eb99437d8d5901ae834c7f1e5a4e7c9b2f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert_into\n\nDocumentation:\nInsert all the records in the batch into the given `MemTable`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert_into(&self, mem: &MemTable) -> Result<()> {\n if self.contents.len() < HEADER_SIZE {\n return Err(Error::Corruption(\n \"[batch] malformed WriteBatch (too small)\".to_owned(),\n ));\n }\n let mut s = &self.contents[HEADER_SIZE..];\n let mut found = 0;\n let mut seq = self.get_sequence();\n while !s.is_empty() {\n found += 1;\n let tag = s[0];\n s = &s[1..];\n match ValueType::from(u64::from(tag)) {\n ValueType::Value => {\n if let Some(key) = VarintU32::get_varint_prefixed_slice(&mut s) {\n if let Some(value) = VarintU32::get_varint_prefixed_slice(&mut s) {\n mem.add(seq, ValueType::Value, key, value);\n seq += 1;\n continue;\n }\n }\n return Err(Error::Corruption(\"[batch] bad WriteBatch put\".to_owned()));\n }\n ValueType::Deletion => {\n if let Some(key) = VarintU32::get_varint_prefixed_slice(&mut s) {\n mem.add(seq, ValueType::Deletion, key, b\"\");\n seq += 1;\n continue;\n }\n return Err(Error::Corruption(\n \"[batch] bad WriteBatch delete\".to_owned(),\n ));\n }\n ValueType::Unknown => {\n return Err(Error::Corruption(\n \"[batch] unknown WriteBatch value type\".to_owned(),\n ))\n }\n }\n }\n if found != self.get_count() {\n return Err(Error::Corruption(\n \"[batch] WriteBatch has wrong count\".to_owned(),\n ));\n }\n Ok(())\n }\n```"}], "func_name": "insert_into", "docstring": "Insert all the records in the batch into the given `MemTable`", "repo": "Fullstop000/wickdb", "path": "src/batch.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/batch.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3aa6c9bd561a164da10b25d1715c40f434bf0dc3f169564e0e93683046ba09a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_input_iterator\n\nDocumentation:\nCreate an iterator that reads over all the compaction input tables with merged order.\nWe produce different iter for tables in level0 and level >0 :\nlevel 0: Since key ranges might be overlapped with each other, we generate\na table iterator over every single level 0 sst file\nlevel > 0: a `ConcatenateIterator` for all the sst file in this level\n\nEntry format:\nkey: internal key\nvalue: value of user key\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_input_iterator(\n &self,\n icmp: InternalKeyComparator,\n table_cache: TableCache,\n ) -> Result>> {\n let read_options = ReadOptions {\n verify_checksums: self.options.paranoid_checks,\n fill_cache: false,\n snapshot: None,\n };\n // Level-0 files have to be merged together so we generate a merging iterator includes iterators for each level 0 file.\n // For other levels, we will make a concatenating iterator per level.\n let mut level0 = Vec::with_capacity(self.inputs.base.len() + 1);\n let mut leveln = Vec::with_capacity(2);\n if self.level == 0 {\n for file in self.inputs.base.iter() {\n debug!(\n \"new level {} table iter: number {}, file size {}, [{:?} ... {:?}]\",\n self.level, file.number, file.file_size, file.smallest, file.largest\n );\n level0.push(table_cache.new_iter(\n icmp.clone(),\n read_options,\n file.number,\n file.file_size,\n )?);\n }\n } else {\n for f in &self.inputs.base {\n debug!(\n \"new level {} table iter: number {}, file size {}, [{:?} ... {:?}]\",\n self.level, f.number, f.file_size, f.smallest, f.largest\n );\n }\n let origin = LevelFileNumIterator::new(icmp.clone(), self.inputs.base.clone());\n let factory = FileIterFactory::new(icmp.clone(), read_options, table_cache.clone());\n leveln.push(ConcatenateIterator::new(origin, factory));\n }\n if !self.inputs.parent.is_empty() {\n for f in &self.inputs.parent {\n debug!(\n \"new level {} table iter: number {}, file size {}, [{:?} ... {:?}]\",\n self.level + 1,\n f.number,\n f.file_size,\n f.smallest,\n f.largest\n );\n }\n let origin = LevelFileNumIterator::new(icmp.clone(), self.inputs.parent.clone());\n let factory = FileIterFactory::new(icmp.clone(), read_options, table_cache);\n leveln.push(ConcatenateIterator::new(origin, factory));\n }\n\n let iter = KMergeIter::new(SSTableIters::new(icmp, level0, leveln));\n Ok(iter)\n }\n```"}], "func_name": "new_input_iterator", "docstring": "Create an iterator that reads over all the compaction input tables with merged order.\nWe produce different iter for tables in level0 and level >0 :\nlevel 0: Since key ranges might be overlapped with each other, we generate\na table iterator over every single level 0 sst file\nlevel > 0: a `ConcatenateIterator` for all the sst file in this level\n\nEntry format:\nkey: internal key\nvalue: value of user key", "repo": "Fullstop000/wickdb", "path": "src/compaction.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/compaction.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eef018b76bc3abfffb094491159a3ea97ac72c8fde311bcdebebc8a58604825c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: should_stop_before\n\nDocumentation:\nReturns true iff we should stop building the current output\nbefore processing `ikey` for too much overlapping with grand parents\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn should_stop_before(&mut self, ikey: &[u8], icmp: &InternalKeyComparator) -> bool {\n // `seen_key` guarantees that we should continue checking for next `ikey`\n // no matter whether the first `ikey` overlaps with grand parents\n while self.grand_parent_index < self.grand_parents.len()\n && icmp.compare(\n ikey,\n self.grand_parents[self.grand_parent_index].largest.data(),\n ) == CmpOrdering::Greater\n {\n if self.seen_key {\n self.overlapped_bytes += self.grand_parents[self.grand_parent_index].file_size\n }\n self.grand_parent_index += 1;\n }\n self.seen_key = true;\n if self.overlapped_bytes > self.options.max_grandparent_overlap_bytes() {\n // Too much overlap for current output, start new output\n self.overlapped_bytes = 0;\n return true;\n }\n false\n }\n```"}], "func_name": "should_stop_before", "docstring": "Returns true iff we should stop building the current output\nbefore processing `ikey` for too much overlapping with grand parents", "repo": "Fullstop000/wickdb", "path": "src/compaction.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/compaction.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "67a2690283be70ffd84336b27aff69164206aa2eb6b03557593f0184b87676ae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: key_exist_in_deeper_level\n\nDocumentation:\nReports whether it is guaranteed that there are no\nkey/value pairs at c.level+2 or higher that have the user key ukey.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn key_exist_in_deeper_level(&mut self, ukey: &[u8]) -> bool {\n let v = self.input_version.as_ref().unwrap();\n let ucmp = &self\n .input_version\n .as_ref()\n .unwrap()\n .comparator()\n .user_comparator;\n let max_levels = self.options.max_levels;\n if self.level + 2 < max_levels {\n for level in self.level + 2..max_levels {\n for f in v.get_level_files(level) {\n if ucmp.compare(ukey, f.largest.user_key()) != CmpOrdering::Greater {\n if ucmp.compare(ukey, f.smallest.user_key()) != CmpOrdering::Less {\n return true;\n }\n // For levels above level 0, the files within a level are in\n // increasing ikey order, so we can break early.\n break;\n }\n }\n }\n }\n false\n }\n```"}], "func_name": "key_exist_in_deeper_level", "docstring": "Reports whether it is guaranteed that there are no\nkey/value pairs at c.level+2 or higher that have the user key ukey.", "repo": "Fullstop000/wickdb", "path": "src/compaction.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/compaction.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d88689acf0a491196d518d2ef47aa55d02461fa47390bfd10b39a7a820896c27"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: apply_to_edit\n\nDocumentation:\nApply deletion for current inputs and current output files to the edit\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn apply_to_edit(&mut self) {\n for f in self.inputs.base.iter() {\n self.edit.delete_file(self.level, f.number)\n }\n for f in self.inputs.parent.iter() {\n self.edit.delete_file(self.level + 1, f.number)\n }\n for output in self.outputs.drain(..) {\n self.edit\n .file_delta\n .new_files\n .push((self.level + 1, output))\n }\n }\n```"}], "func_name": "apply_to_edit", "docstring": "Apply deletion for current inputs and current output files to the edit", "repo": "Fullstop000/wickdb", "path": "src/compaction.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/compaction.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3133f17919b833e09d6c0f19ecb5dd959d33358c5685de9ba7853f7b28b00893"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: base_range\n\nDocumentation:\nReturns the minimal range that covers all entries in `files`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn base_range<'a, C: Comparator>(\n files: &'a [Arc],\n level: usize,\n icmp: &InternalKeyComparator,\n) -> (&'a InternalKey, &'a InternalKey) {\n assert!(\n !files.is_empty(),\n \"[compaction] the input[0] shouldn't be empty when trying to get covered range\"\n );\n if level == 0 {\n // level 0 files are possible to overlaps with each other\n let mut smallest = &files.first().unwrap().smallest;\n let mut largest = &files.first().unwrap().largest;\n for f in files.iter().skip(1) {\n if icmp.compare(f.smallest.data(), smallest.data()) == CmpOrdering::Less {\n smallest = &f.smallest;\n }\n if icmp.compare(f.largest.data(), largest.data()) == CmpOrdering::Greater {\n largest = &f.largest;\n }\n }\n (smallest, largest)\n } else {\n // no overlapping in level > 0 and file is ordered by smallest key\n (\n &files.first().unwrap().smallest,\n &files.last().unwrap().largest,\n )\n }\n}\n```"}], "func_name": "base_range", "docstring": "Returns the minimal range that covers all entries in `files`", "repo": "Fullstop000/wickdb", "path": "src/compaction.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/compaction.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a891af3571ca150e8b277a95cc01464339a467da58065dc7075f40550e7167bb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: total_range\n\nDocumentation:\nReturns the minimal range that covers all key ranges in `current_l_files` and `next_l_files`\n`current_l_files` means current level files to be compacted\n`next_l_files` means next level files to be compacted\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn total_range<'a, C: Comparator>(\n current_l_files: &'a [Arc],\n next_l_files: &'a [Arc],\n level: usize,\n icmp: &InternalKeyComparator,\n) -> (&'a InternalKey, &'a InternalKey) {\n let (mut smallest, mut largest) = base_range(current_l_files, level, icmp);\n if !next_l_files.is_empty() {\n let first = next_l_files.first().unwrap();\n if icmp.compare(first.smallest.data(), smallest.data()) == CmpOrdering::Less {\n smallest = &first.smallest\n }\n let last = next_l_files.last().unwrap();\n if icmp.compare(last.largest.data(), largest.data()) == CmpOrdering::Greater {\n largest = &last.largest\n }\n }\n (smallest, largest)\n}\n```"}], "func_name": "total_range", "docstring": "Returns the minimal range that covers all key ranges in `current_l_files` and `next_l_files`\n`current_l_files` means current level files to be compacted\n`next_l_files` means next level files to be compacted", "repo": "Fullstop000/wickdb", "path": "src/compaction.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/compaction.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bed31225de19cd07ef13ff80196c825c2e168043c61ebf7b6d04a08531d39548"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: smaller\n\nDocumentation:\nUpdates the smallest if given `iter` has a smaller value and returns true.\nOtherwise returns false.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn smaller<'a>(&self, smallest: &mut Option<&'a [u8]>, iter: &'a dyn Iterator) -> bool {\n if iter.valid()\n && (smallest.is_none()\n || self.cmp().compare(iter.key(), smallest.as_ref().unwrap()) == Ordering::Less)\n {\n *smallest = Some(iter.key());\n true\n } else {\n false\n }\n }\n```"}], "func_name": "smaller", "docstring": "Updates the smallest if given `iter` has a smaller value and returns true.\nOtherwise returns false.", "repo": "Fullstop000/wickdb", "path": "src/iterator.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/iterator.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "951ddecfd4d473f7d75fd9deb629171029fdcb41b856bc802142ce8a7908676a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a logger backend\n\nIf `inner` is not `None`, use `inner` logger\nIf `inner` is `None`\n- In dev mode, use a std output\n- In release mode, use a storage specific file with name `LOG`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n inner: Option,\n level: LevelFilter,\n storage: &S,\n db_path: &str,\n ) -> Self {\n let inner = match inner {\n Some(l) => l,\n None => {\n if cfg!(debug_assertions) {\n // Use std out\n let decorator = slog_term::TermDecorator::new().build();\n let drain = Mutex::new(slog_term::FullFormat::new(decorator).build()).fuse();\n slog::Logger::root(drain, o!())\n } else {\n // Use a file `Log` to record all logs\n // TODO: add file rotation\n let file = storage\n .create(generate_filename(db_path, FileType::InfoLog, 0).as_str())\n .unwrap();\n let drain = slog_async::Async::new(FileBasedDrain::new(file))\n .build()\n .fuse();\n slog::Logger::root(drain, o!())\n }\n }\n };\n Self { inner, level }\n }\n```"}], "func_name": "new", "docstring": "Create a logger backend\n\nIf `inner` is not `None`, use `inner` logger\nIf `inner` is `None`\n- In dev mode, use a std output\n- In release mode, use a storage specific file with name `LOG`", "repo": "Fullstop000/wickdb", "path": "src/logger.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/logger.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "62346badda4d2a04d9ef2227a5173c5b34914bd261b693946234f06cb3801507"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expanded_compaction_byte_size_limit\n\nDocumentation:\nMaximum number of bytes in all compacted files. We avoid expanding\nthe lower level file set of a compaction if it would make the\ntotal compaction cover more than this many bytes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn expanded_compaction_byte_size_limit(&self) -> u64 {\n 25 * self.max_file_size\n }\n```"}], "func_name": "expanded_compaction_byte_size_limit", "docstring": "Maximum number of bytes in all compacted files. We avoid expanding\nthe lower level file set of a compaction if it would make the\ntotal compaction cover more than this many bytes.", "repo": "Fullstop000/wickdb", "path": "src/options.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/options.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6635799ed82b78a6d8170b69b804e699dd6b18f6a3d38bfcb316974f61841e03"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: max_grandparent_overlap_bytes\n\nDocumentation:\nMaximum bytes of overlaps in grandparent (i.e., level+2) before we\nstop building a single file in a level-> level+1 compaction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn max_grandparent_overlap_bytes(&self) -> u64 {\n 10 * self.max_file_size\n }\n```"}], "func_name": "max_grandparent_overlap_bytes", "docstring": "Maximum bytes of overlaps in grandparent (i.e., level+2) before we\nstop building a single file in a level-> level+1 compaction.", "repo": "Fullstop000/wickdb", "path": "src/options.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/options.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7f115d70bbb0865433ed7cab999ca7208a8d725f057829d85c15a036c691cc60"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: max_bytes_for_level\n\nDocumentation:\nMaximum bytes of total files in a given level\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn max_bytes_for_level(&self, mut level: usize) -> u64 {\n // Note: the result for level zero is not really used since we set\n // the level-0 compaction threshold based on number of files.\n\n // Result for both level-0 and level-1\n let mut result = self.l1_max_bytes;\n while level > 1 {\n result *= 10;\n level -= 1;\n }\n result\n }\n```"}], "func_name": "max_bytes_for_level", "docstring": "Maximum bytes of total files in a given level", "repo": "Fullstop000/wickdb", "path": "src/options.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/options.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef18042ab045a8372069ab9715502ce0f8ad9d3712d92e73be6bc4ed432d3471"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: table_cache_size\n\nDocumentation:\nReserve `non_table_cache_files` files or so for other uses and give the rest to TableCache\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn table_cache_size(&self) -> usize {\n self.max_open_files - self.non_table_cache_files\n }\n```"}], "func_name": "table_cache_size", "docstring": "Reserve `non_table_cache_files` files or so for other uses and give the rest to TableCache", "repo": "Fullstop000/wickdb", "path": "src/options.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/options.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cec174d5fb6280c8c063b198276d3cb1a65cf97b2b8b3b9c081992fd34800a61"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: acquire\n\nDocumentation:\nCreates a `Snapshot` and appends it to the end of the list\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn acquire(&mut self, seq: u64) -> Arc {\n let last_seq = self.last_seq();\n assert!(seq >= last_seq, \"[snapshot] the sequence number must be monotonically increasing : [new: {}], [last: {}]\", seq, last_seq);\n if last_seq == seq {\n self.newest()\n } else {\n let s = Arc::new(Snapshot {\n sequence_number: seq,\n });\n self.snapshots.push(s.clone());\n s\n }\n }\n```"}], "func_name": "acquire", "docstring": "Creates a `Snapshot` and appends it to the end of the list", "repo": "Fullstop000/wickdb", "path": "src/snapshot.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/snapshot.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "95a81cb000e52bac81c33005567c9e4846cec40462da3bb17ac959ee1fd7228a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: find_table\n\nDocumentation:\nTry to find the sst file from cache. If not found, try to find the file from storage and insert it into the cache\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn find_table(\n &self,\n cmp: TC,\n file_number: u64,\n file_size: u64,\n ) -> Result>> {\n match self.cache.get(&file_number) {\n Some(v) => Ok(v),\n None => {\n let filename = generate_filename(&self.db_path, FileType::Table, file_number);\n let table_file = self.storage.open(&filename)?;\n let table = Table::open(\n table_file,\n file_number,\n file_size,\n self.options.clone(),\n cmp,\n )?;\n let value = Arc::new(table);\n let _ = self.cache.insert(file_number, value.clone(), 1);\n Ok(value)\n }\n }\n }\n```"}], "func_name": "find_table", "docstring": "Try to find the sst file from cache. If not found, try to find the file from storage and insert it into the cache", "repo": "Fullstop000/wickdb", "path": "src/table_cache.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/table_cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "699ddb8f7ce3e41ca592d38fa55d03f17bef12deac7a0ef349e5f221283dcaa4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturns the result of a seek to internal key `key` in specified file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(\n &self,\n cmp: TC,\n options: ReadOptions,\n key: &[u8],\n file_number: u64,\n file_size: u64,\n ) -> Result>> {\n let table = self.find_table(cmp.clone(), file_number, file_size)?;\n table.internal_get(options, cmp, key)\n }\n```"}], "func_name": "get", "docstring": "Returns the result of a seek to internal key `key` in specified file", "repo": "Fullstop000/wickdb", "path": "src/table_cache.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/table_cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d82f985c300f24d65cb1e7d071a0445fbd163eb6facbe8d12997e6cba5013641"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_iter\n\nDocumentation:\nCreate an iterator for the specified `file_number` (the corresponding\nfile length must be exactly `file_size` bytes).\nThe table referenced by returning Iterator will be released after the Iterator is dropped.\n\nEntry format:\nkey: internal key\nvalue: value of user key\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_iter(\n &self,\n cmp: TC,\n options: ReadOptions,\n file_number: u64,\n file_size: u64,\n ) -> Result> {\n let t = self.find_table(cmp.clone(), file_number, file_size)?;\n let iter = new_table_iterator(cmp, t, options);\n Ok(iter)\n }\n```"}], "func_name": "new_iter", "docstring": "Create an iterator for the specified `file_number` (the corresponding\nfile length must be exactly `file_size` bytes).\nThe table referenced by returning Iterator will be released after the Iterator is dropped.\n\nEntry format:\nkey: internal key\nvalue: value of user key", "repo": "Fullstop000/wickdb", "path": "src/table_cache.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/table_cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e42334b5b1af22d878e38568a860e91787e84a34e2bdba0f90243e6dfd0ee282"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new `ShardedCache` with given shards\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(shards: Vec) -> Self {\n Self {\n shards: Arc::new(shards),\n _k: PhantomData,\n _v: PhantomData,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new `ShardedCache` with given shards", "repo": "Fullstop000/wickdb", "path": "src/cache/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/cache/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b1827fb20c1618456800785c8cd90855db8c24d994201bb5558bc410d748f6a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_filename\n\nDocumentation:\nReturns a filename for a certain `FileType` by given sequence number and a `dirname`.\n\n# Safety\n`dirname` must be a valid unicode string\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate_filename(dirname: &str, filetype: FileType, seq: u64) -> String {\n let dirname = Path::new(dirname).to_owned();\n match filetype {\n FileType::Log => dirname\n .join(format!(\"{:06}.log\", seq))\n .into_os_string()\n .into_string()\n .unwrap(),\n FileType::Lock => dirname.join(\"LOCK\").into_os_string().into_string().unwrap(),\n FileType::Table => dirname\n .join(format!(\"{:06}.sst\", seq))\n .into_os_string()\n .into_string()\n .unwrap(),\n FileType::Manifest => dirname\n .join(format!(\"MANIFEST-{:06}\", seq))\n .into_os_string()\n .into_string()\n .unwrap(),\n FileType::Current => dirname\n .join(\"CURRENT\")\n .into_os_string()\n .into_string()\n .unwrap(),\n FileType::Temp => dirname\n .join(format!(\"{:06}.dbtmp\", seq))\n .into_os_string()\n .into_string()\n .unwrap(),\n FileType::InfoLog => dirname.join(\"LOG\").into_os_string().into_string().unwrap(),\n FileType::OldInfoLog => dirname\n .join(\"LOG.old\")\n .into_os_string()\n .into_string()\n .unwrap(),\n }\n}\n```"}], "func_name": "generate_filename", "docstring": "Returns a filename for a certain `FileType` by given sequence number and a `dirname`.\n\n# Safety\n`dirname` must be a valid unicode string", "repo": "Fullstop000/wickdb", "path": "src/db/filename.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/db/filename.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1490ece9faf0e45e70960280d3fc4e0b67fc99f3819bc587d7f4f0e8ecc2b782"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_filename\n\nDocumentation:\nReturns a tuple that contains `FileType` and the sequence number of the file.\nThe `filename` should be a valid path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_filename>(filename: P) -> Option<(FileType, u64)> {\n let invalid = \"invalid\";\n let path = filename.as_ref();\n let file_stem = path.file_stem().unwrap_or_else(|| OsStr::new(invalid));\n match file_stem.to_str() {\n Some(\"CURRENT\") => Some((FileType::Current, 0)),\n Some(\"LOCK\") => Some((FileType::Lock, 0)),\n Some(\"LOG\") => match path.file_name().unwrap_or_else(|| OsStr::new(\"\")).to_str() {\n Some(\"LOG\") => Some((FileType::InfoLog, 0)),\n Some(\"LOG.old\") => Some((FileType::OldInfoLog, 0)),\n _ => None,\n },\n Some(with_seq) => {\n if with_seq.starts_with(\"MANIFEST\") {\n let strs: Vec<&str> = with_seq.split('-').collect();\n if strs.len() != 2 {\n return None;\n }\n if let Ok(seq) = strs[1].parse::() {\n return Some((FileType::Manifest, seq));\n }\n return None;\n };\n if let Ok(seq) = with_seq.parse::() {\n match path\n .extension()\n .unwrap_or_else(|| OsStr::new(invalid))\n .to_str()\n {\n Some(\"log\") => {\n return Some((FileType::Log, seq));\n }\n Some(\"sst\") => {\n return Some((FileType::Table, seq));\n }\n Some(\"dbtmp\") => {\n return Some((FileType::Temp, seq));\n }\n _ => {\n return None;\n }\n }\n };\n None\n }\n _ => None,\n }\n}\n```"}], "func_name": "parse_filename", "docstring": "Returns a tuple that contains `FileType` and the sequence number of the file.\nThe `filename` should be a valid path.", "repo": "Fullstop000/wickdb", "path": "src/db/filename.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/db/filename.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d2200c17f6becae56abd40f1894f970e10a676345b75dd7d1bab252abc97b3ae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_current\n\nDocumentation:\nUpdate the CURRENT file to point to new MANIFEST file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn update_current(env: &S, dir: &str, manifest_file_num: u64) -> Result<()> {\n let mut manifest = generate_filename(dir, FileType::Manifest, manifest_file_num);\n manifest.drain(0..=dir.len());\n let tmp = generate_filename(dir, FileType::Temp, manifest_file_num);\n let result = do_write_string_to_file(env, manifest, &tmp, true);\n match &result {\n Ok(()) => env.rename(&tmp, &generate_filename(dir, FileType::Current, 0))?,\n Err(_) => env.remove(&tmp)?,\n }\n result\n}\n```"}], "func_name": "update_current", "docstring": "Update the CURRENT file to point to new MANIFEST file", "repo": "Fullstop000/wickdb", "path": "src/db/filename.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/db/filename.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b72289b3f88eb0b86ec5262fc21c43f2824a64809d38a0d79ba183ad2268fdd7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decode_from\n\nDocumentation:\nTry to extract a `ParsedInternalKey` from given bytes.\nReturns `None` if data length is less than 8 or getting an unknown value type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn decode_from(internal_key: &'a [u8]) -> Option> {\n let size = internal_key.len();\n if size < INTERNAL_KEY_TAIL {\n return None;\n }\n let num = decode_fixed_64(&internal_key[size - INTERNAL_KEY_TAIL..]);\n let t = ValueType::from(num & 0xff);\n if t == ValueType::Unknown {\n return None;\n }\n let seq = num >> INTERNAL_KEY_TAIL;\n Some(Self {\n user_key: &internal_key[..size - INTERNAL_KEY_TAIL],\n seq,\n value_type: t,\n })\n }\n```"}], "func_name": "decode_from", "docstring": "Try to extract a `ParsedInternalKey` from given bytes.\nReturns `None` if data length is less than 8 or getting an unknown value type.", "repo": "Fullstop000/wickdb", "path": "src/db/format.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/db/format.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6828b7c6f9febdd9374899b5622d3f81283c848e39f033021a008589560cad7f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compact_range\n\nDocumentation:\nSchedule a compaction for the key range `[begin, end]`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compact_range(&self, begin: Option<&[u8]>, end: Option<&[u8]>) -> Result<()> {\n self.inner.compact_range(begin, end)\n }\n```"}], "func_name": "compact_range", "docstring": "Schedule a compaction for the key range `[begin, end]`.", "repo": "Fullstop000/wickdb", "path": "src/db/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/db/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5032dc57aa7d3985d9cb8b1f4ddb681082874247423b569417ee5bb868e8aab5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compact_range_at\n\nDocumentation:\nSchedue a manual compaction for the key range `[begin, end]` at level `level`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compact_range_at(\n &self,\n level: usize,\n begin: Option<&[u8]>,\n end: Option<&[u8]>,\n ) -> Result<()> {\n self.inner.manual_compact_range(level, begin, end)\n }\n```"}], "func_name": "compact_range_at", "docstring": "Schedue a manual compaction for the key range `[begin, end]` at level `level`", "repo": "Fullstop000/wickdb", "path": "src/db/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/db/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b0a93f66a8b17f5b7eb131367bc00586cb85788d4653efa488f47fbd8f9cbff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: release_snapshot\n\nDocumentation:\nReturns true if the given snapshot is removed\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn release_snapshot(&self, s: Arc) -> bool {\n let mut vset = self.inner.versions.lock().unwrap();\n vset.snapshots.release(s)\n }\n```"}], "func_name": "release_snapshot", "docstring": "Returns true if the given snapshot is removed", "repo": "Fullstop000/wickdb", "path": "src/db/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/db/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c57883645b6406ffe945ae22a7705e00bc6743a48dfecd95a68304153d15764d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add\n\nDocumentation:\nAdd an entry into memtable that maps key to value at the\nspecified sequence number and with the specified type.\nTypically value will be empty if the type is `Deletion`.\n\nThe 'key' and 'value' will be bundled together into an 'entry':\n\n```text\n+=================================+\n| format of the entry |\n+=================================+\n| varint32 of internal key length |\n+---------------------------------+ ---------------\n| user key bytes |\n+---------------------------------+ internal key\n| sequence (7) | type (1) |\n+---------------------------------+ ---------------\n| varint32 of value length |\n+---------------------------------+\n| value bytes |\n+---------------------------------+\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add(&self, seq_number: u64, val_type: ValueType, key: &[u8], value: &[u8]) {\n let key_size = key.len();\n let internal_key_size = key_size + INTERNAL_KEY_TAIL;\n let mut buf = vec![];\n VarintU32::put_varint(&mut buf, internal_key_size as u32);\n buf.extend_from_slice(key);\n put_fixed_64(\n &mut buf,\n (seq_number << INTERNAL_KEY_TAIL) | val_type as u64,\n );\n VarintU32::put_varint_prefixed_slice(&mut buf, value);\n self.table.put(buf);\n }\n```"}], "func_name": "add", "docstring": "Add an entry into memtable that maps key to value at the\nspecified sequence number and with the specified type.\nTypically value will be empty if the type is `Deletion`.\n\nThe 'key' and 'value' will be bundled together into an 'entry':\n\n```text\n+=================================+\n| format of the entry |\n+=================================+\n| varint32 of internal key length |\n+---------------------------------+ ---------------\n| user key bytes |\n+---------------------------------+ internal key\n| sequence (7) | type (1) |\n+---------------------------------+ ---------------\n| varint32 of value length |\n+---------------------------------+\n| value bytes |\n+---------------------------------+\n```", "repo": "Fullstop000/wickdb", "path": "src/mem/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/mem/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54b034fe3de37690c4a8fdc80f5e1d316d563dce0c2571cfe15c74416f442961"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nIf memtable contains a value for key, returns it in `Some(Ok())`.\nIf memtable contains a deletion for key, returns `Some(Err(Status::NotFound))` .\nIf memtable does not contain the key, return `None`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(&self, key: &LookupKey) -> Option>> {\n let mk = key.mem_key();\n let mut iter = InlineSkiplistIterator::new(self.table.clone());\n iter.seek(mk);\n if iter.valid() {\n let mut e = iter.key();\n let ikey = extract_varint32_encoded_slice(&mut e);\n let key_size = ikey.len();\n // only check the user key here\n match self\n .cmp\n .icmp\n .user_comparator\n .compare(&ikey[..key_size - INTERNAL_KEY_TAIL], key.user_key())\n {\n Ordering::Equal => {\n let tag = decode_fixed_64(&ikey[key_size - INTERNAL_KEY_TAIL..]);\n match ValueType::from(tag & 0xff_u64) {\n ValueType::Value => {\n return Some(Ok(extract_varint32_encoded_slice(&mut e).to_vec()))\n }\n ValueType::Deletion => return Some(Err(Error::NotFound(None))),\n ValueType::Unknown => { /* fallback to None*/ }\n }\n }\n _ => return None,\n }\n }\n None\n }\n```"}], "func_name": "get", "docstring": "If memtable contains a value for key, returns it in `Some(Ok())`.\nIf memtable contains a deletion for key, returns `Some(Err(Status::NotFound))` .\nIf memtable does not contain the key, return `None`", "repo": "Fullstop000/wickdb", "path": "src/mem/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/mem/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e9310f09c74e09c538ad114123d4bcff8c6e3dc25d87c04b92eedcfc6f2f2c40"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new Skiplist with the given arena capacity\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(cmp: C, arena: A) -> Self {\n let head = Node::new(Bytes::new(), MAX_HEIGHT, &arena);\n Skiplist {\n comparator: cmp,\n // init height is 1 ( ignore the height of head )\n max_height: AtomicUsize::new(1),\n arena,\n head,\n count: AtomicUsize::new(0),\n size: AtomicUsize::new(0),\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new Skiplist with the given arena capacity", "repo": "Fullstop000/wickdb", "path": "src/mem/skiplist.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/mem/skiplist.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "19195b84a390543a201a942b3d13773205c6cbdb1cc248d5b1253e56d1d1b450"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nInsert the given key as a node into the skiplist.\nThe key must be unique otherwise this method panics.\n\n# NOTICE:\n\nConcurrent insertion is not thread safe but concurrent reading with a\nsingle writer is safe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert(&self, key: impl Into) {\n let key = key.into();\n let length = key.len();\n let mut prev = [ptr::null(); MAX_HEIGHT];\n let node = self.find_greater_or_equal(&key, Some(&mut prev));\n if !node.is_null() {\n unsafe {\n assert_ne!(\n self.comparator.compare((&(*node)).key(), &key),\n CmpOrdering::Equal,\n \"[skiplist] duplicate insertion [key={:?}] is not allowed\",\n &key\n );\n }\n }\n let height = rand_height();\n let max_height = self.max_height.load(Ordering::Acquire);\n if height > max_height {\n for p in prev.iter_mut().take(height).skip(max_height) {\n *p = self.head;\n }\n self.max_height.store(height, Ordering::Release);\n }\n // allocate the node\n let new_node = Node::new(key, height, &self.arena);\n unsafe {\n for i in 1..=height {\n (*new_node).set_next(i, (*(prev[i - 1])).get_next(i));\n (*(prev[i - 1])).set_next(i, new_node as *mut Node);\n }\n }\n self.count.fetch_add(1, Ordering::SeqCst);\n self.size.fetch_add(length, Ordering::SeqCst);\n }\n```"}], "func_name": "insert", "docstring": "Insert the given key as a node into the skiplist.\nThe key must be unique otherwise this method panics.\n\n# NOTICE:\n\nConcurrent insertion is not thread safe but concurrent reading with a\nsingle writer is safe.", "repo": "Fullstop000/wickdb", "path": "src/mem/skiplist.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/mem/skiplist.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fab6221a2f83699f82e734d288c988823fe9d159fdb8ff254dbcdcf3ead7adc4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: key_is_less_than_or_equal\n\nDocumentation:\nReturn whether the give key is less than the given node's key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn key_is_less_than_or_equal(&self, key: &[u8], n: *const Node) -> bool {\n if n.is_null() {\n // take nullptr as +infinite large\n true\n } else {\n let node_key = unsafe { (*n).key() };\n !matches!(self.comparator.compare(key, node_key), CmpOrdering::Greater)\n }\n }\n```"}], "func_name": "key_is_less_than_or_equal", "docstring": "Return whether the give key is less than the given node's key.", "repo": "Fullstop000/wickdb", "path": "src/mem/skiplist.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/mem/skiplist.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a21a3b3dac01a947c54b8758f85c68b830c3e8b1ab50e9f14fa88221b08ef88"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_record\n\nDocumentation:\nRead the next complete record into given `buf`.\nReturns true if read successfully, false if we hit end of the input.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_record(&mut self, buf: &mut Vec) -> bool {\n if self.last_record_offset < self.initial_offset && !self.skip_to_initial_block() {\n return false;\n }\n // indicates that a record has been spilt into fragments\n let mut in_fragmented_record = false;\n // Record offset of the logical record that we're reading\n let mut prospective_record_offset = 0;\n loop {\n match self.read_physical_record() {\n Ok(mut record) => {\n if self.resyncing {\n match record.t {\n RecordType::Middle => continue,\n RecordType::Last => {\n self.resyncing = false;\n continue;\n }\n _ => self.resyncing = false,\n }\n }\n let fragment_size = record.data.len() as u64;\n // the start offset of the current read record\n let physical_record_offset = self.end_of_buffer_offset\n - self.buf_length as u64\n - HEADER_SIZE as u64\n - fragment_size;\n match record.t {\n RecordType::Full => {\n if in_fragmented_record {\n self.report_drop(\n buf.len() as u64,\n \"partial record without end(1) for reading a new Full record\",\n );\n }\n // update record offset\n self.last_record_offset = physical_record_offset;\n buf.clear();\n buf.append(&mut record.data);\n return true;\n }\n RecordType::First => {\n if in_fragmented_record {\n self.report_drop(\n buf.len() as u64,\n \"partial record without end(2) for reading a new First record\",\n );\n }\n prospective_record_offset = physical_record_offset;\n\n // clean the potential corruption\n buf.clear();\n buf.append(&mut record.data);\n in_fragmented_record = true;\n }\n RecordType::Middle => {\n if !in_fragmented_record {\n self.report_drop(\n fragment_size,\n format!(\n \"missing start of fragmented record({:?})\",\n RecordType::Middle\n )\n .as_str(),\n );\n // continue reading until find a new first or full record\n } else {\n buf.append(&mut record.data);\n }\n }\n RecordType::Last => {\n if !in_fragmented_record {\n self.report_drop(\n fragment_size,\n format!(\n \"missing start of fragmented record({:?})\",\n RecordType::Last\n )\n .as_str(),\n );\n // continue reading until find a new first or full record\n } else {\n buf.extend(record.data);\n // notice that we update the last_record_offset after we get the Last part but not the First\n self.last_record_offset = prospective_record_offset;\n return true;\n }\n }\n RecordType::Zero => {\n /* zero type record is considered as irrelevant and should never be read out*/\n }\n }\n }\n Err(e) => {\n match e {\n ReaderError::EOF => {\n if in_fragmented_record {\n // This can be caused by the writer dying immediately after writing a\n // physical record but before completing the next\n // one; don't treat it as a corruption,\n // just ignore the entire logical record.\n buf.clear();\n }\n return false;\n }\n ReaderError::BadRecord => {\n if in_fragmented_record {\n self.report_drop(\n buf.len() as u64,\n \"bad record read in middle of record\",\n );\n in_fragmented_record = false;\n buf.clear();\n }\n }\n }\n }\n }\n }\n }\n```"}], "func_name": "read_record", "docstring": "Read the next complete record into given `buf`.\nReturns true if read successfully, false if we hit end of the input.", "repo": "Fullstop000/wickdb", "path": "src/record/reader.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/record/reader.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef90e575db15e8379b899d7f1018edc02746485ce631797314b8fda73944c3be"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: skip_to_initial_block\n\nDocumentation:\nSkips all blocks that are completely before `initial_offset`\nReturns true on success. Handles reporting.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn skip_to_initial_block(&mut self) -> bool {\n let offset_in_block = self.initial_offset % BLOCK_SIZE as u64;\n let mut block_start_location = self.initial_offset - offset_in_block;\n\n // skip to next block starting if we'd be in the trailer\n if offset_in_block > BLOCK_SIZE as u64 - 6 {\n block_start_location += BLOCK_SIZE as u64;\n }\n self.end_of_buffer_offset = block_start_location;\n if block_start_location > 0 {\n if let Err(e) = self.file.seek(SeekFrom::Start(block_start_location)) {\n self.report_drop(block_start_location, &e.to_string());\n return false;\n }\n }\n true\n }\n```"}], "func_name": "skip_to_initial_block", "docstring": "Skips all blocks that are completely before `initial_offset`\nReturns true on success. Handles reporting.", "repo": "Fullstop000/wickdb", "path": "src/record/reader.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/record/reader.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e2eb243a70167f52f416afb9a3f77e7d1602f6e4abeaf740e083b2baf2fa18b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_record\n\nDocumentation:\nAppends a slice into the underlying log file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_record(&mut self, s: &[u8]) -> Result<()> {\n let mut left = s.len();\n let mut begin = true; // indicate the record is a First or Middle record\n while {\n assert!(\n BLOCK_SIZE >= self.block_offset,\n \"[record writer] the 'block_offset' {} overflows the max BLOCK_SIZE {}\",\n self.block_offset,\n BLOCK_SIZE,\n );\n let leftover = BLOCK_SIZE - self.block_offset;\n\n // switch to a new block if the left size is not enough\n // for a record header\n if leftover < HEADER_SIZE {\n if leftover != 0 {\n // fill the rest of the block with zero\n self.dest.write(&[0; 6][..leftover])?;\n }\n self.block_offset = 0; // use a new block\n };\n assert!(\n BLOCK_SIZE >= self.block_offset + HEADER_SIZE,\n \"[record writer] the left space of block {} is less than header size {}\",\n BLOCK_SIZE - self.block_offset,\n HEADER_SIZE,\n );\n let space = BLOCK_SIZE - self.block_offset - HEADER_SIZE;\n let to_write = if left < space { left } else { space };\n let end = to_write == left; // indicates whether the data exhausts a record\n let t = {\n if begin && end {\n RecordType::Full\n } else if begin {\n RecordType::First\n } else if end {\n RecordType::Last\n } else {\n RecordType::Middle\n }\n };\n\n let start = s.len() - left;\n self.write(t, &s[start..start + to_write])?;\n left -= to_write;\n begin = false;\n left > 0\n } { /* empty here */ }\n Ok(())\n }\n```"}], "func_name": "add_record", "docstring": "Appends a slice into the underlying log file", "repo": "Fullstop000/wickdb", "path": "src/record/writer.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/record/writer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "07e9765c699d3bd5456d54091a8d9f639418f3719d438f7b6a2920036b5d0e22"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a `Block` instance.\n\n# Errors\n\nIf the given `data` is invalid, return an error with `Status::Corruption`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(data: Vec) -> Result {\n let size = data.len();\n if size >= U32_LEN {\n let max_restarts_allowed = (size - U32_LEN) / U32_LEN;\n let restarts_len = Self::restarts_len(&data);\n // make sure the size is enough for restarts\n if restarts_len as usize <= max_restarts_allowed {\n return Ok(Self {\n data: Arc::new(data),\n restart_offset: (size - (1 + restarts_len as usize) * U32_LEN) as u32,\n restarts_len,\n });\n }\n };\n Err(Error::Corruption(\n \"[block] read invalid block content\".to_owned(),\n ))\n }\n```"}], "func_name": "new", "docstring": "Create a `Block` instance.\n\n# Errors\n\nIf the given `data` is invalid, return an error with `Status::Corruption`", "repo": "Fullstop000/wickdb", "path": "src/sstable/block.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/block.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2dd7a1d96de49caf723aea9767ffd28c523baef73122e283a72e9ea2964592ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: current_size_estimate\n\nDocumentation:\nReturns the bytes size of `buffer` + bytes size of `restarts` + restart array length\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn current_size_estimate(&self) -> usize {\n self.buffer.len() + self.restarts.len() * 4 + 4\n }\n```"}], "func_name": "current_size_estimate", "docstring": "Returns the bytes size of `buffer` + bytes size of `restarts` + restart array length", "repo": "Fullstop000/wickdb", "path": "src/sstable/block.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/block.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18ee0fa1b89b5bd29822baf0e7c7760285cf37537f7eaa3cd0768446f2d0c537"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish\n\nDocumentation:\nAppends the block restarts metadata and returns the block data\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn finish(&mut self) -> &[u8] {\n for restart in self.restarts.iter() {\n put_fixed_32(&mut self.buffer, *restart)\n }\n put_fixed_32(&mut self.buffer, self.restarts.len() as u32);\n self.finished = true;\n &self.buffer\n }\n```"}], "func_name": "finish", "docstring": "Appends the block restarts metadata and returns the block data", "repo": "Fullstop000/wickdb", "path": "src/sstable/block.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/block.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "59aa22c2edeaf6221c4058c53bf1c6315c719bdba33c126a68a88932d719df29"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add\n\nDocumentation:\nAppends key and value to the buffer\n\n# Panic\n\n* If this BlockBuilder is finished\n* If the `counter` is invalid\n* If the given `key` is not consistent with the previous one\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add(&mut self, key: &[u8], value: &[u8]) {\n assert!(\n !self.finished,\n \"[block builder] add key value to a finished BlockBuilder \"\n );\n assert!(\n self.counter <= self.block_restart_interval,\n \"[block builder] BlockBuilder reaches the counter limit {} \",\n self.block_restart_interval,\n );\n assert!(\n self.buffer.is_empty()\n || self.cmp.compare(key, self.last_key.as_slice()) == Ordering::Greater,\n \"[block builder] inconsistent new key [{:?}] compared to last_key {:?}\",\n key,\n &self.last_key\n );\n let mut shared = 0;\n if self.counter < self.block_restart_interval {\n let min_len = min(self.last_key.len(), key.len());\n // calc the sharing the given key with previous key\n while shared < min_len && self.last_key[shared] == key[shared] {\n shared += 1\n }\n } else {\n // restart compression\n self.restarts.push(self.buffer.len() as u32);\n self.counter = 0;\n }\n let non_shared = key.len() - shared;\n\n // | --- shared --- | --- non_shared --- | --- value length --- |\n VarintU32::put_varint(&mut self.buffer, shared as u32);\n VarintU32::put_varint(&mut self.buffer, non_shared as u32);\n VarintU32::put_varint(&mut self.buffer, value.len() as u32);\n // append delta key and value\n self.buffer.extend_from_slice(&key[shared..]);\n self.buffer.extend_from_slice(value);\n // update last_key\n self.last_key.clear();\n self.last_key.extend_from_slice(key);\n // update counter\n self.counter += 1\n }\n```"}], "func_name": "add", "docstring": "Appends key and value to the buffer\n\n# Panic\n\n* If this BlockBuilder is finished\n* If the `counter` is invalid\n* If the given `key` is not consistent with the previous one", "repo": "Fullstop000/wickdb", "path": "src/sstable/block.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/block.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c2e4514d0bd44e10ce9ef9ffaea876b14c2f76e17e374e49933440c327644ac1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_key\n\nDocumentation:\nAdds the given key into the builder\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_key(&mut self, key: &[u8]) {\n // TODO: remove this clone\n let key = Vec::from(key);\n self.keys.push(key);\n }\n```"}], "func_name": "add_key", "docstring": "Adds the given key into the builder", "repo": "Fullstop000/wickdb", "path": "src/sstable/filter_block.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/filter_block.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9f6a8a85bc7c89b6520cad05ba43bf7748e16d2afb0d8f342eb93f9f1be59b80"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_block\n\nDocumentation:\nGenerates filter data for the data block on given `block_offset`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start_block(&mut self, block_offset: u64) {\n // calc the filter index for the given block offset\n // the filter with the index i handles the block data\n // in offset range [i* FILTER_BASE, (i + 1) * FILTER_BASE)\n let filter_index = block_offset / FILTER_BASE as u64;\n let filters_len = self.filter_offsets.len() as u64;\n assert!(\n filter_index >= filters_len,\n \"[filter block builder] the filter block index {} should larger than built filters {}\",\n filter_index,\n filters_len,\n );\n // the loop here is a little tricky\n while filter_index > self.filter_offsets.len() as u64 {\n self.generate_filter();\n }\n }\n```"}], "func_name": "start_block", "docstring": "Generates filter data for the data block on given `block_offset`", "repo": "Fullstop000/wickdb", "path": "src/sstable/filter_block.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/filter_block.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9739a14df8332d13f865dd14dccdd208b20550b892d99a8344b2bd5551509384"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish\n\nDocumentation:\nAppends the trailer of filter block and returns the filter block data in bytes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn finish(&mut self) -> &[u8] {\n if !self.keys.is_empty() {\n // clean up the remaining keys\n self.generate_filter();\n };\n // append per-filter offsets\n for offset in self.filter_offsets.iter() {\n put_fixed_32(&mut self.data, *offset);\n }\n // append the 4bytes offset length\n put_fixed_32(&mut self.data, self.filter_offsets.len() as u32);\n // append the 1byte base lg\n self.data.push(FILTER_BASE_LG as u8);\n &self.data\n }\n```"}], "func_name": "finish", "docstring": "Appends the trailer of filter block and returns the filter block data in bytes", "repo": "Fullstop000/wickdb", "path": "src/sstable/filter_block.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/filter_block.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7d89a3342f538e4b7d40b72edb60f2e4e4b669baf0648f589158a5b0f0854b05"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: key_may_match\n\nDocumentation:\nReturns true if the given key is probably contained in the given `block_offset` block\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn key_may_match(&self, block_offset: u64, key: &[u8]) -> bool {\n let i = block_offset as usize >> self.base_lg; // a >> b == a / (1 << b)\n if i < self.num {\n let (filter, offsets) = &self\n .data\n .split_at(self.data.len() - self.num * FILTER_OFFSET_LEN);\n let start =\n decode_fixed_32(&offsets[i * FILTER_OFFSET_LEN..(i + 1) * FILTER_OFFSET_LEN])\n as usize;\n let end = {\n if i + 1 >= self.num {\n // this is the last filter\n filter.len()\n } else {\n decode_fixed_32(\n &offsets[(i + 1) * FILTER_OFFSET_LEN..(i + 2) * FILTER_OFFSET_LEN],\n ) as usize\n }\n };\n let filter = &self.data[start..end];\n return self.policy.may_contain(filter, key);\n }\n // errors are treated as potential matches\n // so the iterator will look up the block\n true\n }\n```"}], "func_name": "key_may_match", "docstring": "Returns true if the given key is probably contained in the given `block_offset` block", "repo": "Fullstop000/wickdb", "path": "src/sstable/filter_block.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/filter_block.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "caa89e3578e1d3e4d56b9c191b5a3e4bda8218c3538917b5dd96c90bf6acdf8b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decode_from\n\nDocumentation:\nDecodes a `Footer` from the given `src` bytes and returns the decoded length\n\n# Error\n\nReturns `Status::Corruption` when decoding meta index or index handle fails\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn decode_from(src: &[u8]) -> Result<(Self, usize)> {\n let magic = decode_fixed_64(&src[FOOTER_ENCODED_LENGTH - 8..]);\n if magic != TABLE_MAGIC_NUMBER {\n return Err(Error::Corruption(\n \"not an sstable (bad magic number)\".to_owned(),\n ));\n };\n let (meta_index_handle, n) = BlockHandle::decode_from(src)?;\n let (index_handle, m) = BlockHandle::decode_from(&src[n..])?;\n Ok((\n Self {\n meta_index_handle,\n index_handle,\n },\n m + n,\n ))\n }\n```"}], "func_name": "decode_from", "docstring": "Decodes a `Footer` from the given `src` bytes and returns the decoded length\n\n# Error\n\nReturns `Status::Corruption` when decoding meta index or index handle fails", "repo": "Fullstop000/wickdb", "path": "src/sstable/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fbf91a8428d17710ae41878f6958f396feaf93c7d2eec54a2b73051435c0768c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encoded\n\nDocumentation:\nEncodes footer and returns the encoded bytes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn encoded(&self) -> Vec {\n let mut v = vec![];\n self.meta_index_handle.encoded_to(&mut v);\n self.index_handle.encoded_to(&mut v);\n v.resize(2 * MAX_BLOCK_HANDLE_ENCODE_LENGTH, 0);\n put_fixed_64(&mut v, TABLE_MAGIC_NUMBER);\n assert_eq!(\n v.len(),\n FOOTER_ENCODED_LENGTH,\n \"[footer] the length of encoded footer is {}, expect {}\",\n v.len(),\n FOOTER_ENCODED_LENGTH\n );\n v\n }\n```"}], "func_name": "encoded", "docstring": "Encodes footer and returns the encoded bytes", "repo": "Fullstop000/wickdb", "path": "src/sstable/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0d91e60319384f8e281aeb12facd3d5c8ff7e199bf7d8a0cc0aedbc10d838b2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open\n\nDocumentation:\nAttempt to open the table that is stored in bytes `[0..size)`\nof `file`, and read the metadata entries necessary to allow\nretrieving data from the table.\n\nNOTE: `UC` for user comparator and `TC` for table comparator\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn open(\n file: F,\n file_number: u64,\n file_len: u64,\n options: Arc>,\n cmp: TC,\n ) -> Result {\n if file_len < FOOTER_ENCODED_LENGTH as u64 {\n return Err(Error::Corruption(\n \"file is too short to be an sstable\".to_owned(),\n ));\n };\n // Read footer\n let mut footer_space = vec![0; FOOTER_ENCODED_LENGTH];\n file.read_exact_at(\n footer_space.as_mut_slice(),\n file_len - FOOTER_ENCODED_LENGTH as u64,\n )?;\n let (footer, _) = Footer::decode_from(footer_space.as_slice())?;\n // Read the index block\n let index_block_contents =\n read_block(&file, &footer.index_handle, options.paranoid_checks)?;\n let index_block = Block::new(index_block_contents)?;\n let mut t = Self {\n block_cache: options.block_cache.clone(),\n file,\n file_number,\n filter_reader: None,\n meta_block_handle: None,\n index_block,\n };\n // Read meta block\n if footer.meta_index_handle.size > 0 && options.filter_policy.is_some() {\n // ignore the reading errors since meta info is not needed for operation\n if let Ok(meta_block_contents) =\n read_block(&t.file, &footer.meta_index_handle, options.paranoid_checks)\n {\n if let Ok(meta_block) = Block::new(meta_block_contents) {\n t.meta_block_handle = Some(footer.meta_index_handle);\n let mut iter = meta_block.iter(cmp);\n let filter_key = if let Some(fp) = &options.filter_policy {\n \"filter.\".to_owned() + fp.name()\n } else {\n String::from(\"\")\n };\n // Read filter block\n iter.seek(filter_key.as_bytes());\n if iter.valid() && iter.key() == filter_key.as_bytes() {\n if let Ok((filter_handle, _)) = BlockHandle::decode_from(iter.value()) {\n if let Ok(filter_block) =\n read_block(&t.file, &filter_handle, options.paranoid_checks)\n {\n t.filter_reader = Some(FilterBlockReader::new(\n options.filter_policy.clone().unwrap(),\n filter_block,\n ));\n }\n }\n }\n }\n }\n }\n Ok(t)\n }\n```"}], "func_name": "open", "docstring": "Attempt to open the table that is stored in bytes `[0..size)`\nof `file`, and read the metadata entries necessary to allow\nretrieving data from the table.\n\nNOTE: `UC` for user comparator and `TC` for table comparator", "repo": "Fullstop000/wickdb", "path": "src/sstable/table.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/table.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d4fea108850c427fe89ffbd9e7eda3d20a2447918b22b6b668523829b9ea0b7f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: internal_get\n\nDocumentation:\nFinds the first entry with the key equal or greater than target and\nreturns the block iterator direclty\n\nThe given `key` is an internal key so the `cmp` must be a InternalKeyComparator\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn internal_get(\n &self,\n options: ReadOptions,\n cmp: TC,\n key: &[u8],\n ) -> Result>> {\n let mut index_iter = self.index_block.iter(cmp.clone());\n // seek to the first 'last key' bigger than 'key'\n index_iter.seek(key);\n if index_iter.valid() {\n // It's called 'maybe_contained' not only because the filter policy may report the falsy result,\n // but also even if we've found a block with the last key bigger than the target\n // the key may not be contained if the block is the first block of the sstable.\n let mut maybe_contained = true;\n\n let handle_val = index_iter.value();\n // check the filter block\n if let Some(filter) = &self.filter_reader {\n if let Ok((handle, _)) = BlockHandle::decode_from(handle_val) {\n if !filter.key_may_match(handle.offset, key) {\n maybe_contained = false;\n }\n }\n }\n if maybe_contained {\n let (data_block_handle, _) = BlockHandle::decode_from(handle_val)?;\n let mut block_iter = self.block_reader(cmp, data_block_handle, options)?;\n block_iter.seek(key);\n if block_iter.valid() {\n return Ok(Some(block_iter));\n }\n block_iter.seek_to_first();\n while block_iter.valid() {\n block_iter.next();\n }\n block_iter.status()?;\n }\n }\n index_iter.status()?;\n Ok(None)\n }\n```"}], "func_name": "internal_get", "docstring": "Finds the first entry with the key equal or greater than target and\nreturns the block iterator direclty\n\nThe given `key` is an internal key so the `cmp` must be a InternalKeyComparator", "repo": "Fullstop000/wickdb", "path": "src/sstable/table.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/table.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5775ef0fc51482e5c99c0d9b76a64a1272062e32d61b2605f01746b8b0464436"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: approximate_offset_of\n\nDocumentation:\nGiven a key, return an approximate byte offset in the file where\nthe data for that key begins (or would begin if the key were\npresent in the file). The returned value is in terms of file\nbytes, and so includes effects like compression of the underlying data.\nE.g., the approximate offset of the last key in the table will\nbe close to the file length.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn approximate_offset_of(&self, cmp: TC, key: &[u8]) -> u64 {\n let mut index_iter = self.index_block.iter(cmp);\n index_iter.seek(key);\n if index_iter.valid() {\n let val = index_iter.value();\n if let Ok((h, _)) = BlockHandle::decode_from(val) {\n return h.offset;\n }\n }\n if let Some(meta) = &self.meta_block_handle {\n return meta.offset;\n }\n 0\n }\n```"}], "func_name": "approximate_offset_of", "docstring": "Given a key, return an approximate byte offset in the file where\nthe data for that key begins (or would begin if the key were\npresent in the file). The returned value is in terms of file\nbytes, and so includes effects like compression of the underlying data.\nE.g., the approximate offset of the last key in the table will\nbe close to the file length.", "repo": "Fullstop000/wickdb", "path": "src/sstable/table.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/table.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b5b3c24e150b94149b2a7cd4966b89b852c0ea85219ba1bfe9c5a92df2fe8ecb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_table_iterator\n\nDocumentation:\nCreate a new `ConcatenateIterator` as table iterator.\nThis iterator is able to yield all the key/values in the given `table` file\n\nEntry format:\nkey: internal key\nvalue: value of user key\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_table_iterator(\n cmp: C,\n table: Arc>,\n options: ReadOptions,\n) -> TableIterator {\n let index_iter = table.index_block.iter(cmp.clone());\n let factory = TableIterFactory {\n options,\n table,\n cmp,\n };\n ConcatenateIterator::new(index_iter, factory)\n}\n```"}], "func_name": "new_table_iterator", "docstring": "Create a new `ConcatenateIterator` as table iterator.\nThis iterator is able to yield all the key/values in the given `table` file\n\nEntry format:\nkey: internal key\nvalue: value of user key", "repo": "Fullstop000/wickdb", "path": "src/sstable/table.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/table.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5af0568d9a12d0735b159b264f795f5a3b5d1e03c3303f3dbadc608d4760492"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: flush\n\nDocumentation:\nFlushes any buffered key/value pairs to file.\nCan be used to ensure that two adjacent entries never live in\nthe same data block. Most clients should not need to use this method.\n\n# Panics\n\n* The table builder is closed\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn flush(&mut self) -> Result<()> {\n self.assert_not_closed();\n if !self.data_block.is_empty() {\n assert!(!self.pending_index_entry, \"[table builder] the index for the previous data block should never remain when flushing current block data\");\n let data_block = self.data_block.finish();\n let (compressed, compression) = compress_block(data_block, self.compression)?;\n write_raw_block(\n &mut self.file,\n compressed.as_slice(),\n compression,\n &mut self.pending_handle,\n &mut self.offset,\n )?;\n self.data_block.reset();\n self.pending_index_entry = true;\n self.file.flush()?;\n if let Some(fb) = &mut self.filter_block {\n fb.start_block(self.offset)\n }\n }\n Ok(())\n }\n```"}], "func_name": "flush", "docstring": "Flushes any buffered key/value pairs to file.\nCan be used to ensure that two adjacent entries never live in\nthe same data block. Most clients should not need to use this method.\n\n# Panics\n\n* The table builder is closed", "repo": "Fullstop000/wickdb", "path": "src/sstable/table.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/table.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9e24e22283304c627fe3b8737f1c1b161ea62a9d7bb4eab5cb80d05314fd073d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish\n\nDocumentation:\nFinishes building the table and close the relative file.\nIf `sync` is true, the `File::flush` will be called.\n\n# Panics\n\n* The table builder is closed\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn finish(&mut self, sync: bool) -> Result<()> {\n self.flush()?;\n self.assert_not_closed();\n self.closed = true;\n // write filter block\n let mut filter_block_handler = BlockHandle::new(0, 0);\n let mut has_filter_block = false;\n if let Some(fb) = &mut self.filter_block {\n let data = fb.finish();\n write_raw_block(\n &mut self.file,\n data,\n CompressionType::NoCompression,\n &mut filter_block_handler,\n &mut self.offset,\n )?;\n has_filter_block = true;\n }\n\n // write meta block\n let mut meta_block_handle = BlockHandle::new(0, 0);\n let mut meta_block_builder =\n BlockBuilder::new(self.block_restart_interval, self.cmp.clone());\n let meta_block = {\n if has_filter_block {\n let filter_key = if let Some(fp) = &self.filter_policy {\n \"filter.\".to_owned() + fp.name()\n } else {\n String::from(\"\")\n };\n meta_block_builder.add(filter_key.as_bytes(), &filter_block_handler.encoded());\n }\n meta_block_builder.finish()\n };\n self.write_block(meta_block, &mut meta_block_handle)?;\n\n // Write index block\n self.maybe_append_index_block(None); // flush the last index first\n let index_block = self.index_block.finish();\n let mut index_block_handle = BlockHandle::new(0, 0);\n let (c_index_block, ct) = compress_block(index_block, self.compression)?;\n write_raw_block(\n &mut self.file,\n c_index_block.as_slice(),\n ct,\n &mut index_block_handle,\n &mut self.offset,\n )?;\n self.index_block.reset();\n // write footer\n let footer = Footer::new(meta_block_handle, index_block_handle).encoded();\n self.file.write(footer.as_slice())?;\n self.offset += footer.len() as u64;\n if sync {\n self.file.flush()?;\n self.file.close()?;\n }\n Ok(())\n }\n```"}], "func_name": "finish", "docstring": "Finishes building the table and close the relative file.\nIf `sync` is true, the `File::flush` will be called.\n\n# Panics\n\n* The table builder is closed", "repo": "Fullstop000/wickdb", "path": "src/sstable/table.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/sstable/table.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a180360f671e42d870684f74906b0b60cc33e6f3d87b157365a77ca8a28994b7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_exact_at\n\nDocumentation:\nReads the exact number of bytes required to fill `buf` from an `offset`.\n\nErrors if the \"EOF\" is encountered before filling the buffer.\n\nSee [`Read::read_exact()`](https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact)\nfor details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_exact_at(&self, mut buf: &mut [u8], mut offset: u64) -> Result<()> {\n while !buf.is_empty() {\n match self.read_at(buf, offset) {\n Ok(0) => break,\n Ok(n) => {\n let tmp = buf;\n buf = &mut tmp[n..];\n offset += n as u64;\n }\n Err(e) => match e {\n Error::IO(err) => {\n if err.kind() != io::ErrorKind::Interrupted {\n return Err(Error::IO(err));\n }\n }\n _ => return Err(e),\n },\n }\n }\n if !buf.is_empty() {\n let e = io::Error::new(io::ErrorKind::UnexpectedEof, \"failed to fill whole buffer\");\n Err(Error::IO(e))\n } else {\n Ok(())\n }\n }\n```"}], "func_name": "read_exact_at", "docstring": "Reads the exact number of bytes required to fill `buf` from an `offset`.\n\nErrors if the \"EOF\" is encountered before filling the buffer.\n\nSee [`Read::read_exact()`](https://doc.rust-lang.org/std/io/trait.Read.html#method.read_exact)\nfor details.", "repo": "Fullstop000/wickdb", "path": "src/storage/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d3593d6b91e346a41f4a33a9fefb86a80ff30bae124aed593d5fdd00f988e4c0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: do_write_string_to_file\n\nDocumentation:\nWrite given `data` into underlying `env` file and flush file iff `should_sync` is true\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn do_write_string_to_file>(\n env: &S,\n data: String,\n file_name: P,\n should_sync: bool,\n) -> Result<()> {\n let mut file = env.create(&file_name)?;\n file.write(data.as_bytes())?;\n if should_sync {\n file.flush()?;\n }\n if file.close().is_err() {\n env.remove(&file_name)?;\n }\n Ok(())\n}\n```"}], "func_name": "do_write_string_to_file", "docstring": "Write given `data` into underlying `env` file and flush file iff `should_sync` is true", "repo": "Fullstop000/wickdb", "path": "src/storage/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/storage/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7edf6fbc27cad9299fd728e58f97e69c40d3d2260d91a8a6112ade773703ae69"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode_fixed_32\n\nDocumentation:\nEncodes `value` in little-endian and puts it in the first 4-bytes of `dst`.\n\n# Panics\n\nPanics if `dst.len()` is less than 4.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn encode_fixed_32(dst: &mut [u8], value: u32) {\n assert!(\n dst.len() >= 4,\n \"the length of 'dst' must be at least 4 for a u32, but got {}\",\n dst.len()\n );\n unsafe {\n let bytes = transmute::(value.to_le());\n copy_nonoverlapping(bytes.as_ptr(), dst.as_mut_ptr(), 4);\n }\n}\n```"}], "func_name": "encode_fixed_32", "docstring": "Encodes `value` in little-endian and puts it in the first 4-bytes of `dst`.\n\n# Panics\n\nPanics if `dst.len()` is less than 4.", "repo": "Fullstop000/wickdb", "path": "src/util/coding.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/util/coding.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "996571e5bb070fd68b3a6434a96310e5405fd621302592e93f60d5f65ee5215b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode_fixed_64\n\nDocumentation:\nEncodes `value` in little-endian and puts in the first 8-bytes of `dst`.\n\n# Panics\n\nPanics if `dst.len()` is less than 8.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn encode_fixed_64(dst: &mut [u8], value: u64) {\n assert!(\n dst.len() >= 8,\n \"the length of 'dst' must be at least 8 for a u64, but got {}\",\n dst.len()\n );\n unsafe {\n let bytes = transmute::(value.to_le());\n copy_nonoverlapping(bytes.as_ptr(), dst.as_mut_ptr(), 8);\n }\n}\n```"}], "func_name": "encode_fixed_64", "docstring": "Encodes `value` in little-endian and puts in the first 8-bytes of `dst`.\n\n# Panics\n\nPanics if `dst.len()` is less than 8.", "repo": "Fullstop000/wickdb", "path": "src/util/coding.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/util/coding.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e992bc845b1d7128e5226342216dbdd2efec16038d278e58fa02f9b7971869a0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decode_fixed_32\n\nDocumentation:\nDecodes the first 4-bytes of `src` in little-endian and returns the decoded value.\n\nIf the length of the given `src` is larger than 4, only use `src[0..4]`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn decode_fixed_32(src: &[u8]) -> u32 {\n let mut data: u32 = 0;\n if src.len() >= 4 {\n unsafe {\n copy_nonoverlapping(src.as_ptr(), &mut data as *mut u32 as *mut u8, 4);\n }\n } else {\n for (i, b) in src.iter().enumerate() {\n data += (u32::from(*b)) << (i * 8);\n }\n }\n data.to_le()\n}\n```"}], "func_name": "decode_fixed_32", "docstring": "Decodes the first 4-bytes of `src` in little-endian and returns the decoded value.\n\nIf the length of the given `src` is larger than 4, only use `src[0..4]`", "repo": "Fullstop000/wickdb", "path": "src/util/coding.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/util/coding.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69120e64fe10f94c8ef08ce54716a8fdd1e6d3b144f668bc55bd4ec17c959fa6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decode_fixed_64\n\nDocumentation:\nDecodes the first 8-bytes of `src` in little-endian and returns the decoded value.\n\nIf the length of the given `src` is larger than 8, only use `src[0..8]`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn decode_fixed_64(src: &[u8]) -> u64 {\n let mut data: u64 = 0;\n if src.len() >= 8 {\n unsafe {\n copy_nonoverlapping(src.as_ptr(), &mut data as *mut u64 as *mut u8, 8);\n }\n } else {\n for (i, b) in src.iter().enumerate() {\n data += (u64::from(*b)) << (i * 8);\n }\n }\n data.to_le()\n}\n```"}], "func_name": "decode_fixed_64", "docstring": "Decodes the first 8-bytes of `src` in little-endian and returns the decoded value.\n\nIf the length of the given `src` is larger than 8, only use `src[0..8]`", "repo": "Fullstop000/wickdb", "path": "src/util/coding.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/util/coding.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d5a8c578b48ed462c77664522fd231871565b8f3c01891ab1b86613f5d08477"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: put_fixed_32\n\nDocumentation:\nEncodes the given u32 to bytes and concatenates the result to `dst`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn put_fixed_32(dst: &mut Vec, value: u32) {\n let mut buf = [0u8; 4];\n encode_fixed_32(&mut buf[..], value);\n dst.extend_from_slice(&buf);\n}\n```"}], "func_name": "put_fixed_32", "docstring": "Encodes the given u32 to bytes and concatenates the result to `dst`", "repo": "Fullstop000/wickdb", "path": "src/util/coding.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/util/coding.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "208876cd047296e8370ab0db7f1b91547ae88e32a3c900ef4cc30a2f1d1e1dc5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: put_fixed_64\n\nDocumentation:\nEncodes the given u64 to bytes and concatenates the result to `dst`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn put_fixed_64(dst: &mut Vec, value: u64) {\n let mut buf = [0u8; 8];\n encode_fixed_64(&mut buf[..], value);\n dst.extend_from_slice(&buf);\n}\n```"}], "func_name": "put_fixed_64", "docstring": "Encodes the given u64 to bytes and concatenates the result to `dst`", "repo": "Fullstop000/wickdb", "path": "src/util/coding.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/util/coding.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd9baa6bb4e6fe11c337c857c62f3de9f671a380626887e715f194918e992ba6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: hash\n\nDocumentation:\nReturns a `u32` crc checksum for give data\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn hash(data: &[u8]) -> u32 {\n let mut h = Hasher::new();\n h.update(data);\n h.finalize()\n}\n```"}], "func_name": "hash", "docstring": "Returns a `u32` crc checksum for give data", "repo": "Fullstop000/wickdb", "path": "src/util/crc32.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/util/crc32.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "676755a216d82a33635701150475f5b19f74c5e6c8945cb4212b8290c41aeadc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mask\n\nDocumentation:\nReturn a masked representation of crc.\n\nMotivation: it is problematic to compute the CRC of a string that\ncontains embedded CRCs. Therefore we recommend that CRCs stored\nsomewhere (e.g., in files) should be masked before being stored.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn mask(crc: u32) -> u32 {\n ((crc >> 15) | (crc << 17)).wrapping_add(MASK_DELTA)\n}\n```"}], "func_name": "mask", "docstring": "Return a masked representation of crc.\n\nMotivation: it is problematic to compute the CRC of a string that\ncontains embedded CRCs. Therefore we recommend that CRCs stored\nsomewhere (e.g., in files) should be masked before being stored.", "repo": "Fullstop000/wickdb", "path": "src/util/crc32.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/util/crc32.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e3a73ef8aca07c2e083662cca27e011f46267e2eaa9f2ca60a48081eaa914b8a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unmask\n\nDocumentation:\nReturn the crc whose masked representation is `masked`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unmask(masked: u32) -> u32 {\n let rot = masked.wrapping_sub(MASK_DELTA);\n (rot >> 17) | (rot << 15)\n}\n```"}], "func_name": "unmask", "docstring": "Return the crc whose masked representation is `masked`.", "repo": "Fullstop000/wickdb", "path": "src/util/crc32.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/util/crc32.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a3f5aae0f14cec14a06b9dcbd81e5f9ae717005db0b3556b0ca4bb7d82b4e09"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: index\n\nDocumentation:\nReturn the ith byte in the referenced data\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn index(&self, index: usize) -> &u8 {\n assert!(\n index < self.size,\n \"[slice] out of range. Slice size is [{}] but try to get [{}]\",\n self.size,\n index\n );\n unsafe { &*self.data.add(index) }\n }\n```"}], "func_name": "index", "docstring": "Return the ith byte in the referenced data", "repo": "Fullstop000/wickdb", "path": "src/util/slice.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/util/slice.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3682508ff502a52bb8f71cd7675dbc372a0b92d1f3ad879816a38e61e9202596"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nSearch the value by the given key in sstables level by level\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(\n &self,\n options: ReadOptions,\n key: LookupKey,\n table_cache: &TableCache,\n ) -> Result<(Option>, Option)> {\n let ikey = key.internal_key();\n let ukey = key.user_key();\n let ucmp = &self.icmp.user_comparator;\n let mut seek_stats = None;\n let mut files_to_seek = vec![];\n for (level, files) in self.files.iter().enumerate() {\n if files.is_empty() {\n continue;\n }\n if level == 0 {\n // Level-0 files may overlap each other. Find all files that\n // overlap user_key and process them in order from newest to oldest because\n // the last level-0 file always has the newest entries.\n for f in files.iter().rev() {\n if ucmp.compare(ukey, f.largest.user_key()) != CmpOrdering::Greater\n && ucmp.compare(ukey, f.smallest.user_key()) != CmpOrdering::Less\n {\n files_to_seek.push((f, 0));\n }\n }\n } else {\n let index = find_file(&self.icmp, files, ikey);\n if index >= files.len() {\n // we reach the end but not found a file matches\n } else {\n let target = &files[index];\n // If what we found is the first file, it could still not includes the target\n // so let's check the smallest ukey. We use `ukey` because of the given `LookupKey`\n // may contains the same `ukey` as the `smallest` but a bigger `seq` number than it, which is smaller\n // in a comparison by `icmp`.\n if ucmp.compare(ukey, target.smallest.user_key()) != CmpOrdering::Less\n && level + 1 < self.options.max_levels as usize\n {\n files_to_seek.push((target, level));\n }\n }\n }\n }\n files_to_seek.sort_by(|(a, _), (b, _)| b.number.cmp(&a.number));\n for (file, level) in files_to_seek {\n if seek_stats.is_none() {\n // TODO(fullstop000): leveldb only charge the first file for seek compaction\n seek_stats = Some(SeekStats {\n file: file.clone(),\n level,\n });\n }\n match table_cache.get(\n self.icmp.clone(),\n options,\n ikey,\n file.number,\n file.file_size,\n )? {\n None => continue,\n Some(block_iter) => {\n let encoded_key = block_iter.key();\n let value = block_iter.value();\n match ParsedInternalKey::decode_from(encoded_key) {\n None => return Err(Error::Corruption(\"bad internal key\".to_owned())),\n Some(parsed_key) => {\n if self\n .options\n .comparator\n .compare(parsed_key.user_key, key.user_key())\n == CmpOrdering::Equal\n {\n match parsed_key.value_type {\n ValueType::Value => {\n return Ok((Some(value.to_vec()), seek_stats))\n }\n ValueType::Deletion => return Ok((None, seek_stats)),\n _ => {}\n }\n }\n }\n }\n }\n }\n }\n Ok((None, seek_stats))\n }\n```"}], "func_name": "get", "docstring": "Search the value by the given key in sstables level by level", "repo": "Fullstop000/wickdb", "path": "src/version/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "45c79eb84e547a8714243ea456dcd15dadd3a2ed136b6cb29a76851ddb838a53"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_stats\n\nDocumentation:\nUpdate seek stats for a sstable file. If it runs out of `allow_seek`,\nmark it as a pending compaction file and returns true.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn update_stats(&self, stats: Option) -> bool {\n if let Some(ss) = stats {\n let old = ss\n .file\n .allowed_seeks\n .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |v| {\n Some(if v > 0 { v - 1 } else { 0 })\n })\n .unwrap();\n let mut file_to_compact = self.file_to_compact.write().unwrap();\n if file_to_compact.is_none() && old == 1 {\n *file_to_compact = Some(ss.file);\n self.file_to_compact_level\n .store(ss.level, Ordering::Release);\n return true;\n }\n }\n false\n }\n```"}], "func_name": "update_stats", "docstring": "Update seek stats for a sstable file. If it runs out of `allow_seek`,\nmark it as a pending compaction file and returns true.", "repo": "Fullstop000/wickdb", "path": "src/version/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48197f724c3b36bca309bbcfdcdd8bad3f5bfd6e5941b400a1d5ab9c3921754d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: needs_compaction\n\nDocumentation:\nWhether the version needs to be compacted\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn needs_compaction(&self) -> bool {\n self.compaction_score > 1.0 || self.file_to_compact.read().unwrap().is_some()\n }\n```"}], "func_name": "needs_compaction", "docstring": "Whether the version needs to be compacted", "repo": "Fullstop000/wickdb", "path": "src/version/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1d9f2d530a85b6abf63a02874f40cb2353eaa3b8405b62ceda4621f150524912"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: level_summary\n\nDocumentation:\nReturn a String includes number of files in every level\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn level_summary(&self) -> String {\n let mut s = String::from(\"files[ \");\n let summary = self.files.iter().fold(String::new(), |mut acc, files| {\n acc.push_str(format!(\"{} \", files.len()).as_str());\n acc\n });\n s.push_str(summary.as_str());\n s.push(']');\n s\n }\n```"}], "func_name": "level_summary", "docstring": "Return a String includes number of files in every level", "repo": "Fullstop000/wickdb", "path": "src/version/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "64d05efdd0a6ca7687b6224f0c7a2a1c3255ccd35c9cd70db185883020c552bf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pick_level_for_memtable_output\n\nDocumentation:\nReturn the level at which we should place a new memtable compaction\nresult that covers the range `[smallest_user_key,largest_user_key]`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pick_level_for_memtable_output(\n &self,\n smallest_ukey: &[u8],\n largest_ukey: &[u8],\n ) -> usize {\n let mut level = 0;\n if !self.overlap_in_level(level, Some(smallest_ukey), Some(largest_ukey)) {\n // No overlapping in level 0\n // we might directly push files to next level if there is no overlap in next level\n let smallest_ikey =\n InternalKey::new(smallest_ukey, MAX_KEY_SEQUENCE, VALUE_TYPE_FOR_SEEK);\n let largest_ikey = InternalKey::new(largest_ukey, 0, ValueType::Deletion);\n while level < self.options.max_mem_compact_level {\n // Stops if overlaps at next level\n if self.overlap_in_level(level + 1, Some(smallest_ukey), Some(largest_ukey)) {\n break;\n }\n if level + 2 < self.options.max_levels as usize {\n // Check that file does not overlap too many grandparent bytes\n let overlaps = self.get_overlapping_inputs(\n level + 2,\n Some(&smallest_ikey),\n Some(&largest_ikey),\n );\n if total_file_size(&overlaps) > self.options.max_grandparent_overlap_bytes() {\n break;\n }\n }\n level += 1;\n }\n }\n level\n }\n```"}], "func_name": "pick_level_for_memtable_output", "docstring": "Return the level at which we should place a new memtable compaction\nresult that covers the range `[smallest_user_key,largest_user_key]`.", "repo": "Fullstop000/wickdb", "path": "src/version/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "74a5c1892867aa46641893cf5efb2495c9f9f5b52c4e1490e4976a4e8825d1f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: for_each_overlapping\n\nDocumentation:\nCall `func(level, file)` for every file that overlaps `user_key` in\norder from newest to oldest. If an invocation of func returns\nfalse, makes no more calls.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn for_each_overlapping(\n &self,\n user_key: &[u8],\n internal_key: &[u8],\n mut func: Box) -> bool>,\n ) {\n let ucmp = &self.icmp.user_comparator;\n for (level, files) in self.files.iter().enumerate() {\n if level == 0 {\n let mut target_files = vec![];\n // Search level 0 files\n for f in files.iter() {\n if ucmp.compare(user_key, f.smallest.user_key()) != CmpOrdering::Less\n && ucmp.compare(user_key, f.largest.user_key()) != CmpOrdering::Greater\n {\n target_files.push(f);\n }\n }\n if !target_files.is_empty() {\n target_files.sort_by(|a, b| b.number.cmp(&a.number))\n }\n for target_file in target_files {\n if !func(0, target_file.clone()) {\n return;\n }\n }\n } else {\n if files.is_empty() {\n continue;\n }\n let index = find_file(&self.icmp, self.files[level].as_slice(), internal_key);\n if index >= files.len() {\n // we reach the end but not found a file matches\n } else {\n let target = files[index].clone();\n // if what we found is just the first file, it could still not includes the target\n if ucmp.compare(user_key, target.smallest.data()) != CmpOrdering::Less\n && !func(level, target)\n {\n return;\n }\n }\n }\n }\n }\n```"}], "func_name": "for_each_overlapping", "docstring": "Call `func(level, file)` for every file that overlaps `user_key` in\norder from newest to oldest. If an invocation of func returns\nfalse, makes no more calls.", "repo": "Fullstop000/wickdb", "path": "src/version/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "98405710ec14b865906d4b495f9f0309746952ab550d7b82e0390eebe5769e81"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: record_read_sample\n\nDocumentation:\nRecord a sample of bytes read at the specified internal key.\nReturns true if a new compaction may need to be triggered\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn record_read_sample(&self, internal_key: &[u8]) -> bool {\n if let Some(pkey) = ParsedInternalKey::decode_from(internal_key) {\n let stats = Rc::new(Cell::new(None));\n let matches = Rc::new(RefCell::new(0));\n let stats_clone = stats.clone();\n let matches_clone = matches.clone();\n self.for_each_overlapping(\n pkey.user_key,\n internal_key,\n Box::new(move |level, file| {\n *matches_clone.borrow_mut() += 1;\n if *matches_clone.borrow() == 1 {\n // Remember first match\n stats_clone.set(Some(SeekStats { file, level }));\n }\n *matches_clone.borrow() < 2\n }),\n );\n\n // Must have at least two matches since we want to merge across\n // files. But what if we have a single file that contains many\n // overwrites and deletions? Should we have another mechanism for\n // finding such files?\n if *matches.borrow() >= 2 {\n if let Ok(s) = Rc::try_unwrap(stats) {\n return self.update_stats(s.into_inner());\n }\n }\n }\n false\n }\n```"}], "func_name": "record_read_sample", "docstring": "Record a sample of bytes read at the specified internal key.\nReturns true if a new compaction may need to be triggered", "repo": "Fullstop000/wickdb", "path": "src/version/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba0389c90dab5e940996ab586ea27e5fef733fa3567605ea7ae6ff3186f7821d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: overlap_in_level\n\nDocumentation:\nReturns true iff some file in the specified level overlaps\nsome part of `[smallest_ukey,largest_ukey]`.\n`smallest_ukey` is `None` represents a key smaller than all the DB's keys.\n`largest_ukey` is `None` represents a key largest than all the DB's keys.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn overlap_in_level(\n &self,\n level: usize,\n smallest_ukey: Option<&[u8]>,\n largest_ukey: Option<&[u8]>,\n ) -> bool {\n some_file_overlap_range(\n &self.icmp,\n level > 0,\n &self.files[level],\n smallest_ukey,\n largest_ukey,\n )\n }\n```"}], "func_name": "overlap_in_level", "docstring": "Returns true iff some file in the specified level overlaps\nsome part of `[smallest_ukey,largest_ukey]`.\n`smallest_ukey` is `None` represents a key smaller than all the DB's keys.\n`largest_ukey` is `None` represents a key largest than all the DB's keys.", "repo": "Fullstop000/wickdb", "path": "src/version/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6fc6e6a176f12f22afc05ba11d7203dbcceba4280e7d4ca3db89f9585321e01e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: approximate_offset_of\n\nDocumentation:\nReturn the approximate offset in the database of the data for\ngiven `ikey` in this version\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn approximate_offset_of(\n &self,\n ikey: &InternalKey,\n table_cache: &TableCache,\n ) -> u64 {\n let mut result = 0;\n for (level, files) in self.files.iter().enumerate() {\n for f in files {\n if self.icmp.compare(f.largest.data(), ikey.data()) != CmpOrdering::Greater {\n // Entire file is before \"ikey\", so just add the file size\n result += f.file_size;\n } else if self.icmp.compare(f.smallest.data(), ikey.data()) == CmpOrdering::Greater\n {\n // Entire file is after \"ikey\", so ignore\n if level > 0 {\n // Files other than level 0 are sorted by `smallest`, so\n // no further files in this level will contain data for\n // \"ikey\"\n break;\n }\n } else {\n // \"ikey\" falls in the range for this table. Add the\n // approximate offset of \"ikey\" within the table.\n if let Ok(table) =\n table_cache.find_table(self.icmp.clone(), f.number, f.file_size)\n {\n result += table.approximate_offset_of(self.icmp.clone(), ikey.data());\n }\n }\n }\n }\n result\n }\n```"}], "func_name": "approximate_offset_of", "docstring": "Return the approximate offset in the database of the data for\ngiven `ikey` in this version", "repo": "Fullstop000/wickdb", "path": "src/version/mod.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b177050a7f34929e26859e1d687d250fdb84166144fe5cef4b01b6c8fbe38260"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_file\n\nDocumentation:\nAdd the specified file at the specified number\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_file(\n &mut self,\n level: usize,\n file_number: u64,\n file_size: u64,\n smallest: InternalKey,\n largest: InternalKey,\n ) {\n self.file_delta.new_files.push((\n level,\n FileMetaData {\n allowed_seeks: AtomicUsize::new(0),\n file_size,\n number: file_number,\n smallest,\n largest,\n },\n ))\n }\n```"}], "func_name": "add_file", "docstring": "Add the specified file at the specified number", "repo": "Fullstop000/wickdb", "path": "src/version/version_edit.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/version_edit.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e3b261e04707b3c1e6d09379b1e5e58e81710f76b87cea5dc5bce55c0f3d1e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode_to\n\nDocumentation:\nConvert into bytes and push into given `dst`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn encode_to(&self, dst: &mut Vec) {\n if let Some(cmp_name) = &self.comparator_name {\n VarintU32::put_varint(dst, Comparator as u32);\n VarintU32::put_varint_prefixed_slice(dst, cmp_name.as_bytes());\n }\n if let Some(log_number) = &self.log_number {\n VarintU32::put_varint(dst, LogNumber as u32);\n VarintU64::put_varint(dst, *log_number);\n }\n if let Some(pre_ln) = &self.prev_log_number {\n VarintU32::put_varint(dst, PrevLogNumber as u32);\n VarintU64::put_varint(dst, *pre_ln);\n }\n if let Some(next_fn) = &self.next_file_number {\n VarintU32::put_varint(dst, NextFileNumber as u32);\n VarintU64::put_varint(dst, *next_fn);\n }\n\n if let Some(last_seq) = &self.last_sequence {\n VarintU32::put_varint(dst, LastSequence as u32);\n VarintU64::put_varint(dst, *last_seq);\n }\n\n for (level, key) in self.file_delta.compaction_pointers.iter() {\n VarintU32::put_varint(dst, CompactPointer as u32);\n VarintU32::put_varint(dst, *level as u32);\n VarintU32::put_varint_prefixed_slice(dst, key.data());\n }\n\n for (level, file_num) in self.file_delta.deleted_files.iter() {\n VarintU32::put_varint(dst, DeletedFile as u32);\n VarintU32::put_varint(dst, *level as u32);\n VarintU64::put_varint(dst, *file_num);\n }\n\n for (level, file_meta) in self.file_delta.new_files.iter() {\n VarintU32::put_varint(dst, NewFile as u32);\n VarintU32::put_varint(dst, *level as u32);\n VarintU64::put_varint(dst, file_meta.number);\n VarintU64::put_varint(dst, file_meta.file_size);\n VarintU32::put_varint_prefixed_slice(dst, file_meta.smallest.data());\n VarintU32::put_varint_prefixed_slice(dst, file_meta.largest.data());\n }\n }\n```"}], "func_name": "encode_to", "docstring": "Convert into bytes and push into given `dst`", "repo": "Fullstop000/wickdb", "path": "src/version/version_edit.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/version_edit.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "40ebdff8bf07c7e992611435d7940c6a10507080680b0fba73e79655c61e24a3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accumulate\n\nDocumentation:\nAdd the given `FileDelta` for later applying\n'vset.compaction_pointers' will be updated\nsame as `apply` in C++ implementation\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn accumulate(\n &mut self,\n delta: FileDelta,\n vset: &mut VersionSet,\n ) {\n // update compcation pointers\n for (level, key) in delta.compaction_pointers {\n vset.compaction_pointer[level] = key;\n }\n // delete files\n for (level, deleted_file) in delta.deleted_files {\n self.levels[level].deleted_files.insert(deleted_file);\n }\n for (level, new_file) in delta.new_files {\n // We arrange to automatically compact this file after\n // a certain number of seeks. Let's assume:\n // (1) One seek costs 10ms\n // (2) Writing or reading 1MB costs 10ms (100MB/s)\n // (3) A compaction of 1MB does 25MB of IO:\n // 1MB read from this level\n // 10-12MB read from next level (boundaries may be misaligned)\n // 10-12MB written to next level\n // This implies that 25 seeks cost the same as the compaction\n // of 1MB of data. I.e., one seek costs approximately the\n // same as the compaction of 40KB of data. We are a little\n // conservative and allow approximately one seek for every 16KB\n // of data before triggering a compaction.\n new_file.init_allowed_seeks();\n self.levels[level].deleted_files.remove(&new_file.number);\n self.levels[level].added_files.push(new_file);\n }\n }\n```"}], "func_name": "accumulate", "docstring": "Add the given `FileDelta` for later applying\n'vset.compaction_pointers' will be updated\nsame as `apply` in C++ implementation", "repo": "Fullstop000/wickdb", "path": "src/version/version_set.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/version_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c84af576c385ad7d0e0dcafe2ab437df17fd07d6ea3bd15c6b762919285ac73b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: current_sst_iter\n\nDocumentation:\nReturns the collection of all the file iterators in current version\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn current_sst_iter(\n &self,\n read_opt: ReadOptions,\n table_cache: TableCache,\n ) -> Result>> {\n let version = self.current();\n let mut level0 = vec![];\n // Merge all level zero files together since they may overlap\n for file in version.files[0].iter() {\n level0.push(table_cache.new_iter(\n self.icmp.clone(),\n read_opt,\n file.number,\n file.file_size,\n )?);\n }\n\n let mut leveln = vec![];\n // For levels > 0, we can use a concatenating iterator that sequentially\n // walks through the non-overlapping files in the level, opening them\n // lazily\n for files in version.files.iter().skip(1) {\n if !files.is_empty() {\n let level_file_iter = LevelFileNumIterator::new(self.icmp.clone(), files.clone());\n let factory =\n FileIterFactory::new(self.icmp.clone(), read_opt, table_cache.clone());\n leveln.push(ConcatenateIterator::new(level_file_iter, factory));\n }\n }\n let iter = KMergeIter::new(SSTableIters {\n cmp: self.icmp.clone(),\n level0,\n leveln,\n });\n Ok(iter)\n }\n```"}], "func_name": "current_sst_iter", "docstring": "Returns the collection of all the file iterators in current version", "repo": "Fullstop000/wickdb", "path": "src/version/version_set.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/version_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a3d7e19cb6b9544f719aa9c2d4a56f4086761a068ed255b558248095edc198c6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: log_and_apply\n\nDocumentation:\nApply `edit` to the current version to form a new descriptor that\nis both saved to persistent state and installed as the new\ncurrent version.\n\nOnly called in situations below:\n* After minor compaction\n* After trivial compaction (only file move)\n* After major compaction\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn log_and_apply(&mut self, mut edit: VersionEdit) -> Result<()> {\n let (v, encoded_edit) = {\n let level_summary_before = self.current().level_summary();\n if let Some(target_log) = edit.log_number {\n assert!(target_log >= self.log_number && target_log < self.next_file_number,\n \"[version set] applying VersionEdit use a invalid log number {}, expect to be at [{}, {})\", target_log, self.log_number, self.next_file_number);\n } else {\n edit.set_log_number(self.log_number);\n }\n\n if edit.prev_log_number.is_none() {\n edit.set_prev_log_number(self.prev_log_number);\n }\n\n edit.set_next_file(self.next_file_number);\n edit.set_last_sequence(self.last_sequence);\n\n let mut record = vec![];\n edit.encode_to(&mut record);\n\n let this = self.current();\n let mut builder = VersionBuilder::new(self.options.max_levels as usize, &this);\n builder.accumulate(edit.file_delta, self);\n let mut v = builder.apply_to_new(&self.icmp);\n v.finalize();\n let summary = v.level_summary();\n info!(\n \"level changing result summary : \\n\\t before {} \\n\\t now {}\",\n level_summary_before, summary\n );\n (v, record)\n };\n\n // Initialize new manifest file if necessary by creating a temporary file that contains a snapshot of the current version.\n let mut new_manifest_file = String::new();\n if self.manifest_writer.is_none() {\n new_manifest_file =\n generate_filename(&self.db_path, FileType::Manifest, self.manifest_file_number);\n let f = self.storage.create(&new_manifest_file)?;\n debug!(\"Create new manifest file #{}\", self.manifest_file_number);\n let mut writer = Writer::new(f);\n match self.write_snapshot(&mut writer) {\n Ok(()) => self.manifest_writer = Some(writer),\n Err(_) => {\n return self.storage.remove(&new_manifest_file);\n }\n }\n }\n\n // Write to current MANIFEST\n // In origin C++ implementation, the relative part unlocks the global mutex. But we dont need\n // to do this in wickdb since we split the mutex into several ones for more subtle controlling.\n if let Some(writer) = self.manifest_writer.as_mut() {\n match writer.add_record(&encoded_edit) {\n Ok(()) => {\n match writer.sync() {\n Ok(()) => {\n // If we just created a MANIFEST file, install it by writing a\n // new CURRENT file that points to it.\n if !new_manifest_file.is_empty()\n && update_current(\n &self.storage,\n &self.db_path,\n self.manifest_file_number,\n )\n .is_err()\n {\n self.manifest_writer = None;\n return self.storage.remove(new_manifest_file.as_str());\n }\n // install new version\n self.log_number = edit.log_number.unwrap();\n self.prev_log_number = edit.prev_log_number.unwrap();\n self.append_new_version(v);\n }\n // omit the sync error\n Err(e) => {\n warn!(\"MANIFEST persistent error: {:?}\", e);\n self.manifest_writer = None;\n return self.storage.remove(new_manifest_file.as_str());\n }\n }\n }\n Err(_) => {\n self.manifest_writer = None;\n return self.storage.remove(new_manifest_file.as_str());\n }\n }\n }\n Ok(())\n }\n```"}], "func_name": "log_and_apply", "docstring": "Apply `edit` to the current version to form a new descriptor that\nis both saved to persistent state and installed as the new\ncurrent version.\n\nOnly called in situations below:\n* After minor compaction\n* After trivial compaction (only file move)\n* After major compaction", "repo": "Fullstop000/wickdb", "path": "src/version/version_set.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/version_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b315c0decff96175f53c53ea140dbc369f44b2cd51ee087ea0ad59efab73e652"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compact_range\n\nDocumentation:\nReturn a `Compaction` for compacting the range `[begin,end]` in\nthe specified level. Returns `None` if there is nothing in that\nlevel that overlaps the specified range\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compact_range(\n &mut self,\n level: usize,\n begin: Option<&InternalKey>,\n end: Option<&InternalKey>,\n ) -> Option> {\n let version = self.current();\n let mut overlapping_inputs = version.get_overlapping_inputs(level, begin, end);\n if overlapping_inputs.is_empty() {\n return None;\n }\n // Avoid compacting too much in one shot in case the range is large.\n // But we cannot do this for level-0 since level-0 files can overlap\n // and we must not pick one file and drop another older file if the\n // two files overlap.\n // TODO: The Level 0 files to be compacted could really large. This might hurt the performance.\n if level > 0 {\n let mut total = 0;\n for (i, file) in overlapping_inputs.iter().enumerate() {\n total += file.file_size;\n if total >= version.options.max_file_size {\n overlapping_inputs.truncate(i + 1);\n break;\n }\n }\n }\n let mut c = Compaction::new(self.options.clone(), level, CompactionReason::Manual);\n c.input_version = Some(version);\n c.inputs.base = overlapping_inputs;\n Some(self.setup_other_inputs(c))\n }\n```"}], "func_name": "compact_range", "docstring": "Return a `Compaction` for compacting the range `[begin,end]` in\nthe specified level. Returns `None` if there is nothing in that\nlevel that overlaps the specified range", "repo": "Fullstop000/wickdb", "path": "src/version/version_set.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/version_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3fa695ab67abbd82a358bf38a924dd84398df87994e49abdea1c7843a5cb2f57"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pick_compaction\n\nDocumentation:\nPick level and inputs for a new compaction.\nReturns `None` if no compaction needs to be done.\nOtherwise returns a `Compaction` that\ndescribes the compaction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pick_compaction(&mut self) -> Option> {\n let current = self.current();\n let size_compaction = current.compaction_score >= 1.0;\n let mut file_to_compact = Arc::new(FileMetaData::default());\n let mut seek_compaction = false;\n {\n let guard = current.file_to_compact.read().unwrap();\n if let Some(f) = &(*guard) {\n file_to_compact = f.clone();\n seek_compaction = true;\n }\n }\n // We prefer compactions triggered by too much data in a level over\n // the compactions triggered by seeks\n let mut compaction = {\n if size_compaction {\n let level = current.compaction_level;\n assert!(\n level + 1 < self.options.max_levels as usize,\n \"[compaction] target compaction level {} should be less Lmax {} - 1\",\n level,\n self.options.max_levels as usize\n );\n let mut compaction =\n Compaction::new(self.options.clone(), level, CompactionReason::MaxSize);\n // Pick the first file that comes after compact_pointer[level]\n for file in current.files[level].iter() {\n if self.compaction_pointer[level].is_empty()\n || self\n .icmp\n .compare(file.largest.data(), self.compaction_pointer[level].data())\n == CmpOrdering::Greater\n {\n compaction.inputs.add_base(file.clone());\n break;\n }\n }\n if compaction.inputs.base.is_empty() {\n if let Some(file) = current.files[0].first() {\n // Wrap-around to the beginning of the key space\n compaction.inputs.add_base(file.clone())\n }\n }\n compaction\n } else if seek_compaction {\n let level = current.file_to_compact_level.load(Ordering::Acquire);\n if level < self.options.max_levels as usize - 1 {\n let mut compaction =\n Compaction::new(self.options.clone(), level, CompactionReason::SeekLimit);\n compaction.inputs.add_base(file_to_compact);\n compaction\n } else {\n // We've run out of the levels\n return None;\n }\n } else {\n return None;\n }\n };\n compaction.input_version = Some(current.clone());\n // Files in level 0 may overlap each other, so pick up all overlapping ones\n if compaction.level == 0 {\n let (smallest, largest) =\n base_range(&compaction.inputs.base, compaction.level, &self.icmp);\n // Note that the next call will discard the file we placed in\n // inputs[0] earlier and replace it with an overlapping set\n // which will include the picked file.\n compaction.inputs.base =\n current.get_overlapping_inputs(compaction.level, Some(smallest), Some(largest));\n assert!(!compaction.inputs.base.is_empty());\n }\n\n compaction = self.setup_other_inputs(compaction);\n // Avoid recursively trivial sst moving when target level is empty\n if compaction.level > 1\n && seek_compaction\n && compaction.is_trivial_move()\n && current.files[compaction.level + 1].is_empty()\n {\n for f in compaction.inputs.base {\n f.init_allowed_seeks()\n }\n return None;\n }\n Some(compaction)\n }\n```"}], "func_name": "pick_compaction", "docstring": "Pick level and inputs for a new compaction.\nReturns `None` if no compaction needs to be done.\nOtherwise returns a `Compaction` that\ndescribes the compaction.", "repo": "Fullstop000/wickdb", "path": "src/version/version_set.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/version_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cbded07a3a7babe061f40734466b56d7c7287d9b29b0ddb387296d51385bb786"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_level0_files\n\nDocumentation:\nPersistent given memtable into a single sst file to level0.\nIf `into_base` is true, the file could be pushed into level1 or level2 if there's no too much overlapping.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_level0_files(\n &mut self,\n db_path: &str,\n table_cache: &TableCache,\n mem_iter: &mut dyn Iterator,\n edit: &mut VersionEdit,\n into_base: bool,\n ) -> Result<()> {\n let now = SystemTime::now();\n let mut meta = FileMetaData {\n number: self.inc_next_file_number(),\n ..Default::default()\n };\n info!(\"Level-0 table #{} : start building\", meta.number);\n let build_result = build_table(\n self.options.clone(),\n &self.storage,\n db_path,\n table_cache,\n mem_iter,\n &mut meta,\n );\n let mut level = 0;\n\n // If `file_size` is zero, the file has been deleted and\n // should not be added to the manifest\n if build_result.is_ok() && meta.file_size > 0 {\n info!(\n \"Level-0 table #{} : add {} bytes [{:?}] [key range {:?} ... {:?}]\",\n meta.number, meta.file_size, &build_result, &meta.smallest, &meta.largest,\n );\n let smallest_ukey = meta.smallest.user_key();\n let largest_ukey = meta.largest.user_key();\n if into_base {\n let base = self.current();\n level = base.pick_level_for_memtable_output(smallest_ukey, largest_ukey);\n debug!(\n \"Pick up new level for table: level {}, table #{}\",\n level, meta.number\n );\n }\n edit.add_file(\n level,\n meta.number,\n meta.file_size,\n meta.smallest.clone(),\n meta.largest.clone(),\n );\n }\n info!(\n \"Compactions stats for Level{}: {:?}\",\n level,\n CompactionStats {\n micros: now.elapsed().unwrap().as_micros() as u64,\n bytes_read: 0,\n bytes_written: meta.file_size,\n }\n );\n build_result\n }\n```"}], "func_name": "write_level0_files", "docstring": "Persistent given memtable into a single sst file to level0.\nIf `into_base` is true, the file could be pushed into level1 or level2 if there's no too much overlapping.", "repo": "Fullstop000/wickdb", "path": "src/version/version_set.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/version_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27fa33ca8e54d28693eac4743d0f4077119e836ed3d3908aa64b74e07f9d6bf7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_compaction_output_file\n\nDocumentation:\nCreate new table builder and physical file for current output in Compaction\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn create_compaction_output_file(\n &mut self,\n c: &mut Compaction,\n ) -> Result<()> {\n assert!(c.builder.is_none());\n let file_number = self.inc_next_file_number();\n self.pending_outputs.insert(file_number);\n let output = FileMetaData {\n number: file_number,\n ..Default::default()\n };\n let file_name = generate_filename(&self.db_path, FileType::Table, file_number);\n let file = self.storage.create(file_name.as_str())?;\n c.builder = Some(TableBuilder::new(file, self.icmp.clone(), &self.options));\n c.outputs.push(output);\n Ok(())\n }\n```"}], "func_name": "create_compaction_output_file", "docstring": "Create new table builder and physical file for current output in Compaction", "repo": "Fullstop000/wickdb", "path": "src/version/version_set.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/version_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "85652209b2e7a29a34a4cc2bca6cb0a71116561a323175031ec2ae95ba60db69"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: recover\n\nDocumentation:\nRecover the last saved Version from MANIFEST file.\nReturns whether we need a new MANIFEST file for later usage.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn recover(&mut self) -> Result {\n let env = self.storage.clone();\n // Read \"CURRENT\" file, which contains a pointer to the current manifest file\n let mut current = env.open(&generate_filename(&self.db_path, FileType::Current, 0))?;\n let mut buf = vec![];\n current.read_all(&mut buf)?;\n let (current_manifest, file_name) = match String::from_utf8(buf) {\n Ok(s) => {\n if s.is_empty() {\n return Err(Error::Corruption(\"CURRENT file is empty\".to_owned()));\n }\n let mut file_name = self.db_path.to_owned();\n file_name.push(MAIN_SEPARATOR);\n let file_name = file_name.add(&s);\n (env.open(&file_name)?, file_name)\n }\n Err(e) => {\n return Err(Error::Corruption(format!(\n \"Invalid CURRENT file content: {}\",\n e\n )));\n }\n };\n let file_length = current_manifest.len()?;\n let base = Version::new(self.options.clone(), self.icmp.clone());\n let mut builder = VersionBuilder::new(self.options.max_levels as usize, &base);\n let reporter = LogReporter::new();\n let mut reader = Reader::new(current_manifest, Some(Box::new(reporter.clone())), true, 0);\n let mut buf = vec![];\n\n let mut next_file_number = 0;\n let mut has_next_file_number = false;\n let mut log_number = 0;\n let mut has_log_number = false;\n let mut prev_log_number = 0;\n let mut has_prev_log_number = false;\n let mut last_sequence = 0;\n let mut has_last_sequence = false;\n while reader.read_record(&mut buf) {\n if let Err(e) = reporter.result() {\n return Err(e);\n }\n let mut edit = VersionEdit::new(self.options.max_levels);\n edit.decoded_from(&buf)?;\n debug!(\"Decoded manifest record: {:?}\", &edit);\n if let Some(ref cmp_name) = edit.comparator_name {\n if cmp_name.as_str() != self.icmp.user_comparator.name() {\n return Err(Error::InvalidArgument(\n cmp_name.clone() + \" does not match existing compactor\",\n ));\n }\n }\n builder.accumulate(edit.file_delta, self);\n if let Some(n) = edit.next_file_number {\n next_file_number = n;\n has_next_file_number = true;\n };\n if let Some(n) = edit.log_number {\n log_number = n;\n has_log_number = true;\n };\n if let Some(n) = edit.prev_log_number {\n prev_log_number = n;\n has_prev_log_number = true;\n };\n if let Some(n) = edit.last_sequence {\n last_sequence = n;\n has_last_sequence = true;\n }\n }\n\n if let Err(e) = reporter.result() {\n return Err(e);\n }\n\n if !has_next_file_number {\n return Err(Error::Corruption(\n \"no meta-nextfile entry in manifest\".to_owned(),\n ));\n }\n if !has_log_number {\n return Err(Error::Corruption(\n \"no meta-lognumber entry in manifest\".to_owned(),\n ));\n }\n if !has_last_sequence {\n return Err(Error::Corruption(\n \"no last-sequence-number entry in manifest\".to_owned(),\n ));\n }\n\n if !has_prev_log_number {\n prev_log_number = 0;\n }\n\n self.mark_file_number_used(prev_log_number);\n self.mark_file_number_used(log_number);\n\n let mut new_v = builder.apply_to_new(&self.icmp);\n new_v.finalize();\n self.versions.push(Arc::new(new_v));\n self.manifest_file_number = next_file_number;\n self.next_file_number = next_file_number + 1;\n self.last_sequence = last_sequence;\n self.log_number = log_number;\n self.prev_log_number = prev_log_number;\n Ok(!self.should_reuse_manifest(&file_name, file_length))\n }\n```"}], "func_name": "recover", "docstring": "Recover the last saved Version from MANIFEST file.\nReturns whether we need a new MANIFEST file for later usage.", "repo": "Fullstop000/wickdb", "path": "src/version/version_set.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/version_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "400a95468d37acf66efe0d605a97f914a9ddc2e7394be4e05e4fff254d2b5990"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mark_file_number_used\n\nDocumentation:\nForward to `num + 1` as the next file number\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn mark_file_number_used(&mut self, num: u64) {\n if self.next_file_number <= num {\n self.next_file_number = num + 1\n }\n }\n```"}], "func_name": "mark_file_number_used", "docstring": "Forward to `num + 1` as the next file number", "repo": "Fullstop000/wickdb", "path": "src/version/version_set.rs", "url": "https://github.com/Fullstop000/wickdb/blob/master/src/version/version_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f032f1f3f4134d03f8db2209ce7f77b1d6048df558694e1325f3d2caedec9bbc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ascii_digit\n\nDocumentation:\nConvert the first byte of the source string to a digit.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn ascii_digit<'source, Token>(lexer: &mut logos::Lexer<'source, Token>) -> Option\nwhere\n Token: Logos<'source, Source = [u8]>,\n{\n match lexer.slice().first()? {\n byte @ b'0'..=b'9' => Some(byte - b'0'),\n byte @ b'a'..=b'z' => Some(byte - b'a' + 10),\n byte @ b'A'..=b'Z' => Some(byte - b'A' + 10),\n _ => None,\n }\n}\n```"}], "func_name": "ascii_digit", "docstring": "Convert the first byte of the source string to a digit.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/literal.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/literal.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef2dfe3e8e70b9d57f01f2ecad5e5ffd91ba42b428ce5d4a67ca15f0170d18df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: token_location\n\nDocumentation:\nGet the file-relative location of the current token.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn token_location(&self, lexer: &logos::Lexer<'source, Token>) -> Location\n where\n Token: Logos<'source>,\n {\n match self.location {\n Location::Generated => Location::Generated,\n Location::FileRange(file_id, range) => Location::file_range(\n file_id,\n (range.start + lexer.span().start)..(range.start + lexer.span().end),\n ),\n }\n }\n```"}], "func_name": "token_location", "docstring": "Get the file-relative location of the current token.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/literal.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/literal.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9c908f9578c4e3910b1744c8fa4d1f28c7bc3f54a65a08308ef737da4195c8d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: number_to_unsigned_int\n\nDocumentation:\nParse a numeric literal into an unsigned integer.\n\n# Returns\n\n- `Some(_)`: If the literal was parsed correctly.\n- `None`: If a fatal error when parsing the literal.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn number_to_unsigned_int(self) -> Option {\n let mut lexer = NumericLiteral::lexer(self.source.as_bytes());\n\n let (base, start_digit) = match self.expect_numeric_literal_start(&mut lexer)? {\n (Sign::Positive, base, start_digit) => (base, start_digit),\n (Sign::Negative, _, _) => return self.report(NegativeUnsignedInteger(self.location)),\n };\n\n let mut lexer = lexer.morph();\n let mut integer = T::zero();\n let mut num_digits = 0;\n\n if let Some(digit) = start_digit {\n integer = self.add_integer_digit(Sign::Positive, base, integer, digit)?;\n num_digits += 1;\n }\n\n while let Some(token) = lexer.next() {\n let location = self.token_location(&lexer);\n match token {\n Digit36::Digit(digit) if digit < base.to_u8() => {\n integer = self.add_integer_digit(Sign::Positive, base, integer, digit)?;\n num_digits += 1;\n }\n Digit36::Separator if num_digits != 0 => {}\n Digit36::Separator => return self.report(ExpectedDigit(location, base)),\n Digit36::Digit(_) | Digit36::Error => match num_digits {\n 0 => return self.report(ExpectedDigit(location, base)),\n _ => return self.report(ExpectedDigitOrSeparator(location, base)),\n },\n }\n }\n\n if num_digits == 0 {\n return self.report(UnexpectedEndOfLiteral(self.token_location(&lexer)));\n }\n\n Some(integer)\n }\n```"}], "func_name": "number_to_unsigned_int", "docstring": "Parse a numeric literal into an unsigned integer.\n\n# Returns\n\n- `Some(_)`: If the literal was parsed correctly.\n- `None`: If a fatal error when parsing the literal.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/literal.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/literal.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f72c6c06d4309bf30b25a5acef68a8ae4df2c8ccdd02ca6f0f49c5c0590db19"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: number_to_signed_int\n\nDocumentation:\nParse a numeric literal into a signed integer.\n\n# Returns\n\n- `Some(_)`: If the literal was parsed correctly.\n- `None`: If a fatal error when parsing the literal.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn number_to_signed_int(self) -> Option {\n let mut lexer = NumericLiteral::lexer(self.source.as_bytes());\n\n let (sign, base, start_digit) = self.expect_numeric_literal_start(&mut lexer)?;\n\n let mut lexer = lexer.morph();\n let mut integer = T::zero();\n let mut num_digits = 0;\n\n if let Some(digit) = start_digit {\n integer = self.add_integer_digit(sign, base, integer, digit)?;\n num_digits += 1;\n }\n\n while let Some(token) = lexer.next() {\n let location = self.token_location(&lexer);\n match token {\n Digit36::Digit(digit) if digit < base.to_u8() => {\n integer = self.add_integer_digit(sign, base, integer, digit)?;\n num_digits += 1;\n }\n Digit36::Separator if num_digits != 0 => {}\n Digit36::Separator => return self.report(ExpectedDigit(location, base)),\n Digit36::Digit(_) | Digit36::Error => match num_digits {\n 0 => return self.report(ExpectedDigit(location, base)),\n _ => return self.report(ExpectedDigitOrSeparator(location, base)),\n },\n }\n }\n\n if num_digits == 0 {\n return self.report(UnexpectedEndOfLiteral(self.token_location(&lexer)));\n }\n\n Some(integer)\n }\n```"}], "func_name": "number_to_signed_int", "docstring": "Parse a numeric literal into a signed integer.\n\n# Returns\n\n- `Some(_)`: If the literal was parsed correctly.\n- `None`: If a fatal error when parsing the literal.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/literal.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/literal.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d2c095c2db3a54f7d1969e6b820ea240e94a95dfcd09fdfaa95f905a79ca637b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: number_to_float\n\nDocumentation:\nParse a numeric literal into a float.\n\n# Returns\n\n- `Some(_)`: If the literal was parsed correctly.\n- `None`: If a fatal error when parsing the literal.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn number_to_float>(self) -> Option {\n // NOTE: This could probably be improved a great deal.\n // It might be worth looking at `lexical-core` crate as an alternative\n // to implementing our own parser: https://github.com/Alexhuszagh/rust-lexical/\n\n let mut lexer = NumericLiteral::lexer(self.source.as_bytes());\n\n let add_digit = |sign, base: Base, float: T, digit: u8| match sign {\n Sign::Positive => float * base.to_u8().into() + digit.into(),\n Sign::Negative => float * base.to_u8().into() - digit.into(),\n };\n\n let (sign, base, start_digit) = self.expect_numeric_literal_start(&mut lexer)?;\n\n let mut float = T::zero();\n let mut num_integer_digits = 0;\n\n if let Some(digit) = start_digit {\n float = add_digit(sign, base, float, digit);\n num_integer_digits += 1;\n }\n\n if base == Base::Decimal {\n let mut lexer = lexer.morph();\n let mut has_fractional = false;\n let mut has_exponent = false;\n\n while let Some(token) = lexer.next() {\n let location = self.token_location(&lexer);\n match token {\n Digit10::Digit(digit) if digit < base.to_u8() => {\n float = add_digit(sign, base, float, digit);\n num_integer_digits += 1;\n }\n Digit10::Separator if num_integer_digits != 0 => {}\n Digit10::Separator => return self.report(ExpectedDigit(location, base)),\n Digit10::StartFractional => {\n has_fractional = true;\n break;\n }\n Digit10::StartExponent => {\n has_exponent = true;\n break;\n }\n Digit10::Digit(_) | Digit10::Error => match num_integer_digits {\n 0 => return self.report(ExpectedDigit(location, base)),\n _ => return self.report(ExpectedDigitSeparatorFracOrExp(location, base)),\n },\n }\n }\n\n if num_integer_digits == 0 {\n return self.report(ExpectedDigit(self.token_location(&lexer), base));\n }\n\n if has_fractional {\n let mut frac = T::zero();\n let mut num_frac_digits = 0;\n\n while let Some(token) = lexer.next() {\n let location = self.token_location(&lexer);\n match token {\n Digit10::Digit(digit) if digit < base.to_u8() => {\n frac = add_digit(sign, base, frac, digit);\n num_frac_digits += 1;\n }\n Digit10::Separator if num_frac_digits != 0 => {}\n Digit10::Separator => return self.report(ExpectedDigit(location, base)),\n Digit10::StartExponent => {\n has_exponent = true;\n break;\n }\n Digit10::Digit(_) | Digit10::StartFractional | Digit10::Error => {\n match num_frac_digits {\n 0 => return self.report(ExpectedDigit(location, base)),\n _ => {\n return self.report(ExpectedDigitSeparatorOrExp(location, base))\n }\n }\n }\n }\n }\n\n if num_frac_digits == 0 {\n return self.report(ExpectedDigit(self.token_location(&lexer), base));\n }\n\n float = float + frac / T::powi(base.to_u8().into(), num_frac_digits);\n }\n\n if has_exponent {\n return self.report(FloatLiteralExponentNotSupported(\n self.token_location(&lexer),\n ));\n }\n\n Some(float)\n } else {\n self.report(UnsupportedFloatLiteralBase(self.location, base))\n }\n }\n```"}], "func_name": "number_to_float", "docstring": "Parse a numeric literal into a float.\n\n# Returns\n\n- `Some(_)`: If the literal was parsed correctly.\n- `None`: If a fatal error when parsing the literal.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/literal.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/literal.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0486f456f5c6778645878a21136b854e1e1cb7500d132e108e03ce3908f31222"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_integer_digit\n\nDocumentation:\nAdd a new place to the given integer, handling overflow and underflow.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_integer_digit(&self, sign: Sign, base: Base, integer: T, digit: u8) -> Option\n where\n T: PrimInt,\n {\n T::checked_mul(&integer, &T::from(base.to_u8()).unwrap())\n .and_then(|place_shifted| match sign {\n Sign::Positive => T::checked_add(&place_shifted, &T::from(digit).unwrap()),\n Sign::Negative => T::checked_sub(&place_shifted, &T::from(digit).unwrap()),\n })\n .or_else(|| self.report(LiteralOutOfRange(self.location)))\n }\n```"}], "func_name": "add_integer_digit", "docstring": "Add a new place to the given integer, handling overflow and underflow.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/literal.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/literal.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "11d7a8752e98fd24ff9f8f2ed38572596ec43a7671b0dc4b0d45e2200215e1f2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: quoted_to_unicode_char\n\nDocumentation:\nParse a quoted literal into a Unicode encoded character.\n\n# Returns\n\n- `Some(_)`: If the literal was parsed correctly.\n- `None`: If a fatal error when parsing the literal.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn quoted_to_unicode_char(self) -> Option {\n let mut lexer = QuotedLiteral::lexer(self.source);\n\n let (mut lexer, end_quote) = match self.expect_token(&mut lexer)? {\n QuotedLiteral::Start(quote) => (lexer.morph(), quote),\n QuotedLiteral::Error => return self.report(InvalidToken(self.token_location(&lexer))),\n };\n\n let mut character = None;\n\n 'quoted_text: loop {\n match self.expect_token(&mut lexer)? {\n QuotedText::Utf8Text(text) => {\n for ch in text.chars() {\n match character {\n None => character = Some(ch),\n Some(_) => return self.report(OverlongCharLiteral(self.location)),\n }\n }\n }\n QuotedText::StartEscape => match character {\n None => match self.expect_escape_sequence(lexer.morph(), end_quote)? {\n (_, None) => return None,\n (escape, Some(ch)) => {\n character = Some(ch);\n lexer = escape.morph();\n }\n },\n Some(_) => {\n return self.report(OverlongCharLiteral(self.token_location(&lexer)))\n }\n },\n QuotedText::End(quote) if quote == end_quote => match lexer.next() {\n None => break 'quoted_text,\n Some(_) => {\n return self.report(ExpectedEndOfLiteral(self.token_location(&lexer)))\n }\n },\n QuotedText::End(quote) => match character {\n None => character = Some(quote.to_char()),\n Some(_) => return self.report(OverlongCharLiteral(self.location)),\n },\n\n QuotedText::Error => return self.report(InvalidToken(self.token_location(&lexer))),\n }\n }\n\n match character {\n Some(ch) => Some(ch),\n None => self.report(EmptyCharLiteral(self.location)),\n }\n }\n```"}], "func_name": "quoted_to_unicode_char", "docstring": "Parse a quoted literal into a Unicode encoded character.\n\n# Returns\n\n- `Some(_)`: If the literal was parsed correctly.\n- `None`: If a fatal error when parsing the literal.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/literal.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/literal.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9f5f60d9b59f0df37f6382c22cd508e0834083d452b984bcff1e2be88083d794"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: quoted_to_utf8_string\n\nDocumentation:\nParse a double quoted literal into a UTF-8 encoded string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn quoted_to_utf8_string(self) -> Option {\n let mut lexer = QuotedLiteral::lexer(self.source);\n\n let (mut lexer, end_quote) = match self.expect_token(&mut lexer)? {\n QuotedLiteral::Start(quote) => (lexer.morph(), quote),\n QuotedLiteral::Error => return self.report(InvalidToken(self.token_location(&lexer))),\n };\n\n let mut string = Some(String::new());\n\n 'quoted_text: loop {\n match self.expect_token(&mut lexer)? {\n QuotedText::Utf8Text(text) => {\n if let Some(string) = &mut string {\n string.push_str(text);\n }\n }\n QuotedText::StartEscape => {\n let (escape_lexer, ch) =\n self.expect_escape_sequence(lexer.morph(), end_quote)?;\n lexer = escape_lexer.morph();\n\n match ch {\n None => string = None,\n Some(ch) => {\n if let Some(string) = &mut string {\n string.push(ch);\n }\n }\n }\n }\n QuotedText::End(quote) if quote == end_quote => match lexer.next() {\n None => break 'quoted_text,\n Some(_) => {\n return self.report(ExpectedEndOfLiteral(self.token_location(&lexer)))\n }\n },\n QuotedText::End(quote) => {\n if let Some(string) = &mut string {\n string.push(quote.to_char());\n }\n }\n\n QuotedText::Error => return self.report(InvalidToken(self.token_location(&lexer))),\n }\n }\n\n string\n }\n```"}], "func_name": "quoted_to_utf8_string", "docstring": "Parse a double quoted literal into a UTF-8 encoded string.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/literal.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/literal.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dbe52497f1efcacf3608219fa34eb2b377307682e9dfcf0f0fcf0dff4494ba31"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_token\n\nDocumentation:\nExpect another token to be present in the lexer, reporting an error if not.\n\n# Returns\n\n- `Some(_)`: If another token was found in the source stream\n- `None`: If we reached the end of the source stream and we need to terminate parsing\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn expect_token>(\n &self,\n lexer: &mut logos::Lexer<'source, Token>,\n ) -> Option {\n match lexer.next() {\n Some(token) => Some(token),\n None => self.report(UnexpectedEndOfLiteral(self.token_location(&lexer))),\n }\n }\n```"}], "func_name": "expect_token", "docstring": "Expect another token to be present in the lexer, reporting an error if not.\n\n# Returns\n\n- `Some(_)`: If another token was found in the source stream\n- `None`: If we reached the end of the source stream and we need to terminate parsing", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/literal.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/literal.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f2f9633d06a9171983fc84bc738526e19b08973ebeba342838de03e77bc69a4f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_escape_sequence\n\nDocumentation:\nExpect an escape sequence.\n\n# Returns\n\n- `Some(_, Some(_))`: If we succeeded in parsing an escape sequence\n- `Some(_, None)`: If error ocurred but we may continue parsing in a degraded state\n- `None`: If a fatal error has ocurred and we need to terminate parsing the literal\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn expect_escape_sequence(\n &self,\n mut lexer: logos::Lexer<'source, EscapeSequence>,\n end_quote: Quote,\n ) -> Option<(logos::Lexer<'source, EscapeSequence>, Option)> {\n match self.expect_token(&mut lexer)? {\n EscapeSequence::Single(ch) => Some((lexer, Some(ch))),\n EscapeSequence::StartUnicodeEscape => {\n let mut unicode_lexer = lexer.morph();\n let next = self.expect_token(&mut unicode_lexer)?;\n let location = self.token_location(&unicode_lexer);\n lexer = unicode_lexer.morph();\n\n let ch = match next {\n UnicodeEscape::CharCode(code) => match code.len() {\n 1..=6 => match u32::from_str_radix(code, 16).unwrap() {\n code @ 0..=MAX_UNICODE => Some(std::char::from_u32(code).unwrap()),\n _ => self.report(OversizedUnicodeEscapeCode(location)),\n },\n 0 => self.report(EmptyUnicodeEscapeCode(location)),\n _ => self.report(OverlongUnicodeEscapeCode(location)),\n },\n UnicodeEscape::InvalidCharCode => {\n self.report(InvalidUnicodeEscapeCode(location))\n }\n UnicodeEscape::End(quote) if end_quote == quote => {\n return self.report(InvalidUnicodeEscape(location));\n }\n UnicodeEscape::End(_) | UnicodeEscape::Error => {\n self.report(InvalidUnicodeEscape(location))\n }\n };\n\n Some((lexer, ch))\n }\n EscapeSequence::StartAsciiEscape => {\n let mut ascii_lexer = lexer.morph();\n let next = self.expect_token(&mut ascii_lexer)?;\n let location = self.token_location(&ascii_lexer);\n lexer = ascii_lexer.morph();\n\n let ch = match next {\n AsciiEscape::CharCode(code) if code.len() == 2 => {\n match u32::from_str_radix(code, 16).unwrap() {\n code @ 0..=MAX_ASCII => Some(std::char::from_u32(code).unwrap()),\n _ => self.report(OversizedAsciiEscapeCode(location)),\n }\n }\n AsciiEscape::End(quote) if end_quote == quote => {\n return self.report(InvalidUnicodeEscape(location));\n }\n AsciiEscape::CharCode(_) | AsciiEscape::End(_) | AsciiEscape::Error => {\n self.report(InvalidAsciiEscape(location))\n }\n };\n\n Some((lexer, ch))\n }\n\n EscapeSequence::Error => {\n let location = self.token_location(&lexer);\n Some((lexer, self.report(UnknownEscapeSequence(location))))\n }\n }\n }\n```"}], "func_name": "expect_escape_sequence", "docstring": "Expect an escape sequence.\n\n# Returns\n\n- `Some(_, Some(_))`: If we succeeded in parsing an escape sequence\n- `Some(_, None)`: If error ocurred but we may continue parsing in a degraded state\n- `None`: If a fatal error has ocurred and we need to terminate parsing the literal", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/literal.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/literal.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "31dd83d91f6a66977448b6b6ccff625fce6a38ab8a35b21ea2e1c877614350fd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: primary\n\nDocumentation:\nCreate a new label with a style of [`LabelStyle::Primary`].\n\n[`LabelStyle::Primary`]: LabelStyle::Primary\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn primary(location: &Location) -> Option> {\n match location {\n Location::Generated => None,\n Location::FileRange(file_id, range) => Some(Label::primary(*file_id, *range)),\n }\n}\n```"}], "func_name": "primary", "docstring": "Create a new label with a style of [`LabelStyle::Primary`].\n\n[`LabelStyle::Primary`]: LabelStyle::Primary", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/reporting.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/reporting.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "71b5ca6e3f5a90c3a6d904be1ebd46273d0f2d4814273552b31c50a8ada1f9b7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: secondary\n\nDocumentation:\nCreate a new label with a style of [`LabelStyle::Secondary`].\n\n[`LabelStyle::Secondary`]: LabelStyle::Secondary\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn secondary(location: &Location) -> Option> {\n match location {\n Location::Generated => None,\n Location::FileRange(file_id, range) => Some(Label::secondary(*file_id, *range)),\n }\n}\n```"}], "func_name": "secondary", "docstring": "Create a new label with a style of [`LabelStyle::Secondary`].\n\n[`LabelStyle::Secondary`]: LabelStyle::Secondary", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/reporting.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/reporting.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aa07507d7cfb3f07300e0669fe1a3686a55105643e8b9c340c80872fc3072631"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_global\n\nDocumentation:\nAttempt to match against a stuck global.\n\nThis can help to clean up pattern matches in lieu of\n[`match_default_bindings`](https://github.com/rust-lang/rust/issues/42640).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_global(&self) -> Option<(&str, &[Elim])> {\n match self {\n Value::Stuck(Head::Global(name), elims) => Some((name, elims)),\n _ => None,\n }\n }\n```"}], "func_name": "try_global", "docstring": "Attempt to match against a stuck global.\n\nThis can help to clean up pattern matches in lieu of\n[`match_default_bindings`](https://github.com/rust-lang/rust/issues/42640).", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/semantics.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/semantics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9faf224270aa24885c9404621f86ec76027f98b0e18ed063ff4962fac1678a3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: apply\n\nDocumentation:\nApply an input to the function closure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn apply(&self, globals: &Globals, input: Arc) -> Arc {\n let mut values = self.values.clone();\n values.push(input);\n eval(globals, &mut values, &self.term)\n }\n```"}], "func_name": "apply", "docstring": "Apply an input to the function closure.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/semantics.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/semantics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "926ccfc51defc620e594211da7a61e9d357d891f01e4c5c22b6bf23477577499"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: for_each_entry\n\nDocumentation:\nApply a callback to each of the entries in the record closure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn for_each_entry(\n &self,\n globals: &Globals,\n mut on_entry: impl FnMut(Arc) -> Arc,\n ) {\n let mut values = self.values.clone();\n\n for entry_term in self.entries.iter() {\n let entry_value = eval(globals, &mut values, entry_term);\n values.push(on_entry(entry_value));\n }\n }\n```"}], "func_name": "for_each_entry", "docstring": "Apply a callback to each of the entries in the record closure.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/semantics.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/semantics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b6d4a1152da0c753a5c339f66f1571bf3c9c4e40b4ace6535818845ae9e97cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: eval\n\nDocumentation:\nLazily evaluate a term using the given universe offset and environment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn eval(values: Env>, term: Arc) -> LazyValue {\n LazyValue {\n init: RefCell::new(Some(LazyInit::EvalTerm(values, term))),\n cell: OnceCell::new(),\n }\n }\n```"}], "func_name": "eval", "docstring": "Lazily evaluate a term using the given universe offset and environment.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/semantics.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/semantics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "540e2f883ebc48138db17c450dd5356f9ccbf4d0c57ce689325f164ce4259ed6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: force\n\nDocumentation:\nForce the evaluation of a lazy value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn force(&self, globals: &Globals) -> &Arc {\n self.cell.get_or_init(|| match self.init.replace(None) {\n Some(LazyInit::EvalTerm(mut values, term)) => eval(globals, &mut values, &term),\n Some(LazyInit::ApplyElim(head, elim)) => match elim {\n Elim::Record(label) => record_elim(globals, head.force(globals).clone(), &label),\n Elim::Function(input) => function_elim(globals, head.force(globals).clone(), input),\n },\n None => panic!(\"Lazy instance has previously been poisoned\"),\n })\n }\n```"}], "func_name": "force", "docstring": "Force the evaluation of a lazy value.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/semantics.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/semantics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0be231e482904cdfb3eff9aa246d9f97c220879b8df9fabd062be0730749a46"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: record_elim_type\n\nDocumentation:\nReturn the type of the record elimination.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn record_elim_type(\n globals: &Globals,\n term_values: &mut Env>,\n head_term: &Term,\n head_type: &Arc,\n label: &str,\n) -> Option> {\n match head_type.force(globals) {\n Value::RecordType(labels, closure) => {\n // Evaluate the head of the record elimination now that we know we\n // are dealing with a dependent record type.\n let head_value = eval(globals, term_values, head_term);\n // Type values, which will be used to substitute the values\n // associated with earlier entries into subsequent entry types.\n let mut type_values = closure.values.clone();\n\n // Iterate over the entry labels their and associated types.\n for (entry_label, entry_type) in Iterator::zip(labels.iter(), closure.entries.iter()) {\n if entry_label == label {\n // We've reached the entry associated with the requested\n // `label`, so evaluate the entry type using the current\n // `type_values` and return it.\n let entry_type = eval(globals, &mut type_values, entry_type);\n return Some(entry_type);\n } else {\n // We have not yet reached the entry associated with the\n // requested `label`, so lookup the value associated with\n // the `entry_label` in the `head_value` and store it in\n // the `type_values`, ready for substitution later on.\n let entry_value = record_elim(globals, head_value.clone(), entry_label);\n type_values.push(entry_value);\n }\n }\n\n // No entry corresponding to the request `label` was found in the\n // `head_value`.\n None\n }\n Value::Error => Some(Arc::new(Value::Error)),\n _ => None,\n }\n}\n```"}], "func_name": "record_elim_type", "docstring": "Return the type of the record elimination.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/semantics.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/semantics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "551c59244024d2974f252de335dcbcf69d30a2281836c3a325b03ecc1029a222"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_back_stuck\n\nDocumentation:\nRead-back a stuck value into the term syntax.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_back_stuck(\n globals: &Globals,\n size: EnvSize,\n unfold: Unfold,\n head: &Head,\n spine: &[Elim],\n) -> Term {\n let head = match head {\n Head::Global(name) => Term::generated(TermData::Global(name.clone())),\n Head::Var(level) => {\n let index = size.level_to_index(*level).unwrap();\n Term::generated(TermData::Var(index)) // TODO: Handle overflow\n }\n };\n\n spine.iter().fold(head, |head, elim| match elim {\n Elim::Function(input) => {\n let input = read_back(globals, size, unfold, input.force(globals));\n Term::generated(TermData::FunctionElim(Arc::new(head), Arc::new(input)))\n }\n Elim::Record(label) => Term::generated(TermData::RecordElim(Arc::new(head), label.clone())),\n })\n}\n```"}], "func_name": "read_back_stuck", "docstring": "Read-back a stuck value into the term syntax.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/semantics.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/semantics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e287c1f9a2a07da350783f7a1efd1c31c19891190b162b00c3d8c2d388b46756"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_back\n\nDocumentation:\nRead-back a value into the term syntax.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_back(globals: &Globals, size: EnvSize, unfold: Unfold, value: &Value) -> Term {\n match value {\n Value::Stuck(head, spine) => read_back_stuck(globals, size, unfold, head, spine),\n Value::Unstuck(head, spine, value) => match unfold {\n Unfold::Never => read_back_stuck(globals, size, unfold, head, spine),\n Unfold::Always => read_back(globals, size, unfold, value.force(globals)),\n },\n\n Value::TypeType => Term::generated(TermData::TypeType),\n\n Value::FunctionType(input_name_hint, input_type, output_closure) => {\n let var = Arc::new(Value::var(size.next_level(), []));\n let input_type = read_back(globals, size, unfold, input_type);\n let output_type = output_closure.apply(globals, var);\n let output_type = read_back(globals, size.next_size(), unfold, &output_type);\n\n Term::generated(TermData::FunctionType(\n input_name_hint.clone(),\n Arc::new(input_type),\n Arc::new(output_type),\n ))\n }\n Value::FunctionTerm(input_name_hint, output_closure) => {\n let var = Arc::new(Value::var(size.next_level(), []));\n let output_term = output_closure.apply(globals, var);\n let output_term = read_back(globals, size.next_size(), unfold, &output_term);\n\n Term::generated(TermData::FunctionTerm(\n input_name_hint.clone(),\n Arc::new(output_term),\n ))\n }\n\n Value::RecordType(labels, closure) => {\n let mut size = size;\n let mut types = Vec::with_capacity(closure.entries.len());\n\n closure.for_each_entry(globals, |entry_type| {\n let entry_type = read_back(globals, size, unfold, &entry_type);\n types.push(Arc::new(entry_type));\n\n let level = size.next_level();\n size = size.next_size();\n\n Arc::new(Value::var(level, []))\n });\n\n Term::generated(TermData::RecordType(labels.clone(), types.into()))\n }\n Value::RecordTerm(labels, closure) => {\n let mut size = size;\n let mut terms = Vec::with_capacity(closure.entries.len());\n\n closure.for_each_entry(globals, |entry_term| {\n let entry_term = read_back(globals, size, unfold, &entry_term);\n terms.push(Arc::new(entry_term));\n\n let level = size.next_level();\n size = size.next_size();\n\n Arc::new(Value::var(level, []))\n });\n\n Term::generated(TermData::RecordTerm(labels.clone(), terms.into()))\n }\n\n Value::ArrayTerm(value_entries) => {\n let term_entries = value_entries\n .iter()\n .map(|value_entry| Arc::new(read_back(globals, size, unfold, value_entry)))\n .collect();\n\n Term::generated(TermData::ArrayTerm(term_entries))\n }\n Value::ListTerm(value_entries) => {\n let term_entries = value_entries\n .iter()\n .map(|value_entry| Arc::new(read_back(globals, size, unfold, value_entry)))\n .collect();\n\n Term::generated(TermData::ListTerm(term_entries))\n }\n\n Value::Constant(constant) => Term::generated(TermData::from(constant.clone())),\n\n Value::Error => Term::generated(TermData::Error),\n }\n}\n```"}], "func_name": "read_back", "docstring": "Read-back a value into the term syntax.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/semantics.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/semantics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e55ad08f89c80e92bd528739952d105d0a0ba403d431b2a944028007125dc61a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_equal_stuck\n\nDocumentation:\nCheck that one stuck value is equal to another stuck value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_equal_stuck(\n globals: &Globals,\n size: EnvSize,\n (head0, spine0): (&Head, &[Elim]),\n (head1, spine1): (&Head, &[Elim]),\n) -> bool {\n if head0 != head1 || spine0.len() != spine1.len() {\n return false;\n }\n\n for (elim0, elim1) in Iterator::zip(spine0.iter(), spine1.iter()) {\n match (elim0, elim1) {\n (Elim::Function(input0), Elim::Function(input1)) => {\n let input0 = input0.force(globals);\n let input1 = input1.force(globals);\n\n if !is_equal(globals, size, input0, input1) {\n return false;\n }\n }\n (Elim::Record(label0), Elim::Record(label1)) if label0 == label1 => {}\n (_, _) => return false,\n }\n }\n\n true\n}\n```"}], "func_name": "is_equal_stuck", "docstring": "Check that one stuck value is equal to another stuck value.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/semantics.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/semantics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3cfec00f871280de9b4fbb24120e3c8a9ef6a36ed512c9bddc2c5e10eb335d62"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_equal_function_closure\n\nDocumentation:\nCheck that one function closure is equal to another function closure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_equal_function_closure(\n globals: &Globals,\n size: EnvSize,\n closure0: &FunctionClosure,\n closure1: &FunctionClosure,\n) -> bool {\n let var = Arc::new(Value::var(size.next_level(), []));\n let term0 = closure0.apply(globals, var.clone());\n let term1 = closure1.apply(globals, var);\n is_equal(globals, size.next_size(), &term0, &term1)\n}\n```"}], "func_name": "is_equal_function_closure", "docstring": "Check that one function closure is equal to another function closure.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/semantics.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/semantics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0afcf5899aff2d885e8bcf7a3c1ad49575abe3203d8a2f67753ea59b9486f5e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_equal_record_closure\n\nDocumentation:\nCheck that one record closure is equal to another record closure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_equal_record_closure(\n globals: &Globals,\n mut size: EnvSize,\n closure0: &RecordClosure,\n closure1: &RecordClosure,\n) -> bool {\n if closure0.entries.len() != closure1.entries.len() {\n return false;\n }\n\n let mut values0 = closure0.values.clone();\n let mut values1 = closure1.values.clone();\n\n for (entry0, entry1) in Iterator::zip(closure0.entries.iter(), closure1.entries.iter()) {\n let entry0 = eval(globals, &mut values0, entry0);\n let entry1 = eval(globals, &mut values1, entry1);\n\n if !is_equal(globals, size, &entry0, &entry1) {\n return false;\n }\n\n let var = Arc::new(Value::var(size.next_level(), []));\n values0.push(var.clone());\n values1.push(var);\n size = size.next_size();\n }\n\n true\n}\n```"}], "func_name": "is_equal_record_closure", "docstring": "Check that one record closure is equal to another record closure.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/semantics.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/semantics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "34858579602c80547a089543d99078b134078231d785e41a431cd779788cc393"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_equal\n\nDocumentation:\nCheck that one value is [computationally equal] to another value.\n\n[computationally equal]: https://ncatlab.org/nlab/show/equality#computational_equality\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_equal(globals: &Globals, size: EnvSize, value0: &Value, value1: &Value) -> bool {\n match (value0, value1) {\n (Value::Stuck(head0, spine0), Value::Stuck(head1, spine1)) => {\n is_equal_stuck(globals, size, (head0, spine0), (head1, spine1))\n }\n (Value::Unstuck(head0, spine0, value0), Value::Unstuck(head1, spine1, value1)) => {\n if is_equal_stuck(globals, size, (head0, spine0), (head1, spine1)) {\n // No need to force computation if the stuck values are the same!\n return true;\n }\n\n let value0 = value0.force(globals);\n let value1 = value1.force(globals);\n is_equal(globals, size, value0, value1)\n }\n (Value::Unstuck(_, _, value0), value1) => {\n is_equal(globals, size, value0.force(globals), value1)\n }\n (value0, Value::Unstuck(_, _, value1)) => {\n is_equal(globals, size, value0, value1.force(globals))\n }\n\n (Value::TypeType, Value::TypeType) => true,\n\n (\n Value::FunctionType(_, input_type0, output_closure0),\n Value::FunctionType(_, input_type1, output_closure1),\n ) => {\n is_equal(globals, size, input_type1, input_type0)\n && is_equal_function_closure(globals, size, output_closure0, output_closure1)\n }\n (Value::FunctionTerm(_, output_closure0), Value::FunctionTerm(_, output_closure1)) => {\n is_equal_function_closure(globals, size, output_closure0, output_closure1)\n }\n\n (Value::RecordType(labels0, closure0), Value::RecordType(labels1, closure1))\n | (Value::RecordTerm(labels0, closure0), Value::RecordTerm(labels1, closure1)) => {\n labels0 == labels1 && is_equal_record_closure(globals, size, closure0, closure1)\n }\n\n (Value::ArrayTerm(value_entries0), Value::ArrayTerm(value_entries1))\n | (Value::ListTerm(value_entries0), Value::ListTerm(value_entries1)) => {\n if value_entries0.len() != value_entries1.len() {\n return false;\n }\n\n Iterator::zip(value_entries0.iter(), value_entries1.iter()).all(\n |(value_entry0, value_entry1)| is_equal(globals, size, value_entry0, value_entry1),\n )\n }\n\n (Value::Constant(constant0), Value::Constant(constant1)) => constant0 == constant1,\n\n // Errors are always treated as equal, regardless of what they are compared with.\n (Value::Error, _) | (_, Value::Error) => true,\n // Anything else is not equal!\n (_, _) => false,\n }\n}\n```"}], "func_name": "is_equal", "docstring": "Check that one value is [computationally equal] to another value.\n\n[computationally equal]: https://ncatlab.org/nlab/show/equality#computational_equality", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/semantics.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/semantics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "23d9b6921eb4946199a63cd8a90970c7c6c279fbabd6f08e5a1cbb00d30d6a9c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_definition\n\nDocumentation:\nPush a new definition onto the context, along with its type annotation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn push_definition(&mut self, value: Arc, r#type: Arc) {\n self.types.push(r#type);\n self.values.push(value);\n }\n```"}], "func_name": "push_definition", "docstring": "Push a new definition onto the context, along with its type annotation.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/typing.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/typing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9d9369e06548b362a46039d06afb1ea99798ebd3f741731b96753c0e54b66b87"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: truncate_scopes\n\nDocumentation:\nTruncate the scopes in the context to the given size.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn truncate_scopes(&mut self, env_size: EnvSize) {\n self.types.truncate(env_size.to_usize());\n self.values.truncate(env_size);\n }\n```"}], "func_name": "truncate_scopes", "docstring": "Truncate the scopes in the context to the given size.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/typing.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/typing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "629179d9c77e719309ee6cbed63c925f8c87c558ca6980674aaee45cb73b9e46"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: eval\n\nDocumentation:\nEvaluate a [`Term`] into a [`Value`].\n\n[`Value`]: crate::lang::core::semantics::Value\n[`Term`]: crate::lang::core::Term\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn eval(&mut self, term: &Term) -> Arc {\n semantics::eval(self.globals, &mut self.values, term)\n }\n```"}], "func_name": "eval", "docstring": "Evaluate a [`Term`] into a [`Value`].\n\n[`Value`]: crate::lang::core::semantics::Value\n[`Term`]: crate::lang::core::Term", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/typing.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/typing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "633aa19ce126c6c9d8fb5a6af6a5c78d01918a99cec8d8cf4c79bd7890def3eb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_back\n\nDocumentation:\nRead back a value into a normal form using the current state of the elaborator.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_back(&self, value: &Value) -> Term {\n semantics::read_back(self.globals, self.size(), Unfold::Never, value)\n }\n```"}], "func_name": "read_back", "docstring": "Read back a value into a normal form using the current state of the elaborator.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/typing.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/typing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca65cba29a4ff1c2b2749e9c62a4ab1ff6692c5d4bbaa42a096a32447a7122c9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_equal\n\nDocumentation:\nCheck that one [`Value`] is computationally equal to another [`Value`].\n\nReturns `false` if either value is not a type.\n\n[`Value`]: crate::lang::core::semantics::Value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_equal(&self, value0: &Value, value1: &Value) -> bool {\n semantics::is_equal(self.globals, self.size(), value0, value1)\n }\n```"}], "func_name": "is_equal", "docstring": "Check that one [`Value`] is computationally equal to another [`Value`].\n\nReturns `false` if either value is not a type.\n\n[`Value`]: crate::lang::core::semantics::Value", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/lang/core/typing.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/lang/core/typing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6bfaeba29b16059f1f5a88bca225e54cde89852cd68268e91fe14c1e791abd5f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_type\n\nDocumentation:\nGet the type of a variable and its index at the current binding depth.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_type(&self, name: &str) -> Option<(&Arc, core::VarIndex)> {\n Iterator::zip(core::var_indices(), self.types.iter().rev()).find_map(\n |(index, (decl_name, r#type))| match decl_name {\n Some(decl_name) if decl_name == name => Some((r#type, index)),\n Some(_) | None => None,\n },\n )\n }\n```"}], "func_name": "get_type", "docstring": "Get the type of a variable and its index at the current binding depth.", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/pass/surface_to_core.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/pass/surface_to_core.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8f0407fb0a69b549dfb9115a08594b548cf671ef5f9e0062afcef09cafbdf20f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: eval\n\nDocumentation:\nEvaluate a [`core::Term`] into a [`Value`].\n\n[`Value`]: crate::lang::core::semantics::Value\n[`core::Term`]: crate::lang::core::Term\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn eval(&mut self, term: &core::Term) -> Arc {\n semantics::eval(self.globals, &mut self.values, term)\n }\n```"}], "func_name": "eval", "docstring": "Evaluate a [`core::Term`] into a [`Value`].\n\n[`Value`]: crate::lang::core::semantics::Value\n[`core::Term`]: crate::lang::core::Term", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/pass/surface_to_core.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/pass/surface_to_core.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e5b0a1363ddbabfdb8f67dce0d99304f01ddfd20e61d27cf6358ebd075089ef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: normalize\n\nDocumentation:\nFully normalize a [`core::Term`] using [normalization by evaluation].\n\n[`core::Term`]: crate::lang::core::Term\n[normalization by evaluation]: https://en.wikipedia.org/wiki/Normalisation_by_evaluation\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn normalize(&mut self, term: &core::Term) -> core::Term {\n semantics::normalize(self.globals, &mut self.values, term)\n }\n```"}], "func_name": "normalize", "docstring": "Fully normalize a [`core::Term`] using [normalization by evaluation].\n\n[`core::Term`]: crate::lang::core::Term\n[normalization by evaluation]: https://en.wikipedia.org/wiki/Normalisation_by_evaluation", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/pass/surface_to_core.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/pass/surface_to_core.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fea975d5d080fb977b61559b57517ec34ad80fc60db88b4c1456e8c51783b357"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_back\n\nDocumentation:\nRead back a [`Value`] to a [`core::Term`] using the current\nstate of the elaborator.\n\nUnstuck eliminations are not unfolded, making this useful for printing\nterms and types in user-facing diagnostics.\n\n[`Value`]: crate::lang::core::semantics::Value\n[`core::Term`]: crate::lang::core::Term\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_back(&self, value: &Value) -> core::Term {\n semantics::read_back(self.globals, self.size(), Unfold::Never, value)\n }\n```"}], "func_name": "read_back", "docstring": "Read back a [`Value`] to a [`core::Term`] using the current\nstate of the elaborator.\n\nUnstuck eliminations are not unfolded, making this useful for printing\nterms and types in user-facing diagnostics.\n\n[`Value`]: crate::lang::core::semantics::Value\n[`core::Term`]: crate::lang::core::Term", "repo": "pikelet-lang/pikelet", "path": "pikelet/src/pass/surface_to_core.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet/src/pass/surface_to_core.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "767607296f89fa843a785339e742f82a16b30a1904e4b85a1b18a9c231923bd5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRun the CLI with the given options\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn run(options: Options) -> anyhow::Result<()> {\n match options {\n Options::Check(options) => check::run(options),\n #[cfg(feature = \"editor\")]\n Options::Editor => {\n // FIXME: `iced::Error` is not `Send + Sync`, and so is incompatible with `anyhow::Result`.\n // See this issue for more information: https://github.com/hecrj/iced/issues/516\n pikelet_editor::run().map_err(|err| anyhow!(\"{}\", err))\n }\n #[cfg(feature = \"language-server\")]\n Options::LanguageServer => pikelet_language_server::run(),\n Options::Repl(options) => repl::run(options),\n }\n}\n```"}], "func_name": "run", "docstring": "Run the CLI with the given options", "repo": "pikelet-lang/pikelet", "path": "pikelet-cli/src/lib.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet-cli/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8b9b49819edd9e3bdd7bcda291d7aca37404dee4c8bddbecd39b1e27ea26161c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: walk_files\n\nDocumentation:\nRecursively walk over test files under a file path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn walk_files(root: impl AsRef) -> impl Iterator {\n WalkDir::new(root)\n .into_iter()\n .filter_map(|dir_entry| dir_entry.ok())\n .filter(|dir_entry| dir_entry.file_type().is_file())\n .map(|dir_entry| dir_entry.into_path())\n}\n```"}], "func_name": "walk_files", "docstring": "Recursively walk over test files under a file path.", "repo": "pikelet-lang/pikelet", "path": "pikelet-test/src/lib.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet-test/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dc186e9b01e11dfd721fd221c48b21456a22cee14d8c063b8e721554db53aca5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_simple_test\n\nDocumentation:\nExtract a new simple test from the given file path\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn extract_simple_test(path: PathBuf) -> Option> {\n is_pikelet_path(&path).then(|| Test {\n name: path.display().to_string(),\n kind: String::new(),\n is_ignored: false,\n is_bench: false,\n data: TestData {\n input_file: path,\n parse_config: false,\n },\n })\n}\n```"}], "func_name": "extract_simple_test", "docstring": "Extract a new simple test from the given file path", "repo": "pikelet-lang/pikelet", "path": "pikelet-test/src/lib.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet-test/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d3599b0615d627729c5d01cf1e7dd5848e4fa6e45abf05bfb53c0c7cc180416e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_config_test\n\nDocumentation:\nExtract a new test configured with TOML-formatted comments from the given file path\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn extract_config_test(path: PathBuf) -> Option> {\n is_pikelet_path(&path).then(|| Test {\n name: path.display().to_string(),\n kind: String::new(),\n is_ignored: false,\n is_bench: false,\n data: TestData {\n input_file: path,\n parse_config: true,\n },\n })\n}\n```"}], "func_name": "extract_config_test", "docstring": "Extract a new test configured with TOML-formatted comments from the given file path", "repo": "pikelet-lang/pikelet", "path": "pikelet-test/src/lib.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet-test/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54a0e03fbe1b0412226617a4115b10d30bf3df20aaeace3b5a6721a6a778a57a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_test\n\nDocumentation:\nCreate a test runner function using the given Pikelet executable\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn run_test(\n pikelet_exe: &'static str,\n) -> impl Fn(&Test) -> Outcome + 'static + Send + Sync {\n move |test| run_test_impl(pikelet_exe, test)\n}\n```"}], "func_name": "run_test", "docstring": "Create a test runner function using the given Pikelet executable", "repo": "pikelet-lang/pikelet", "path": "pikelet-test/src/lib.rs", "url": "https://github.com/pikelet-lang/pikelet/blob/master/pikelet-test/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fd2e6f7cebaa84f61d790afa95e878d1c4d41d6c53eddeddf33a858fd439510f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: server_endpoint\n\nDocumentation:\nCreates a server endpoint which runs on the given runtime\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn server_endpoint(\n rt: &tokio::runtime::Runtime,\n cert: CertificateDer<'static>,\n key: PrivateKeyDer<'static>,\n opt: &Opt,\n) -> (SocketAddr, quinn::Endpoint) {\n let cert_chain = vec![cert];\n let mut server_config = quinn::ServerConfig::with_single_cert(cert_chain, key).unwrap();\n server_config.transport = Arc::new(transport_config(opt));\n\n let endpoint = {\n let _guard = rt.enter();\n quinn::Endpoint::server(\n server_config,\n SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 0),\n )\n .unwrap()\n };\n let server_addr = endpoint.local_addr().unwrap();\n (server_addr, endpoint)\n}\n```"}], "func_name": "server_endpoint", "docstring": "Creates a server endpoint which runs on the given runtime", "repo": "quinn-rs/quinn", "path": "bench/src/lib.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/bench/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "61e8e1e6929d8489f50f58c649f491f514112425bc255d7a576b8250136825dd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect_client\n\nDocumentation:\nCreate a client endpoint and client connection\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn connect_client(\n server_addr: SocketAddr,\n server_cert: CertificateDer<'_>,\n opt: Opt,\n) -> Result<(quinn::Endpoint, quinn::Connection)> {\n let endpoint =\n quinn::Endpoint::client(SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 0)).unwrap();\n\n let mut roots = RootCertStore::empty();\n roots.add(server_cert)?;\n\n let default_provider = rustls::crypto::ring::default_provider();\n let provider = rustls::crypto::CryptoProvider {\n cipher_suites: vec![opt.cipher.as_rustls()],\n ..default_provider\n };\n\n let crypto = rustls::ClientConfig::builder_with_provider(provider.into())\n .with_protocol_versions(&[&rustls::version::TLS13])\n .unwrap()\n .with_root_certificates(roots)\n .with_no_client_auth();\n\n let mut client_config = quinn::ClientConfig::new(Arc::new(QuicClientConfig::try_from(crypto)?));\n client_config.transport_config(Arc::new(transport_config(&opt)));\n\n let connection = endpoint\n .connect_with(client_config, server_addr, \"localhost\")\n .unwrap()\n .await\n .context(\"unable to connect\")?;\n trace!(\"connected\");\n\n Ok((endpoint, connection))\n}\n```"}], "func_name": "connect_client", "docstring": "Create a client endpoint and client connection", "repo": "quinn-rs/quinn", "path": "bench/src/lib.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/bench/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e2b0636dfc3e5946e19f0c84502962ff9ff42c5ad748eb2cbaea38cbce00a22d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wrap_packet_keys\n\nDocumentation:\nWraps the provided keys in `NoProtectionPacketKey` to disable packet encryption / decryption\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn wrap_packet_keys(\n keys: crypto::KeyPair>,\n ) -> crypto::KeyPair> {\n crypto::KeyPair {\n local: Box::new(NoProtectionPacketKey::new(keys.local)),\n remote: Box::new(NoProtectionPacketKey::new(keys.remote)),\n }\n }\n```"}], "func_name": "wrap_packet_keys", "docstring": "Wraps the provided keys in `NoProtectionPacketKey` to disable packet encryption / decryption", "repo": "quinn-rs/quinn", "path": "perf/src/noprotection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/perf/src/noprotection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c06f8c2591c4b50253a623fbbccde8283483b30886966d7fc0795bb4573a9bc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_server\n\nDocumentation:\nRuns a QUIC server bound to given address.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_server(addr: SocketAddr) {\n let (endpoint, _server_cert) = make_server_endpoint(addr).unwrap();\n // accept a single connection\n let incoming_conn = endpoint.accept().await.unwrap();\n let conn = incoming_conn.await.unwrap();\n println!(\n \"[server] connection accepted: addr={}\",\n conn.remote_address()\n );\n}\n```"}], "func_name": "run_server", "docstring": "Runs a QUIC server bound to given address.", "repo": "quinn-rs/quinn", "path": "quinn/examples/insecure_connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/examples/insecure_connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc90707361886d251a3a8b8f3fd4022e33c41cae0452181897dbe9b093a84abc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_server\n\nDocumentation:\nRuns a QUIC server bound to given address and returns server certificate.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn run_server(\n addr: SocketAddr,\n) -> Result, Box> {\n let (endpoint, server_cert) = make_server_endpoint(addr)?;\n // accept a single connection\n tokio::spawn(async move {\n let connection = endpoint.accept().await.unwrap().await.unwrap();\n println!(\n \"[server] incoming connection: addr={}\",\n connection.remote_address()\n );\n });\n\n Ok(server_cert)\n}\n```"}], "func_name": "run_server", "docstring": "Runs a QUIC server bound to given address and returns server certificate.", "repo": "quinn-rs/quinn", "path": "quinn/examples/single_socket.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/examples/single_socket.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "50bda079418f0a97e8fd9d98fca19038219a641a36f62090b75373f544dda871"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_client\n\nDocumentation:\nAttempt QUIC connection with the given server address.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_client(endpoint: &Endpoint, server_addr: SocketAddr) {\n let connect = endpoint.connect(server_addr, \"localhost\").unwrap();\n let connection = connect.await.unwrap();\n println!(\"[client] connected: addr={}\", connection.remote_address());\n}\n```"}], "func_name": "run_client", "docstring": "Attempt QUIC connection with the given server address.", "repo": "quinn-rs/quinn", "path": "quinn/examples/single_socket.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/examples/single_socket.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "769da4b3cae9129b67f722caa5c1e2654b265c8b733c7752e2de36738fd37d04"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: configure_client\n\nDocumentation:\nBuilds default quinn client config and trusts given certificates.\n\n## Args\n\n- server_certs: a list of trusted certificates in DER format.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn configure_client(\n server_certs: &[&[u8]],\n) -> Result> {\n let mut certs = rustls::RootCertStore::empty();\n for cert in server_certs {\n certs.add(CertificateDer::from(*cert))?;\n }\n\n Ok(ClientConfig::with_root_certificates(Arc::new(certs))?)\n}\n```"}], "func_name": "configure_client", "docstring": "Builds default quinn client config and trusts given certificates.\n\n## Args\n\n- server_certs: a list of trusted certificates in DER format.", "repo": "quinn-rs/quinn", "path": "quinn/examples/common/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/examples/common/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a95ae38ebed6b25b0cfab055b6c1b6b55a23696c1c32838874f647b6cabda7b3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: configure_server\n\nDocumentation:\nReturns default server configuration along with its certificate.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn configure_server()\n-> Result<(ServerConfig, CertificateDer<'static>), Box> {\n let cert = rcgen::generate_simple_self_signed(vec![\"localhost\".into()]).unwrap();\n let cert_der = CertificateDer::from(cert.cert);\n let priv_key = PrivatePkcs8KeyDer::from(cert.key_pair.serialize_der());\n\n let mut server_config =\n ServerConfig::with_single_cert(vec![cert_der.clone()], priv_key.into())?;\n let transport_config = Arc::get_mut(&mut server_config.transport).unwrap();\n transport_config.max_concurrent_uni_streams(0_u8.into());\n\n Ok((server_config, cert_der))\n}\n```"}], "func_name": "configure_server", "docstring": "Returns default server configuration along with its certificate.", "repo": "quinn-rs/quinn", "path": "quinn/examples/common/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/examples/common/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f1fb803517394859fbfaa9cfb67a6fda08bb0f69714a31e718541efecbb194b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handshake_data\n\nDocumentation:\nParameters negotiated during the handshake\n\nThe dynamic type returned is determined by the configured\n[`Session`](proto::crypto::Session). For the default `rustls` session, the return value can\nbe [`downcast`](Box::downcast) to a\n[`crypto::rustls::HandshakeData`](crate::crypto::rustls::HandshakeData).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn handshake_data(&mut self) -> Result, ConnectionError> {\n // Taking &mut self allows us to use a single oneshot channel rather than dealing with\n // potentially many tasks waiting on the same event. It's a bit of a hack, but keeps things\n // simple.\n if let Some(x) = self.handshake_data_ready.take() {\n let _ = x.await;\n }\n let conn = self.conn.as_ref().unwrap();\n let inner = conn.state.lock(\"handshake\");\n inner\n .inner\n .crypto_session()\n .handshake_data()\n .ok_or_else(|| {\n inner\n .error\n .clone()\n .expect(\"spurious handshake data ready notification\")\n })\n }\n```"}], "func_name": "handshake_data", "docstring": "Parameters negotiated during the handshake\n\nThe dynamic type returned is determined by the configured\n[`Session`](proto::crypto::Session). For the default `rustls` session, the return value can\nbe [`downcast`](Box::downcast) to a\n[`crypto::rustls::HandshakeData`](crate::crypto::rustls::HandshakeData).", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be10800cb9aeaaea30a31f3052c28dd9dcc894be9ff8ef09466537bca977d5e8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: local_ip\n\nDocumentation:\nThe local IP address which was used when the peer established\nthe connection\n\nThis can be different from the address the endpoint is bound to, in case\nthe endpoint is bound to a wildcard address like `0.0.0.0` or `::`.\n\nThis will return `None` for clients, or when the platform does not expose this\ninformation. See [`quinn_udp::RecvMeta::dst_ip`](udp::RecvMeta::dst_ip) for a list of\nsupported platforms when using [`quinn_udp`](udp) for I/O, which is the default.\n\nWill panic if called after `poll` has returned `Ready`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn local_ip(&self) -> Option {\n let conn = self.conn.as_ref().unwrap();\n let inner = conn.state.lock(\"local_ip\");\n\n inner.inner.local_ip()\n }\n```"}], "func_name": "local_ip", "docstring": "The local IP address which was used when the peer established\nthe connection\n\nThis can be different from the address the endpoint is bound to, in case\nthe endpoint is bound to a wildcard address like `0.0.0.0` or `::`.\n\nThis will return `None` for clients, or when the platform does not expose this\ninformation. See [`quinn_udp::RecvMeta::dst_ip`](udp::RecvMeta::dst_ip) for a list of\nsupported platforms when using [`quinn_udp`](udp) for I/O, which is the default.\n\nWill panic if called after `poll` has returned `Ready`.", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0122089aa737d751a4e4b8846d4f9e084a5218813e197538523acbc2838b6b2f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remote_address\n\nDocumentation:\nThe peer's UDP address\n\nWill panic if called after `poll` has returned `Ready`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn remote_address(&self) -> SocketAddr {\n let conn_ref: &ConnectionRef = self.conn.as_ref().expect(\"used after yielding Ready\");\n conn_ref.state.lock(\"remote_address\").inner.remote_address()\n }\n```"}], "func_name": "remote_address", "docstring": "The peer's UDP address\n\nWill panic if called after `poll` has returned `Ready`.", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0974f2607af7b5f807a0bec62de477dfa628c1fa07668230b1a249206c26c014"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open_uni\n\nDocumentation:\nInitiate a new outgoing unidirectional stream.\n\nStreams are cheap and instantaneous to open unless blocked by flow control. As a\nconsequence, the peer won't be notified that a stream has been opened until the stream is\nactually used.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn open_uni(&self) -> OpenUni<'_> {\n OpenUni {\n conn: &self.0,\n notify: self.0.shared.stream_budget_available[Dir::Uni as usize].notified(),\n }\n }\n```"}], "func_name": "open_uni", "docstring": "Initiate a new outgoing unidirectional stream.\n\nStreams are cheap and instantaneous to open unless blocked by flow control. As a\nconsequence, the peer won't be notified that a stream has been opened until the stream is\nactually used.", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a698c41543b45e08e50488c6822b3283f1bf2bd8b6c8069295e3fb210efabb8a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open_bi\n\nDocumentation:\nInitiate a new outgoing bidirectional stream.\n\nStreams are cheap and instantaneous to open unless blocked by flow control. As a\nconsequence, the peer won't be notified that a stream has been opened until the stream is\nactually used. Calling [`open_bi()`] then waiting on the [`RecvStream`] without writing\nanything to [`SendStream`] will never succeed.\n\n[`open_bi()`]: crate::Connection::open_bi\n[`SendStream`]: crate::SendStream\n[`RecvStream`]: crate::RecvStream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn open_bi(&self) -> OpenBi<'_> {\n OpenBi {\n conn: &self.0,\n notify: self.0.shared.stream_budget_available[Dir::Bi as usize].notified(),\n }\n }\n```"}], "func_name": "open_bi", "docstring": "Initiate a new outgoing bidirectional stream.\n\nStreams are cheap and instantaneous to open unless blocked by flow control. As a\nconsequence, the peer won't be notified that a stream has been opened until the stream is\nactually used. Calling [`open_bi()`] then waiting on the [`RecvStream`] without writing\nanything to [`SendStream`] will never succeed.\n\n[`open_bi()`]: crate::Connection::open_bi\n[`SendStream`]: crate::SendStream\n[`RecvStream`]: crate::RecvStream", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f3f5e0ce275efd2ac3adf38d5bb9b1023423dc9cb2c2b354c3f1c23605069bf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accept_uni\n\nDocumentation:\nAccept the next incoming uni-directional stream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn accept_uni(&self) -> AcceptUni<'_> {\n AcceptUni {\n conn: &self.0,\n notify: self.0.shared.stream_incoming[Dir::Uni as usize].notified(),\n }\n }\n```"}], "func_name": "accept_uni", "docstring": "Accept the next incoming uni-directional stream", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0661c27df9fe3028a03e89d4c75ee018496eddadf7bb630e44a8137e3d4b41d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accept_bi\n\nDocumentation:\nAccept the next incoming bidirectional stream\n\n**Important Note**: The `Connection` that calls [`open_bi()`] must write to its [`SendStream`]\nbefore the other `Connection` is able to `accept_bi()`. Calling [`open_bi()`] then\nwaiting on the [`RecvStream`] without writing anything to [`SendStream`] will never succeed.\n\n[`accept_bi()`]: crate::Connection::accept_bi\n[`open_bi()`]: crate::Connection::open_bi\n[`SendStream`]: crate::SendStream\n[`RecvStream`]: crate::RecvStream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn accept_bi(&self) -> AcceptBi<'_> {\n AcceptBi {\n conn: &self.0,\n notify: self.0.shared.stream_incoming[Dir::Bi as usize].notified(),\n }\n }\n```"}], "func_name": "accept_bi", "docstring": "Accept the next incoming bidirectional stream\n\n**Important Note**: The `Connection` that calls [`open_bi()`] must write to its [`SendStream`]\nbefore the other `Connection` is able to `accept_bi()`. Calling [`open_bi()`] then\nwaiting on the [`RecvStream`] without writing anything to [`SendStream`] will never succeed.\n\n[`accept_bi()`]: crate::Connection::accept_bi\n[`open_bi()`]: crate::Connection::open_bi\n[`SendStream`]: crate::SendStream\n[`RecvStream`]: crate::RecvStream", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "376a051a18a5311a8221c2d2eb262862fd1c443f60db470a40789ffd086cc797"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: closed\n\nDocumentation:\nWait for the connection to be closed for any reason\n\nDespite the return type's name, closed connections are often not an error condition at the\napplication layer. Cases that might be routine include [`ConnectionError::LocallyClosed`]\nand [`ConnectionError::ApplicationClosed`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn closed(&self) -> ConnectionError {\n {\n let conn = self.0.state.lock(\"closed\");\n if let Some(error) = conn.error.as_ref() {\n return error.clone();\n }\n // Construct the future while the lock is held to ensure we can't miss a wakeup if\n // the `Notify` is signaled immediately after we release the lock. `await` it after\n // the lock guard is out of scope.\n self.0.shared.closed.notified()\n }\n .await;\n self.0\n .state\n .lock(\"closed\")\n .error\n .as_ref()\n .expect(\"closed without an error\")\n .clone()\n }\n```"}], "func_name": "closed", "docstring": "Wait for the connection to be closed for any reason\n\nDespite the return type's name, closed connections are often not an error condition at the\napplication layer. Cases that might be routine include [`ConnectionError::LocallyClosed`]\nand [`ConnectionError::ApplicationClosed`].", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94609e32b412c65fef18a6057140694b8067bc67d15a2a2004115a038eb12394"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: close\n\nDocumentation:\nClose the connection immediately.\n\nPending operations will fail immediately with [`ConnectionError::LocallyClosed`]. No\nmore data is sent to the peer and the peer may drop buffered data upon receiving\nthe CONNECTION_CLOSE frame.\n\n`error_code` and `reason` are not interpreted, and are provided directly to the peer.\n\n`reason` will be truncated to fit in a single packet with overhead; to improve odds that it\nis preserved in full, it should be kept under 1KiB.\n\n# Gracefully closing a connection\n\nOnly the peer last receiving application data can be certain that all data is\ndelivered. The only reliable action it can then take is to close the connection,\npotentially with a custom error code. The delivery of the final CONNECTION_CLOSE\nframe is very likely if both endpoints stay online long enough, and\n[`Endpoint::wait_idle()`] can be used to provide sufficient time. Otherwise, the\nremote peer will time out the connection, provided that the idle timeout is not\ndisabled.\n\nThe sending side can not guarantee all stream data is delivered to the remote\napplication. It only knows the data is delivered to the QUIC stack of the remote\nendpoint. Once the local side sends a CONNECTION_CLOSE frame in response to calling\n[`close()`] the remote endpoint may drop any data it received but is as yet\nundelivered to the application, including data that was acknowledged as received to\nthe local endpoint.\n\n[`ConnectionError::LocallyClosed`]: crate::ConnectionError::LocallyClosed\n[`Endpoint::wait_idle()`]: crate::Endpoint::wait_idle\n[`close()`]: Connection::close\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn close(&self, error_code: VarInt, reason: &[u8]) {\n let conn = &mut *self.0.state.lock(\"close\");\n conn.close(error_code, Bytes::copy_from_slice(reason), &self.0.shared);\n }\n```"}], "func_name": "close", "docstring": "Close the connection immediately.\n\nPending operations will fail immediately with [`ConnectionError::LocallyClosed`]. No\nmore data is sent to the peer and the peer may drop buffered data upon receiving\nthe CONNECTION_CLOSE frame.\n\n`error_code` and `reason` are not interpreted, and are provided directly to the peer.\n\n`reason` will be truncated to fit in a single packet with overhead; to improve odds that it\nis preserved in full, it should be kept under 1KiB.\n\n# Gracefully closing a connection\n\nOnly the peer last receiving application data can be certain that all data is\ndelivered. The only reliable action it can then take is to close the connection,\npotentially with a custom error code. The delivery of the final CONNECTION_CLOSE\nframe is very likely if both endpoints stay online long enough, and\n[`Endpoint::wait_idle()`] can be used to provide sufficient time. Otherwise, the\nremote peer will time out the connection, provided that the idle timeout is not\ndisabled.\n\nThe sending side can not guarantee all stream data is delivered to the remote\napplication. It only knows the data is delivered to the QUIC stack of the remote\nendpoint. Once the local side sends a CONNECTION_CLOSE frame in response to calling\n[`close()`] the remote endpoint may drop any data it received but is as yet\nundelivered to the application, including data that was acknowledged as received to\nthe local endpoint.\n\n[`ConnectionError::LocallyClosed`]: crate::ConnectionError::LocallyClosed\n[`Endpoint::wait_idle()`]: crate::Endpoint::wait_idle\n[`close()`]: Connection::close", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f3373a49f01198ff29837edf8deb3f2f49c30f697163a8cffb6337a6921b1579"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: datagram_send_buffer_space\n\nDocumentation:\nBytes available in the outgoing datagram buffer\n\nWhen greater than zero, calling [`send_datagram()`](Self::send_datagram) with a datagram of\nat most this size is guaranteed not to cause older datagrams to be dropped.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn datagram_send_buffer_space(&self) -> usize {\n self.0\n .state\n .lock(\"datagram_send_buffer_space\")\n .inner\n .datagrams()\n .send_buffer_space()\n }\n```"}], "func_name": "datagram_send_buffer_space", "docstring": "Bytes available in the outgoing datagram buffer\n\nWhen greater than zero, calling [`send_datagram()`](Self::send_datagram) with a datagram of\nat most this size is guaranteed not to cause older datagrams to be dropped.", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d993bc73c25dbaf5174bad01f950ae605f993afae38ccb7d99397a543f1f6818"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: congestion_state\n\nDocumentation:\nCurrent state of the congestion control algorithm, for debugging purposes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn congestion_state(&self) -> Box {\n self.0\n .state\n .lock(\"congestion_state\")\n .inner\n .congestion_state()\n .clone_box()\n }\n```"}], "func_name": "congestion_state", "docstring": "Current state of the congestion control algorithm, for debugging purposes", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8574e7e94251578bb87050606c435627cbad3e294ddd64bc8a24154ef93d31ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handshake_data\n\nDocumentation:\nParameters negotiated during the handshake\n\nGuaranteed to return `Some` on fully established connections or after\n[`Connecting::handshake_data()`] succeeds. See that method's documentations for details on\nthe returned value.\n\n[`Connection::handshake_data()`]: crate::Connecting::handshake_data\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn handshake_data(&self) -> Option> {\n self.0\n .state\n .lock(\"handshake_data\")\n .inner\n .crypto_session()\n .handshake_data()\n }\n```"}], "func_name": "handshake_data", "docstring": "Parameters negotiated during the handshake\n\nGuaranteed to return `Some` on fully established connections or after\n[`Connecting::handshake_data()`] succeeds. See that method's documentations for details on\nthe returned value.\n\n[`Connection::handshake_data()`]: crate::Connecting::handshake_data", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac3dd32f07ba54c0f6e66ba4d1c3f941d09cb275702cd6fa7ce83d04bfe5e5a7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: peer_identity\n\nDocumentation:\nCryptographic identity of the peer\n\nThe dynamic type returned is determined by the configured\n[`Session`](proto::crypto::Session). For the default `rustls` session, the return value can\nbe [`downcast`](Box::downcast) to a Vec<[rustls::pki_types::CertificateDer]>\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn peer_identity(&self) -> Option> {\n self.0\n .state\n .lock(\"peer_identity\")\n .inner\n .crypto_session()\n .peer_identity()\n }\n```"}], "func_name": "peer_identity", "docstring": "Cryptographic identity of the peer\n\nThe dynamic type returned is determined by the configured\n[`Session`](proto::crypto::Session). For the default `rustls` session, the return value can\nbe [`downcast`](Box::downcast) to a Vec<[rustls::pki_types::CertificateDer]>", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c4d9f0b07540e73cc9fe1408f0af9b29bff204ff1d541c79ca43d6c38100de6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: force_key_update\n\nDocumentation:\nUpdate traffic keys spontaneously\n\nThis primarily exists for testing purposes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn force_key_update(&self) {\n self.0\n .state\n .lock(\"force_key_update\")\n .inner\n .force_key_update()\n }\n```"}], "func_name": "force_key_update", "docstring": "Update traffic keys spontaneously\n\nThis primarily exists for testing purposes.", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "03b37703b18731a3d5370283f1be23d477f1ea4ed5b032f89b0aae29dafbe25a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: export_keying_material\n\nDocumentation:\nDerive keying material from this connection's TLS session secrets.\n\nWhen both peers call this method with the same `label` and `context`\narguments and `output` buffers of equal length, they will get the\nsame sequence of bytes in `output`. These bytes are cryptographically\nstrong and pseudorandom, and are suitable for use as keying material.\n\nSee [RFC5705](https://tools.ietf.org/html/rfc5705) for more information.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn export_keying_material(\n &self,\n output: &mut [u8],\n label: &[u8],\n context: &[u8],\n ) -> Result<(), proto::crypto::ExportKeyingMaterialError> {\n self.0\n .state\n .lock(\"export_keying_material\")\n .inner\n .crypto_session()\n .export_keying_material(output, label, context)\n }\n```"}], "func_name": "export_keying_material", "docstring": "Derive keying material from this connection's TLS session secrets.\n\nWhen both peers call this method with the same `label` and `context`\narguments and `output` buffers of equal length, they will get the\nsame sequence of bytes in `output`. These bytes are cryptographically\nstrong and pseudorandom, and are suitable for use as keying material.\n\nSee [RFC5705](https://tools.ietf.org/html/rfc5705) for more information.", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "966211832e1e844d17b00e42e8f7473110425ff114de3985db235e348175d937"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_max_concurrent_uni_streams\n\nDocumentation:\nModify the number of remotely initiated unidirectional streams that may be concurrently open\n\nNo streams may be opened by the peer unless fewer than `count` are already open. Large\n`count`s increase both minimum and worst-case memory consumption.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_max_concurrent_uni_streams(&self, count: VarInt) {\n let mut conn = self.0.state.lock(\"set_max_concurrent_uni_streams\");\n conn.inner.set_max_concurrent_streams(Dir::Uni, count);\n // May need to send MAX_STREAMS to make progress\n conn.wake();\n }\n```"}], "func_name": "set_max_concurrent_uni_streams", "docstring": "Modify the number of remotely initiated unidirectional streams that may be concurrently open\n\nNo streams may be opened by the peer unless fewer than `count` are already open. Large\n`count`s increase both minimum and worst-case memory consumption.", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "36c636624a6661695f40c6cb157b676f6ca87b837c5798cb8eef03278a86e636"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_max_concurrent_bi_streams\n\nDocumentation:\nModify the number of remotely initiated bidirectional streams that may be concurrently open\n\nNo streams may be opened by the peer unless fewer than `count` are already open. Large\n`count`s increase both minimum and worst-case memory consumption.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_max_concurrent_bi_streams(&self, count: VarInt) {\n let mut conn = self.0.state.lock(\"set_max_concurrent_bi_streams\");\n conn.inner.set_max_concurrent_streams(Dir::Bi, count);\n // May need to send MAX_STREAMS to make progress\n conn.wake();\n }\n```"}], "func_name": "set_max_concurrent_bi_streams", "docstring": "Modify the number of remotely initiated bidirectional streams that may be concurrently open\n\nNo streams may be opened by the peer unless fewer than `count` are already open. Large\n`count`s increase both minimum and worst-case memory consumption.", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b6b979ba256de1edfba5b69f037ad85cf9e80a05c99260947fe639071f665ce9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_conn_events\n\nDocumentation:\nIf this returns `Err`, the endpoint is dead, so the driver should exit immediately.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_conn_events(\n &mut self,\n shared: &Shared,\n cx: &mut Context,\n ) -> Result<(), ConnectionError> {\n loop {\n match self.conn_events.poll_recv(cx) {\n Poll::Ready(Some(ConnectionEvent::Rebind(socket))) => {\n self.socket = socket;\n self.io_poller = self.socket.clone().create_io_poller();\n self.inner.local_address_changed();\n }\n Poll::Ready(Some(ConnectionEvent::Proto(event))) => {\n self.inner.handle_event(event);\n }\n Poll::Ready(Some(ConnectionEvent::Close { reason, error_code })) => {\n self.close(error_code, reason, shared);\n }\n Poll::Ready(None) => {\n return Err(ConnectionError::TransportError(proto::TransportError {\n code: proto::TransportErrorCode::INTERNAL_ERROR,\n frame: None,\n reason: \"endpoint driver future was dropped\".to_string(),\n }));\n }\n Poll::Pending => {\n return Ok(());\n }\n }\n }\n }\n```"}], "func_name": "process_conn_events", "docstring": "If this returns `Err`, the endpoint is dead, so the driver should exit immediately.", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "afebb8ac779ad99e1cf8f6e03bdc95947352d4834b84ed7e45ac9a291c3b3ad0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wake\n\nDocumentation:\nWake up a blocked `Driver` task to process I/O\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn wake(&mut self) {\n if let Some(x) = self.driver.take() {\n x.wake();\n }\n }\n```"}], "func_name": "wake", "docstring": "Wake up a blocked `Driver` task to process I/O", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c03b65e6e1ada7ee4b9896f97510bd95950034f833854bb7d8fe23d2766ae0ca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: terminate\n\nDocumentation:\nUsed to wake up all blocked futures when the connection becomes closed for any reason\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn terminate(&mut self, reason: ConnectionError, shared: &Shared) {\n self.error = Some(reason.clone());\n if let Some(x) = self.on_handshake_data.take() {\n let _ = x.send(());\n }\n wake_all(&mut self.blocked_writers);\n wake_all(&mut self.blocked_readers);\n shared.stream_budget_available[Dir::Uni as usize].notify_waiters();\n shared.stream_budget_available[Dir::Bi as usize].notify_waiters();\n shared.stream_incoming[Dir::Uni as usize].notify_waiters();\n shared.stream_incoming[Dir::Bi as usize].notify_waiters();\n shared.datagram_received.notify_waiters();\n shared.datagrams_unblocked.notify_waiters();\n if let Some(x) = self.on_connected.take() {\n let _ = x.send(false);\n }\n wake_all_notify(&mut self.stopped);\n shared.closed.notify_waiters();\n }\n```"}], "func_name": "terminate", "docstring": "Used to wake up all blocked futures when the connection becomes closed for any reason", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "59726f2f16fc09bfc8b800ca85c071efd585e3a4a17b5d8ab8a0e4c7d376f067"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: implicit_close\n\nDocumentation:\nClose for a reason other than the application's explicit request\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn implicit_close(&mut self, shared: &Shared) {\n self.close(0u32.into(), Bytes::new(), shared);\n }\n```"}], "func_name": "implicit_close", "docstring": "Close for a reason other than the application's explicit request", "repo": "quinn-rs/quinn", "path": "quinn/src/connection.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f4b51e249d5a43b0cbc704effc81716a56e98ee599a841b0ee73b7b2a4ab3b34"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_with_abstract_socket\n\nDocumentation:\nConstruct an endpoint with arbitrary configuration and pre-constructed abstract socket\n\nUseful when `socket` has additional state (e.g. sidechannels) attached for which shared\nownership is needed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_with_abstract_socket(\n config: EndpointConfig,\n server_config: Option,\n socket: Arc,\n runtime: Arc,\n ) -> io::Result {\n let addr = socket.local_addr()?;\n let allow_mtud = !socket.may_fragment();\n let rc = EndpointRef::new(\n socket,\n proto::Endpoint::new(\n Arc::new(config),\n server_config.map(Arc::new),\n allow_mtud,\n None,\n ),\n addr.is_ipv6(),\n runtime.clone(),\n );\n let driver = EndpointDriver(rc.clone());\n runtime.spawn(Box::pin(\n async {\n if let Err(e) = driver.await {\n tracing::error!(\"I/O error: {}\", e);\n }\n }\n .instrument(Span::current()),\n ));\n Ok(Self {\n inner: rc,\n default_client_config: None,\n runtime,\n })\n }\n```"}], "func_name": "new_with_abstract_socket", "docstring": "Construct an endpoint with arbitrary configuration and pre-constructed abstract socket\n\nUseful when `socket` has additional state (e.g. sidechannels) attached for which shared\nownership is needed.", "repo": "quinn-rs/quinn", "path": "quinn/src/endpoint.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5e0e120f668b5d2fafd859ab363a34e8e49b23e45cdde6d8790141d6826c0566"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accept\n\nDocumentation:\nGet the next incoming connection attempt from a client\n\nYields [`Incoming`]s, or `None` if the endpoint is [`close`](Self::close)d. [`Incoming`]\ncan be `await`ed to obtain the final [`Connection`](crate::Connection), or used to e.g.\nfilter connection attempts or force address validation, or converted into an intermediate\n`Connecting` future which can be used to e.g. send 0.5-RTT data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn accept(&self) -> Accept<'_> {\n Accept {\n endpoint: self,\n notify: self.inner.shared.incoming.notified(),\n }\n }\n```"}], "func_name": "accept", "docstring": "Get the next incoming connection attempt from a client\n\nYields [`Incoming`]s, or `None` if the endpoint is [`close`](Self::close)d. [`Incoming`]\ncan be `await`ed to obtain the final [`Connection`](crate::Connection), or used to e.g.\nfilter connection attempts or force address validation, or converted into an intermediate\n`Connecting` future which can be used to e.g. send 0.5-RTT data.", "repo": "quinn-rs/quinn", "path": "quinn/src/endpoint.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "205c7cb51a0e2d8efc644b1f072619774fd55f645bc5ccd78bbfea0b943bdb14"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_default_client_config\n\nDocumentation:\nSet the client configuration used by `connect`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_default_client_config(&mut self, config: ClientConfig) {\n self.default_client_config = Some(config);\n }\n```"}], "func_name": "set_default_client_config", "docstring": "Set the client configuration used by `connect`", "repo": "quinn-rs/quinn", "path": "quinn/src/endpoint.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0973f7fa52f9ada83af3a098f3443c710ef9e20c04bf66ad5d948cdc75e7c23f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nConnect to a remote endpoint\n\n`server_name` must be covered by the certificate presented by the server. This prevents a\nconnection from being intercepted by an attacker with a valid certificate for some other\nserver.\n\nMay fail immediately due to configuration errors, or in the future if the connection could\nnot be established.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connect(&self, addr: SocketAddr, server_name: &str) -> Result {\n let config = match &self.default_client_config {\n Some(config) => config.clone(),\n None => return Err(ConnectError::NoDefaultClientConfig),\n };\n\n self.connect_with(config, addr, server_name)\n }\n```"}], "func_name": "connect", "docstring": "Connect to a remote endpoint\n\n`server_name` must be covered by the certificate presented by the server. This prevents a\nconnection from being intercepted by an attacker with a valid certificate for some other\nserver.\n\nMay fail immediately due to configuration errors, or in the future if the connection could\nnot be established.", "repo": "quinn-rs/quinn", "path": "quinn/src/endpoint.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3dc726fb450e224a6a1d8179bccfcc32aa83dd25e2459f93476a9977335ae3d2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect_with\n\nDocumentation:\nConnect to a remote endpoint using a custom configuration.\n\nSee [`connect()`] for details.\n\n[`connect()`]: Endpoint::connect\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connect_with(\n &self,\n config: ClientConfig,\n addr: SocketAddr,\n server_name: &str,\n ) -> Result {\n let mut endpoint = self.inner.state.lock().unwrap();\n if endpoint.driver_lost || endpoint.recv_state.connections.close.is_some() {\n return Err(ConnectError::EndpointStopping);\n }\n if addr.is_ipv6() && !endpoint.ipv6 {\n return Err(ConnectError::InvalidRemoteAddress(addr));\n }\n let addr = if endpoint.ipv6 {\n SocketAddr::V6(ensure_ipv6(addr))\n } else {\n addr\n };\n\n let (ch, conn) = endpoint\n .inner\n .connect(self.runtime.now(), config, addr, server_name)?;\n\n let socket = endpoint.socket.clone();\n endpoint.stats.outgoing_handshakes += 1;\n Ok(endpoint\n .recv_state\n .connections\n .insert(ch, conn, socket, self.runtime.clone()))\n }\n```"}], "func_name": "connect_with", "docstring": "Connect to a remote endpoint using a custom configuration.\n\nSee [`connect()`] for details.\n\n[`connect()`]: Endpoint::connect", "repo": "quinn-rs/quinn", "path": "quinn/src/endpoint.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9679865a7f1192c9430fa70b7f70c3e872bd073dbf51bfbd88fd2402477a35fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rebind_abstract\n\nDocumentation:\nSwitch to a new UDP socket\n\nAllows the endpoint's address to be updated live, affecting all active connections. Incoming\nconnections and connections to servers unreachable from the new address will be lost.\n\nOn error, the old UDP socket is retained.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn rebind_abstract(&self, socket: Arc) -> io::Result<()> {\n let addr = socket.local_addr()?;\n let mut inner = self.inner.state.lock().unwrap();\n inner.prev_socket = Some(mem::replace(&mut inner.socket, socket));\n inner.ipv6 = addr.is_ipv6();\n\n // Update connection socket references\n for sender in inner.recv_state.connections.senders.values() {\n // Ignoring errors from dropped connections\n let _ = sender.send(ConnectionEvent::Rebind(inner.socket.clone()));\n }\n\n Ok(())\n }\n```"}], "func_name": "rebind_abstract", "docstring": "Switch to a new UDP socket\n\nAllows the endpoint's address to be updated live, affecting all active connections. Incoming\nconnections and connections to servers unreachable from the new address will be lost.\n\nOn error, the old UDP socket is retained.", "repo": "quinn-rs/quinn", "path": "quinn/src/endpoint.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa0a34895867f1755f06bb906d5d49545e944f1244397e6c7c898db0e4dfa315"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_server_config\n\nDocumentation:\nReplace the server configuration, affecting new incoming connections only\n\nUseful for e.g. refreshing TLS certificates without disrupting existing connections.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_server_config(&self, server_config: Option) {\n self.inner\n .state\n .lock()\n .unwrap()\n .inner\n .set_server_config(server_config.map(Arc::new))\n }\n```"}], "func_name": "set_server_config", "docstring": "Replace the server configuration, affecting new incoming connections only\n\nUseful for e.g. refreshing TLS certificates without disrupting existing connections.", "repo": "quinn-rs/quinn", "path": "quinn/src/endpoint.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9655754fffd4a85d41d044415d085d9f65b4ddd238ad00065d2532532c1d1300"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: close\n\nDocumentation:\nClose all of this endpoint's connections immediately and cease accepting new connections.\n\nSee [`Connection::close()`] for details.\n\n[`Connection::close()`]: crate::Connection::close\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn close(&self, error_code: VarInt, reason: &[u8]) {\n let reason = Bytes::copy_from_slice(reason);\n let mut endpoint = self.inner.state.lock().unwrap();\n endpoint.recv_state.connections.close = Some((error_code, reason.clone()));\n for sender in endpoint.recv_state.connections.senders.values() {\n // Ignoring errors from dropped connections\n let _ = sender.send(ConnectionEvent::Close {\n error_code,\n reason: reason.clone(),\n });\n }\n self.inner.shared.incoming.notify_waiters();\n }\n```"}], "func_name": "close", "docstring": "Close all of this endpoint's connections immediately and cease accepting new connections.\n\nSee [`Connection::close()`] for details.\n\n[`Connection::close()`]: crate::Connection::close", "repo": "quinn-rs/quinn", "path": "quinn/src/endpoint.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b1348469e0b3cca9aab70e98abdf64d7774fc895df3e0b4900d78edd65ae8362"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait_idle\n\nDocumentation:\nWait for all connections on the endpoint to be cleanly shut down\n\nWaiting for this condition before exiting ensures that a good-faith effort is made to notify\npeers of recent connection closes, whereas exiting immediately could force them to wait out\nthe idle timeout period.\n\nDoes not proactively close existing connections or cause incoming connections to be\nrejected. Consider calling [`close()`] if that is desired.\n\n[`close()`]: Endpoint::close\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn wait_idle(&self) {\n loop {\n {\n let endpoint = &mut *self.inner.state.lock().unwrap();\n if endpoint.recv_state.connections.is_empty() {\n break;\n }\n // Construct future while lock is held to avoid race\n self.inner.shared.idle.notified()\n }\n .await;\n }\n }\n```"}], "func_name": "wait_idle", "docstring": "Wait for all connections on the endpoint to be cleanly shut down\n\nWaiting for this condition before exiting ensures that a good-faith effort is made to notify\npeers of recent connection closes, whereas exiting immediately could force them to wait out\nthe idle timeout period.\n\nDoes not proactively close existing connections or cause incoming connections to be\nrejected. Consider calling [`close()`] if that is desired.\n\n[`close()`]: Endpoint::close", "repo": "quinn-rs/quinn", "path": "quinn/src/endpoint.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "05d271e2897a8fe497e9248a45af0b99b9b01d70f165ce4216271349308ef519"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accept\n\nDocumentation:\nAttempt to accept this incoming connection (an error may still occur)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn accept(mut self) -> Result {\n let state = self.0.take().unwrap();\n state.endpoint.accept(state.inner, None)\n }\n```"}], "func_name": "accept", "docstring": "Attempt to accept this incoming connection (an error may still occur)", "repo": "quinn-rs/quinn", "path": "quinn/src/incoming.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/incoming.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "181b65052858d3a6ddfe5431a0712f5172cd047f9520b4215f8a904e474fea83"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accept_with\n\nDocumentation:\nAccept this incoming connection using a custom configuration\n\nSee [`accept()`][Incoming::accept] for more details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn accept_with(\n mut self,\n server_config: Arc,\n ) -> Result {\n let state = self.0.take().unwrap();\n state.endpoint.accept(state.inner, Some(server_config))\n }\n```"}], "func_name": "accept_with", "docstring": "Accept this incoming connection using a custom configuration\n\nSee [`accept()`][Incoming::accept] for more details.", "repo": "quinn-rs/quinn", "path": "quinn/src/incoming.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/incoming.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3ef7ae71d17b35e34a6a16532c323e5b4ea4e3bd231e6471a5d1646fb177db8b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: retry\n\nDocumentation:\nRespond with a retry packet, requiring the client to retry with address validation\n\nErrors if `may_retry()` is false.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn retry(mut self) -> Result<(), RetryError> {\n let state = self.0.take().unwrap();\n state.endpoint.retry(state.inner).map_err(|e| {\n RetryError(Box::new(Self(Some(State {\n inner: e.into_incoming(),\n endpoint: state.endpoint,\n }))))\n })\n }\n```"}], "func_name": "retry", "docstring": "Respond with a retry packet, requiring the client to retry with address validation\n\nErrors if `may_retry()` is false.", "repo": "quinn-rs/quinn", "path": "quinn/src/incoming.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/incoming.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81bf5bfcafb3b10fa4ee3adb0c7ab459c2691d988507de77c2012610bdc81a93"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ignore\n\nDocumentation:\nIgnore this incoming connection attempt, not sending any packet in response\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ignore(mut self) {\n let state = self.0.take().unwrap();\n state.endpoint.ignore(state.inner);\n }\n```"}], "func_name": "ignore", "docstring": "Ignore this incoming connection attempt, not sending any packet in response", "repo": "quinn-rs/quinn", "path": "quinn/src/incoming.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/incoming.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c392c3ed4ca7cec66b05b813d14c918735c76e71d4c35580ab845ba22873223d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lock\n\nDocumentation:\nAcquires the lock for a certain purpose\n\nThe purpose will be recorded in the list of last lock owners\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn lock(&self, purpose: &'static str) -> MutexGuard {\n // We don't bother dispatching through Runtime::now because they're pure performance\n // diagnostics.\n let now = Instant::now();\n let guard = self.inner.lock().unwrap();\n\n let lock_time = Instant::now();\n let elapsed = lock_time.duration_since(now);\n\n if elapsed > Duration::from_millis(1) {\n warn!(\n \"Locking the connection for {} took {:?}. Last owners: {:?}\",\n purpose, elapsed, guard.last_lock_owner\n );\n }\n\n MutexGuard {\n guard,\n start_time: lock_time,\n purpose,\n }\n }\n```"}], "func_name": "lock", "docstring": "Acquires the lock for a certain purpose\n\nThe purpose will be recorded in the list of last lock owners", "repo": "quinn-rs/quinn", "path": "quinn/src/mutex.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/mutex.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a297fb651a53e3bae8409385eaba41f4b436f0a8c2e8019ea6d7b28a03013e08"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read\n\nDocumentation:\nRead data contiguously from the stream.\n\nYields the number of bytes read into `buf` on success, or `None` if the stream was finished.\n\nThis operation is cancel-safe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn read(&mut self, buf: &mut [u8]) -> Result, ReadError> {\n Read {\n stream: self,\n buf: ReadBuf::new(buf),\n }\n .await\n }\n```"}], "func_name": "read", "docstring": "Read data contiguously from the stream.\n\nYields the number of bytes read into `buf` on success, or `None` if the stream was finished.\n\nThis operation is cancel-safe.", "repo": "quinn-rs/quinn", "path": "quinn/src/recv_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/recv_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "79242c2574fd6504ed3ca01975889ecd4546c915a83f7d83bef92482123561ea"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_exact\n\nDocumentation:\nRead an exact number of bytes contiguously from the stream.\n\nSee [`read()`] for details. This operation is *not* cancel-safe.\n\n[`read()`]: RecvStream::read\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), ReadExactError> {\n ReadExact {\n stream: self,\n buf: ReadBuf::new(buf),\n }\n .await\n }\n```"}], "func_name": "read_exact", "docstring": "Read an exact number of bytes contiguously from the stream.\n\nSee [`read()`] for details. This operation is *not* cancel-safe.\n\n[`read()`]: RecvStream::read", "repo": "quinn-rs/quinn", "path": "quinn/src/recv_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/recv_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f7669a9c8817d2ce930790cd725e091a099baac53c76b5fee0cfc7bf143c8c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: poll_read\n\nDocumentation:\nAttempts to read from the stream into the provided buffer\n\nOn success, returns `Poll::Ready(Ok(num_bytes_read))` and places data into `buf`. If this\nreturns zero bytes read (and `buf` has a non-zero length), that indicates that the remote\nside has [`finish`]ed the stream and the local side has already read all bytes.\n\nIf no data is available for reading, this returns `Poll::Pending` and arranges for the\ncurrent task (via `cx.waker()`) to be notified when the stream becomes readable or is\nclosed.\n\n[`finish`]: crate::SendStream::finish\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn poll_read(\n &mut self,\n cx: &mut Context,\n buf: &mut [u8],\n ) -> Poll> {\n let mut buf = ReadBuf::new(buf);\n ready!(self.poll_read_buf(cx, &mut buf))?;\n Poll::Ready(Ok(buf.filled().len()))\n }\n```"}], "func_name": "poll_read", "docstring": "Attempts to read from the stream into the provided buffer\n\nOn success, returns `Poll::Ready(Ok(num_bytes_read))` and places data into `buf`. If this\nreturns zero bytes read (and `buf` has a non-zero length), that indicates that the remote\nside has [`finish`]ed the stream and the local side has already read all bytes.\n\nIf no data is available for reading, this returns `Poll::Pending` and arranges for the\ncurrent task (via `cx.waker()`) to be notified when the stream becomes readable or is\nclosed.\n\n[`finish`]: crate::SendStream::finish", "repo": "quinn-rs/quinn", "path": "quinn/src/recv_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/recv_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "55b85fcf9df690440c2448b8a65c80cc5bb8f7c06ace1a91eef9b32aac3c15a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: poll_read_buf\n\nDocumentation:\nAttempts to read from the stream into the provided buffer, which may be uninitialized\n\nOn success, returns `Poll::Ready(Ok(()))` and places data into the unfilled portion of\n`buf`. If this does not write any bytes to `buf` (and `buf.remaining()` is non-zero), that\nindicates that the remote side has [`finish`]ed the stream and the local side has already\nread all bytes.\n\nIf no data is available for reading, this returns `Poll::Pending` and arranges for the\ncurrent task (via `cx.waker()`) to be notified when the stream becomes readable or is\nclosed.\n\n[`finish`]: crate::SendStream::finish\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn poll_read_buf(\n &mut self,\n cx: &mut Context,\n buf: &mut ReadBuf<'_>,\n ) -> Poll> {\n if buf.remaining() == 0 {\n return Poll::Ready(Ok(()));\n }\n\n self.poll_read_generic(cx, true, |chunks| {\n let mut read = false;\n loop {\n if buf.remaining() == 0 {\n // We know `read` is `true` because `buf.remaining()` was not 0 before\n return ReadStatus::Readable(());\n }\n\n match chunks.next(buf.remaining()) {\n Ok(Some(chunk)) => {\n buf.put_slice(&chunk.bytes);\n read = true;\n }\n res => return (if read { Some(()) } else { None }, res.err()).into(),\n }\n }\n })\n .map(|res| res.map(|_| ()))\n }\n```"}], "func_name": "poll_read_buf", "docstring": "Attempts to read from the stream into the provided buffer, which may be uninitialized\n\nOn success, returns `Poll::Ready(Ok(()))` and places data into the unfilled portion of\n`buf`. If this does not write any bytes to `buf` (and `buf.remaining()` is non-zero), that\nindicates that the remote side has [`finish`]ed the stream and the local side has already\nread all bytes.\n\nIf no data is available for reading, this returns `Poll::Pending` and arranges for the\ncurrent task (via `cx.waker()`) to be notified when the stream becomes readable or is\nclosed.\n\n[`finish`]: crate::SendStream::finish", "repo": "quinn-rs/quinn", "path": "quinn/src/recv_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/recv_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d7c5240c7e958c87a1505e9156d56ca38f839ad709e9284eb5bb603310dc971f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_chunk\n\nDocumentation:\nRead the next segment of data\n\nYields `None` if the stream was finished. Otherwise, yields a segment of data and its\noffset in the stream. If `ordered` is `true`, the chunk's offset will be immediately after\nthe last data yielded by `read()` or `read_chunk()`. If `ordered` is `false`, segments may\nbe received in any order, and the `Chunk`'s `offset` field can be used to determine\nordering in the caller. Unordered reads are less prone to head-of-line blocking within a\nstream, but require the application to manage reassembling the original data.\n\nSlightly more efficient than `read` due to not copying. Chunk boundaries do not correspond\nto peer writes, and hence cannot be used as framing.\n\nThis operation is cancel-safe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn read_chunk(\n &mut self,\n max_length: usize,\n ordered: bool,\n ) -> Result, ReadError> {\n ReadChunk {\n stream: self,\n max_length,\n ordered,\n }\n .await\n }\n```"}], "func_name": "read_chunk", "docstring": "Read the next segment of data\n\nYields `None` if the stream was finished. Otherwise, yields a segment of data and its\noffset in the stream. If `ordered` is `true`, the chunk's offset will be immediately after\nthe last data yielded by `read()` or `read_chunk()`. If `ordered` is `false`, segments may\nbe received in any order, and the `Chunk`'s `offset` field can be used to determine\nordering in the caller. Unordered reads are less prone to head-of-line blocking within a\nstream, but require the application to manage reassembling the original data.\n\nSlightly more efficient than `read` due to not copying. Chunk boundaries do not correspond\nto peer writes, and hence cannot be used as framing.\n\nThis operation is cancel-safe.", "repo": "quinn-rs/quinn", "path": "quinn/src/recv_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/recv_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f43df182c555a12dfe3991a4940082828366deeb57d016847d6b8a028fab2f79"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: poll_read_chunk\n\nDocumentation:\nAttempts to read a chunk from the stream.\n\nOn success, returns `Poll::Ready(Ok(Some(chunk)))`. If `Poll::Ready(Ok(None))`\nis returned, it implies that EOF has been reached.\n\nIf no data is available for reading, the method returns `Poll::Pending`\nand arranges for the current task (via cx.waker()) to receive a notification\nwhen the stream becomes readable or is closed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn poll_read_chunk(\n &mut self,\n cx: &mut Context,\n max_length: usize,\n ordered: bool,\n ) -> Poll, ReadError>> {\n self.poll_read_generic(cx, ordered, |chunks| match chunks.next(max_length) {\n Ok(Some(chunk)) => ReadStatus::Readable(chunk),\n res => (None, res.err()).into(),\n })\n }\n```"}], "func_name": "poll_read_chunk", "docstring": "Attempts to read a chunk from the stream.\n\nOn success, returns `Poll::Ready(Ok(Some(chunk)))`. If `Poll::Ready(Ok(None))`\nis returned, it implies that EOF has been reached.\n\nIf no data is available for reading, the method returns `Poll::Pending`\nand arranges for the current task (via cx.waker()) to receive a notification\nwhen the stream becomes readable or is closed.", "repo": "quinn-rs/quinn", "path": "quinn/src/recv_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/recv_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f1ea0e34b4d6a20209668d8284ac68d83ff8f58ae1723dce69f82d320bd41658"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_chunks\n\nDocumentation:\nRead the next segments of data\n\nFills `bufs` with the segments of data beginning immediately after the\nlast data yielded by `read` or `read_chunk`, or `None` if the stream was\nfinished.\n\nSlightly more efficient than `read` due to not copying. Chunk boundaries\ndo not correspond to peer writes, and hence cannot be used as framing.\n\nThis operation is cancel-safe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn read_chunks(&mut self, bufs: &mut [Bytes]) -> Result, ReadError> {\n ReadChunks { stream: self, bufs }.await\n }\n```"}], "func_name": "read_chunks", "docstring": "Read the next segments of data\n\nFills `bufs` with the segments of data beginning immediately after the\nlast data yielded by `read` or `read_chunk`, or `None` if the stream was\nfinished.\n\nSlightly more efficient than `read` due to not copying. Chunk boundaries\ndo not correspond to peer writes, and hence cannot be used as framing.\n\nThis operation is cancel-safe.", "repo": "quinn-rs/quinn", "path": "quinn/src/recv_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/recv_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3db6439736e41b118c885cd9b1d3e6c04bf69c42b680a36dde225f46f8bc3334"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: received_reset\n\nDocumentation:\nCompletes when the stream has been reset by the peer or otherwise closed\n\nYields `Some` with the reset error code when the stream is reset by the peer. Yields `None`\nwhen the stream was previously [`stop()`](Self::stop)ed, or when the stream was\n[`finish()`](crate::SendStream::finish)ed by the peer and all data has been received, after\nwhich it is no longer meaningful for the stream to be reset.\n\nThis operation is cancel-safe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn received_reset(&mut self) -> Result, ResetError> {\n poll_fn(|cx| {\n let mut conn = self.conn.state.lock(\"RecvStream::reset\");\n if self.is_0rtt && conn.check_0rtt().is_err() {\n return Poll::Ready(Err(ResetError::ZeroRttRejected));\n }\n\n if let Some(code) = self.reset {\n return Poll::Ready(Ok(Some(code)));\n }\n\n match conn.inner.recv_stream(self.stream).received_reset() {\n Err(_) => Poll::Ready(Ok(None)),\n Ok(Some(error_code)) => {\n // Stream state has just now been freed, so the connection may need to issue new\n // stream ID flow control credit\n conn.wake();\n Poll::Ready(Ok(Some(error_code)))\n }\n Ok(None) => {\n if let Some(e) = &conn.error {\n return Poll::Ready(Err(e.clone().into()));\n }\n // Resets always notify readers, since a reset is an immediate read error. We\n // could introduce a dedicated channel to reduce the risk of spurious wakeups,\n // but that increased complexity is probably not justified, as an application\n // that is expecting a reset is not likely to receive large amounts of data.\n conn.blocked_readers.insert(self.stream, cx.waker().clone());\n Poll::Pending\n }\n }\n })\n .await\n }\n```"}], "func_name": "received_reset", "docstring": "Completes when the stream has been reset by the peer or otherwise closed\n\nYields `Some` with the reset error code when the stream is reset by the peer. Yields `None`\nwhen the stream was previously [`stop()`](Self::stop)ed, or when the stream was\n[`finish()`](crate::SendStream::finish)ed by the peer and all data has been received, after\nwhich it is no longer meaningful for the stream to be reset.\n\nThis operation is cancel-safe.", "repo": "quinn-rs/quinn", "path": "quinn/src/recv_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/recv_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9864fce7980c31625a605b2e32bb8f758df627adde44e939a69e289ad76420dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: poll_read_generic\n\nDocumentation:\nHandle common logic related to reading out of a receive stream\n\nThis takes an `FnMut` closure that takes care of the actual reading process, matching\nthe detailed read semantics for the calling function with a particular return type.\nThe closure can read from the passed `&mut Chunks` and has to return the status after\nreading: the amount of data read, and the status after the final read call.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn poll_read_generic(\n &mut self,\n cx: &mut Context,\n ordered: bool,\n mut read_fn: T,\n ) -> Poll, ReadError>>\n where\n T: FnMut(&mut Chunks) -> ReadStatus,\n {\n use proto::ReadError::*;\n if self.all_data_read {\n return Poll::Ready(Ok(None));\n }\n\n let mut conn = self.conn.state.lock(\"RecvStream::poll_read\");\n if self.is_0rtt {\n conn.check_0rtt().map_err(|()| ReadError::ZeroRttRejected)?;\n }\n\n // If we stored an error during a previous call, return it now. This can happen if a\n // `read_fn` both wants to return data and also returns an error in its final stream status.\n let status = match self.reset {\n Some(code) => ReadStatus::Failed(None, Reset(code)),\n None => {\n let mut recv = conn.inner.recv_stream(self.stream);\n let mut chunks = recv.read(ordered)?;\n let status = read_fn(&mut chunks);\n if chunks.finalize().should_transmit() {\n conn.wake();\n }\n status\n }\n };\n\n match status {\n ReadStatus::Readable(read) => Poll::Ready(Ok(Some(read))),\n ReadStatus::Finished(read) => {\n self.all_data_read = true;\n Poll::Ready(Ok(read))\n }\n ReadStatus::Failed(read, Blocked) => match read {\n Some(val) => Poll::Ready(Ok(Some(val))),\n None => {\n if let Some(ref x) = conn.error {\n return Poll::Ready(Err(ReadError::ConnectionLost(x.clone())));\n }\n conn.blocked_readers.insert(self.stream, cx.waker().clone());\n Poll::Pending\n }\n },\n ReadStatus::Failed(read, Reset(error_code)) => match read {\n None => {\n self.all_data_read = true;\n self.reset = Some(error_code);\n Poll::Ready(Err(ReadError::Reset(error_code)))\n }\n done => {\n self.reset = Some(error_code);\n Poll::Ready(Ok(done))\n }\n },\n }\n }\n```"}], "func_name": "poll_read_generic", "docstring": "Handle common logic related to reading out of a receive stream\n\nThis takes an `FnMut` closure that takes care of the actual reading process, matching\nthe detailed read semantics for the calling function with a particular return type.\nThe closure can read from the passed `&mut Chunks` and has to return the status after\nreading: the amount of data read, and the status after the final read call.", "repo": "quinn-rs/quinn", "path": "quinn/src/recv_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/recv_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "791611996718dad0ac0ecfdb997fdc89bd7a5f7e07d2e89e939b3d5296f57ce1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write\n\nDocumentation:\nWrite bytes to the stream\n\nYields the number of bytes written on success. Congestion and flow control may cause this to\nbe shorter than `buf.len()`, indicating that only a prefix of `buf` was written.\n\nThis operation is cancel-safe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn write(&mut self, buf: &[u8]) -> Result {\n poll_fn(|cx| self.execute_poll(cx, |s| s.write(buf))).await\n }\n```"}], "func_name": "write", "docstring": "Write bytes to the stream\n\nYields the number of bytes written on success. Congestion and flow control may cause this to\nbe shorter than `buf.len()`, indicating that only a prefix of `buf` was written.\n\nThis operation is cancel-safe.", "repo": "quinn-rs/quinn", "path": "quinn/src/send_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/send_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f277b233419a575277ff8775faa74de30bc61c9142fe2c363f6a65af4b80825"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_all\n\nDocumentation:\nConvenience method to write an entire buffer to the stream\n\nThis operation is *not* cancel-safe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn write_all(&mut self, mut buf: &[u8]) -> Result<(), WriteError> {\n while !buf.is_empty() {\n let written = self.write(buf).await?;\n buf = &buf[written..];\n }\n Ok(())\n }\n```"}], "func_name": "write_all", "docstring": "Convenience method to write an entire buffer to the stream\n\nThis operation is *not* cancel-safe.", "repo": "quinn-rs/quinn", "path": "quinn/src/send_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/send_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d9420346cda642a51484e210f0bed3b67f908c80590c7d3cf027da699b136447"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_chunks\n\nDocumentation:\nWrite chunks to the stream\n\nYields the number of bytes and chunks written on success.\nCongestion and flow control may cause this to be shorter than `buf.len()`,\nindicating that only a prefix of `bufs` was written\n\nThis operation is cancel-safe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn write_chunks(&mut self, bufs: &mut [Bytes]) -> Result {\n poll_fn(|cx| self.execute_poll(cx, |s| s.write_chunks(bufs))).await\n }\n```"}], "func_name": "write_chunks", "docstring": "Write chunks to the stream\n\nYields the number of bytes and chunks written on success.\nCongestion and flow control may cause this to be shorter than `buf.len()`,\nindicating that only a prefix of `bufs` was written\n\nThis operation is cancel-safe.", "repo": "quinn-rs/quinn", "path": "quinn/src/send_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/send_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "191965f92f658cf7edb63f1c5fba6959aac811cf711913c0027e7d4946bdbf0b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_chunk\n\nDocumentation:\nConvenience method to write a single chunk in its entirety to the stream\n\nThis operation is *not* cancel-safe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn write_chunk(&mut self, buf: Bytes) -> Result<(), WriteError> {\n self.write_all_chunks(&mut [buf]).await?;\n Ok(())\n }\n```"}], "func_name": "write_chunk", "docstring": "Convenience method to write a single chunk in its entirety to the stream\n\nThis operation is *not* cancel-safe.", "repo": "quinn-rs/quinn", "path": "quinn/src/send_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/send_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b042bd4ae3c66446ec6344aaad512c063bdae5aa6835b66b370a61f461e83198"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_all_chunks\n\nDocumentation:\nConvenience method to write an entire list of chunks to the stream\n\nThis operation is *not* cancel-safe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn write_all_chunks(&mut self, mut bufs: &mut [Bytes]) -> Result<(), WriteError> {\n while !bufs.is_empty() {\n let written = self.write_chunks(bufs).await?;\n bufs = &mut bufs[written.chunks..];\n }\n Ok(())\n }\n```"}], "func_name": "write_all_chunks", "docstring": "Convenience method to write an entire list of chunks to the stream\n\nThis operation is *not* cancel-safe.", "repo": "quinn-rs/quinn", "path": "quinn/src/send_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/send_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "97858bf6dee02ad34aa80c6443cad361c22f5ce55911fbecda7ac13d34c66a70"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish\n\nDocumentation:\nNotify the peer that no more data will ever be written to this stream\n\nIt is an error to write to a [`SendStream`] after `finish()`ing it. [`reset()`](Self::reset)\nmay still be called after `finish` to abandon transmission of any stream data that might\nstill be buffered.\n\nTo wait for the peer to receive all buffered stream data, see [`stopped()`](Self::stopped).\n\nMay fail if [`finish()`](Self::finish) or [`reset()`](Self::reset) was previously\ncalled. This error is harmless and serves only to indicate that the caller may have\nincorrect assumptions about the stream's state.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn finish(&mut self) -> Result<(), ClosedStream> {\n let mut conn = self.conn.state.lock(\"finish\");\n match conn.inner.send_stream(self.stream).finish() {\n Ok(()) => {\n conn.wake();\n Ok(())\n }\n Err(FinishError::ClosedStream) => Err(ClosedStream::default()),\n // Harmless. If the application needs to know about stopped streams at this point, it\n // should call `stopped`.\n Err(FinishError::Stopped(_)) => Ok(()),\n }\n }\n```"}], "func_name": "finish", "docstring": "Notify the peer that no more data will ever be written to this stream\n\nIt is an error to write to a [`SendStream`] after `finish()`ing it. [`reset()`](Self::reset)\nmay still be called after `finish` to abandon transmission of any stream data that might\nstill be buffered.\n\nTo wait for the peer to receive all buffered stream data, see [`stopped()`](Self::stopped).\n\nMay fail if [`finish()`](Self::finish) or [`reset()`](Self::reset) was previously\ncalled. This error is harmless and serves only to indicate that the caller may have\nincorrect assumptions about the stream's state.", "repo": "quinn-rs/quinn", "path": "quinn/src/send_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/send_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f2b516c404e5f927b8fca71aae94b2b4727154b2733c8dbcce8925139f62e92"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: priority\n\nDocumentation:\nGet the priority of the send stream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn priority(&self) -> Result {\n let mut conn = self.conn.state.lock(\"SendStream::priority\");\n conn.inner.send_stream(self.stream).priority()\n }\n```"}], "func_name": "priority", "docstring": "Get the priority of the send stream", "repo": "quinn-rs/quinn", "path": "quinn/src/send_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/send_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0f7c86a0f5435290118b38ccf946f6e951d341655ef841dfe9a19ad9ae949ac5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stopped\n\nDocumentation:\nCompletes when the peer stops the stream or reads the stream to completion\n\nYields `Some` with the stop error code if the peer stops the stream. Yields `None` if the\nlocal side [`finish()`](Self::finish)es the stream and then the peer acknowledges receipt\nof all stream data (although not necessarily the processing of it), after which the peer\nclosing the stream is no longer meaningful.\n\nFor a variety of reasons, the peer may not send acknowledgements immediately upon receiving\ndata. As such, relying on `stopped` to know when the peer has read a stream to completion\nmay introduce more latency than using an application-level response of some sort.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stopped(\n &self,\n ) -> impl Future, StoppedError>> + Send + Sync + 'static {\n let conn = self.conn.clone();\n let stream = self.stream;\n let is_0rtt = self.is_0rtt;\n async move {\n loop {\n // The `Notify::notified` future needs to be created while the lock is being held,\n // otherwise a wakeup could be missed if triggered inbetween releasing the lock\n // and creating the future.\n // The lock may only be held in a block without `await`s, otherwise the future\n // becomes `!Send`. `Notify::notified` is lifetime-bound to `Notify`, therefore\n // we need to declare `notify` outside of the block, and initialize it inside.\n let notify;\n {\n let mut conn = conn.state.lock(\"SendStream::stopped\");\n if let Some(output) = send_stream_stopped(&mut conn, stream, is_0rtt) {\n return output;\n }\n\n notify = conn.stopped.entry(stream).or_default().clone();\n notify.notified()\n }\n .await\n }\n }\n }\n```"}], "func_name": "stopped", "docstring": "Completes when the peer stops the stream or reads the stream to completion\n\nYields `Some` with the stop error code if the peer stops the stream. Yields `None` if the\nlocal side [`finish()`](Self::finish)es the stream and then the peer acknowledges receipt\nof all stream data (although not necessarily the processing of it), after which the peer\nclosing the stream is no longer meaningful.\n\nFor a variety of reasons, the peer may not send acknowledgements immediately upon receiving\ndata. As such, relying on `stopped` to know when the peer has read a stream to completion\nmay introduce more latency than using an application-level response of some sort.", "repo": "quinn-rs/quinn", "path": "quinn/src/send_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/send_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a34b9d88a11fd4b34f6140d195f3611aae89c3b5e42bbd51de0550538d66b1f8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: poll_write\n\nDocumentation:\nAttempt to write bytes from buf into the stream.\n\nOn success, returns Poll::Ready(Ok(num_bytes_written)).\n\nIf the stream is not ready for writing, the method returns Poll::Pending and arranges\nfor the current task (via cx.waker().wake_by_ref()) to receive a notification when the\nstream becomes writable or is closed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn poll_write(\n self: Pin<&mut Self>,\n cx: &mut Context,\n buf: &[u8],\n ) -> Poll> {\n pin!(self.get_mut().write(buf)).as_mut().poll(cx)\n }\n```"}], "func_name": "poll_write", "docstring": "Attempt to write bytes from buf into the stream.\n\nOn success, returns Poll::Ready(Ok(num_bytes_written)).\n\nIf the stream is not ready for writing, the method returns Poll::Pending and arranges\nfor the current task (via cx.waker().wake_by_ref()) to receive a notification when the\nstream becomes writable or is closed.", "repo": "quinn-rs/quinn", "path": "quinn/src/send_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/send_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "52d87993eca67e2ccaa3bc944ae75e8b7a076d4158777a66a1cf0de184a690a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_stream_stopped\n\nDocumentation:\nCheck if a send stream is stopped.\n\nReturns `Some` if the stream is stopped or the connection is closed.\nReturns `None` if the stream is not stopped.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn send_stream_stopped(\n conn: &mut State,\n stream: StreamId,\n is_0rtt: bool,\n) -> Option, StoppedError>> {\n if is_0rtt && conn.check_0rtt().is_err() {\n return Some(Err(StoppedError::ZeroRttRejected));\n }\n match conn.inner.send_stream(stream).stopped() {\n Err(ClosedStream { .. }) => Some(Ok(None)),\n Ok(Some(error_code)) => Some(Ok(Some(error_code))),\n Ok(None) => conn.error.clone().map(|error| Err(error.into())),\n }\n}\n```"}], "func_name": "send_stream_stopped", "docstring": "Check if a send stream is stopped.\n\nReturns `Some` if the stream is stopped or the connection is closed.\nReturns `None` if the stream is not stopped.", "repo": "quinn-rs/quinn", "path": "quinn/src/send_stream.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/send_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a3bf0552b5ce80a5371801d1728703245c284b0468fd441c1bad0a06927e96d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: allow_work\n\nDocumentation:\nReturns whether more work can be performed inside the `desired_cycle_time`\n\nRequires that previous work was tracked using `record_work`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn allow_work(&mut self, now: impl Fn() -> Instant) -> bool {\n match self.mode {\n Mode::Measure => (now() - self.start_time.unwrap()) < self.desired_cycle_time,\n Mode::HistoricData => self.completed < self.allowed,\n }\n }\n```"}], "func_name": "allow_work", "docstring": "Returns whether more work can be performed inside the `desired_cycle_time`\n\nRequires that previous work was tracked using `record_work`.", "repo": "quinn-rs/quinn", "path": "quinn/src/work_limiter.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/work_limiter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf1f224e5903a5dd9716ba82238e5b77371bbc433437f283adecdf24481b7c8d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: record_work\n\nDocumentation:\nRecords that `work` additional work items have been completed inside the cycle\n\nMust be called between `start_cycle` and `finish_cycle`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn record_work(&mut self, work: usize) {\n self.completed += work;\n }\n```"}], "func_name": "record_work", "docstring": "Records that `work` additional work items have been completed inside the cycle\n\nMust be called between `start_cycle` and `finish_cycle`.", "repo": "quinn-rs/quinn", "path": "quinn/src/work_limiter.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/src/work_limiter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2936b9ce2e29cb8746a315760490e1c5915ed744e5a5ccc3afe49a5c5e1a6b57"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: configure_connector\n\nDocumentation:\nBuilds client configuration. Trusts given node certificate.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn configure_connector(node_cert: CertificateDer<'static>) -> quinn::ClientConfig {\n let mut roots = rustls::RootCertStore::empty();\n roots.add(node_cert).unwrap();\n\n let mut transport_config = TransportConfig::default();\n transport_config.max_idle_timeout(Some(Duration::from_secs(20).try_into().unwrap()));\n\n let mut peer_cfg = quinn::ClientConfig::with_root_certificates(Arc::new(roots)).unwrap();\n peer_cfg.transport_config(Arc::new(transport_config));\n peer_cfg\n}\n```"}], "func_name": "configure_connector", "docstring": "Builds client configuration. Trusts given node certificate.", "repo": "quinn-rs/quinn", "path": "quinn/tests/many_connections.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/tests/many_connections.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8bfb14d25e8ca208e1e58fee4ed99504394de12ec508c4222ab23600f5a52b92"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: configure_listener\n\nDocumentation:\nBuilds listener configuration along with its certificate.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn configure_listener() -> (quinn::ServerConfig, CertificateDer<'static>) {\n let (our_cert, our_priv_key) = gen_cert();\n let mut our_cfg =\n quinn::ServerConfig::with_single_cert(vec![our_cert.clone()], our_priv_key.into()).unwrap();\n\n let transport_config = Arc::get_mut(&mut our_cfg.transport).unwrap();\n transport_config.max_idle_timeout(Some(Duration::from_secs(20).try_into().unwrap()));\n\n (our_cfg, our_cert)\n}\n```"}], "func_name": "configure_listener", "docstring": "Builds listener configuration along with its certificate.", "repo": "quinn-rs/quinn", "path": "quinn/tests/many_connections.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/tests/many_connections.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5155d95822e4b739f5b76d36bfcc964ed93f85fd798d35ebd2435f7bf8b51a6e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: random_data_with_hash\n\nDocumentation:\nConstructs a buffer with random bytes of given size prefixed with a hash of this data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn random_data_with_hash(size: usize, crc: &Crc) -> Vec {\n let mut data = random_vec(size + 4);\n let hash = crc.checksum(&data[4..]);\n // write hash in big endian\n data[0] = (hash >> 24) as u8;\n data[1] = ((hash >> 16) & 0xff) as u8;\n data[2] = ((hash >> 8) & 0xff) as u8;\n data[3] = (hash & 0xff) as u8;\n data\n}\n```"}], "func_name": "random_data_with_hash", "docstring": "Constructs a buffer with random bytes of given size prefixed with a hash of this data.", "repo": "quinn-rs/quinn", "path": "quinn/tests/many_connections.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/tests/many_connections.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d7a49da98ba4b8f56b6fb20c9399b25fd9bdc3ea757d519d948dd32c2d9f634a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: hash_correct\n\nDocumentation:\nChecks if given data buffer hash is correct. Hash itself is a 4 byte prefix in the data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn hash_correct(data: &[u8], crc: &Crc) -> bool {\n let encoded_hash = ((data[0] as u32) << 24)\n | ((data[1] as u32) << 16)\n | ((data[2] as u32) << 8)\n | data[3] as u32;\n let actual_hash = crc.checksum(&data[4..]);\n encoded_hash == actual_hash\n}\n```"}], "func_name": "hash_correct", "docstring": "Checks if given data buffer hash is correct. Hash itself is a 4 byte prefix in the data.", "repo": "quinn-rs/quinn", "path": "quinn/tests/many_connections.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn/tests/many_connections.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "595f3b56aad84d9ffa26fee3d220a89d03658f8a5083c932eb8cf27a42e39264"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_expected_items\n\nDocumentation:\nConstruct with an approximate maximum memory usage and expected number of validation token\nusages per expiration period\n\nCalculates the optimal bloom filter k number automatically.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_expected_items(max_bytes: usize, expected_hits: u64) -> Self {\n Self::new(max_bytes, optimal_k_num(max_bytes, expected_hits))\n }\n```"}], "func_name": "new_expected_items", "docstring": "Construct with an approximate maximum memory usage and expected number of validation token\nusages per expiration period\n\nCalculates the optimal bloom filter k number automatically.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/bloom_token_log.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/bloom_token_log.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "603e40bd4a2d85033e7a2ebb445e9a72c3acc87b52a02268e72727f899a4a2ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConstruct with an approximate maximum memory usage and a [bloom filter k number][bloom]\n\n[bloom]: https://en.wikipedia.org/wiki/Bloom_filter\n\nIf choosing a custom k number, note that `BloomTokenLog` always maintains two filters\nbetween them and divides the allocation budget of `max_bytes` evenly between them. As such,\neach bloom filter will contain `max_bytes * 4` bits.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(max_bytes: usize, k_num: u32) -> Self {\n Self(Mutex::new(State {\n config: FilterConfig {\n filter_max_bytes: max_bytes / 2,\n k_num,\n },\n period_1_start: UNIX_EPOCH,\n filter_1: Filter::default(),\n filter_2: Filter::default(),\n }))\n }\n```"}], "func_name": "new", "docstring": "Construct with an approximate maximum memory usage and a [bloom filter k number][bloom]\n\n[bloom]: https://en.wikipedia.org/wiki/Bloom_filter\n\nIf choosing a custom k number, note that `BloomTokenLog` always maintains two filters\nbetween them and divides the allocation budget of `max_bytes` evenly between them. As such,\neach bloom filter will contain `max_bytes * 4` bits.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/bloom_token_log.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/bloom_token_log.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3180cf5ff045dac949729232dd8d76933b2e2a575be261c46476318bbccd5875"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nInitialize Random CID generator with a fixed CID length\n\nThe given length must be less than or equal to MAX_CID_SIZE.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(cid_len: usize) -> Self {\n debug_assert!(cid_len <= MAX_CID_SIZE);\n Self {\n cid_len,\n ..Self::default()\n }\n }\n```"}], "func_name": "new", "docstring": "Initialize Random CID generator with a fixed CID length\n\nThe given length must be less than or equal to MAX_CID_SIZE.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/cid_generator.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/cid_generator.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb928e223d560e85e13a0d4546e0dded4c689f22b3c598d625c62a92e352d8b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_lifetime\n\nDocumentation:\nSet the lifetime of CIDs created by this generator\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_lifetime(&mut self, d: Duration) -> &mut Self {\n self.lifetime = Some(d);\n self\n }\n```"}], "func_name": "set_lifetime", "docstring": "Set the lifetime of CIDs created by this generator", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/cid_generator.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/cid_generator.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6b8599b42f672480465d9aaebd3ef669234aeb53afc8fcb141eefe07a85e8e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_key\n\nDocumentation:\nCreate a generator with a specific key\n\nAllows [`validate`](ConnectionIdGenerator::validate) to recognize a consistent set of\nconnection IDs across restarts\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_key(key: u64) -> Self {\n Self {\n key,\n lifetime: None,\n }\n }\n```"}], "func_name": "from_key", "docstring": "Create a generator with a specific key\n\nAllows [`validate`](ConnectionIdGenerator::validate) to recognize a consistent set of\nconnection IDs across restarts", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/cid_generator.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/cid_generator.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca03a14efd2794872e9323203e2fd5722117aadb99018cd492e6ad68667a7cfe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nHandle a `NEW_CONNECTION_ID` frame\n\nReturns a non-empty range of retired sequence numbers and the reset token of the new active\nCID iff any CIDs were retired.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn insert(\n &mut self,\n cid: NewConnectionId,\n ) -> Result, ResetToken)>, InsertError> {\n // Position of new CID wrt. the current active CID\n let index = match cid.sequence.checked_sub(self.offset) {\n None => return Err(InsertError::Retired),\n Some(x) => x,\n };\n\n let retired_count = cid.retire_prior_to.saturating_sub(self.offset);\n if index >= Self::LEN as u64 + retired_count {\n return Err(InsertError::ExceedsLimit);\n }\n\n // Discard retired CIDs, if any\n for i in 0..(retired_count.min(Self::LEN as u64) as usize) {\n self.buffer[(self.cursor + i) % Self::LEN] = None;\n }\n\n // Record the new CID\n let index = ((self.cursor as u64 + index) % Self::LEN as u64) as usize;\n self.buffer[index] = Some((cid.id, Some(cid.reset_token)));\n\n if retired_count == 0 {\n return Ok(None);\n }\n\n // The active CID was retired. Find the first known CID with sequence number of at least\n // retire_prior_to, and inform the caller that all prior CIDs have been retired, and of\n // the new CID's reset token.\n self.cursor = ((self.cursor as u64 + retired_count) % Self::LEN as u64) as usize;\n let (i, (_, token)) = self\n .iter()\n .next()\n .expect(\"it is impossible to retire a CID without supplying a new one\");\n self.cursor = (self.cursor + i) % Self::LEN;\n let orig_offset = self.offset;\n self.offset = cid.retire_prior_to + i as u64;\n // We don't immediately retire CIDs in the range (orig_offset +\n // Self::LEN)..self.offset. These are CIDs that we haven't yet received from a\n // NEW_CONNECTION_ID frame, since having previously received them would violate the\n // connection ID limit we specified based on Self::LEN. If we do receive a such a frame\n // in the future, e.g. due to reordering, we'll retire it then. This ensures we can't be\n // made to buffer an arbitrarily large number of RETIRE_CONNECTION_ID frames.\n Ok(Some((\n orig_offset..self.offset.min(orig_offset + Self::LEN as u64),\n token.expect(\"non-initial CID missing reset token\"),\n )))\n }\n```"}], "func_name": "insert", "docstring": "Handle a `NEW_CONNECTION_ID` frame\n\nReturns a non-empty range of retired sequence numbers and the reset token of the new active\nCID iff any CIDs were retired.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/cid_queue.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/cid_queue.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e4d87531aebd719884762a2cc1bc9fab01bb50189d9364e0d69a06bde2da79f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next\n\nDocumentation:\nSwitch to next active CID if possible, return\n1) the corresponding ResetToken and 2) a non-empty range preceding it to retire\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn next(&mut self) -> Option<(ResetToken, Range)> {\n let (i, cid_data) = self.iter().nth(1)?;\n self.buffer[self.cursor] = None;\n\n let orig_offset = self.offset;\n self.offset += i as u64;\n self.cursor = (self.cursor + i) % Self::LEN;\n Some((cid_data.1.unwrap(), orig_offset..self.offset))\n }\n```"}], "func_name": "next", "docstring": "Switch to next active CID if possible, return\n1) the corresponding ResetToken and 2) a non-empty range preceding it to retire", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/cid_queue.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/cid_queue.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2d81ad72a7602210c97095601bc81e1c616796553af87240de89ffb628ccfd8c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: iter\n\nDocumentation:\nIterate CIDs in CidQueue that are not `None`, including the active CID\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn iter(&self) -> impl Iterator + '_ {\n (0..Self::LEN).filter_map(move |step| {\n let index = (self.cursor + step) % Self::LEN;\n self.buffer[index].map(|cid_data| (step, cid_data))\n })\n }\n```"}], "func_name": "iter", "docstring": "Iterate CIDs in CidQueue that are not `None`, including the active CID", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/cid_queue.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/cid_queue.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2336bcc98c953a0714d45d4829277de88659f9f75f2be264873129726074a91f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: eq\n\nDocumentation:\nCompares byte strings in constant time.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn eq(a: &[u8], b: &[u8]) -> bool {\n a.len() == b.len() && constant_time_ne(a, b) == 0\n}\n```"}], "func_name": "eq", "docstring": "Compares byte strings in constant time.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/constant_time.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/constant_time.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ed1cdbd1ce6980a14e0fb0e103cc0640bcfe18cd33da4fd2b476d6cae1b62429"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new endpoint\n\n`allow_mtud` enables path MTU detection when requested by `Connection` configuration for\nbetter performance. This requires that outgoing packets are never fragmented, which can be\nachieved via e.g. the `IPV6_DONTFRAG` socket option.\n\nIf `rng_seed` is provided, it will be used to initialize the endpoint's rng (having priority\nover the rng seed configured in [`EndpointConfig`]). Note that the `rng_seed` parameter will\nbe removed in a future release, so prefer setting it to `None` and configuring rng seeds\nusing [`EndpointConfig::rng_seed`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n config: Arc,\n server_config: Option>,\n allow_mtud: bool,\n rng_seed: Option<[u8; 32]>,\n ) -> Self {\n let rng_seed = rng_seed.or(config.rng_seed);\n Self {\n rng: rng_seed.map_or(StdRng::from_os_rng(), StdRng::from_seed),\n index: ConnectionIndex::default(),\n connections: Slab::new(),\n local_cid_generator: (config.connection_id_generator_factory.as_ref())(),\n config,\n server_config,\n allow_mtud,\n last_stateless_reset: None,\n incoming_buffers: Slab::new(),\n all_incoming_buffers_total_bytes: 0,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new endpoint\n\n`allow_mtud` enables path MTU detection when requested by `Connection` configuration for\nbetter performance. This requires that outgoing packets are never fragmented, which can be\nachieved via e.g. the `IPV6_DONTFRAG` socket option.\n\nIf `rng_seed` is provided, it will be used to initialize the endpoint's rng (having priority\nover the rng seed configured in [`EndpointConfig`]). Note that the `rng_seed` parameter will\nbe removed in a future release, so prefer setting it to `None` and configuring rng seeds\nusing [`EndpointConfig::rng_seed`].", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/endpoint.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "944e1f202522f68d8a964a8a7ccb59ef93606c9c6efb3e0d98aeff89779c5ee1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_server_config\n\nDocumentation:\nReplace the server configuration, affecting new incoming connections only\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_server_config(&mut self, server_config: Option>) {\n self.server_config = server_config;\n }\n```"}], "func_name": "set_server_config", "docstring": "Replace the server configuration, affecting new incoming connections only", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/endpoint.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d6167b9167c4cdb5fbc4030aa629a15bc87d3538b6e1f41bc5dee245a572c32"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: scan_ack_blocks\n\nDocumentation:\nValidate exactly `n` ACK ranges in `buf` and return the number of bytes they cover\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn scan_ack_blocks(mut buf: &[u8], largest: u64, n: usize) -> Result {\n let total_len = buf.remaining();\n let first_block = buf.get_var()?;\n let mut smallest = largest.checked_sub(first_block).ok_or(IterErr::Malformed)?;\n for _ in 0..n {\n let gap = buf.get_var()?;\n smallest = smallest.checked_sub(gap + 2).ok_or(IterErr::Malformed)?;\n let block = buf.get_var()?;\n smallest = smallest.checked_sub(block).ok_or(IterErr::Malformed)?;\n }\n Ok(total_len - buf.remaining())\n}\n```"}], "func_name": "scan_ack_blocks", "docstring": "Validate exactly `n` ACK ranges in `buf` and return the number of bytes they cover", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/frame.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/frame.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "377e9e593fd541e49945eeb9c57b7e6606e35f33aa80c98538b80a11e635d3a2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: initiator\n\nDocumentation:\nWhich side of a connection initiated the stream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn initiator(self) -> Side {\n if self.0 & 0x1 == 0 {\n Side::Client\n } else {\n Side::Server\n }\n }\n```"}], "func_name": "initiator", "docstring": "Which side of a connection initiated the stream", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/lib.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5490459a0fcbe6ea87bffbbc8f03391c46bc720795d57915510aa18c2f03c766"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nBegin decoding a QUIC packet from `bytes`, returning any trailing data not part of that packet\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n bytes: BytesMut,\n cid_parser: &(impl ConnectionIdParser + ?Sized),\n supported_versions: &[u32],\n grease_quic_bit: bool,\n ) -> Result<(Self, Option), PacketDecodeError> {\n let mut buf = io::Cursor::new(bytes);\n let plain_header =\n ProtectedHeader::decode(&mut buf, cid_parser, supported_versions, grease_quic_bit)?;\n let dgram_len = buf.get_ref().len();\n let packet_len = plain_header\n .payload_len()\n .map(|len| (buf.position() + len) as usize)\n .unwrap_or(dgram_len);\n match dgram_len.cmp(&packet_len) {\n Ordering::Equal => Ok((Self { plain_header, buf }, None)),\n Ordering::Less => Err(PacketDecodeError::InvalidHeader(\n \"packet too short to contain payload length\",\n )),\n Ordering::Greater => {\n let rest = Some(buf.get_mut().split_off(packet_len));\n Ok((Self { plain_header, buf }, rest))\n }\n }\n }\n```"}], "func_name": "new", "docstring": "Begin decoding a QUIC packet from `bytes`, returning any trailing data not part of that packet", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/packet.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/packet.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6b4b5ed1ca7af13ffb2d14d60176a215b13f519751c2fe6f79429887f51f5fcb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_protected\n\nDocumentation:\nWhether the packet is encrypted on the wire\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn is_protected(&self) -> bool {\n !matches!(*self, Self::Retry { .. } | Self::VersionNegotiate { .. })\n }\n```"}], "func_name": "is_protected", "docstring": "Whether the packet is encrypted on the wire", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/packet.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/packet.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "10d86e909248d5de72e75ab0a3025ae9f4c2642f470b6a977a0b1dedd1d556be"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_frames\n\nDocumentation:\nWhether the payload of this packet contains QUIC frames\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn has_frames(&self) -> bool {\n use Header::*;\n match *self {\n Initial(_) => true,\n Long { .. } => true,\n Retry { .. } => false,\n Short { .. } => true,\n VersionNegotiate { .. } => false,\n }\n }\n```"}], "func_name": "has_frames", "docstring": "Whether the payload of this packet contains QUIC frames", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/packet.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/packet.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94ce8b500acb04b8f0aa83323521fc200dc1fd285f9814e7cd848993efabad4e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dst_cid\n\nDocumentation:\nThe destination Connection ID of the packet\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn dst_cid(&self) -> &ConnectionId {\n use ProtectedHeader::*;\n match self {\n Initial(header) => &header.dst_cid,\n Long { dst_cid, .. } => dst_cid,\n Retry { dst_cid, .. } => dst_cid,\n Short { dst_cid, .. } => dst_cid,\n VersionNegotiate { dst_cid, .. } => dst_cid,\n }\n }\n```"}], "func_name": "dst_cid", "docstring": "The destination Connection ID of the packet", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/packet.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/packet.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f0fcc4b42e953645b13189a48be2b68d694afb804cedcbbf9c782b3bb1bd618"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decode\n\nDocumentation:\nDecode a plain header from given buffer, with given [`ConnectionIdParser`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn decode(\n buf: &mut io::Cursor,\n cid_parser: &(impl ConnectionIdParser + ?Sized),\n supported_versions: &[u32],\n grease_quic_bit: bool,\n ) -> Result {\n let first = buf.get::()?;\n if !grease_quic_bit && first & FIXED_BIT == 0 {\n return Err(PacketDecodeError::InvalidHeader(\"fixed bit unset\"));\n }\n if first & LONG_HEADER_FORM == 0 {\n let spin = first & SPIN_BIT != 0;\n\n Ok(Self::Short {\n spin,\n dst_cid: cid_parser.parse(buf)?,\n })\n } else {\n let version = buf.get::()?;\n\n let dst_cid = ConnectionId::decode_long(buf)\n .ok_or(PacketDecodeError::InvalidHeader(\"malformed cid\"))?;\n let src_cid = ConnectionId::decode_long(buf)\n .ok_or(PacketDecodeError::InvalidHeader(\"malformed cid\"))?;\n\n // TODO: Support long CIDs for compatibility with future QUIC versions\n if version == 0 {\n let random = first & !LONG_HEADER_FORM;\n return Ok(Self::VersionNegotiate {\n random,\n dst_cid,\n src_cid,\n });\n }\n\n if !supported_versions.contains(&version) {\n return Err(PacketDecodeError::UnsupportedVersion {\n src_cid,\n dst_cid,\n version,\n });\n }\n\n match LongHeaderType::from_byte(first)? {\n LongHeaderType::Initial => {\n let token_len = buf.get_var()? as usize;\n let token_start = buf.position() as usize;\n if token_len > buf.remaining() {\n return Err(PacketDecodeError::InvalidHeader(\"token out of bounds\"));\n }\n buf.advance(token_len);\n\n let len = buf.get_var()?;\n Ok(Self::Initial(ProtectedInitialHeader {\n dst_cid,\n src_cid,\n token_pos: token_start..token_start + token_len,\n len,\n version,\n }))\n }\n LongHeaderType::Retry => Ok(Self::Retry {\n dst_cid,\n src_cid,\n version,\n }),\n LongHeaderType::Standard(ty) => Ok(Self::Long {\n ty,\n dst_cid,\n src_cid,\n len: buf.get_var()?,\n version,\n }),\n }\n }\n }\n```"}], "func_name": "decode", "docstring": "Decode a plain header from given buffer, with given [`ConnectionIdParser`].", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/packet.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/packet.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4af74d6757341f3f39458fc5a6806e9b13a602a0374522caf05e81cfb7522a66"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_buf\n\nDocumentation:\nConstructs cid by reading `len` bytes from a `Buf`\n\nCallers need to assure that `buf.remaining() >= len`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_buf(buf: &mut (impl Buf + ?Sized), len: usize) -> Self {\n debug_assert!(len <= MAX_CID_SIZE);\n let mut res = Self {\n len: len as u8,\n bytes: [0; MAX_CID_SIZE],\n };\n buf.copy_to_slice(&mut res[..len]);\n res\n }\n```"}], "func_name": "from_buf", "docstring": "Constructs cid by reading `len` bytes from a `Buf`\n\nCallers need to assure that `buf.remaining() >= len`", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/shared.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/shared.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d98e2f4d133fb28289d86545e3107ccaee6bd92c58d737eacb3cdb19fe2b2870"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_bits\n\nDocumentation:\nCreate new object from the given bits\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_bits(x: u8) -> Option {\n use EcnCodepoint::*;\n Some(match x & 0b11 {\n 0b10 => Ect0,\n 0b01 => Ect1,\n 0b11 => Ce,\n _ => {\n return None;\n }\n })\n }\n```"}], "func_name": "from_bits", "docstring": "Create new object from the given bits", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/shared.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/shared.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25dd3556afa99e974b2db5fdcd4b8d4ee35fdba88295d594a958a758d22a1381"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_ce\n\nDocumentation:\nReturns whether the codepoint is a CE, signalling that congestion was experienced\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_ce(self) -> bool {\n matches!(self, Self::Ce)\n }\n```"}], "func_name": "is_ce", "docstring": "Returns whether the codepoint is a CE, signalling that congestion was experienced", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/shared.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/shared.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e08b2b7a54ea016e4bdab23b1b5c57f2f3674cd975a0e9ae5db26be93724f5d1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: crypto\n\nDocumentation:\nCreate QUIC error code from TLS alert code\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn crypto(code: u8) -> Self {\n Self(0x100 | u64::from(code))\n }\n```"}], "func_name": "crypto", "docstring": "Create QUIC error code from TLS alert code", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/transport_error.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/transport_error.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b4850b8dacd61dc45b39fb497eeb76c347e09d0d9a86db9d8b155899401dbe1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: validate_resumption_from\n\nDocumentation:\nCheck that these parameters are legal when resuming from\ncertain cached parameters\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn validate_resumption_from(&self, cached: &Self) -> Result<(), TransportError> {\n if cached.active_connection_id_limit > self.active_connection_id_limit\n || cached.initial_max_data > self.initial_max_data\n || cached.initial_max_stream_data_bidi_local > self.initial_max_stream_data_bidi_local\n || cached.initial_max_stream_data_bidi_remote > self.initial_max_stream_data_bidi_remote\n || cached.initial_max_stream_data_uni > self.initial_max_stream_data_uni\n || cached.initial_max_streams_bidi > self.initial_max_streams_bidi\n || cached.initial_max_streams_uni > self.initial_max_streams_uni\n || cached.max_datagram_frame_size > self.max_datagram_frame_size\n || cached.grease_quic_bit && !self.grease_quic_bit\n {\n return Err(TransportError::PROTOCOL_VIOLATION(\n \"0-RTT accepted with incompatible transport parameters\",\n ));\n }\n Ok(())\n }\n```"}], "func_name": "validate_resumption_from", "docstring": "Check that these parameters are legal when resuming from\ncertain cached parameters", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/transport_parameters.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/transport_parameters.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00de13a38c858a12bf815915dd64fa79afb4b4065c663dcaf8d4ab7edf132a87"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: random\n\nDocumentation:\nGenerates a transport parameter with a random payload and a reserved ID.\n\nThe implementation is inspired by quic-go and quiche:\n1. \n2. \n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn random(rng: &mut impl RngCore) -> Self {\n let id = Self::generate_reserved_id(rng);\n\n let payload_len = rng.random_range(0..Self::MAX_PAYLOAD_LEN);\n\n let payload = {\n let mut slice = [0u8; Self::MAX_PAYLOAD_LEN];\n rng.fill_bytes(&mut slice[..payload_len]);\n slice\n };\n\n Self {\n id,\n payload,\n payload_len,\n }\n }\n```"}], "func_name": "random", "docstring": "Generates a transport parameter with a random payload and a reserved ID.\n\nThe implementation is inspired by quic-go and quiche:\n1. \n2. ", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/transport_parameters.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/transport_parameters.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1d76090826e52b6144ec8b95c19df4d0d5b9b8a8f351f6b672d978be81fe7bc2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_reserved_id\n\nDocumentation:\nGenerates a random reserved identifier of the form `31 * N + 27`, as required by RFC 9000.\nReserved transport parameter identifiers are used to test compliance with the requirement\nthat unknown transport parameters must be ignored by peers.\nSee: and \n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_reserved_id(rng: &mut impl RngCore) -> VarInt {\n let id = {\n let rand = rng.random_range(0u64..(1 << 62) - 27);\n let n = rand / 31;\n 31 * n + 27\n };\n debug_assert!(\n id % 31 == 27,\n \"generated id does not have the form of 31 * N + 27\"\n );\n VarInt::from_u64(id).expect(\n \"generated id does fit into range of allowed transport parameter IDs: [0; 2^62)\",\n )\n }\n```"}], "func_name": "generate_reserved_id", "docstring": "Generates a random reserved identifier of the form `31 * N + 27`, as required by RFC 9000.\nReserved transport parameter identifiers are used to test compliance with the requirement\nthat unknown transport parameters must be ignored by peers.\nSee: and ", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/transport_parameters.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/transport_parameters.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "23fc288fc70eb05028a983b83685eef91013bf0e878b9a4f311e85f8667f8465"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: size\n\nDocumentation:\nCompute the number of bytes needed to encode this value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) const fn size(self) -> usize {\n let x = self.0;\n if x < 2u64.pow(6) {\n 1\n } else if x < 2u64.pow(14) {\n 2\n } else if x < 2u64.pow(30) {\n 4\n } else if x < 2u64.pow(62) {\n 8\n } else {\n panic!(\"malformed VarInt\");\n }\n }\n```"}], "func_name": "size", "docstring": "Compute the number of bytes needed to encode this value", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/varint.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/varint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "837e57f246a82d81e076be1424b2c47b17951cf113639261fec0ed1f1b0db677"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cid_generator\n\nDocumentation:\nSupply a custom connection ID generator factory\n\nCalled once by each `Endpoint` constructed from this configuration to obtain the CID\ngenerator which will be used to generate the CIDs used for incoming packets on all\nconnections involving that `Endpoint`. A custom CID generator allows applications to embed\ninformation in local connection IDs, e.g. to support stateless packet-level load balancers.\n\nDefaults to [`HashedConnectionIdGenerator`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn cid_generator Box + Send + Sync + 'static>(\n &mut self,\n factory: F,\n ) -> &mut Self {\n self.connection_id_generator_factory = Arc::new(factory);\n self\n }\n```"}], "func_name": "cid_generator", "docstring": "Supply a custom connection ID generator factory\n\nCalled once by each `Endpoint` constructed from this configuration to obtain the CID\ngenerator which will be used to generate the CIDs used for incoming packets on all\nconnections involving that `Endpoint`. A custom CID generator allows applications to embed\ninformation in local connection IDs, e.g. to support stateless packet-level load balancers.\n\nDefaults to [`HashedConnectionIdGenerator`].", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c6885cde37dda2d11cb74cdfd77c73506992cfec98eb91d2481af29e301cdea"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_key\n\nDocumentation:\nPrivate key used to send authenticated connection resets to peers who were\ncommunicating with a previous instance of this endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reset_key(&mut self, key: Arc) -> &mut Self {\n self.reset_key = key;\n self\n }\n```"}], "func_name": "reset_key", "docstring": "Private key used to send authenticated connection resets to peers who were\ncommunicating with a previous instance of this endpoint.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0edb892e2dfba84e1da7caa93fe5877201685cd03017dd8f2635ac9479f7fd75"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: grease_quic_bit\n\nDocumentation:\nWhether to accept QUIC packets containing any value for the fixed bit\n\nEnabled by default. Helps protect against protocol ossification and makes traffic less\nidentifiable to observers. Disable if helping observers identify this traffic as QUIC is\ndesired.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn grease_quic_bit(&mut self, value: bool) -> &mut Self {\n self.grease_quic_bit = value;\n self\n }\n```"}], "func_name": "grease_quic_bit", "docstring": "Whether to accept QUIC packets containing any value for the fixed bit\n\nEnabled by default. Helps protect against protocol ossification and makes traffic less\nidentifiable to observers. Disable if helping observers identify this traffic as QUIC is\ndesired.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9bd5af5917873971a91b72518723d68c4584a9cc40965c4427d1e18792a7ff8e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rng_seed\n\nDocumentation:\nOptional seed to be used internally for random number generation\n\nBy default, quinn will initialize an endpoint's rng using a platform entropy source.\nHowever, you can seed the rng yourself through this method (e.g. if you need to run quinn\ndeterministically or if you are using quinn in an environment that doesn't have a source of\nentropy available).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn rng_seed(&mut self, seed: Option<[u8; 32]>) -> &mut Self {\n self.rng_seed = seed;\n self\n }\n```"}], "func_name": "rng_seed", "docstring": "Optional seed to be used internally for random number generation\n\nBy default, quinn will initialize an endpoint's rng using a platform entropy source.\nHowever, you can seed the rng yourself through this method (e.g. if you need to run quinn\ndeterministically or if you are using quinn in an environment that doesn't have a source of\nentropy available).", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2d5915ac7513bf29dc51860d34a90c85fe37847d98b70a48dcbfdf971d7aa0be"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a default config with a particular handshake token key\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n crypto: Arc,\n token_key: Arc,\n ) -> Self {\n Self {\n transport: Arc::new(TransportConfig::default()),\n crypto,\n\n token_key,\n retry_token_lifetime: Duration::from_secs(15),\n\n migration: true,\n\n validation_token: ValidationTokenConfig::default(),\n\n preferred_address_v4: None,\n preferred_address_v6: None,\n\n max_incoming: 1 << 16,\n incoming_buffer_size: 10 << 20,\n incoming_buffer_size_total: 100 << 20,\n\n time_source: Arc::new(StdSystemTime),\n }\n }\n```"}], "func_name": "new", "docstring": "Create a default config with a particular handshake token key", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "52d89db3123ad1b446ee94dad8be341fd7d39948ce4d2fdbfce9610201f5bd9f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: token_key\n\nDocumentation:\nPrivate key used to authenticate data included in handshake tokens\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn token_key(&mut self, value: Arc) -> &mut Self {\n self.token_key = value;\n self\n }\n```"}], "func_name": "token_key", "docstring": "Private key used to authenticate data included in handshake tokens", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "515d89c9e733f099c4dc5e9b7796131b7a1e92f1ccdc8bdd8ccca42152228422"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: retry_token_lifetime\n\nDocumentation:\nDuration after a retry token was issued for which it's considered valid\n\nDefaults to 15 seconds.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn retry_token_lifetime(&mut self, value: Duration) -> &mut Self {\n self.retry_token_lifetime = value;\n self\n }\n```"}], "func_name": "retry_token_lifetime", "docstring": "Duration after a retry token was issued for which it's considered valid\n\nDefaults to 15 seconds.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "76114ef318ee447e7ce08639d03366723aab280c0dab9d56279f914002d27348"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: migration\n\nDocumentation:\nWhether to allow clients to migrate to new addresses\n\nImproves behavior for clients that move between different internet connections or suffer NAT\nrebinding. Enabled by default.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn migration(&mut self, value: bool) -> &mut Self {\n self.migration = value;\n self\n }\n```"}], "func_name": "migration", "docstring": "Whether to allow clients to migrate to new addresses\n\nImproves behavior for clients that move between different internet connections or suffer NAT\nrebinding. Enabled by default.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2c107492ac848f967e1b8bc316aaf06444fe0b1bef26e29ed28b120c9e84d3b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: preferred_address_v4\n\nDocumentation:\nThe preferred IPv4 address that will be communicated to clients during handshaking\n\nIf the client is able to reach this address, it will switch to it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn preferred_address_v4(&mut self, address: Option) -> &mut Self {\n self.preferred_address_v4 = address;\n self\n }\n```"}], "func_name": "preferred_address_v4", "docstring": "The preferred IPv4 address that will be communicated to clients during handshaking\n\nIf the client is able to reach this address, it will switch to it.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9eec5ef8f8534d5d99b81e3b3197b13b4207986aff8a0cc9556bb5ff0aed78d9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: preferred_address_v6\n\nDocumentation:\nThe preferred IPv6 address that will be communicated to clients during handshaking\n\nIf the client is able to reach this address, it will switch to it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn preferred_address_v6(&mut self, address: Option) -> &mut Self {\n self.preferred_address_v6 = address;\n self\n }\n```"}], "func_name": "preferred_address_v6", "docstring": "The preferred IPv6 address that will be communicated to clients during handshaking\n\nIf the client is able to reach this address, it will switch to it.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8bb71ab8c57ccb03daee15af984404f1e59ad7711cfb2052773722b57a0cabd8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: time_source\n\nDocumentation:\nObject to get current [`SystemTime`]\n\nThis exists to allow system time to be mocked in tests, or wherever else desired.\n\nDefaults to [`StdSystemTime`], which simply calls [`SystemTime::now()`](SystemTime::now).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn time_source(&mut self, time_source: Arc) -> &mut Self {\n self.time_source = time_source;\n self\n }\n```"}], "func_name": "time_source", "docstring": "Object to get current [`SystemTime`]\n\nThis exists to allow system time to be mocked in tests, or wherever else desired.\n\nDefaults to [`StdSystemTime`], which simply calls [`SystemTime::now()`](SystemTime::now).", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ed60ff146c13539eba6fc2eed809935030f492bbccac5ac0b9c551220295c030"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_single_cert\n\nDocumentation:\nCreate a server config with the given certificate chain to be presented to clients\n\nUses a randomized handshake token key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_single_cert(\n cert_chain: Vec>,\n key: PrivateKeyDer<'static>,\n ) -> Result {\n Ok(Self::with_crypto(Arc::new(QuicServerConfig::new(\n cert_chain, key,\n )?)))\n }\n```"}], "func_name": "with_single_cert", "docstring": "Create a server config with the given certificate chain to be presented to clients\n\nUses a randomized handshake token key.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ab6839146860ad32596598c67abeaef0e050783cd0c21199ade73e2de1dd8d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_crypto\n\nDocumentation:\nCreate a server config with the given [`crypto::ServerConfig`]\n\nUses a randomized handshake token key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_crypto(crypto: Arc) -> Self {\n #[cfg(all(feature = \"aws-lc-rs\", not(feature = \"ring\")))]\n use aws_lc_rs::hkdf;\n use rand::RngCore;\n #[cfg(feature = \"ring\")]\n use ring::hkdf;\n\n let rng = &mut rand::rng();\n let mut master_key = [0u8; 64];\n rng.fill_bytes(&mut master_key);\n let master_key = hkdf::Salt::new(hkdf::HKDF_SHA256, &[]).extract(&master_key);\n\n Self::new(crypto, Arc::new(master_key))\n }\n```"}], "func_name": "with_crypto", "docstring": "Create a server config with the given [`crypto::ServerConfig`]\n\nUses a randomized handshake token key.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80c10f0e654c5aca10421834794ac680f4e75ae0b99ad10d7a57c3e661722a97"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lifetime\n\nDocumentation:\nDuration after an address validation token was issued for which it's considered valid\n\nThis refers only to tokens sent in NEW_TOKEN frames, in contrast to retry tokens.\n\nDefaults to 2 weeks.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn lifetime(&mut self, value: Duration) -> &mut Self {\n self.lifetime = value;\n self\n }\n```"}], "func_name": "lifetime", "docstring": "Duration after an address validation token was issued for which it's considered valid\n\nThis refers only to tokens sent in NEW_TOKEN frames, in contrast to retry tokens.\n\nDefaults to 2 weeks.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "135b669620a13b92e43ba03df8e6af1b3ea9ab78e65ace85fac3d2de93097422"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: log\n\nDocumentation:\nSet a custom [`TokenLog`]\n\nIf the `bloom` feature is enabled (which it is by default), defaults to a default\n[`BloomTokenLog`][crate::BloomTokenLog], which is suitable for most internet applications.\n\nIf the `bloom` feature is disabled, defaults to [`NoneTokenLog`][crate::NoneTokenLog],\nwhich makes the server ignore all address validation tokens (that is, tokens originating\nfrom NEW_TOKEN frames--retry tokens are not affected).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn log(&mut self, log: Arc) -> &mut Self {\n self.log = log;\n self\n }\n```"}], "func_name": "log", "docstring": "Set a custom [`TokenLog`]\n\nIf the `bloom` feature is enabled (which it is by default), defaults to a default\n[`BloomTokenLog`][crate::BloomTokenLog], which is suitable for most internet applications.\n\nIf the `bloom` feature is disabled, defaults to [`NoneTokenLog`][crate::NoneTokenLog],\nwhich makes the server ignore all address validation tokens (that is, tokens originating\nfrom NEW_TOKEN frames--retry tokens are not affected).", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e68016bb70ccb2d748f7331f5bbb180a23d01629c86e1a6d93190ab849332f66"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sent\n\nDocumentation:\nNumber of address validation tokens sent to a client when its path is validated\n\nThis refers only to tokens sent in NEW_TOKEN frames, in contrast to retry tokens.\n\nIf the `bloom` feature is enabled (which it is by default), defaults to 2. Otherwise,\ndefaults to 0.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sent(&mut self, value: u32) -> &mut Self {\n self.sent = value;\n self\n }\n```"}], "func_name": "sent", "docstring": "Number of address validation tokens sent to a client when its path is validated\n\nThis refers only to tokens sent in NEW_TOKEN frames, in contrast to retry tokens.\n\nIf the `bloom` feature is enabled (which it is by default), defaults to 2. Otherwise,\ndefaults to 0.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17d75c91ef76ad3cd8db175a754f53c54c36dc251cce5269c0a35d8f9899743b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a default config with a particular cryptographic config\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(crypto: Arc) -> Self {\n Self {\n transport: Default::default(),\n crypto,\n token_store: Arc::new(TokenMemoryCache::default()),\n initial_dst_cid_provider: Arc::new(|| {\n RandomConnectionIdGenerator::new(MAX_CID_SIZE).generate_cid()\n }),\n version: 1,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a default config with a particular cryptographic config", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aa3f57c0105f45c82c2a81b97ec5b93c99552ab1c6353c3f42ae4ba6b05be7ee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: initial_dst_cid_provider\n\nDocumentation:\nConfigure how to populate the destination CID of the initial packet when attempting to\nestablish a new connection\n\nBy default, it's populated with random bytes with reasonable length, so unless you have\na good reason, you do not need to change it.\n\nWhen prefer to override the default, please note that the generated connection ID MUST be\nat least 8 bytes long and unpredictable, as per section 7.2 of RFC 9000.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn initial_dst_cid_provider(\n &mut self,\n initial_dst_cid_provider: Arc ConnectionId + Send + Sync>,\n ) -> &mut Self {\n self.initial_dst_cid_provider = initial_dst_cid_provider;\n self\n }\n```"}], "func_name": "initial_dst_cid_provider", "docstring": "Configure how to populate the destination CID of the initial packet when attempting to\nestablish a new connection\n\nBy default, it's populated with random bytes with reasonable length, so unless you have\na good reason, you do not need to change it.\n\nWhen prefer to override the default, please note that the generated connection ID MUST be\nat least 8 bytes long and unpredictable, as per section 7.2 of RFC 9000.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ebe0529bb8a5d27c6d4022d4d2efa7026b2f48bd7b9c5eacb7fb74eaab244a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: token_store\n\nDocumentation:\nSet a custom [`TokenStore`]\n\nDefaults to [`TokenMemoryCache`], which is suitable for most internet applications.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn token_store(&mut self, store: Arc) -> &mut Self {\n self.token_store = store;\n self\n }\n```"}], "func_name": "token_store", "docstring": "Set a custom [`TokenStore`]\n\nDefaults to [`TokenMemoryCache`], which is suitable for most internet applications.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc6fff4b51df40e20e0edb6471232b14df6b04fccc8a5e0f670c5e946fa07f24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: version\n\nDocumentation:\nSet the QUIC version to use\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn version(&mut self, version: u32) -> &mut Self {\n self.version = version;\n self\n }\n```"}], "func_name": "version", "docstring": "Set the QUIC version to use", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b11f406998dad046d3a01efaf703163e36be4ce9d3d15afd955949fb968c429e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_root_certificates\n\nDocumentation:\nCreate a client configuration that trusts specified trust anchors\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_root_certificates(\n roots: Arc,\n ) -> Result {\n Ok(Self::new(Arc::new(crypto::rustls::QuicClientConfig::new(\n WebPkiServerVerifier::builder_with_provider(roots, configured_provider()).build()?,\n ))))\n }\n```"}], "func_name": "with_root_certificates", "docstring": "Create a client configuration that trusts specified trust anchors", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "01c71b75a3cd4fa7e5bbe6d9c33b5ef103c8dd4891bccf929d2e5f5faac3ffe6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: max_concurrent_bidi_streams\n\nDocumentation:\nMaximum number of incoming bidirectional streams that may be open concurrently\n\nMust be nonzero for the peer to open any bidirectional streams.\n\nWorst-case memory use is directly proportional to `max_concurrent_bidi_streams *\nstream_receive_window`, with an upper bound proportional to `receive_window`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn max_concurrent_bidi_streams(&mut self, value: VarInt) -> &mut Self {\n self.max_concurrent_bidi_streams = value;\n self\n }\n```"}], "func_name": "max_concurrent_bidi_streams", "docstring": "Maximum number of incoming bidirectional streams that may be open concurrently\n\nMust be nonzero for the peer to open any bidirectional streams.\n\nWorst-case memory use is directly proportional to `max_concurrent_bidi_streams *\nstream_receive_window`, with an upper bound proportional to `receive_window`.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2fe8ffae6b1f7e4b392d5b26e5d3178c3da0fa5a471bac070a778c548914cfef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: max_idle_timeout\n\nDocumentation:\nMaximum duration of inactivity to accept before timing out the connection.\n\nThe true idle timeout is the minimum of this and the peer's own max idle timeout. `None`\nrepresents an infinite timeout. Defaults to 30 seconds.\n\n**WARNING**: If a peer or its network path malfunctions or acts maliciously, an infinite\nidle timeout can result in permanently hung futures!\n\n```\n# use std::{convert::TryInto, time::Duration};\n# use quinn_proto::{TransportConfig, VarInt, VarIntBoundsExceeded};\n# fn main() -> Result<(), VarIntBoundsExceeded> {\nlet mut config = TransportConfig::default();\n\n// Set the idle timeout as `VarInt`-encoded milliseconds\nconfig.max_idle_timeout(Some(VarInt::from_u32(10_000).into()));\n\n// Set the idle timeout as a `Duration`\nconfig.max_idle_timeout(Some(Duration::from_secs(10).try_into()?));\n# Ok(())\n# }\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn max_idle_timeout(&mut self, value: Option) -> &mut Self {\n self.max_idle_timeout = value.map(|t| t.0);\n self\n }\n```"}], "func_name": "max_idle_timeout", "docstring": "Maximum duration of inactivity to accept before timing out the connection.\n\nThe true idle timeout is the minimum of this and the peer's own max idle timeout. `None`\nrepresents an infinite timeout. Defaults to 30 seconds.\n\n**WARNING**: If a peer or its network path malfunctions or acts maliciously, an infinite\nidle timeout can result in permanently hung futures!\n\n```\n# use std::{convert::TryInto, time::Duration};\n# use quinn_proto::{TransportConfig, VarInt, VarIntBoundsExceeded};\n# fn main() -> Result<(), VarIntBoundsExceeded> {\nlet mut config = TransportConfig::default();\n\n// Set the idle timeout as `VarInt`-encoded milliseconds\nconfig.max_idle_timeout(Some(VarInt::from_u32(10_000).into()));\n\n// Set the idle timeout as a `Duration`\nconfig.max_idle_timeout(Some(Duration::from_secs(10).try_into()?));\n# Ok(())\n# }\n```", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eaf136042ef651ffa2c88e59e1c6014a3b1573299d41201e6b00f7648e890aa6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_fairness\n\nDocumentation:\nWhether to implement fair queuing for send streams having the same priority.\n\nWhen enabled, connections schedule data from outgoing streams having the same priority in a\nround-robin fashion. When disabled, streams are scheduled in the order they are written to.\n\nNote that this only affects streams with the same priority. Higher priority streams always\ntake precedence over lower priority streams.\n\nDisabling fairness can reduce fragmentation and protocol overhead for workloads that use\nmany small streams.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn send_fairness(&mut self, value: bool) -> &mut Self {\n self.send_fairness = value;\n self\n }\n```"}], "func_name": "send_fairness", "docstring": "Whether to implement fair queuing for send streams having the same priority.\n\nWhen enabled, connections schedule data from outgoing streams having the same priority in a\nround-robin fashion. When disabled, streams are scheduled in the order they are written to.\n\nNote that this only affects streams with the same priority. Higher priority streams always\ntake precedence over lower priority streams.\n\nDisabling fairness can reduce fragmentation and protocol overhead for workloads that use\nmany small streams.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6910a1e6c15eb6e8563ab79c70cede00f8fbdb5c93383c7a76ab720b3297f837"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: packet_threshold\n\nDocumentation:\nMaximum reordering in packet number space before FACK style loss detection considers a\npacket lost. Should not be less than 3, per RFC5681.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn packet_threshold(&mut self, value: u32) -> &mut Self {\n self.packet_threshold = value;\n self\n }\n```"}], "func_name": "packet_threshold", "docstring": "Maximum reordering in packet number space before FACK style loss detection considers a\npacket lost. Should not be less than 3, per RFC5681.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c5a42118bdd13a3c68cd8d9522693901cedd5135af39478bfac4f12e7d1c99e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: time_threshold\n\nDocumentation:\nMaximum reordering in time space before time based loss detection considers a packet lost,\nas a factor of RTT\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn time_threshold(&mut self, value: f32) -> &mut Self {\n self.time_threshold = value;\n self\n }\n```"}], "func_name": "time_threshold", "docstring": "Maximum reordering in time space before time based loss detection considers a packet lost,\nas a factor of RTT", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1971da77678a5e7e6cf8d3556b44bb76e5856cfcaec036177a94297d18a9b9aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: initial_rtt\n\nDocumentation:\nThe RTT used before an RTT sample is taken\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn initial_rtt(&mut self, value: Duration) -> &mut Self {\n self.initial_rtt = value;\n self\n }\n```"}], "func_name": "initial_rtt", "docstring": "The RTT used before an RTT sample is taken", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f18544b2926d0b550b098424196f053d6d57699de000e375c8f38b0f3d1e7fc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: initial_mtu\n\nDocumentation:\nThe initial value to be used as the maximum UDP payload size before running MTU discovery\n(see [`TransportConfig::mtu_discovery_config`]).\n\nMust be at least 1200, which is the default, and known to be safe for typical internet\napplications. Larger values are more efficient, but increase the risk of packet loss due to\nexceeding the network path's IP MTU. If the provided value is higher than what the network\npath actually supports, packet loss will eventually trigger black hole detection and bring\nit down to [`TransportConfig::min_mtu`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn initial_mtu(&mut self, value: u16) -> &mut Self {\n self.initial_mtu = value.max(INITIAL_MTU);\n self\n }\n```"}], "func_name": "initial_mtu", "docstring": "The initial value to be used as the maximum UDP payload size before running MTU discovery\n(see [`TransportConfig::mtu_discovery_config`]).\n\nMust be at least 1200, which is the default, and known to be safe for typical internet\napplications. Larger values are more efficient, but increase the risk of packet loss due to\nexceeding the network path's IP MTU. If the provided value is higher than what the network\npath actually supports, packet loss will eventually trigger black hole detection and bring\nit down to [`TransportConfig::min_mtu`].", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "07b61a3e8e008a1b47abbc783daa85a59fe93465dfb555d7c2afe56c061ed8e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: min_mtu\n\nDocumentation:\nThe maximum UDP payload size guaranteed to be supported by the network.\n\nMust be at least 1200, which is the default, and lower than or equal to\n[`TransportConfig::initial_mtu`].\n\nReal-world MTUs can vary according to ISP, VPN, and properties of intermediate network links\noutside of either endpoint's control. Extreme care should be used when raising this value\noutside of private networks where these factors are fully controlled. If the provided value\nis higher than what the network path actually supports, the result will be unpredictable and\ncatastrophic packet loss, without a possibility of repair. Prefer\n[`TransportConfig::initial_mtu`] together with\n[`TransportConfig::mtu_discovery_config`] to set a maximum UDP payload size that robustly\nadapts to the network.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn min_mtu(&mut self, value: u16) -> &mut Self {\n self.min_mtu = value.max(INITIAL_MTU);\n self\n }\n```"}], "func_name": "min_mtu", "docstring": "The maximum UDP payload size guaranteed to be supported by the network.\n\nMust be at least 1200, which is the default, and lower than or equal to\n[`TransportConfig::initial_mtu`].\n\nReal-world MTUs can vary according to ISP, VPN, and properties of intermediate network links\noutside of either endpoint's control. Extreme care should be used when raising this value\noutside of private networks where these factors are fully controlled. If the provided value\nis higher than what the network path actually supports, the result will be unpredictable and\ncatastrophic packet loss, without a possibility of repair. Prefer\n[`TransportConfig::initial_mtu`] together with\n[`TransportConfig::mtu_discovery_config`] to set a maximum UDP payload size that robustly\nadapts to the network.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d3a8b9638e5af59501285b0e917481aeebab7345759c767fb81b0e3ba9fa4a9b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mtu_discovery_config\n\nDocumentation:\nSpecifies the MTU discovery config (see [`MtuDiscoveryConfig`] for details).\n\nEnabled by default.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn mtu_discovery_config(&mut self, value: Option) -> &mut Self {\n self.mtu_discovery_config = value;\n self\n }\n```"}], "func_name": "mtu_discovery_config", "docstring": "Specifies the MTU discovery config (see [`MtuDiscoveryConfig`] for details).\n\nEnabled by default.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2087d2e5123171fe4be5dc46d33acdad6c9e58f68c0c02d84821f42fc1d79757"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ack_frequency_config\n\nDocumentation:\nSpecifies the ACK frequency config (see [`AckFrequencyConfig`] for details)\n\nThe provided configuration will be ignored if the peer does not support the acknowledgement\nfrequency QUIC extension.\n\nDefaults to `None`, which disables controlling the peer's acknowledgement frequency. Even\nif set to `None`, the local side still supports the acknowledgement frequency QUIC\nextension and may use it in other ways.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ack_frequency_config(&mut self, value: Option) -> &mut Self {\n self.ack_frequency_config = value;\n self\n }\n```"}], "func_name": "ack_frequency_config", "docstring": "Specifies the ACK frequency config (see [`AckFrequencyConfig`] for details)\n\nThe provided configuration will be ignored if the peer does not support the acknowledgement\nfrequency QUIC extension.\n\nDefaults to `None`, which disables controlling the peer's acknowledgement frequency. Even\nif set to `None`, the local side still supports the acknowledgement frequency QUIC\nextension and may use it in other ways.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2c8757feb083ae06e26c9744abb9bb30f41adf0e23321d8fd1f27d0eb4fe5a59"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: persistent_congestion_threshold\n\nDocumentation:\nNumber of consecutive PTOs after which network is considered to be experiencing persistent congestion.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn persistent_congestion_threshold(&mut self, value: u32) -> &mut Self {\n self.persistent_congestion_threshold = value;\n self\n }\n```"}], "func_name": "persistent_congestion_threshold", "docstring": "Number of consecutive PTOs after which network is considered to be experiencing persistent congestion.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0cd3bf648816b068ef5eac9313c44df996ce84ce08116c450b26722124d6cc0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: keep_alive_interval\n\nDocumentation:\nPeriod of inactivity before sending a keep-alive packet\n\nKeep-alive packets prevent an inactive but otherwise healthy connection from timing out.\n\n`None` to disable, which is the default. Only one side of any given connection needs keep-alive\nenabled for the connection to be preserved. Must be set lower than the idle_timeout of both\npeers to be effective.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn keep_alive_interval(&mut self, value: Option) -> &mut Self {\n self.keep_alive_interval = value;\n self\n }\n```"}], "func_name": "keep_alive_interval", "docstring": "Period of inactivity before sending a keep-alive packet\n\nKeep-alive packets prevent an inactive but otherwise healthy connection from timing out.\n\n`None` to disable, which is the default. Only one side of any given connection needs keep-alive\nenabled for the connection to be preserved. Must be set lower than the idle_timeout of both\npeers to be effective.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a759c3f641d3ef3010b25b60aaa39081e09ba106eb6aee19ec86258986ced34"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: crypto_buffer_size\n\nDocumentation:\nMaximum quantity of out-of-order crypto layer data to buffer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn crypto_buffer_size(&mut self, value: usize) -> &mut Self {\n self.crypto_buffer_size = value;\n self\n }\n```"}], "func_name": "crypto_buffer_size", "docstring": "Maximum quantity of out-of-order crypto layer data to buffer", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c58d1552e485ec948696bccd31373e2403098b0b23376e107074e49c6c3226e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: datagram_receive_buffer_size\n\nDocumentation:\nMaximum number of incoming application datagram bytes to buffer, or None to disable\nincoming datagrams\n\nThe peer is forbidden to send single datagrams larger than this size. If the aggregate size\nof all datagrams that have been received from the peer but not consumed by the application\nexceeds this value, old datagrams are dropped until it is no longer exceeded.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn datagram_receive_buffer_size(&mut self, value: Option) -> &mut Self {\n self.datagram_receive_buffer_size = value;\n self\n }\n```"}], "func_name": "datagram_receive_buffer_size", "docstring": "Maximum number of incoming application datagram bytes to buffer, or None to disable\nincoming datagrams\n\nThe peer is forbidden to send single datagrams larger than this size. If the aggregate size\nof all datagrams that have been received from the peer but not consumed by the application\nexceeds this value, old datagrams are dropped until it is no longer exceeded.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ddd9f671d42b2ffa01037f0b4e5499069a1ffd8260824590d09ecda810487f02"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: congestion_controller_factory\n\nDocumentation:\nHow to construct new `congestion::Controller`s\n\nTypically the refcounted configuration of a `congestion::Controller`,\ne.g. a `congestion::NewRenoConfig`.\n\n# Example\n```\n# use quinn_proto::*; use std::sync::Arc;\nlet mut config = TransportConfig::default();\nconfig.congestion_controller_factory(Arc::new(congestion::NewRenoConfig::default()));\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn congestion_controller_factory(\n &mut self,\n factory: Arc,\n ) -> &mut Self {\n self.congestion_controller_factory = factory;\n self\n }\n```"}], "func_name": "congestion_controller_factory", "docstring": "How to construct new `congestion::Controller`s\n\nTypically the refcounted configuration of a `congestion::Controller`,\ne.g. a `congestion::NewRenoConfig`.\n\n# Example\n```\n# use quinn_proto::*; use std::sync::Arc;\nlet mut config = TransportConfig::default();\nconfig.congestion_controller_factory(Arc::new(congestion::NewRenoConfig::default()));\n```", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/config/transport.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/config/transport.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c65bd56ba8ccae8b68f0e71c8cdf503406be6562e006263da676ff7e83547482"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConstruct a state using the given `config` and current time `now`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(config: Arc, _now: Instant, current_mtu: u16) -> Self {\n Self {\n window: config.initial_window,\n ssthresh: u64::MAX,\n recovery_start_time: None,\n config,\n cubic_state: Default::default(),\n current_mtu: current_mtu as u64,\n }\n }\n```"}], "func_name": "new", "docstring": "Construct a state using the given `config` and current time `now`", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/congestion/cubic.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/congestion/cubic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f69d2738414e86afbfd485a6b37b20c9750a1f70254a60e1aa20a64e26bc9233"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: loss_reduction_factor\n\nDocumentation:\nReduction in congestion window when a new loss event is detected.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn loss_reduction_factor(&mut self, value: f32) -> &mut Self {\n self.loss_reduction_factor = value;\n self\n }\n```"}], "func_name": "loss_reduction_factor", "docstring": "Reduction in congestion window when a new loss event is detected.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/congestion/new_reno.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/congestion/new_reno.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d9cd41ce50ce9f4032e4835e655169699aa237bac9a79d6d19fee148f5fbe74b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_max\n\nDocumentation:\nupdate_min is also defined in the original source, but removed here since it is not used.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn update_max(&mut self, current_round: u64, measurement: u64) {\n let sample = MinMaxSample {\n time: current_round,\n value: measurement,\n };\n\n if self.samples[0].value == 0 /* uninitialised */\n || /* found new max? */ sample.value >= self.samples[0].value\n || /* nothing left in window? */ sample.time - self.samples[2].time > self.window\n {\n self.fill(sample); /* forget earlier samples */\n return;\n }\n\n if sample.value >= self.samples[1].value {\n self.samples[2] = sample;\n self.samples[1] = sample;\n } else if sample.value >= self.samples[2].value {\n self.samples[2] = sample;\n }\n\n self.subwin_update(sample);\n }\n```"}], "func_name": "update_max", "docstring": "update_min is also defined in the original source, but removed here since it is not used.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/congestion/bbr/min_max.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/congestion/bbr/min_max.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e90176a4e45783e7569c6880bf560524821358f01348b58c85dbf3c2244cbf99"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_if_full_bw_reached\n\nDocumentation:\n\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_if_full_bw_reached(&mut self, app_limited: bool) {\n if app_limited {\n return;\n }\n let target = (self.bw_at_last_round as f64 * K_STARTUP_GROWTH_TARGET as f64) as u64;\n let bw = self.max_bandwidth.get_estimate();\n if bw >= target {\n self.bw_at_last_round = bw;\n self.round_wo_bw_gain = 0;\n self.ack_aggregation.max_ack_height.reset();\n return;\n }\n\n self.round_wo_bw_gain += 1;\n if self.round_wo_bw_gain >= K_ROUND_TRIPS_WITHOUT_GROWTH_BEFORE_EXITING_STARTUP as u64\n || (self.recovery_state.in_recovery())\n {\n self.is_at_full_bandwidth = true;\n }\n }\n```"}], "func_name": "check_if_full_bw_reached", "docstring": "", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/congestion/bbr/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/congestion/bbr/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c2624e82dcbca698bb54a4c89245c2a54199cccd99da682f207471a7ce7fe84e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: candidate_max_ack_delay\n\nDocumentation:\nReturns the `max_ack_delay` that should be requested of the peer when sending an\nACK_FREQUENCY frame\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn candidate_max_ack_delay(\n &self,\n rtt: Duration,\n config: &AckFrequencyConfig,\n peer_params: &TransportParameters,\n ) -> Duration {\n // Use the peer's max_ack_delay if no custom max_ack_delay was provided in the config\n let min_ack_delay =\n Duration::from_micros(peer_params.min_ack_delay.map_or(0, |x| x.into()));\n config\n .max_ack_delay\n .unwrap_or(self.peer_max_ack_delay)\n .clamp(min_ack_delay, rtt.max(MIN_AUTOMATIC_ACK_DELAY))\n }\n```"}], "func_name": "candidate_max_ack_delay", "docstring": "Returns the `max_ack_delay` that should be requested of the peer when sending an\nACK_FREQUENCY frame", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/ack_frequency.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/ack_frequency.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f2379ac798d6f2f1f2b57bd7739c94a29892be8aaf2986e687e77507965b128"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: max_ack_delay_for_pto\n\nDocumentation:\nReturns the `max_ack_delay` for the purposes of calculating the PTO\n\nThis `max_ack_delay` is defined as the maximum of the peer's current `max_ack_delay` and all\nin-flight `max_ack_delay`s (i.e. proposed values that haven't been acknowledged yet, but\nmight be already in use by the peer).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn max_ack_delay_for_pto(&self) -> Duration {\n // Note: we have at most one in-flight ACK_FREQUENCY frame\n if let Some((_, max_ack_delay)) = self.in_flight_ack_frequency_frame {\n self.peer_max_ack_delay.max(max_ack_delay)\n } else {\n self.peer_max_ack_delay\n }\n }\n```"}], "func_name": "max_ack_delay_for_pto", "docstring": "Returns the `max_ack_delay` for the purposes of calculating the PTO\n\nThis `max_ack_delay` is defined as the maximum of the peer's current `max_ack_delay` and all\nin-flight `max_ack_delay`s (i.e. proposed values that haven't been acknowledged yet, but\nmight be already in use by the peer).", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/ack_frequency.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/ack_frequency.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "89c12c07ab132de2c0d5a1b1ecda070a272bb8f2e282ee791e8080dad2d210e3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next_sequence_number\n\nDocumentation:\nReturns the next sequence number for an ACK_FREQUENCY frame\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn next_sequence_number(&mut self) -> VarInt {\n assert!(self.next_outgoing_sequence_number <= VarInt::MAX);\n\n let seq = self.next_outgoing_sequence_number;\n self.next_outgoing_sequence_number.0 += 1;\n seq\n }\n```"}], "func_name": "next_sequence_number", "docstring": "Returns the next sequence number for an ACK_FREQUENCY frame", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/ack_frequency.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/ack_frequency.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ec126eddc5ecec87dfe4cbf036e6389fd70e908f248e34662e5f1dd24967aa0c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: should_send_ack_frequency\n\nDocumentation:\nReturns true if we should send an ACK_FREQUENCY frame\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn should_send_ack_frequency(\n &self,\n rtt: Duration,\n config: &AckFrequencyConfig,\n peer_params: &TransportParameters,\n ) -> bool {\n if self.next_outgoing_sequence_number.0 == 0 {\n // Always send at startup\n return true;\n }\n let current = self\n .in_flight_ack_frequency_frame\n .map_or(self.peer_max_ack_delay, |(_, pending)| pending);\n let desired = self.candidate_max_ack_delay(rtt, config, peer_params);\n let error = (desired.as_secs_f32() / current.as_secs_f32()) - 1.0;\n error.abs() > MAX_RTT_ERROR\n }\n```"}], "func_name": "should_send_ack_frequency", "docstring": "Returns true if we should send an ACK_FREQUENCY frame", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/ack_frequency.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/ack_frequency.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "738268d31bc5cc6db7be7b95aaaaa113307f225295081d1ff07f8d7d9312d351"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ack_frequency_sent\n\nDocumentation:\nNotifies the [`AckFrequencyState`] that a packet containing an ACK_FREQUENCY frame was sent\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn ack_frequency_sent(&mut self, pn: u64, requested_max_ack_delay: Duration) {\n self.in_flight_ack_frequency_frame = Some((pn, requested_max_ack_delay));\n }\n```"}], "func_name": "ack_frequency_sent", "docstring": "Notifies the [`AckFrequencyState`] that a packet containing an ACK_FREQUENCY frame was sent", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/ack_frequency.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/ack_frequency.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "de539ded7cdf2e1c95a326e03e48d1fc60e4d331da02f648237b60834a84c9aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_acked\n\nDocumentation:\nNotifies the [`AckFrequencyState`] that a packet has been ACKed\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn on_acked(&mut self, pn: u64) {\n match self.in_flight_ack_frequency_frame {\n Some((number, requested_max_ack_delay)) if number == pn => {\n self.in_flight_ack_frequency_frame = None;\n self.peer_max_ack_delay = requested_max_ack_delay;\n }\n _ => {}\n }\n }\n```"}], "func_name": "on_acked", "docstring": "Notifies the [`AckFrequencyState`] that a packet has been ACKed", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/ack_frequency.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/ack_frequency.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b189583937de4c98c04336b5ccb43c8ac9bc7df0a7c954d326701fa42bd5682f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ack_frequency_received\n\nDocumentation:\nNotifies the [`AckFrequencyState`] that an ACK_FREQUENCY frame was received\n\nUpdates the endpoint's params according to the payload of the ACK_FREQUENCY frame, or\nreturns an error in case the requested `max_ack_delay` is invalid.\n\nReturns `true` if the frame was processed and `false` if it was ignored because of being\nstale.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn ack_frequency_received(\n &mut self,\n frame: &AckFrequency,\n pending_acks: &mut PendingAcks,\n ) -> Result {\n if self\n .last_ack_frequency_frame\n .is_some_and(|highest_sequence_nr| frame.sequence.into_inner() <= highest_sequence_nr)\n {\n return Ok(false);\n }\n\n self.last_ack_frequency_frame = Some(frame.sequence.into_inner());\n\n // Update max_ack_delay\n let max_ack_delay = Duration::from_micros(frame.request_max_ack_delay.into_inner());\n if max_ack_delay < TIMER_GRANULARITY {\n return Err(TransportError::PROTOCOL_VIOLATION(\n \"Requested Max Ack Delay in ACK_FREQUENCY frame is less than min_ack_delay\",\n ));\n }\n self.max_ack_delay = max_ack_delay;\n\n // Update the rest of the params\n pending_acks.set_ack_frequency_params(frame);\n\n Ok(true)\n }\n```"}], "func_name": "ack_frequency_received", "docstring": "Notifies the [`AckFrequencyState`] that an ACK_FREQUENCY frame was received\n\nUpdates the endpoint's params according to the payload of the ACK_FREQUENCY frame, or\nreturns an error in case the requested `max_ack_delay` is invalid.\n\nReturns `true` if the frame was processed and `false` if it was ignored because of being\nstale.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/ack_frequency.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/ack_frequency.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7a59bb421e6a56b6ea4a05dcd1542261d6a62cac7019948356ac5ff7f32b8a8f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: defragment\n\nDocumentation:\nCopy fragmented chunk data to new chunks backed by a single buffer\n\nThis makes sure we're not unnecessarily holding on to many larger allocations.\nWe merge contiguous chunks in the process of doing so.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn defragment(&mut self) {\n let new = BinaryHeap::with_capacity(self.data.len());\n let old = mem::replace(&mut self.data, new);\n let mut buffers = old.into_sorted_vec();\n self.buffered = 0;\n let mut fragmented_buffered = 0;\n let mut offset = 0;\n for chunk in buffers.iter_mut().rev() {\n chunk.try_mark_defragment(offset);\n let size = chunk.bytes.len();\n offset = chunk.offset + size as u64;\n self.buffered += size;\n if !chunk.defragmented {\n fragmented_buffered += size;\n }\n }\n self.allocated = self.buffered;\n let mut buffer = BytesMut::with_capacity(fragmented_buffered);\n let mut offset = 0;\n for chunk in buffers.into_iter().rev() {\n if chunk.defragmented {\n // bytes might be empty after try_mark_defragment\n if !chunk.bytes.is_empty() {\n self.data.push(chunk);\n }\n continue;\n }\n // Overlap is resolved by try_mark_defragment\n if chunk.offset != offset + (buffer.len() as u64) {\n if !buffer.is_empty() {\n self.data\n .push(Buffer::new_defragmented(offset, buffer.split().freeze()));\n }\n offset = chunk.offset;\n }\n buffer.extend_from_slice(&chunk.bytes);\n }\n if !buffer.is_empty() {\n self.data\n .push(Buffer::new_defragmented(offset, buffer.split().freeze()));\n }\n }\n```"}], "func_name": "defragment", "docstring": "Copy fragmented chunk data to new chunks backed by a single buffer\n\nThis makes sure we're not unnecessarily holding on to many larger allocations.\nWe merge contiguous chunks in the process of doing so.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/assembler.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/assembler.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3eb629cd4a071e340bca66b201a895a11d54970650eee509353b60f92ea78efd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_mark_defragment\n\nDocumentation:\nDiscards data before `offset` and flags `self` as defragmented if it has good utilization\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn try_mark_defragment(&mut self, offset: u64) {\n let duplicate = offset.saturating_sub(self.offset) as usize;\n self.offset = self.offset.max(offset);\n if duplicate >= self.bytes.len() {\n // All bytes are duplicate\n self.bytes = Bytes::new();\n self.defragmented = true;\n self.allocation_size = 0;\n return;\n }\n self.bytes.advance(duplicate);\n // Make sure that fragmented buffers with high utilization become defragmented and\n // defragmented buffers remain defragmented\n self.defragmented = self.defragmented || self.bytes.len() * 6 / 5 >= self.allocation_size;\n if self.defragmented {\n // Make sure that defragmented buffers do not contribute to over-allocation\n self.allocation_size = self.bytes.len();\n }\n }\n```"}], "func_name": "try_mark_defragment", "docstring": "Discards data before `offset` and flags `self` as defragmented if it has good utilization", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/assembler.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/assembler.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "afa06495a5a23ee72fa33d85ea165e0faa5f675ee6f3d179538f6efbead7e99f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next_timeout\n\nDocumentation:\nFind the next timestamp when previously issued CID should be retired\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn next_timeout(&mut self) -> Option {\n self.retire_timestamp.front().map(|nc| {\n trace!(\"CID {} will expire at {:?}\", nc.sequence, nc.timestamp);\n nc.timestamp\n })\n }\n```"}], "func_name": "next_timeout", "docstring": "Find the next timestamp when previously issued CID should be retired", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/cid_state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/cid_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c79d5882a3319f83f0f34a6c47af871a620877fb579d0f28c1c7e40cca1fa180"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: track_lifetime\n\nDocumentation:\nTrack the lifetime of issued cids in `retire_timestamp`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn track_lifetime(&mut self, new_cid_seq: u64, now: Instant) {\n let lifetime = match self.cid_lifetime {\n Some(lifetime) => lifetime,\n None => return,\n };\n\n let expire_timestamp = now.checked_add(lifetime);\n let expire_at = match expire_timestamp {\n Some(expire_at) => expire_at,\n None => return,\n };\n\n let last_record = self.retire_timestamp.back_mut();\n if let Some(last) = last_record {\n // Compare the timestamp with the last inserted record\n // Combine into a single batch if timestamp of current cid is same as the last record\n if expire_at == last.timestamp {\n debug_assert!(new_cid_seq > last.sequence);\n last.sequence = new_cid_seq;\n return;\n }\n }\n\n self.retire_timestamp.push_back(CidTimestamp {\n sequence: new_cid_seq,\n timestamp: expire_at,\n });\n }\n```"}], "func_name": "track_lifetime", "docstring": "Track the lifetime of issued cids in `retire_timestamp`", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/cid_state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/cid_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4207ea0de3f85e43cbbca0830db020730884a1c1e9b4418ce083379fbd7ee217"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_cid_timeout\n\nDocumentation:\nUpdate local CID state when previously issued CID is retired\n\nReturn whether a new CID needs to be pushed that notifies remote peer to respond `RETIRE_CONNECTION_ID`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn on_cid_timeout(&mut self) -> bool {\n // Whether the peer hasn't retired all the CIDs we asked it to yet\n let unretired_ids_found =\n (self.prev_retire_seq..self.retire_seq).any(|seq| self.active_seq.contains(&seq));\n\n let current_retire_prior_to = self.retire_seq;\n let next_retire_sequence = self\n .retire_timestamp\n .pop_front()\n .map(|seq| seq.sequence + 1);\n\n // According to RFC:\n // Endpoints SHOULD NOT issue updates of the Retire Prior To field\n // before receiving RETIRE_CONNECTION_ID frames that retire all\n // connection IDs indicated by the previous Retire Prior To value.\n // https://tools.ietf.org/html/draft-ietf-quic-transport-29#section-5.1.2\n if !unretired_ids_found {\n // All Cids are retired, `prev_retire_cid_seq` can be assigned to `retire_cid_seq`\n self.prev_retire_seq = self.retire_seq;\n // Advance `retire_seq` if next cid that needs to be retired exists\n if let Some(next_retire_prior_to) = next_retire_sequence {\n self.retire_seq = next_retire_prior_to;\n }\n }\n\n // Check if retirement of all CIDs that reach their lifetime is still needed\n // According to RFC:\n // An endpoint MUST NOT\n // provide more connection IDs than the peer's limit. An endpoint MAY\n // send connection IDs that temporarily exceed a peer's limit if the\n // NEW_CONNECTION_ID frame also requires the retirement of any excess,\n // by including a sufficiently large value in the Retire Prior To field.\n //\n // If yes (return true), a new CID must be pushed with updated `retire_prior_to` field to remote peer.\n // If no (return false), it means CIDs that reach the end of lifetime have been retired already. Do not push a new CID in order to avoid violating above RFC.\n (current_retire_prior_to..self.retire_seq).any(|seq| self.active_seq.contains(&seq))\n }\n```"}], "func_name": "on_cid_timeout", "docstring": "Update local CID state when previously issued CID is retired\n\nReturn whether a new CID needs to be pushed that notifies remote peer to respond `RETIRE_CONNECTION_ID`", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/cid_state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/cid_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f60eba1430b3303e85fdd2ac6793f2bdcb083c061c6a6c173e8a85bdb1261f14"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_cids\n\nDocumentation:\nUpdate cid state when `NewIdentifiers` event is received\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new_cids(&mut self, ids: &[IssuedCid], now: Instant) {\n // `ids` could be `None` once active_connection_id_limit is set to 1 by peer\n let last_cid = match ids.last() {\n Some(cid) => cid,\n None => return,\n };\n self.issued += ids.len() as u64;\n // Record the timestamp of CID with the largest seq number\n let sequence = last_cid.sequence;\n ids.iter().for_each(|frame| {\n self.active_seq.insert(frame.sequence);\n });\n self.track_lifetime(sequence, now);\n }\n```"}], "func_name": "new_cids", "docstring": "Update cid state when `NewIdentifiers` event is received", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/cid_state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/cid_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb319eb76bc8b5982cdbcd5743f39d3251c9023bdadf5d5144e53279d4773909"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_cid_retirement\n\nDocumentation:\nUpdate CidState for receipt of a `RETIRE_CONNECTION_ID` frame\n\nReturns whether a new CID can be issued, or an error if the frame was illegal.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn on_cid_retirement(\n &mut self,\n sequence: u64,\n limit: u64,\n ) -> Result {\n if self.cid_len == 0 {\n return Err(TransportError::PROTOCOL_VIOLATION(\n \"RETIRE_CONNECTION_ID when CIDs aren't in use\",\n ));\n }\n if sequence > self.issued {\n debug!(\n sequence,\n \"got RETIRE_CONNECTION_ID for unissued sequence number\"\n );\n return Err(TransportError::PROTOCOL_VIOLATION(\n \"RETIRE_CONNECTION_ID for unissued sequence number\",\n ));\n }\n self.active_seq.remove(&sequence);\n // Consider a scenario where peer A has active remote cid 0,1,2.\n // Peer B first send a NEW_CONNECTION_ID with cid 3 and retire_prior_to set to 1.\n // Peer A processes this NEW_CONNECTION_ID frame; update remote cid to 1,2,3\n // and meanwhile send a RETIRE_CONNECTION_ID to retire cid 0 to peer B.\n // If peer B doesn't check the cid limit here and send a new cid again, peer A will then face CONNECTION_ID_LIMIT_ERROR\n Ok(limit > self.active_seq.len() as u64)\n }\n```"}], "func_name": "on_cid_retirement", "docstring": "Update CidState for receipt of a `RETIRE_CONNECTION_ID` frame\n\nReturns whether a new CID can be issued, or an error if the frame was illegal.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/cid_state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/cid_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5eabb740af44b428d6ce09d82a4d15918deb0454cbc6751a9461cb66fd6a677f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_buffer_space\n\nDocumentation:\nBytes available in the outgoing datagram buffer\n\nWhen greater than zero, [`send`](Self::send)ing a datagram of at most this size is\nguaranteed not to cause older datagrams to be dropped.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn send_buffer_space(&self) -> usize {\n self.conn\n .config\n .datagram_send_buffer_size\n .saturating_sub(self.conn.datagrams.outgoing_total)\n }\n```"}], "func_name": "send_buffer_space", "docstring": "Bytes available in the outgoing datagram buffer\n\nWhen greater than zero, [`send`](Self::send)ing a datagram of at most this size is\nguaranteed not to cause older datagrams to be dropped.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/datagrams.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/datagrams.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac29cd6765aaba0823bcb5120147dfa6453ba2095fb8ad35105db9cfc0d0ba10"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: drop_oversized\n\nDocumentation:\nDiscard outgoing datagrams with a payload larger than `max_payload` bytes\n\nUsed to ensure that reductions in MTU don't get us stuck in a state where we have a datagram\nqueued but can't send it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn drop_oversized(&mut self, max_payload: usize) {\n self.outgoing.retain(|datagram| {\n let result = datagram.data.len() < max_payload;\n if !result {\n trace!(\n \"dropping {} byte datagram violating {} byte limit\",\n datagram.data.len(),\n max_payload\n );\n self.outgoing_total -= datagram.data.len();\n }\n result\n });\n }\n```"}], "func_name": "drop_oversized", "docstring": "Discard outgoing datagrams with a payload larger than `max_payload` bytes\n\nUsed to ensure that reductions in MTU don't get us stuck in a state where we have a datagram\nqueued but can't send it.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/datagrams.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/datagrams.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6acdfd47b93a684851a923c59a28b62bec93e4169a4f97bbf1b76e37060c06d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write\n\nDocumentation:\nAttempt to write a datagram frame into `buf`, consuming it from `self.outgoing`\n\nReturns whether a frame was written. At most `max_size` bytes will be written, including\nframing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn write(&mut self, buf: &mut Vec, max_size: usize) -> bool {\n let datagram = match self.outgoing.pop_front() {\n Some(x) => x,\n None => return false,\n };\n\n if buf.len() + datagram.size(true) > max_size {\n // Future work: we could be more clever about cramming small datagrams into\n // mostly-full packets when a larger one is queued first\n self.outgoing.push_front(datagram);\n return false;\n }\n\n trace!(len = datagram.data.len(), \"DATAGRAM\");\n\n self.outgoing_total -= datagram.data.len();\n datagram.encode(true, buf);\n true\n }\n```"}], "func_name": "write", "docstring": "Attempt to write a datagram frame into `buf`, consuming it from `self.outgoing`\n\nReturns whether a frame was written. At most `max_size` bytes will be written, including\nframing.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/datagrams.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/datagrams.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0663c731aa2a1f6b463eea0d3475f0bf3b59f4cee25f93d93bd84306e20f147b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_path_challenge\n\nDocumentation:\nSend PATH_CHALLENGE for a previous path if necessary\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn send_path_challenge(&mut self, now: Instant, buf: &mut Vec) -> Option {\n let (prev_cid, prev_path) = self.prev_path.as_mut()?;\n if !prev_path.challenge_pending {\n return None;\n }\n prev_path.challenge_pending = false;\n let token = prev_path\n .challenge\n .expect(\"previous path challenge pending without token\");\n let destination = prev_path.remote;\n debug_assert_eq!(\n self.highest_space,\n SpaceId::Data,\n \"PATH_CHALLENGE queued without 1-RTT keys\"\n );\n buf.reserve(MIN_INITIAL_SIZE as usize);\n\n let buf_capacity = buf.capacity();\n\n // Use the previous CID to avoid linking the new path with the previous path. We\n // don't bother accounting for possible retirement of that prev_cid because this is\n // sent once, immediately after migration, when the CID is known to be valid. Even\n // if a post-migration packet caused the CID to be retired, it's fair to pretend\n // this is sent first.\n let mut builder = PacketBuilder::new(\n now,\n SpaceId::Data,\n *prev_cid,\n buf,\n buf_capacity,\n 0,\n false,\n self,\n )?;\n trace!(\"validating previous path with PATH_CHALLENGE {:08x}\", token);\n buf.write(frame::FrameType::PATH_CHALLENGE);\n buf.write(token);\n self.stats.frame_tx.path_challenge += 1;\n\n // An endpoint MUST expand datagrams that contain a PATH_CHALLENGE frame\n // to at least the smallest allowed maximum datagram size of 1200 bytes,\n // unless the anti-amplification limit for the path does not permit\n // sending a datagram of this size\n builder.pad_to(MIN_INITIAL_SIZE);\n\n builder.finish(self, buf);\n self.stats.udp_tx.on_sent(1, buf.len());\n\n Some(Transmit {\n destination,\n size: buf.len(),\n ecn: None,\n segment_size: None,\n src_ip: self.local_ip,\n })\n }\n```"}], "func_name": "send_path_challenge", "docstring": "Send PATH_CHALLENGE for a previous path if necessary", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "95eaafa2cf71302fed1c7bd0b1a455bacf8a1a62e19530a8338211cce7fc34ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: space_can_send\n\nDocumentation:\nIndicate what types of frames are ready to send for the given space\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn space_can_send(&self, space_id: SpaceId, frame_space_1rtt: usize) -> SendableFrames {\n if self.spaces[space_id].crypto.is_none()\n && (space_id != SpaceId::Data\n || self.zero_rtt_crypto.is_none()\n || self.side.is_server())\n {\n // No keys available for this space\n return SendableFrames::empty();\n }\n let mut can_send = self.spaces[space_id].can_send(&self.streams);\n if space_id == SpaceId::Data {\n can_send.other |= self.can_send_1rtt(frame_space_1rtt);\n }\n can_send\n }\n```"}], "func_name": "space_can_send", "docstring": "Indicate what types of frames are ready to send for the given space", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a254dd1ddccfba475a025e8c21992b6b943bfadcb4ddbd96cfd9a9e07c6f1a4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_event\n\nDocumentation:\nProcess `ConnectionEvent`s generated by the associated `Endpoint`\n\nWill execute protocol logic upon receipt of a connection event, in turn preparing signals\n(including application `Event`s, `EndpointEvent`s and outgoing datagrams) that should be\nextracted through the relevant methods.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn handle_event(&mut self, event: ConnectionEvent) {\n use ConnectionEventInner::*;\n match event.0 {\n Datagram(DatagramConnectionEvent {\n now,\n remote,\n ecn,\n first_decode,\n remaining,\n }) => {\n // If this packet could initiate a migration and we're a client or a server that\n // forbids migration, drop the datagram. This could be relaxed to heuristically\n // permit NAT-rebinding-like migration.\n if remote != self.path.remote && !self.side.remote_may_migrate() {\n trace!(\"discarding packet from unrecognized peer {}\", remote);\n return;\n }\n\n let was_anti_amplification_blocked = self.path.anti_amplification_blocked(1);\n\n self.stats.udp_rx.datagrams += 1;\n self.stats.udp_rx.bytes += first_decode.len() as u64;\n let data_len = first_decode.len();\n\n self.handle_decode(now, remote, ecn, first_decode);\n // The current `path` might have changed inside `handle_decode`,\n // since the packet could have triggered a migration. Make sure\n // the data received is accounted for the most recent path by accessing\n // `path` after `handle_decode`.\n self.path.total_recvd = self.path.total_recvd.saturating_add(data_len as u64);\n\n if let Some(data) = remaining {\n self.stats.udp_rx.bytes += data.len() as u64;\n self.handle_coalesced(now, remote, ecn, data);\n }\n\n if was_anti_amplification_blocked {\n // A prior attempt to set the loss detection timer may have failed due to\n // anti-amplification, so ensure it's set now. Prevents a handshake deadlock if\n // the server's first flight is lost.\n self.set_loss_detection_timer(now);\n }\n }\n NewIdentifiers(ids, now) => {\n self.local_cid_state.new_cids(&ids, now);\n ids.into_iter().rev().for_each(|frame| {\n self.spaces[SpaceId::Data].pending.new_cids.push(frame);\n });\n // Update Timer::PushNewCid\n if self\n .timers\n .get(Timer::PushNewCid)\n .map_or(true, |x| x <= now)\n {\n self.reset_cid_retirement();\n }\n }\n }\n }\n```"}], "func_name": "handle_event", "docstring": "Process `ConnectionEvent`s generated by the associated `Endpoint`\n\nWill execute protocol logic upon receipt of a connection event, in turn preparing signals\n(including application `Event`s, `EndpointEvent`s and outgoing datagrams) that should be\nextracted through the relevant methods.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f7bfaf4e5fb99f0997cc3c7815fe9bf798195ef2d0b21123f668995cb8937a9a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_timeout\n\nDocumentation:\nProcess timer expirations\n\nExecutes protocol logic, potentially preparing signals (including application `Event`s,\n`EndpointEvent`s and outgoing datagrams) that should be extracted through the relevant\nmethods.\n\nIt is most efficient to call this immediately after the system clock reaches the latest\n`Instant` that was output by `poll_timeout`; however spurious extra calls will simply\nno-op and therefore are safe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn handle_timeout(&mut self, now: Instant) {\n for &timer in &Timer::VALUES {\n if !self.timers.is_expired(timer, now) {\n continue;\n }\n self.timers.stop(timer);\n trace!(timer = ?timer, \"timeout\");\n match timer {\n Timer::Close => {\n self.state = State::Drained;\n self.endpoint_events.push_back(EndpointEventInner::Drained);\n }\n Timer::Idle => {\n self.kill(ConnectionError::TimedOut);\n }\n Timer::KeepAlive => {\n trace!(\"sending keep-alive\");\n self.ping();\n }\n Timer::LossDetection => {\n self.on_loss_detection_timeout(now);\n }\n Timer::KeyDiscard => {\n self.zero_rtt_crypto = None;\n self.prev_crypto = None;\n }\n Timer::PathValidation => {\n debug!(\"path validation failed\");\n if let Some((_, prev)) = self.prev_path.take() {\n self.path = prev;\n }\n self.path.challenge = None;\n self.path.challenge_pending = false;\n }\n Timer::Pacing => trace!(\"pacing timer expired\"),\n Timer::PushNewCid => {\n // Update `retire_prior_to` field in NEW_CONNECTION_ID frame\n let num_new_cid = self.local_cid_state.on_cid_timeout().into();\n if !self.state.is_closed() {\n trace!(\n \"push a new cid to peer RETIRE_PRIOR_TO field {}\",\n self.local_cid_state.retire_prior_to()\n );\n self.endpoint_events\n .push_back(EndpointEventInner::NeedIdentifiers(now, num_new_cid));\n }\n }\n Timer::MaxAckDelay => {\n trace!(\"max ack delay reached\");\n // This timer is only armed in the Data space\n self.spaces[SpaceId::Data]\n .pending_acks\n .on_max_ack_delay_timeout()\n }\n }\n }\n }\n```"}], "func_name": "handle_timeout", "docstring": "Process timer expirations\n\nExecutes protocol logic, potentially preparing signals (including application `Event`s,\n`EndpointEvent`s and outgoing datagrams) that should be extracted through the relevant\nmethods.\n\nIt is most efficient to call this immediately after the system clock reaches the latest\n`Instant` that was output by `poll_timeout`; however spurious extra calls will simply\nno-op and therefore are safe.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0dc18853e041633fd9efe4a50bc5652e096edab67d8d535766b9b78fc117607"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: close\n\nDocumentation:\nClose a connection immediately\n\nThis does not ensure delivery of outstanding data. It is the application's responsibility to\ncall this only when all important communications have been completed, e.g. by calling\n[`SendStream::finish`] on outstanding streams and waiting for the corresponding\n[`StreamEvent::Finished`] event.\n\nIf [`Streams::send_streams`] returns 0, all outstanding stream data has been\ndelivered. There may still be data from the peer that has not been received.\n\n[`StreamEvent::Finished`]: crate::StreamEvent::Finished\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn close(&mut self, now: Instant, error_code: VarInt, reason: Bytes) {\n self.close_inner(\n now,\n Close::Application(frame::ApplicationClose { error_code, reason }),\n )\n }\n```"}], "func_name": "close", "docstring": "Close a connection immediately\n\nThis does not ensure delivery of outstanding data. It is the application's responsibility to\ncall this only when all important communications have been completed, e.g. by calling\n[`SendStream::finish`] on outstanding streams and waiting for the corresponding\n[`StreamEvent::Finished`] event.\n\nIf [`Streams::send_streams`] returns 0, all outstanding stream data has been\ndelivered. There may still be data from the peer that has not been received.\n\n[`StreamEvent::Finished`]: crate::StreamEvent::Finished", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f043a356cecf34ad5d3788d5cbdcc0a572eecdad8770db7a10f9b35f0f85eaa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: force_key_update\n\nDocumentation:\nUpdate traffic keys spontaneously\n\nThis can be useful for testing key updates, as they otherwise only happen infrequently.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn force_key_update(&mut self) {\n self.update_keys(None, false);\n }\n```"}], "func_name": "force_key_update", "docstring": "Update traffic keys spontaneously\n\nThis can be useful for testing key updates, as they otherwise only happen infrequently.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "33b11c816695096604a493eaf8e122f3611cc3b17edc5196e940df32d3331814"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: path_changed\n\nDocumentation:\nResets path-specific settings.\n\nThis will force-reset several subsystems related to a specific network path.\nCurrently this is the congestion controller, round-trip estimator, and the MTU\ndiscovery.\n\nThis is useful when it is known the underlying network path has changed and the old\nstate of these subsystems is no longer valid or optimal. In this case it might be\nfaster or reduce loss to settle on optimal values by restarting from the initial\nconfiguration in the [`TransportConfig`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn path_changed(&mut self, now: Instant) {\n self.path.reset(now, &self.config);\n }\n```"}], "func_name": "path_changed", "docstring": "Resets path-specific settings.\n\nThis will force-reset several subsystems related to a specific network path.\nCurrently this is the congestion controller, round-trip estimator, and the MTU\ndiscovery.\n\nThis is useful when it is known the underlying network path has changed and the old\nstate of these subsystems is no longer valid or optimal. In this case it might be\nfaster or reduce loss to settle on optimal values by restarting from the initial\nconfiguration in the [`TransportConfig`].", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "669b1526839f1b41fea1b25906d48935e650f9562d441aec0ea5ff69733aab7b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_max_concurrent_streams\n\nDocumentation:\nModify the number of remotely initiated streams that may be concurrently open\n\nNo streams may be opened by the peer unless fewer than `count` are already open. Large\n`count`s increase both minimum and worst-case memory consumption.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_max_concurrent_streams(&mut self, dir: Dir, count: VarInt) {\n self.streams.set_max_concurrent(dir, count);\n // If the limit was reduced, then a flow control update previously deemed insignificant may\n // now be significant.\n let pending = &mut self.spaces[SpaceId::Data].pending;\n self.streams.queue_max_stream_id(pending);\n }\n```"}], "func_name": "set_max_concurrent_streams", "docstring": "Modify the number of remotely initiated streams that may be concurrently open\n\nNo streams may be opened by the peer unless fewer than `count` are already open. Large\n`count`s increase both minimum and worst-case memory consumption.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8a3b2c9e0089f3f7319032ae34575266c6191a7fb1c6c320cc9bf497328a1c1e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_ecn\n\nDocumentation:\nProcess a new ECN block from an in-order ACK\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_ecn(\n &mut self,\n now: Instant,\n space: SpaceId,\n newly_acked: u64,\n ecn: frame::EcnCounts,\n largest_sent_time: Instant,\n ) {\n match self.spaces[space].detect_ecn(newly_acked, ecn) {\n Err(e) => {\n debug!(\"halting ECN due to verification failure: {}\", e);\n self.path.sending_ecn = false;\n // Wipe out the existing value because it might be garbage and could interfere with\n // future attempts to use ECN on new paths.\n self.spaces[space].ecn_feedback = frame::EcnCounts::ZERO;\n }\n Ok(false) => {}\n Ok(true) => {\n self.stats.path.congestion_events += 1;\n self.path\n .congestion\n .on_congestion_event(now, largest_sent_time, false, 0);\n }\n }\n }\n```"}], "func_name": "process_ecn", "docstring": "Process a new ECN block from an in-order ACK", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d80caf08bfd8f5e510763f819e9f5888b25727749ee0b3a22524c1cdeaf96508"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: disabled\n\nDocumentation:\nMTU discovery will be disabled and the current MTU will be fixed to the provided value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn disabled(plpmtu: u16, min_mtu: u16) -> Self {\n Self::with_state(plpmtu, min_mtu, None)\n }\n```"}], "func_name": "disabled", "docstring": "MTU discovery will be disabled and the current MTU will be fixed to the provided value", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8a04f887eeb9cbd36f4148128b1b472f9e40c7c97c1d0217bb2495fbc6c182de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: poll_transmit\n\nDocumentation:\nReturns the amount of bytes that should be sent as an MTU probe, if any\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn poll_transmit(&mut self, now: Instant, next_pn: u64) -> Option {\n self.state\n .as_mut()\n .and_then(|state| state.poll_transmit(now, self.current_mtu, next_pn))\n }\n```"}], "func_name": "poll_transmit", "docstring": "Returns the amount of bytes that should be sent as an MTU probe, if any", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e1a3ee24bbaa7f97f4e890c8d0adb0df06774d9e50d62aa5885b0a20af13f84a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_peer_max_udp_payload_size_received\n\nDocumentation:\nNotifies the [`MtuDiscovery`] that the peer's `max_udp_payload_size` transport parameter has\nbeen received\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn on_peer_max_udp_payload_size_received(&mut self, peer_max_udp_payload_size: u16) {\n self.current_mtu = self.current_mtu.min(peer_max_udp_payload_size);\n\n if let Some(state) = self.state.as_mut() {\n // MTUD is only active after the connection has been fully established, so it is\n // guaranteed we will receive the peer's transport parameters before we start probing\n debug_assert!(matches!(state.phase, Phase::Initial));\n state.peer_max_udp_payload_size = peer_max_udp_payload_size;\n }\n }\n```"}], "func_name": "on_peer_max_udp_payload_size_received", "docstring": "Notifies the [`MtuDiscovery`] that the peer's `max_udp_payload_size` transport parameter has\nbeen received", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f35ebd8e27437edaf6b2cfd1700ea333ecde82c864a09b035ffe49854d1849d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_acked\n\nDocumentation:\nNotifies the [`MtuDiscovery`] that a packet has been ACKed\n\nReturns true if the packet was an MTU probe\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn on_acked(&mut self, space: SpaceId, pn: u64, len: u16) -> bool {\n // MTU probes are only sent in application data space\n if space != SpaceId::Data {\n return false;\n }\n\n // Update the state of the MTU search\n if let Some(new_mtu) = self\n .state\n .as_mut()\n .and_then(|state| state.on_probe_acked(pn))\n {\n self.current_mtu = new_mtu;\n trace!(current_mtu = self.current_mtu, \"new MTU detected\");\n\n self.black_hole_detector.on_probe_acked(pn, len);\n true\n } else {\n self.black_hole_detector.on_non_probe_acked(pn, len);\n false\n }\n }\n```"}], "func_name": "on_acked", "docstring": "Notifies the [`MtuDiscovery`] that a packet has been ACKed\n\nReturns true if the packet was an MTU probe", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0998d2ddf3a106196560b87054218f2fda1d951b96521042b165daf26670585a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: in_flight_mtu_probe\n\nDocumentation:\nReturns the packet number of the in-flight MTU probe, if any\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn in_flight_mtu_probe(&self) -> Option {\n match &self.state {\n Some(EnabledMtuDiscovery {\n phase: Phase::Searching(search_state),\n ..\n }) => search_state.in_flight_probe,\n _ => None,\n }\n }\n```"}], "func_name": "in_flight_mtu_probe", "docstring": "Returns the packet number of the in-flight MTU probe, if any", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c3f8d3a2d4338869f5a9a726a05170a48dc1a41b57006d7789e06d00d6de993c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_probe_lost\n\nDocumentation:\nNotifies the [`MtuDiscovery`] that the in-flight MTU probe was lost\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn on_probe_lost(&mut self) {\n if let Some(state) = &mut self.state {\n state.on_probe_lost();\n }\n }\n```"}], "func_name": "on_probe_lost", "docstring": "Notifies the [`MtuDiscovery`] that the in-flight MTU probe was lost", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8266485bdab78a857184b6f3a252fa2b05cb47de738960e4c09b6e16022bdb8a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_non_probe_lost\n\nDocumentation:\nNotifies the [`MtuDiscovery`] that a non-probe packet was lost\n\nWhen done notifying of lost packets, [`MtuDiscovery::black_hole_detected`] must be called, to\nensure the last loss burst is properly processed and to trigger black hole recovery logic if\nnecessary.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn on_non_probe_lost(&mut self, pn: u64, len: u16) {\n self.black_hole_detector.on_non_probe_lost(pn, len);\n }\n```"}], "func_name": "on_non_probe_lost", "docstring": "Notifies the [`MtuDiscovery`] that a non-probe packet was lost\n\nWhen done notifying of lost packets, [`MtuDiscovery::black_hole_detected`] must be called, to\nensure the last loss burst is properly processed and to trigger black hole recovery logic if\nnecessary.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "148f6ee295312f8c8208baa0c68928ec9587f85f00cda90c4c9dcf9959a77599"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: black_hole_detected\n\nDocumentation:\nReturns true if a black hole was detected\n\nCalling this function will close the previous loss burst. If a black hole is detected, the\ncurrent MTU will be reset to `min_mtu`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn black_hole_detected(&mut self, now: Instant) -> bool {\n if !self.black_hole_detector.black_hole_detected() {\n return false;\n }\n\n self.current_mtu = self.black_hole_detector.min_mtu;\n\n if let Some(state) = &mut self.state {\n state.on_black_hole_detected(now);\n }\n\n true\n }\n```"}], "func_name": "black_hole_detected", "docstring": "Returns true if a black hole was detected\n\nCalling this function will close the previous loss burst. If a black hole is detected, the\ncurrent MTU will be reset to `min_mtu`.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7134218cc9b680a1f6fec710f6fab33e9574913e23d2bc4dc146d6e744d755bc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_probe_acked\n\nDocumentation:\nCalled when a packet is acknowledged in [`SpaceId::Data`]\n\nReturns the new `current_mtu` if the packet number corresponds to the in-flight MTU probe\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn on_probe_acked(&mut self, pn: u64) -> Option {\n match &mut self.phase {\n Phase::Searching(state) if state.in_flight_probe == Some(pn) => {\n state.in_flight_probe = None;\n state.lost_probe_count = 0;\n Some(state.last_probed_mtu)\n }\n _ => None,\n }\n }\n```"}], "func_name": "on_probe_acked", "docstring": "Called when a packet is acknowledged in [`SpaceId::Data`]\n\nReturns the new `current_mtu` if the packet number corresponds to the in-flight MTU probe", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "340f7c35ee40f9332460d551161dc86adb2c0d737593b77b3a0f4d867774659e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_probe_lost\n\nDocumentation:\nCalled when the in-flight MTU probe was lost\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn on_probe_lost(&mut self) {\n // We might no longer be searching, e.g. if a black hole was detected\n if let Phase::Searching(state) = &mut self.phase {\n state.in_flight_probe = None;\n state.lost_probe_count += 1;\n }\n }\n```"}], "func_name": "on_probe_lost", "docstring": "Called when the in-flight MTU probe was lost", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b7dd6c963025633b90e8c066f2ebef24f6d817b28eea85b9b2fbe99e171b19ae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_black_hole_detected\n\nDocumentation:\nCalled when a black hole is detected\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn on_black_hole_detected(&mut self, now: Instant) {\n // Stop searching, if applicable, and reset the timer\n let next_mtud_activation = now + self.config.black_hole_cooldown;\n self.phase = Phase::Complete(next_mtud_activation);\n }\n```"}], "func_name": "on_black_hole_detected", "docstring": "Called when a black hole is detected", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d9eff2dbe863468b450701d4732dfaece239c60da14513c08de922af5d4a1266"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new search state, with the specified lower bound (the upper bound is derived from\nthe config and the peer's `max_udp_payload_size` transport parameter)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(\n mut lower_bound: u16,\n peer_max_udp_payload_size: u16,\n config: &MtuDiscoveryConfig,\n ) -> Self {\n lower_bound = lower_bound.min(peer_max_udp_payload_size);\n let upper_bound = config\n .upper_bound\n .clamp(lower_bound, peer_max_udp_payload_size);\n\n Self {\n in_flight_probe: None,\n lost_probe_count: 0,\n lower_bound,\n upper_bound,\n minimum_change: config.minimum_change,\n // During initialization, we consider the lower bound to have already been\n // successfully probed\n last_probed_mtu: lower_bound,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new search state, with the specified lower bound (the upper bound is derived from\nthe config and the peer's `max_udp_payload_size` transport parameter)", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "15012fcca8f59db242806c7a2b0318539468d933877242b623350f009d25d22d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next_mtu_to_probe\n\nDocumentation:\nDetermines the next MTU to probe using binary search\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn next_mtu_to_probe(&mut self, last_probe_succeeded: bool) -> Option {\n debug_assert_eq!(self.in_flight_probe, None);\n\n if last_probe_succeeded {\n self.lower_bound = self.last_probed_mtu;\n } else {\n self.upper_bound = self.last_probed_mtu - 1;\n }\n\n let next_mtu = (self.lower_bound as i32 + self.upper_bound as i32) / 2;\n\n // Binary search stopping condition\n if ((next_mtu - self.last_probed_mtu as i32).unsigned_abs() as u16) < self.minimum_change {\n // Special case: if the upper bound is far enough, we want to probe it as a last\n // step (otherwise we will never achieve the upper bound)\n if self.upper_bound.saturating_sub(self.last_probed_mtu) >= self.minimum_change {\n return Some(self.upper_bound);\n }\n\n return None;\n }\n\n Some(next_mtu as u16)\n }\n```"}], "func_name": "next_mtu_to_probe", "docstring": "Determines the next MTU to probe using binary search", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4cb624f3dda82724817d162de35f79751e05e9fc177d0ccf4632a1873e3daa26"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish_loss_burst\n\nDocumentation:\nMarks the end of the current loss burst, checking whether it was suspicious\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn finish_loss_burst(&mut self) {\n let Some(burst) = self.current_loss_burst.take() else {\n return;\n };\n // If a loss burst contains a packet smaller than the minimum MTU or a more recently\n // transmitted packet, it is not suspicious.\n if burst.smallest_packet_size < self.min_mtu\n || (burst.latest_non_probe < self.largest_post_loss_packet\n && burst.smallest_packet_size < self.acked_mtu)\n {\n return;\n }\n // The loss burst is now deemed suspicious.\n\n // A suspicious loss burst more recent than `largest_post_loss_packet` invalidates it. This\n // makes `acked_mtu` a conservative approximation. Ideally we'd update `safe_mtu` and\n // `largest_post_loss_packet` to describe the largest acknowledged packet sent later than\n // this burst, but that would require tracking the size of an unpredictable number of\n // recently acknowledged packets, and erring on the side of false positives is safe.\n if burst.latest_non_probe > self.largest_post_loss_packet {\n self.acked_mtu = self.min_mtu;\n }\n\n let burst = LossBurst {\n smallest_packet_size: burst.smallest_packet_size,\n };\n\n if self.suspicious_loss_bursts.len() <= BLACK_HOLE_THRESHOLD {\n self.suspicious_loss_bursts.push(burst);\n return;\n }\n\n // To limit memory use, only track the most suspicious loss bursts.\n let smallest = self\n .suspicious_loss_bursts\n .iter_mut()\n .min_by_key(|prev| prev.smallest_packet_size)\n .filter(|prev| prev.smallest_packet_size < burst.smallest_packet_size);\n if let Some(smallest) = smallest {\n *smallest = burst;\n }\n }\n```"}], "func_name": "finish_loss_burst", "docstring": "Marks the end of the current loss burst, checking whether it was suspicious", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "76c47da06def55fc1a623e9a04b31b4cf29e991d3884f7c6fbeddddf6139dd7f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: drive_to_completion\n\nDocumentation:\nDrives mtud until it reaches `Phase::Completed`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn drive_to_completion(\n mtud: &mut MtuDiscovery,\n now: Instant,\n link_payload_size_limit: u16,\n ) -> Vec {\n let mut probed_sizes = Vec::new();\n for probe_pn in 1..100 {\n let result = mtud.poll_transmit(now, probe_pn);\n\n if completed(mtud) {\n break;\n }\n\n // \"Send\" next probe\n assert!(result.is_some());\n let probe_size = result.unwrap();\n probed_sizes.push(probe_size);\n\n if probe_size <= link_payload_size_limit {\n mtud.on_acked(SpaceId::Data, probe_pn, probe_size);\n } else {\n mtud.on_probe_lost();\n }\n }\n probed_sizes\n }\n```"}], "func_name": "drive_to_completion", "docstring": "Drives mtud until it reaches `Phase::Completed`", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/mtud.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/mtud.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d0d439b1bb2919a37c3c6d6ace75c2d9548d657a126d8c422565692be1e7d5b8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delay\n\nDocumentation:\nReturn how long we need to wait before sending `bytes_to_send`\n\nIf we can send a packet right away, this returns `None`. Otherwise, returns `Some(d)`,\nwhere `d` is the time before this function should be called again.\n\nThe 5/4 ratio used here comes from the suggestion that N = 1.25 in the draft IETF RFC for\nQUIC.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn delay(\n &mut self,\n smoothed_rtt: Duration,\n bytes_to_send: u64,\n mtu: u16,\n window: u64,\n now: Instant,\n ) -> Option {\n debug_assert_ne!(\n window, 0,\n \"zero-sized congestion control window is nonsense\"\n );\n\n if window != self.last_window || mtu != self.last_mtu {\n self.capacity = optimal_capacity(smoothed_rtt, window, mtu);\n\n // Clamp the tokens\n self.tokens = self.capacity.min(self.tokens);\n self.last_window = window;\n self.last_mtu = mtu;\n }\n\n // if we can already send a packet, there is no need for delay\n if self.tokens >= bytes_to_send {\n return None;\n }\n\n // we disable pacing for extremely large windows\n if window > u64::from(u32::MAX) {\n return None;\n }\n\n let window = window as u32;\n\n let time_elapsed = now.checked_duration_since(self.prev).unwrap_or_else(|| {\n warn!(\"received a timestamp early than a previous recorded time, ignoring\");\n Default::default()\n });\n\n if smoothed_rtt.as_nanos() == 0 {\n return None;\n }\n\n let elapsed_rtts = time_elapsed.as_secs_f64() / smoothed_rtt.as_secs_f64();\n let new_tokens = window as f64 * 1.25 * elapsed_rtts;\n self.tokens = self\n .tokens\n .saturating_add(new_tokens as _)\n .min(self.capacity);\n\n self.prev = now;\n\n // if we can already send a packet, there is no need for delay\n if self.tokens >= bytes_to_send {\n return None;\n }\n\n let unscaled_delay = smoothed_rtt\n .checked_mul((bytes_to_send.max(self.capacity) - self.tokens) as _)\n .unwrap_or(Duration::MAX)\n / window;\n\n // divisions come before multiplications to prevent overflow\n // this is the time at which the pacing window becomes empty\n Some(self.prev + (unscaled_delay / 5) * 4)\n }\n```"}], "func_name": "delay", "docstring": "Return how long we need to wait before sending `bytes_to_send`\n\nIf we can send a packet right away, this returns `None`. Otherwise, returns `Some(d)`,\nwhere `d` is the time before this function should be called again.\n\nThe 5/4 ratio used here comes from the suggestion that N = 1.25 in the draft IETF RFC for\nQUIC.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/pacing.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/pacing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3c021a21e3818f9ea7dee72efb5ce24e203f91796a000d0194ee157ae064c958"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pad_to\n\nDocumentation:\nAppend the minimum amount of padding to the packet such that, after encryption, the\nenclosing datagram will occupy at least `min_size` bytes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn pad_to(&mut self, min_size: u16) {\n // The datagram might already have a larger minimum size than the caller is requesting, if\n // e.g. we're coalescing packets and have populated more than `min_size` bytes with packets\n // already.\n self.min_size = Ord::max(\n self.min_size,\n self.datagram_start + (min_size as usize) - self.tag_len,\n );\n }\n```"}], "func_name": "pad_to", "docstring": "Append the minimum amount of padding to the packet such that, after encryption, the\nenclosing datagram will occupy at least `min_size` bytes", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/packet_builder.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/packet_builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c45748092fe461e22a118b8a2f2d1bdf1edd448c18f9e359fcd1736b3f1daa1a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish\n\nDocumentation:\nEncrypt packet, returning the length of the packet and whether padding was added\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn finish(self, conn: &mut Connection, buffer: &mut Vec) -> (usize, bool) {\n let pad = buffer.len() < self.min_size;\n if pad {\n trace!(\"PADDING * {}\", self.min_size - buffer.len());\n buffer.resize(self.min_size, 0);\n }\n\n let space = &conn.spaces[self.space];\n let (header_crypto, packet_crypto) = if let Some(ref crypto) = space.crypto {\n (&*crypto.header.local, &*crypto.packet.local)\n } else if self.space == SpaceId::Data {\n let zero_rtt = conn.zero_rtt_crypto.as_ref().unwrap();\n (&*zero_rtt.header, &*zero_rtt.packet)\n } else {\n unreachable!(\"tried to send {:?} packet without keys\", self.space);\n };\n\n debug_assert_eq!(\n packet_crypto.tag_len(),\n self.tag_len,\n \"Mismatching crypto tag len\"\n );\n\n buffer.resize(buffer.len() + packet_crypto.tag_len(), 0);\n let encode_start = self.partial_encode.start;\n let packet_buf = &mut buffer[encode_start..];\n self.partial_encode.finish(\n packet_buf,\n header_crypto,\n Some((self.exact_number, packet_crypto)),\n );\n\n (buffer.len() - encode_start, pad)\n }\n```"}], "func_name": "finish", "docstring": "Encrypt packet, returning the length of the packet and whether padding was added", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/packet_builder.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/packet_builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94f9b62895f85a2b532baf0eb4e8fcd683e88290baca168a1fc9c2e22ff3d71d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unprotect_header\n\nDocumentation:\nRemoves header protection of a packet, or returns `None` if the packet was dropped\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn unprotect_header(\n partial_decode: PartialDecode,\n spaces: &[PacketSpace; 3],\n zero_rtt_crypto: Option<&ZeroRttCrypto>,\n stateless_reset_token: Option,\n) -> Option {\n let header_crypto = if partial_decode.is_0rtt() {\n if let Some(crypto) = zero_rtt_crypto {\n Some(&*crypto.header)\n } else {\n debug!(\"dropping unexpected 0-RTT packet\");\n return None;\n }\n } else if let Some(space) = partial_decode.space() {\n if let Some(ref crypto) = spaces[space].crypto {\n Some(&*crypto.header.remote)\n } else {\n debug!(\n \"discarding unexpected {:?} packet ({} bytes)\",\n space,\n partial_decode.len(),\n );\n return None;\n }\n } else {\n // Unprotected packet\n None\n };\n\n let packet = partial_decode.data();\n let stateless_reset = packet.len() >= RESET_TOKEN_SIZE + 5\n && stateless_reset_token.as_deref() == Some(&packet[packet.len() - RESET_TOKEN_SIZE..]);\n\n match partial_decode.finish(header_crypto) {\n Ok(packet) => Some(UnprotectHeaderResult {\n packet: Some(packet),\n stateless_reset,\n }),\n Err(_) if stateless_reset => Some(UnprotectHeaderResult {\n packet: None,\n stateless_reset: true,\n }),\n Err(e) => {\n trace!(\"unable to complete packet decoding: {}\", e);\n None\n }\n }\n}\n```"}], "func_name": "unprotect_header", "docstring": "Removes header protection of a packet, or returns `None` if the packet was dropped", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/packet_crypto.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/packet_crypto.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5740d1420212c03db467e3b34cc387eea9413b243f522ff37a1a7f2b9d91a3c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset\n\nDocumentation:\nResets RTT, congestion control and MTU states.\n\nThis is useful when it is known the underlying path has changed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn reset(&mut self, now: Instant, config: &TransportConfig) {\n self.rtt = RttEstimator::new(config.initial_rtt);\n self.congestion = config\n .congestion_controller_factory\n .clone()\n .build(now, config.get_initial_mtu());\n self.mtud.reset(config.get_initial_mtu(), config.min_mtu);\n }\n```"}], "func_name": "reset", "docstring": "Resets RTT, congestion control and MTU states.\n\nThis is useful when it is known the underlying path has changed.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/paths.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/paths.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ff6b3beccdc1ef5bdf98947e634568f07af49fa53d42da61524d01ca19f779ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sent\n\nDocumentation:\nAccount for transmission of `packet` with number `pn` in `space`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn sent(&mut self, pn: u64, packet: SentPacket, space: &mut PacketSpace) {\n self.in_flight.insert(&packet);\n if self.first_packet.is_none() {\n self.first_packet = Some(pn);\n }\n self.in_flight.bytes -= space.sent(pn, packet);\n }\n```"}], "func_name": "sent", "docstring": "Account for transmission of `packet` with number `pn` in `space`", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/paths.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/paths.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "05024a4913aac8c88fe1a239455ddee189fe6555fec11330070eba935b48538e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_in_flight\n\nDocumentation:\nRemove `packet` with number `pn` from this path's congestion control counters, or return\n`false` if `pn` was sent before this path was established.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn remove_in_flight(&mut self, pn: u64, packet: &SentPacket) -> bool {\n if self.first_packet.map_or(true, |first| first > pn) {\n return false;\n }\n self.in_flight.remove(packet);\n true\n }\n```"}], "func_name": "remove_in_flight", "docstring": "Remove `packet` with number `pn` from this path's congestion control counters, or return\n`false` if `pn` was sent before this path was established.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/paths.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/paths.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82a454b80de7321f47448c1a61963676db88b3c20caabeda49a84630d961d09b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove\n\nDocumentation:\nUpdate counters to account for a packet becoming acknowledged, lost, or abandoned\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn remove(&mut self, packet: &SentPacket) {\n self.bytes -= u64::from(packet.size);\n self.ack_eliciting -= u64::from(packet.ack_eliciting);\n }\n```"}], "func_name": "remove", "docstring": "Update counters to account for a packet becoming acknowledged, lost, or abandoned", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/paths.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/paths.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ab37dfdf0844a0d934285461946ff6ffd92f32a5928f59824b964c12c154f911"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write\n\nDocumentation:\nAppend application data to the end of the stream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn write(&mut self, data: Bytes) {\n self.unacked_len += data.len();\n self.offset += data.len() as u64;\n self.unacked_segments.push_back(data);\n }\n```"}], "func_name": "write", "docstring": "Append application data to the end of the stream", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/send_buffer.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/send_buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "342bdfef9c5cd5937b040570c7e24e4bab01f6017ecbb0da5f901e36854b04e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ack\n\nDocumentation:\nDiscard a range of acknowledged stream data\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn ack(&mut self, mut range: Range) {\n // Clamp the range to data which is still tracked\n let base_offset = self.offset - self.unacked_len as u64;\n range.start = base_offset.max(range.start);\n range.end = base_offset.max(range.end);\n\n self.acks.insert(range);\n\n while self.acks.min() == Some(self.offset - self.unacked_len as u64) {\n let prefix = self.acks.pop_min().unwrap();\n let mut to_advance = (prefix.end - prefix.start) as usize;\n\n self.unacked_len -= to_advance;\n while to_advance > 0 {\n let front = self\n .unacked_segments\n .front_mut()\n .expect(\"Expected buffered data\");\n\n if front.len() <= to_advance {\n to_advance -= front.len();\n self.unacked_segments.pop_front();\n\n if self.unacked_segments.len() * 4 < self.unacked_segments.capacity() {\n self.unacked_segments.shrink_to_fit();\n }\n } else {\n front.advance(to_advance);\n to_advance = 0;\n }\n }\n }\n }\n```"}], "func_name": "ack", "docstring": "Discard a range of acknowledged stream data", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/send_buffer.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/send_buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17773647ea96d99857ecf452a1d33d350d28146c918667b6aa26c188d66664c9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturns data which is associated with a range\n\nThis function can return a subset of the range, if the data is stored\nin noncontiguous fashion in the send buffer. In this case callers\nshould call the function again with an incremented start offset to\nretrieve more data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn get(&self, offsets: Range) -> &[u8] {\n let base_offset = self.offset - self.unacked_len as u64;\n\n let mut segment_offset = base_offset;\n for segment in self.unacked_segments.iter() {\n if offsets.start >= segment_offset\n && offsets.start < segment_offset + segment.len() as u64\n {\n let start = (offsets.start - segment_offset) as usize;\n let end = (offsets.end - segment_offset) as usize;\n\n return &segment[start..end.min(segment.len())];\n }\n segment_offset += segment.len() as u64;\n }\n\n &[]\n }\n```"}], "func_name": "get", "docstring": "Returns data which is associated with a range\n\nThis function can return a subset of the range, if the data is stored\nin noncontiguous fashion in the send buffer. In this case callers\nshould call the function again with an incremented start offset to\nretrieve more data.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/send_buffer.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/send_buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6d3efe0a91e90bedb0137a560c290b8457de9f6e4b3a48f6ef7fe1b63298642b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_fully_acked\n\nDocumentation:\nWhether all sent data has been acknowledged\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn is_fully_acked(&self) -> bool {\n self.unacked_len == 0\n }\n```"}], "func_name": "is_fully_acked", "docstring": "Whether all sent data has been acknowledged", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/send_buffer.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/send_buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3d22d874fc7be80d1b70f680a2a0aa8e92ed6cdf89599549f365e17ee5d028c0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_unsent_data\n\nDocumentation:\nWhether there's data to send\n\nThere may be sent unacknowledged data even when this is false.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn has_unsent_data(&self) -> bool {\n self.unsent != self.offset || !self.retransmits.is_empty()\n }\n```"}], "func_name": "has_unsent_data", "docstring": "Whether there's data to send\n\nThere may be sent unacknowledged data even when this is false.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/send_buffer.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/send_buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "89d703755d92dc74aef86344baf66610077b3dcd8cd05bf66e70a958fcc22f77"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unacked\n\nDocumentation:\nCompute the amount of data that hasn't been acknowledged\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn unacked(&self) -> u64 {\n self.unacked_len as u64 - self.acks.iter().map(|x| x.end - x.start).sum::()\n }\n```"}], "func_name": "unacked", "docstring": "Compute the amount of data that hasn't been acknowledged", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/send_buffer.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/send_buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "da2de80aa9c5769da368c491e406621f24af0fcec9086c26fe9ad7835e8dda27"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_tx_number\n\nDocumentation:\nGet the next outgoing packet number in this space\n\nIn the Data space, the connection's [`PacketNumberFilter`] must be used rather than calling\nthis directly.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn get_tx_number(&mut self) -> u64 {\n // TODO: Handle packet number overflow gracefully\n assert!(self.next_packet_number < 2u64.pow(62));\n let x = self.next_packet_number;\n self.next_packet_number += 1;\n self.sent_with_keys += 1;\n x\n }\n```"}], "func_name": "get_tx_number", "docstring": "Get the next outgoing packet number in this space\n\nIn the Data space, the connection's [`PacketNumberFilter`] must be used rather than calling\nthis directly.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "919357d58e78dcb416eaedd419cfbaae18f5f6643916bf4d91bdaea799e7a35c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: detect_ecn\n\nDocumentation:\nVerifies sanity of an ECN block and returns whether congestion was encountered.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn detect_ecn(\n &mut self,\n newly_acked: u64,\n ecn: frame::EcnCounts,\n ) -> Result {\n let ect0_increase = ecn\n .ect0\n .checked_sub(self.ecn_feedback.ect0)\n .ok_or(\"peer ECT(0) count regression\")?;\n let ect1_increase = ecn\n .ect1\n .checked_sub(self.ecn_feedback.ect1)\n .ok_or(\"peer ECT(1) count regression\")?;\n let ce_increase = ecn\n .ce\n .checked_sub(self.ecn_feedback.ce)\n .ok_or(\"peer CE count regression\")?;\n let total_increase = ect0_increase + ect1_increase + ce_increase;\n if total_increase < newly_acked {\n return Err(\"ECN bleaching\");\n }\n if (ect0_increase + ce_increase) < newly_acked || ect1_increase != 0 {\n return Err(\"ECN corruption\");\n }\n // If total_increase > newly_acked (which happens when ACKs are lost), this is required by\n // the draft so that long-term drift does not occur. If =, then the only question is whether\n // to count CE packets as CE or ECT0. Recording them as CE is more consistent and keeps the\n // congestion check obvious.\n self.ecn_feedback = ecn;\n Ok(ce_increase != 0)\n }\n```"}], "func_name": "detect_ecn", "docstring": "Verifies sanity of an ECN block and returns whether congestion was encountered.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c17e5b5f6e6c8466e67177c0e786bd55ece670178759291d28dc9ed4f46673d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: take\n\nDocumentation:\nStop tracking sent packet `number`, and return what we knew about it\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn take(&mut self, number: u64) -> Option {\n let packet = self.sent_packets.remove(&number)?;\n self.in_flight -= u64::from(packet.size);\n if !packet.ack_eliciting && number > self.largest_ack_eliciting_sent {\n self.unacked_non_ack_eliciting_tail =\n self.unacked_non_ack_eliciting_tail.checked_sub(1).unwrap();\n }\n Some(packet)\n }\n```"}], "func_name": "take", "docstring": "Stop tracking sent packet `number`, and return what we knew about it", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0f5a5e39838a40bf262a14e64cbeb122a379d7e1540ae614510e27656be11ca1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sent\n\nDocumentation:\nReturns the number of bytes to *remove* from the connection's in-flight count\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn sent(&mut self, number: u64, packet: SentPacket) -> u64 {\n // Retain state for at most this many non-ACK-eliciting packets sent after the most recently\n // sent ACK-eliciting packet. We're never guaranteed to receive an ACK for those, and we\n // can't judge them as lost without an ACK, so to limit memory in applications which receive\n // packets but don't send ACK-eliciting data for long periods use we must eventually start\n // forgetting about them, although it might also be reasonable to just kill the connection\n // due to weird peer behavior.\n const MAX_UNACKED_NON_ACK_ELICTING_TAIL: u64 = 1_000;\n\n let mut forgotten_bytes = 0;\n if packet.ack_eliciting {\n self.unacked_non_ack_eliciting_tail = 0;\n self.largest_ack_eliciting_sent = number;\n } else if self.unacked_non_ack_eliciting_tail > MAX_UNACKED_NON_ACK_ELICTING_TAIL {\n let oldest_after_ack_eliciting = *self\n .sent_packets\n .range((\n Bound::Excluded(self.largest_ack_eliciting_sent),\n Bound::Unbounded,\n ))\n .next()\n .unwrap()\n .0;\n // Per https://www.rfc-editor.org/rfc/rfc9000.html#name-frames-and-frame-types,\n // non-ACK-eliciting packets must only contain PADDING, ACK, and CONNECTION_CLOSE\n // frames, which require no special handling on ACK or loss beyond removal from\n // in-flight counters if padded.\n let packet = self\n .sent_packets\n .remove(&oldest_after_ack_eliciting)\n .unwrap();\n forgotten_bytes = u64::from(packet.size);\n self.in_flight -= forgotten_bytes;\n } else {\n self.unacked_non_ack_eliciting_tail += 1;\n }\n\n self.in_flight += u64::from(packet.size);\n self.sent_packets.insert(number, packet);\n forgotten_bytes\n }\n```"}], "func_name": "sent", "docstring": "Returns the number of bytes to *remove* from the connection's in-flight count", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "40f7f89af95b0f773515cb09b471f44471ebdf48a4ed29b0fd6fe52588368e94"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConstruct an empty window positioned at the start.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn new() -> Self {\n Self { window: 0, next: 0 }\n }\n```"}], "func_name": "new", "docstring": "Construct an empty window positioned at the start.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6fdf15a19cf44e3be83cf9ffc4b8a2ceb449a92a7da2d9c1eb7806381e48c9d8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nRecord a newly authenticated packet number.\n\nReturns whether the packet might be a duplicate.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn insert(&mut self, packet: u64) -> bool {\n if let Some(diff) = packet.checked_sub(self.next) {\n // Right of window\n self.window = ((self.window << 1) | 1)\n .checked_shl(cmp::min(diff, u64::from(u32::MAX)) as u32)\n .unwrap_or(0);\n self.next = packet + 1;\n false\n } else if self.highest() - packet < WINDOW_SIZE {\n // Within window\n if let Some(bit) = (self.highest() - packet).checked_sub(1) {\n // < highest\n let mask = 1 << bit;\n let duplicate = self.window & mask != 0;\n self.window |= mask;\n duplicate\n } else {\n // == highest\n true\n }\n } else {\n // Left of window\n true\n }\n }\n```"}], "func_name": "insert", "docstring": "Record a newly authenticated packet number.\n\nReturns whether the packet might be a duplicate.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ec4d7bcc9e2525dd443cb119f0e63d4e50a8f0781eb38d2b8ce302df930dc42"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: smallest_missing_in_interval\n\nDocumentation:\nReturns the packet number of the smallest packet missing between the provided interval\n\nIf there are no missing packets, returns `None`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn smallest_missing_in_interval(&self, lower_bound: u64, upper_bound: u64) -> Option {\n debug_assert!(lower_bound <= upper_bound);\n debug_assert!(upper_bound <= self.highest());\n const BITFIELD_SIZE: u64 = (mem::size_of::() * 8) as u64;\n\n // Since we already know the packets at the boundaries have been received, we only need to\n // check those in between them (this removes the necessity of extra logic to deal with the\n // highest packet, which is stored outside the bitfield)\n let lower_bound = lower_bound + 1;\n let upper_bound = upper_bound.saturating_sub(1);\n\n // Note: the offsets are counted from the right\n // The highest packet is not included in the bitfield, so we subtract 1 to account for that\n let start_offset = (self.highest() - upper_bound).max(1) - 1;\n if start_offset >= BITFIELD_SIZE {\n // The start offset is outside of the window. All packets outside of the window are\n // considered to be received.\n return None;\n }\n\n let end_offset_exclusive = self.highest().saturating_sub(lower_bound);\n\n // The range is clamped at the edge of the window, because any earlier packets are\n // considered to be received\n let range_len = end_offset_exclusive\n .saturating_sub(start_offset)\n .min(BITFIELD_SIZE);\n if range_len == 0 {\n return None;\n }\n\n // Ensure the shift is within bounds (we already know start_offset < BITFIELD_SIZE,\n // because of the early return)\n let mask = if range_len == BITFIELD_SIZE {\n u128::MAX\n } else {\n ((1u128 << range_len) - 1) << start_offset\n };\n let gaps = !self.window & mask;\n\n let smallest_missing_offset = 128 - gaps.leading_zeros() as u64;\n let smallest_missing_packet = self.highest() - smallest_missing_offset;\n\n if smallest_missing_packet <= upper_bound {\n Some(smallest_missing_packet)\n } else {\n None\n }\n }\n```"}], "func_name": "smallest_missing_in_interval", "docstring": "Returns the packet number of the smallest packet missing between the provided interval\n\nIf there are no missing packets, returns `None`", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "07225a3513dfbb44ffbb241e98c2a25782c042c378bf00039de6c53a11c79fba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: missing_in_interval\n\nDocumentation:\nReturns true if there are any missing packets between the provided interval\n\nThe provided packet numbers must have been received before calling this function\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn missing_in_interval(&self, lower_bound: u64, upper_bound: u64) -> bool {\n self.smallest_missing_in_interval(lower_bound, upper_bound)\n .is_some()\n }\n```"}], "func_name": "missing_in_interval", "docstring": "Returns true if there are any missing packets between the provided interval\n\nThe provided packet numbers must have been received before calling this function", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d325e797e8849e6471a0b311e7c27f431a8d71feac5176567828aacd0942f769"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: empty\n\nDocumentation:\nReturns that no data is available for sending\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn empty() -> Self {\n Self {\n acks: false,\n other: false,\n }\n }\n```"}], "func_name": "empty", "docstring": "Returns that no data is available for sending", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a6db6ec7dfd0fe41b1a22e67f8457e5c7c32490c0951b5392e10624af13bdcd9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: can_send\n\nDocumentation:\nWhether any ACK frames can be sent\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn can_send(&self) -> bool {\n self.immediate_ack_required && !self.ranges.is_empty()\n }\n```"}], "func_name": "can_send", "docstring": "Whether any ACK frames can be sent", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7af2e2b498c50bab679c1508e9ba3ff8044e38b78fb4985a70f9d95ccbc3f57c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ack_delay\n\nDocumentation:\nReturns the delay since the packet with the largest packet number was received\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn ack_delay(&self, now: Instant) -> Duration {\n self.largest_packet\n .map_or(Duration::default(), |(_, received)| now - received)\n }\n```"}], "func_name": "ack_delay", "docstring": "Returns the delay since the packet with the largest packet number was received", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "883f10c4804402aa793ebfec66850c96fea641c458aa8c0d28febd4c0d6ac9e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: packet_received\n\nDocumentation:\nHandle receipt of a new packet\n\nReturns true if the max ack delay timer should be armed\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn packet_received(\n &mut self,\n now: Instant,\n packet_number: u64,\n ack_eliciting: bool,\n dedup: &Dedup,\n ) -> bool {\n if !ack_eliciting {\n self.non_ack_eliciting_since_last_ack_sent += 1;\n return false;\n }\n\n let prev_largest_ack_eliciting = self.largest_ack_eliciting_packet.unwrap_or(0);\n\n // Track largest ack-eliciting packet\n self.largest_ack_eliciting_packet = self\n .largest_ack_eliciting_packet\n .map(|pn| pn.max(packet_number))\n .or(Some(packet_number));\n\n // Handle ack_eliciting_threshold\n self.ack_eliciting_since_last_ack_sent += 1;\n self.immediate_ack_required |=\n self.ack_eliciting_since_last_ack_sent > self.ack_eliciting_threshold;\n\n // Handle out-of-order packets\n self.immediate_ack_required |=\n self.is_out_of_order(packet_number, prev_largest_ack_eliciting, dedup);\n\n // Arm max_ack_delay timer if necessary\n if self.earliest_ack_eliciting_since_last_ack_sent.is_none() && !self.can_send() {\n self.earliest_ack_eliciting_since_last_ack_sent = Some(now);\n return true;\n }\n\n false\n }\n```"}], "func_name": "packet_received", "docstring": "Handle receipt of a new packet\n\nReturns true if the max ack delay timer should be armed", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "747af57f0c863d32b600bd25e9ecf0b70dc8b2101d663d3cbd4680ecffb2ed9f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: acks_sent\n\nDocumentation:\nShould be called whenever ACKs have been sent\n\nThis will suppress sending further ACKs until additional ACK eliciting frames arrive\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn acks_sent(&mut self) {\n // It is possible (though unlikely) that the ACKs we just sent do not cover all the\n // ACK-eliciting packets we have received (e.g. if there is not enough room in the packet to\n // fit all the ranges). To keep things simple, however, we assume they do. If there are\n // indeed some ACKs that weren't covered, the packets might be ACKed later anyway, because\n // they are still contained in `self.ranges`. If we somehow fail to send the ACKs at a later\n // moment, the peer will assume the packets got lost and will retransmit their frames in a\n // new packet, which is suboptimal, because we already received them. Our assumption here is\n // that simplicity results in code that is more performant, even in the presence of\n // occasional redundant retransmits.\n self.immediate_ack_required = false;\n self.ack_eliciting_since_last_ack_sent = 0;\n self.non_ack_eliciting_since_last_ack_sent = 0;\n self.earliest_ack_eliciting_since_last_ack_sent = None;\n self.largest_acked = self.largest_ack_eliciting_packet;\n }\n```"}], "func_name": "acks_sent", "docstring": "Should be called whenever ACKs have been sent\n\nThis will suppress sending further ACKs until additional ACK eliciting frames arrive", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8caee61e1e54efc9d3c155d9463c7819fbb96ca8b62cdde77f53bbca47dc8768"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert_one\n\nDocumentation:\nInsert one packet that needs to be acknowledged\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn insert_one(&mut self, packet: u64, now: Instant) {\n self.ranges.insert_one(packet);\n\n if self.largest_packet.map_or(true, |(pn, _)| packet > pn) {\n self.largest_packet = Some((packet, now));\n }\n\n if self.ranges.len() > MAX_ACK_BLOCKS {\n self.ranges.pop_min();\n }\n }\n```"}], "func_name": "insert_one", "docstring": "Insert one packet that needs to be acknowledged", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "53a6cf7b5f4fcffcae20f8570475bd36ceeb1c93274e82d0d7436900c8306e69"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: subtract_below\n\nDocumentation:\nRemove ACKs of packets numbered at or below `max` from the set of pending ACKs\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn subtract_below(&mut self, max: u64) {\n self.ranges.remove(0..(max + 1));\n }\n```"}], "func_name": "subtract_below", "docstring": "Remove ACKs of packets numbered at or below `max` from the set of pending ACKs", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/spaces.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/spaces.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ec433beee2b261b714125d29b32e0757d79f3afe667f60bbb2661f979ea8c6de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open\n\nDocumentation:\nOpen a single stream if possible\n\nReturns `None` if the streams in the given direction are currently exhausted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn open(&mut self, dir: Dir) -> Option {\n if self.conn_state.is_closed() {\n return None;\n }\n\n // TODO: Queue STREAM_ID_BLOCKED if this fails\n if self.state.next[dir as usize] >= self.state.max[dir as usize] {\n return None;\n }\n\n self.state.next[dir as usize] += 1;\n let id = StreamId::new(self.state.side, dir, self.state.next[dir as usize] - 1);\n self.state.insert(false, id);\n self.state.send_streams += 1;\n Some(id)\n }\n```"}], "func_name": "open", "docstring": "Open a single stream if possible\n\nReturns `None` if the streams in the given direction are currently exhausted.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6b0ff093f9db88d1ba0f7bdc390c321712ba967ed3b00e0055d056105a6158c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: received_reset\n\nDocumentation:\nCheck whether this stream has been reset by the peer, returning the reset error code if so\n\nAfter returning `Ok(Some(_))` once, stream state will be discarded and all future calls will\nreturn `Err(ClosedStream)`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn received_reset(&mut self) -> Result, ClosedStream> {\n let hash_map::Entry::Occupied(entry) = self.state.recv.entry(self.id) else {\n return Err(ClosedStream { _private: () });\n };\n let Some(s) = entry.get().as_ref().and_then(|s| s.as_open_recv()) else {\n return Ok(None);\n };\n if s.stopped {\n return Err(ClosedStream { _private: () });\n }\n let Some(code) = s.reset_code() else {\n return Ok(None);\n };\n\n // Clean up state after application observes the reset, since there's no reason for the\n // application to attempt to read or stop the stream once it knows it's reset\n let (_, recv) = entry.remove_entry();\n self.state\n .stream_recv_freed(self.id, recv.expect(\"must have recv on reset\"));\n self.state.queue_max_stream_id(self.pending);\n\n Ok(Some(code))\n }\n```"}], "func_name": "received_reset", "docstring": "Check whether this stream has been reset by the peer, returning the reset error code if so\n\nAfter returning `Ok(Some(_))` once, stream state will be discarded and all future calls will\nreturn `Err(ClosedStream)`.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "472da34583608b6a31152c0e34a53f0bf7a8f4dca99a20c3c19900d8c80139ce"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write\n\nDocumentation:\nSend data on the given stream\n\nReturns the number of bytes successfully written.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write(&mut self, data: &[u8]) -> Result {\n Ok(self.write_source(&mut ByteSlice::from_slice(data))?.bytes)\n }\n```"}], "func_name": "write", "docstring": "Send data on the given stream\n\nReturns the number of bytes successfully written.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d6370e278dcbd63c56d61476c7925e1ac91beab8cf95ed439b789667d8c2f34"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_chunks\n\nDocumentation:\nSend data on the given stream\n\nReturns the number of bytes and chunks successfully written.\nNote that this method might also write a partial chunk. In this case\n[`Written::chunks`] will not count this chunk as fully written. However\nthe chunk will be advanced and contain only non-written data after the call.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_chunks(&mut self, data: &mut [Bytes]) -> Result {\n self.write_source(&mut BytesArray::from_chunks(data))\n }\n```"}], "func_name": "write_chunks", "docstring": "Send data on the given stream\n\nReturns the number of bytes and chunks successfully written.\nNote that this method might also write a partial chunk. In this case\n[`Written::chunks`] will not count this chunk as fully written. However\nthe chunk will be advanced and contain only non-written data after the call.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9c46271dc0939ee7c575e6e46057a7dd003610cc27d2b741ab5c207bae58b51"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stopped\n\nDocumentation:\nCheck if this stream was stopped, get the reason if it was\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stopped(&self) -> Result, ClosedStream> {\n match self.state.send.get(&self.id).as_ref() {\n Some(Some(s)) => Ok(s.stop_reason),\n Some(None) => Ok(None),\n None => Err(ClosedStream { _private: () }),\n }\n }\n```"}], "func_name": "stopped", "docstring": "Check if this stream was stopped, get the reason if it was", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9552c51e5e8a3dd1be30d4039f15e653023776fd5ed63c3e462a52c7375a829e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish\n\nDocumentation:\nFinish a send stream, signalling that no more data will be sent.\n\nIf this fails, no [`StreamEvent::Finished`] will be generated.\n\n[`StreamEvent::Finished`]: crate::StreamEvent::Finished\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn finish(&mut self) -> Result<(), FinishError> {\n let max_send_data = self.state.max_send_data(self.id);\n let stream = self\n .state\n .send\n .get_mut(&self.id)\n .map(get_or_insert_send(max_send_data))\n .ok_or(FinishError::ClosedStream)?;\n\n let was_pending = stream.is_pending();\n stream.finish()?;\n if !was_pending {\n self.state.pending.push_pending(self.id, stream.priority);\n }\n\n Ok(())\n }\n```"}], "func_name": "finish", "docstring": "Finish a send stream, signalling that no more data will be sent.\n\nIf this fails, no [`StreamEvent::Finished`] will be generated.\n\n[`StreamEvent::Finished`]: crate::StreamEvent::Finished", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f6ef8a8771622fa170e65bd843d24bcf61b59dbfba04fc4ac79925087543a479"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_priority\n\nDocumentation:\nSet the priority of a stream\n\n# Panics\n- when applied to a receive stream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_priority(&mut self, priority: i32) -> Result<(), ClosedStream> {\n let max_send_data = self.state.max_send_data(self.id);\n let stream = self\n .state\n .send\n .get_mut(&self.id)\n .map(get_or_insert_send(max_send_data))\n .ok_or(ClosedStream { _private: () })?;\n\n stream.priority = priority;\n Ok(())\n }\n```"}], "func_name": "set_priority", "docstring": "Set the priority of a stream\n\n# Panics\n- when applied to a receive stream", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c30bac02a2692b9af0365259dad117ca11e1d6e87c80a5d576251a53b1b9b1c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: priority\n\nDocumentation:\nGet the priority of a stream\n\n# Panics\n- when applied to a receive stream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn priority(&self) -> Result {\n let stream = self\n .state\n .send\n .get(&self.id)\n .ok_or(ClosedStream { _private: () })?;\n\n Ok(stream.as_ref().map(|s| s.priority).unwrap_or_default())\n }\n```"}], "func_name": "priority", "docstring": "Get the priority of a stream\n\n# Panics\n- when applied to a receive stream", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bfeef041fa7101bd91478de4599415de6af7d8ddfd7894c530f5ff8204ef082d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reinsert_pending\n\nDocumentation:\nReinsert a stream that was pending and still contains unsent data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reinsert_pending(&mut self, id: StreamId, priority: i32) {\n assert!(self.next.is_none());\n\n self.next = Some(PendingStream {\n priority,\n recency: self.recency, // the value here doesn't really matter\n id,\n });\n }\n```"}], "func_name": "reinsert_pending", "docstring": "Reinsert a stream that was pending and still contains unsent data.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f486c0527e39cc1652e2e3fbd208365fb8cb36f3211014eb2ce72e1e9b9f2eda"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_pending\n\nDocumentation:\nPush a pending stream ID with the given priority, queued after any already-queued streams for the priority\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn push_pending(&mut self, id: StreamId, priority: i32) {\n // Note that in the case where fairness is disabled, if we have a reinserted stream we don't\n // bump it even if priority > next.priority. In order to minimize fragmentation we\n // always try to complete a stream once part of it has been written.\n\n // As the recency counter is monotonically decreasing, we know that using its value to sort this stream will queue it\n // after all other queued streams of the same priority.\n // This is enough to implement round-robin scheduling for streams that are still pending even after being handled,\n // as in that case they are removed from the `BinaryHeap`, handled, and then immediately reinserted.\n self.recency -= 1;\n self.streams.push(PendingStream {\n priority,\n recency: self.recency,\n id,\n });\n }\n```"}], "func_name": "push_pending", "docstring": "Push a pending stream ID with the given priority, queued after any already-queued streams for the priority", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b88b68018e7847b3a9accb88b25fd87ca5ee62de2ab254f421ab09c85ce9c519"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ingest\n\nDocumentation:\nProcess a STREAM frame\n\nReturn value is `(number_of_new_bytes_ingested, stream_is_closed)`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn ingest(\n &mut self,\n frame: frame::Stream,\n payload_len: usize,\n received: u64,\n max_data: u64,\n ) -> Result<(u64, bool), TransportError> {\n let end = frame.offset + frame.data.len() as u64;\n if end >= 2u64.pow(62) {\n return Err(TransportError::FLOW_CONTROL_ERROR(\n \"maximum stream offset too large\",\n ));\n }\n\n if let Some(final_offset) = self.final_offset() {\n if end > final_offset || (frame.fin && end != final_offset) {\n debug!(end, final_offset, \"final size error\");\n return Err(TransportError::FINAL_SIZE_ERROR(\"\"));\n }\n }\n\n let new_bytes = self.credit_consumed_by(end, received, max_data)?;\n\n // Stopped streams don't need to wait for the actual data, they just need to know\n // how much there was.\n if frame.fin && !self.stopped {\n if let RecvState::Recv { ref mut size } = self.state {\n *size = Some(end);\n }\n }\n\n self.end = self.end.max(end);\n // Don't bother storing data or releasing stream-level flow control credit if the stream's\n // already stopped\n if !self.stopped {\n self.assembler.insert(frame.offset, frame.data, payload_len);\n }\n\n Ok((new_bytes, frame.fin && self.stopped))\n }\n```"}], "func_name": "ingest", "docstring": "Process a STREAM frame\n\nReturn value is `(number_of_new_bytes_ingested, stream_is_closed)`", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/recv.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/recv.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3254c98bee983f8b96da72e4b99dd9b5291b549689af5f65b826c465420e7938"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: record_sent_max_stream_data\n\nDocumentation:\nRecords that a `MAX_STREAM_DATA` announcing a certain window was sent\n\nThis will suppress enqueuing further `MAX_STREAM_DATA` frames unless\neither the previous transmission was not acknowledged or the window\nfurther increased.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn record_sent_max_stream_data(&mut self, sent_value: u64) {\n if sent_value > self.sent_max_stream_data {\n self.sent_max_stream_data = sent_value;\n }\n }\n```"}], "func_name": "record_sent_max_stream_data", "docstring": "Records that a `MAX_STREAM_DATA` announcing a certain window was sent\n\nThis will suppress enqueuing further `MAX_STREAM_DATA` frames unless\neither the previous transmission was not acknowledged or the window\nfurther increased.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/recv.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/recv.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44149f70460519c8bc2dc03fd6ea5af61c114acb2a6c0015b2afce32e09cbe56"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: final_offset_unknown\n\nDocumentation:\nWhether the total amount of data that the peer will send on this stream is unknown\n\nTrue until we've received either a reset or the final frame.\n\nImplies that the sender might benefit from stream-level flow control updates, and we might\nneed to issue connection-level flow control updates due to flow control budget use by this\nstream in the future, even if it's been stopped.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn final_offset_unknown(&self) -> bool {\n matches!(self.state, RecvState::Recv { size: None })\n }\n```"}], "func_name": "final_offset_unknown", "docstring": "Whether the total amount of data that the peer will send on this stream is unknown\n\nTrue until we've received either a reset or the final frame.\n\nImplies that the sender might benefit from stream-level flow control updates, and we might\nneed to issue connection-level flow control updates due to flow control budget use by this\nstream in the future, even if it's been stopped.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/recv.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/recv.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d0f3baa0d1d2380ee757a103fe19dd5ef62c860a161511605f213f84a238b2bb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: can_send_flow_control\n\nDocumentation:\nWhether stream-level flow control updates should be sent for this stream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn can_send_flow_control(&self) -> bool {\n // Stream-level flow control is redundant if the sender has already sent the whole stream,\n // and moot if we no longer want data on this stream.\n self.final_offset_unknown() && !self.stopped\n }\n```"}], "func_name": "can_send_flow_control", "docstring": "Whether stream-level flow control updates should be sent for this stream", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/recv.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/recv.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3b85d889b14cc4dd69b052a66ba69c3dae0463f7352e51332951e1b59e722ff9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_receiving\n\nDocumentation:\nWhether data is still being accepted from the peer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn is_receiving(&self) -> bool {\n matches!(self.state, RecvState::Recv { .. })\n }\n```"}], "func_name": "is_receiving", "docstring": "Whether data is still being accepted from the peer", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/recv.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/recv.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7f2db39e2751878e1f262f1504b63462e9272a4d98801ab32e40465788fb59cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset\n\nDocumentation:\nReturns `false` iff the reset was redundant\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn reset(\n &mut self,\n error_code: VarInt,\n final_offset: VarInt,\n received: u64,\n max_data: u64,\n ) -> Result {\n // Validate final_offset\n if let Some(offset) = self.final_offset() {\n if offset != final_offset.into_inner() {\n return Err(TransportError::FINAL_SIZE_ERROR(\"inconsistent value\"));\n }\n } else if self.end > u64::from(final_offset) {\n return Err(TransportError::FINAL_SIZE_ERROR(\n \"lower than high water mark\",\n ));\n }\n self.credit_consumed_by(final_offset.into(), received, max_data)?;\n\n if matches!(self.state, RecvState::ResetRecvd { .. }) {\n return Ok(false);\n }\n self.state = RecvState::ResetRecvd {\n size: final_offset.into(),\n error_code,\n };\n // Nuke buffers so that future reads fail immediately, which ensures future reads don't\n // issue flow control credit redundant to that already issued. We could instead special-case\n // reset streams during read, but it's unclear if there's any benefit to retaining data for\n // reset streams.\n self.assembler.clear();\n Ok(true)\n }\n```"}], "func_name": "reset", "docstring": "Returns `false` iff the reset was redundant", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/recv.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/recv.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "99f092b7eaf66813753100200b47c6b362a89e9c974ddc986800a6b3c7c7301a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: credit_consumed_by\n\nDocumentation:\nCompute the amount of flow control credit consumed, or return an error if more was consumed\nthan issued\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn credit_consumed_by(\n &self,\n offset: u64,\n received: u64,\n max_data: u64,\n ) -> Result {\n let prev_end = self.end;\n let new_bytes = offset.saturating_sub(prev_end);\n if offset > self.sent_max_stream_data || received + new_bytes > max_data {\n debug!(\n received,\n new_bytes,\n max_data,\n offset,\n stream_max_data = self.sent_max_stream_data,\n \"flow control error\"\n );\n return Err(TransportError::FLOW_CONTROL_ERROR(\"\"));\n }\n\n Ok(new_bytes)\n }\n```"}], "func_name": "credit_consumed_by", "docstring": "Compute the amount of flow control credit consumed, or return an error if more was consumed\nthan issued", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/recv.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/recv.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "574f336b94115aa165cdb2ab07fb8eaaa16c517538351ffa6aaa310b20f5602a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next\n\nDocumentation:\nNext\n\nShould call finalize() when done calling this.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn next(&mut self, max_length: usize) -> Result, ReadError> {\n let rs = match self.state {\n ChunksState::Readable(ref mut rs) => rs,\n ChunksState::Reset(error_code) => {\n return Err(ReadError::Reset(error_code));\n }\n ChunksState::Finished => {\n return Ok(None);\n }\n ChunksState::Finalized => panic!(\"must not call next() after finalize()\"),\n };\n\n if let Some(chunk) = rs.assembler.read(max_length, self.ordered) {\n self.read += chunk.bytes.len() as u64;\n return Ok(Some(chunk));\n }\n\n match rs.state {\n RecvState::ResetRecvd { error_code, .. } => {\n debug_assert_eq!(self.read, 0, \"reset streams have empty buffers\");\n let state = mem::replace(&mut self.state, ChunksState::Reset(error_code));\n // At this point if we have `rs` self.state must be `ChunksState::Readable`\n let recv = match state {\n ChunksState::Readable(recv) => StreamRecv::Open(recv),\n _ => unreachable!(\"state must be ChunkState::Readable\"),\n };\n self.streams.stream_recv_freed(self.id, recv);\n Err(ReadError::Reset(error_code))\n }\n RecvState::Recv { size } => {\n if size == Some(rs.end) && rs.assembler.bytes_read() == rs.end {\n let state = mem::replace(&mut self.state, ChunksState::Finished);\n // At this point if we have `rs` self.state must be `ChunksState::Readable`\n let recv = match state {\n ChunksState::Readable(recv) => StreamRecv::Open(recv),\n _ => unreachable!(\"state must be ChunkState::Readable\"),\n };\n self.streams.stream_recv_freed(self.id, recv);\n Ok(None)\n } else {\n // We don't need a distinct `ChunksState` variant for a blocked stream because\n // retrying a read harmlessly re-traces our steps back to returning\n // `Err(Blocked)` again. The buffers can't refill and the stream's own state\n // can't change so long as this `Chunks` exists.\n Err(ReadError::Blocked)\n }\n }\n }\n }\n```"}], "func_name": "next", "docstring": "Next\n\nShould call finalize() when done calling this.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/recv.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/recv.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9eea57c5e2f829920fd3fabb3184057314d08b439d9a206704b599356c4fe042"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_reset\n\nDocumentation:\nWhether the stream has been reset\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn is_reset(&self) -> bool {\n matches!(self.state, SendState::ResetSent)\n }\n```"}], "func_name": "is_reset", "docstring": "Whether the stream has been reset", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/send.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/send.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "810e8f0613555f003b7aeb051ad2499269ae7d9277a21624cc8023b1f2b2d709"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset\n\nDocumentation:\nUpdate stream state due to a reset sent by the local application\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn reset(&mut self) {\n use SendState::*;\n if let DataSent { .. } | Ready = self.state {\n self.state = ResetSent;\n }\n }\n```"}], "func_name": "reset", "docstring": "Update stream state due to a reset sent by the local application", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/send.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/send.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0b57be422da9efeedd5820a76ac821c16ad6b5fd11e388cef9f12f07962d2e45"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_stop\n\nDocumentation:\nHandle STOP_SENDING\n\nReturns true if the stream was stopped due to this frame, and false\nif it had been stopped before\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn try_stop(&mut self, error_code: VarInt) -> bool {\n if self.stop_reason.is_none() {\n self.stop_reason = Some(error_code);\n true\n } else {\n false\n }\n }\n```"}], "func_name": "try_stop", "docstring": "Handle STOP_SENDING\n\nReturns true if the stream was stopped due to this frame, and false\nif it had been stopped before", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/send.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/send.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a596820d559f2a75171f46c912750f464d9fa83b36dab0bb8b53a08f31d69319"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ack\n\nDocumentation:\nReturns whether the stream has been finished and all data has been acknowledged by the peer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn ack(&mut self, frame: frame::StreamMeta) -> bool {\n self.pending.ack(frame.offsets);\n match self.state {\n SendState::DataSent {\n ref mut finish_acked,\n } => {\n *finish_acked |= frame.fin;\n *finish_acked && self.pending.is_fully_acked()\n }\n _ => false,\n }\n }\n```"}], "func_name": "ack", "docstring": "Returns whether the stream has been finished and all data has been acknowledged by the peer", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/send.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/send.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "47eefc3c96a183aaecc8cdaa87d5a23abd6f6371aba0745e3af395da0cdf80d1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_open_recv\n\nDocumentation:\nReturns a reference to the inner `Recv` if the stream is open\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn as_open_recv(&self) -> Option<&Recv> {\n match self {\n Self::Open(r) => Some(r),\n _ => None,\n }\n }\n```"}], "func_name": "as_open_recv", "docstring": "Returns a reference to the inner `Recv` if the stream is open", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cba30c1bfd4fe165aecd1667da1374b3d55c84a8382060c0167c3f30393931ce"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ensure_remote_streams\n\nDocumentation:\nEnsure we have space for at least a full flow control window of remotely-initiated streams\nto be open, and notify the peer if the window has moved\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn ensure_remote_streams(&mut self, dir: Dir) {\n let new_count = self.max_concurrent_remote_count[dir as usize]\n .saturating_sub(self.allocated_remote_count[dir as usize]);\n for i in 0..new_count {\n let id = StreamId::new(!self.side, dir, self.max_remote[dir as usize] + i);\n self.insert(true, id);\n }\n self.allocated_remote_count[dir as usize] += new_count;\n self.max_remote[dir as usize] += new_count;\n }\n```"}], "func_name": "ensure_remote_streams", "docstring": "Ensure we have space for at least a full flow control window of remotely-initiated streams\nto be open, and notify the peer if the window has moved", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "89fd3c00be099144c90bdd586606281b501da46b29e4c3cf5b65d56af8eb10f1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: can_send_stream_data\n\nDocumentation:\nWhether any stream data is queued, regardless of control frames\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn can_send_stream_data(&self) -> bool {\n // Reset streams may linger in the pending stream list, but will never produce stream frames\n self.pending.iter().any(|stream| {\n self.send\n .get(&stream.id)\n .and_then(|s| s.as_ref())\n .is_some_and(|s| !s.is_reset())\n })\n }\n```"}], "func_name": "can_send_stream_data", "docstring": "Whether any stream data is queued, regardless of control frames", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1043b4dd05c1672aec893b3847c839eafbbb0e8496cadb890c47d261321cb4d7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: can_send_flow_control\n\nDocumentation:\nWhether MAX_STREAM_DATA frames could be sent for stream `id`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn can_send_flow_control(&self, id: StreamId) -> bool {\n self.recv\n .get(&id)\n .and_then(|s| s.as_ref())\n .and_then(|s| s.as_open_recv())\n .is_some_and(|s| s.can_send_flow_control())\n }\n```"}], "func_name": "can_send_flow_control", "docstring": "Whether MAX_STREAM_DATA frames could be sent for stream `id`", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1534f9aa9e0661c4425614df746d0af388b07609b7534aad51d2c8a276853742"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_stream_frame\n\nDocumentation:\nNotify the application that new streams were opened or a stream became readable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn on_stream_frame(&mut self, notify_readable: bool, stream: StreamId) {\n if stream.initiator() == self.side {\n // Notifying about the opening of locally-initiated streams would be redundant.\n if notify_readable {\n self.events.push_back(StreamEvent::Readable { id: stream });\n }\n return;\n }\n let next = &mut self.next_remote[stream.dir() as usize];\n if stream.index() >= *next {\n *next = stream.index() + 1;\n self.opened[stream.dir() as usize] = true;\n } else if notify_readable {\n self.events.push_back(StreamEvent::Readable { id: stream });\n }\n }\n```"}], "func_name": "on_stream_frame", "docstring": "Notify the application that new streams were opened or a stream became readable.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "862cb8e24076616318b2d424056904d632e9f486527cd75bbeb6b482fa7a0e55"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_limit\n\nDocumentation:\nReturns the maximum amount of data this is allowed to be written on the connection\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn write_limit(&self) -> u64 {\n (self.max_data - self.data_sent).min(self.send_window - self.unacked_data)\n }\n```"}], "func_name": "write_limit", "docstring": "Returns the maximum amount of data this is allowed to be written on the connection", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "110fdb512c98427b75619e5810633ecff802ed4b61fd055222eb648e26049be7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: queue_max_stream_id\n\nDocumentation:\nQueues MAX_STREAM_ID frames in `pending` if needed\n\nReturns whether any frames were queued.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn queue_max_stream_id(&mut self, pending: &mut Retransmits) -> bool {\n let mut queued = false;\n for dir in Dir::iter() {\n let diff = self.max_remote[dir as usize] - self.sent_max_remote[dir as usize];\n // To reduce traffic, only announce updates if at least 1/8 of the flow control window\n // has been consumed.\n if diff > self.max_concurrent_remote_count[dir as usize] / 8 {\n pending.max_stream_id[dir as usize] = true;\n queued = true;\n }\n }\n queued\n }\n```"}], "func_name": "queue_max_stream_id", "docstring": "Queues MAX_STREAM_ID frames in `pending` if needed\n\nReturns whether any frames were queued.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c4f14b7ea864de498ec9efa5f22592900de96a48e421890f2d8db5beedb463f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: validate_receive_id\n\nDocumentation:\nCheck for errors entailed by the peer's use of `id` as a send stream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn validate_receive_id(&mut self, id: StreamId) -> Result<(), TransportError> {\n if self.side == id.initiator() {\n match id.dir() {\n Dir::Uni => {\n return Err(TransportError::STREAM_STATE_ERROR(\n \"illegal operation on send-only stream\",\n ));\n }\n Dir::Bi if id.index() >= self.next[Dir::Bi as usize] => {\n return Err(TransportError::STREAM_STATE_ERROR(\n \"operation on unopened stream\",\n ));\n }\n Dir::Bi => {}\n };\n } else {\n let limit = self.max_remote[id.dir() as usize];\n if id.index() >= limit {\n return Err(TransportError::STREAM_LIMIT_ERROR(\"\"));\n }\n }\n Ok(())\n }\n```"}], "func_name": "validate_receive_id", "docstring": "Check for errors entailed by the peer's use of `id` as a send stream", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18a95817e9b0ecd26e327738fe3852e62b7b95d685031d288f913f1b8c220f76"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_local_unopened\n\nDocumentation:\nWhether a locally initiated stream has never been open\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn is_local_unopened(&self, id: StreamId) -> bool {\n id.index() >= self.next[id.dir() as usize]\n }\n```"}], "func_name": "is_local_unopened", "docstring": "Whether a locally initiated stream has never been open", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "674b6bcd63794c830b372bbdbdf754af0a1b65a6e1a7aa7ac7ee993542025a15"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_receive_window\n\nDocumentation:\nSet the receive_window and returns whether the receive_window has been\nexpanded or shrunk: true if expanded, false if shrunk.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn set_receive_window(&mut self, receive_window: VarInt) -> bool {\n let receive_window = receive_window.into();\n let mut expanded = false;\n if receive_window > self.receive_window {\n self.local_max_data = self\n .local_max_data\n .saturating_add(receive_window - self.receive_window);\n expanded = true;\n } else {\n let diff = self.receive_window - receive_window;\n self.receive_window_shrink_debt = self.receive_window_shrink_debt.saturating_add(diff);\n }\n self.receive_window = receive_window;\n expanded\n }\n```"}], "func_name": "set_receive_window", "docstring": "Set the receive_window and returns whether the receive_window has been\nexpanded or shrunk: true if expanded, false if shrunk.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e455a548c309a948525a77e4937214758a9e8ce73f0002053c8a90dd48c6913"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_read_credits\n\nDocumentation:\nAdds credits to the connection flow control window\n\nReturns whether a `MAX_DATA` frame should be enqueued as soon as possible.\nThis will only be the case if the window update would is significant\nenough. As soon as a window update with a `MAX_DATA` frame has been\nqueued, the [`Recv::record_sent_max_stream_data`] function should be called to\nsuppress sending further updates until the window increases significantly\nagain.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn add_read_credits(&mut self, credits: u64) -> ShouldTransmit {\n if credits > self.receive_window_shrink_debt {\n let net_credits = credits - self.receive_window_shrink_debt;\n self.local_max_data = self.local_max_data.saturating_add(net_credits);\n self.receive_window_shrink_debt = 0;\n } else {\n self.receive_window_shrink_debt -= credits;\n }\n\n if self.local_max_data > VarInt::MAX.into_inner() {\n return ShouldTransmit(false);\n }\n\n // Only announce a window update if it's significant enough\n // to make it worthwhile sending a MAX_DATA frame.\n // We use a fraction of the configured connection receive window to make\n // the decision, to accommodate for connection using bigger windows requiring\n // less updates.\n let diff = self.local_max_data - self.sent_max_data.into_inner();\n ShouldTransmit(diff >= (self.receive_window / 8))\n }\n```"}], "func_name": "add_read_credits", "docstring": "Adds credits to the connection flow control window\n\nReturns whether a `MAX_DATA` frame should be enqueued as soon as possible.\nThis will only be the case if the window update would is significant\nenough. As soon as a window update with a `MAX_DATA` frame has been\nqueued, the [`Recv::record_sent_max_stream_data`] function should be called to\nsuppress sending further updates until the window increases significantly\nagain.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ee74ab115802f0200c47a1d6dd3f10a5abe9bac7bdac9fe5065707967a8b7a3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stream_freed\n\nDocumentation:\nUpdate counters for removal of a stream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn stream_freed(&mut self, id: StreamId, half: StreamHalf) {\n if id.initiator() != self.side {\n let fully_free = id.dir() == Dir::Uni\n || match half {\n StreamHalf::Send => !self.recv.contains_key(&id),\n StreamHalf::Recv => !self.send.contains_key(&id),\n };\n if fully_free {\n self.allocated_remote_count[id.dir() as usize] -= 1;\n self.ensure_remote_streams(id.dir());\n }\n }\n if half == StreamHalf::Send {\n self.send_streams -= 1;\n }\n }\n```"}], "func_name": "stream_freed", "docstring": "Update counters for removal of a stream", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/connection/streams/state.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/connection/streams/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc97b9f8e768b708817176c4d4e1488599bbf44350978ea7eea5a2ae4bc85bd4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: peer_identity\n\nDocumentation:\nFor the rustls `TlsSession`, the `Any` type is `Vec`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn peer_identity(&self) -> Option> {\n self.inner.peer_certificates().map(|v| -> Box {\n Box::new(\n v.iter()\n .map(|v| v.clone().into_owned())\n .collect::>>(),\n )\n })\n }\n```"}], "func_name": "peer_identity", "docstring": "For the rustls `TlsSession`, the `Any` type is `Vec`", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/crypto/rustls.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/crypto/rustls.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a6c3911829b7a407c0599cc42bb8f025850452f9fe99c42733cd807cac1350de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nInitialize a sane QUIC-compatible TLS client configuration\n\nQUIC requires that TLS 1.3 be enabled. Advanced users can use any [`rustls::ClientConfig`] that\nsatisfies this requirement.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new(verifier: Arc) -> Self {\n let inner = Self::inner(verifier);\n Self {\n // We're confident that the *ring* default provider contains TLS13_AES_128_GCM_SHA256\n initial: initial_suite_from_provider(inner.crypto_provider())\n .expect(\"no initial cipher suite found\"),\n inner: Arc::new(inner),\n }\n }\n```"}], "func_name": "new", "docstring": "Initialize a sane QUIC-compatible TLS client configuration\n\nQUIC requires that TLS 1.3 be enabled. Advanced users can use any [`rustls::ClientConfig`] that\nsatisfies this requirement.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/crypto/rustls.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/crypto/rustls.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "916c7fcd19912d8d0a91f69299d9a49271ccd902a0e6d078b1f379014d530f05"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_initial\n\nDocumentation:\nInitialize a QUIC-compatible TLS client configuration with a separate initial cipher suite\n\nThis is useful if you want to avoid the initial cipher suite for traffic encryption.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_initial(\n inner: Arc,\n initial: Suite,\n ) -> Result {\n match initial.suite.common.suite {\n CipherSuite::TLS13_AES_128_GCM_SHA256 => Ok(Self { inner, initial }),\n _ => Err(NoInitialCipherSuite { specific: true }),\n }\n }\n```"}], "func_name": "with_initial", "docstring": "Initialize a QUIC-compatible TLS client configuration with a separate initial cipher suite\n\nThis is useful if you want to avoid the initial cipher suite for traffic encryption.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/crypto/rustls.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/crypto/rustls.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fd1123c381f8a1f64e0c4ac6b53b7d661bc5b921ca3e2dab5c3ed8869d0103f1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: inner\n\nDocumentation:\nInitialize a sane QUIC-compatible TLS server configuration\n\nQUIC requires that TLS 1.3 be enabled, and that the maximum early data size is either 0 or\n`u32::MAX`. Advanced users can use any [`rustls::ServerConfig`] that satisfies these\nrequirements.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn inner(\n cert_chain: Vec>,\n key: PrivateKeyDer<'static>,\n ) -> Result {\n let mut inner = rustls::ServerConfig::builder_with_provider(configured_provider())\n .with_protocol_versions(&[&rustls::version::TLS13])\n .unwrap() // The *ring* default provider supports TLS 1.3\n .with_no_client_auth()\n .with_single_cert(cert_chain, key)?;\n\n inner.max_early_data_size = u32::MAX;\n Ok(inner)\n }\n```"}], "func_name": "inner", "docstring": "Initialize a sane QUIC-compatible TLS server configuration\n\nQUIC requires that TLS 1.3 be enabled, and that the maximum early data size is either 0 or\n`u32::MAX`. Advanced users can use any [`rustls::ServerConfig`] that satisfies these\nrequirements.", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/crypto/rustls.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/crypto/rustls.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "13e5096d1c3dbe936d3ca087fba4bf04491b833d66a292e5b5a8de70be5efa23"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pred\n\nDocumentation:\nFind closest range to `x` that begins at or before it\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn pred(&self, x: u64) -> Option<(u64, u64)> {\n self.0\n .range((Included(0), Included(x)))\n .next_back()\n .map(|(&x, &y)| (x, y))\n }\n```"}], "func_name": "pred", "docstring": "Find closest range to `x` that begins at or before it", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/range_set/btree_range_set.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/range_set/btree_range_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "86a23271fa543239e39e33293ab3a60255d3276c20beb0b77a3345e9176d1194"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: succ\n\nDocumentation:\nFind the closest range to `x` that begins after it\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn succ(&self, x: u64) -> Option<(u64, u64)> {\n self.0\n .range((Excluded(x), Included(u64::MAX)))\n .next()\n .map(|(&x, &y)| (x, y))\n }\n```"}], "func_name": "succ", "docstring": "Find the closest range to `x` that begins after it", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/range_set/btree_range_set.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/range_set/btree_range_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "24f3b0f320703c1194df2c5c0c1915c94fd71e985024088f26403ceec2d5112c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: replace\n\nDocumentation:\nAdd a range to the set, returning the intersection of current ranges with the new one\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn replace(&mut self, mut range: Range) -> Replace<'_> {\n let pred = if let Some((prev_start, prev_end)) = self\n .pred(range.start)\n .filter(|&(_, end)| end >= range.start)\n {\n self.0.remove(&prev_start);\n let replaced_start = range.start;\n range.start = range.start.min(prev_start);\n let replaced_end = range.end.min(prev_end);\n range.end = range.end.max(prev_end);\n if replaced_start != replaced_end {\n Some(replaced_start..replaced_end)\n } else {\n None\n }\n } else {\n None\n };\n Replace {\n set: self,\n range,\n pred,\n }\n }\n```"}], "func_name": "replace", "docstring": "Add a range to the set, returning the intersection of current ranges with the new one", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/range_set/btree_range_set.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/range_set/btree_range_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27e00f923cd5089e6b4a37b683ad12e7c934abf8d643933d63bf2266b81cdf45"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish_acked\n\nDocumentation:\nEnsure that we don't yield a finish event before the actual FIN is acked so the peer isn't left\nhanging\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn finish_acked() {\n let _guard = subscribe();\n let mut pair = Pair::default();\n let (client_ch, server_ch) = pair.connect();\n\n let s = pair.client_streams(client_ch).open(Dir::Uni).unwrap();\n\n const MSG: &[u8] = b\"hello\";\n pair.client_send(client_ch, s).write(MSG).unwrap();\n info!(\"client sends data to server\");\n pair.drive_client(); // send data to server\n info!(\"server acknowledges data\");\n pair.drive_server(); // process data and send data ack\n\n // Receive data\n assert_matches!(\n pair.server_conn_mut(server_ch).poll(),\n Some(Event::Stream(StreamEvent::Opened { dir: Dir::Uni }))\n );\n assert_matches!(pair.server_conn_mut(server_ch).poll(), None);\n\n assert_matches!(pair.server_streams(server_ch).accept(Dir::Uni), Some(stream) if stream == s);\n\n let mut recv = pair.server_recv(server_ch, s);\n let mut chunks = recv.read(false).unwrap();\n assert_matches!(\n chunks.next(usize::MAX),\n Ok(Some(chunk)) if chunk.offset == 0 && chunk.bytes == MSG\n );\n assert_matches!(chunks.next(usize::MAX), Err(ReadError::Blocked));\n let _ = chunks.finalize();\n\n // Finish before receiving data ack\n pair.client_send(client_ch, s).finish().unwrap();\n // Send FIN, receive data ack\n info!(\"client receives ACK, sends FIN\");\n pair.drive_client();\n // Check for premature finish from data ack\n assert_matches!(pair.client_conn_mut(client_ch).poll(), None);\n // Process FIN ack\n info!(\"server ACKs FIN\");\n pair.drive();\n assert_matches!(\n pair.client_conn_mut(client_ch).poll(),\n Some(Event::Stream(StreamEvent::Finished { id })) if id == s\n );\n\n let mut recv = pair.server_recv(server_ch, s);\n let mut chunks = recv.read(false).unwrap();\n assert_matches!(chunks.next(usize::MAX), Ok(None));\n let _ = chunks.finalize();\n}\n```"}], "func_name": "finish_acked", "docstring": "Ensure that we don't yield a finish event before the actual FIN is acked so the peer isn't left\nhanging", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/tests/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/tests/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d5d79b40fcf3987712e5fa0dbd5fb4a45fda3f4f3ee4dc31836c1855a3086174"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish_retransmit\n\nDocumentation:\nEnsure that we don't yield a finish event while there's still unacknowledged data\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn finish_retransmit() {\n let _guard = subscribe();\n let mut pair = Pair::default();\n let (client_ch, server_ch) = pair.connect();\n\n let s = pair.client_streams(client_ch).open(Dir::Uni).unwrap();\n\n const MSG: &[u8] = b\"hello\";\n pair.client_send(client_ch, s).write(MSG).unwrap();\n pair.drive_client(); // send data to server\n pair.server.inbound.clear(); // Lose it\n\n // Send FIN\n pair.client_send(client_ch, s).finish().unwrap();\n pair.drive_client();\n // Process FIN\n pair.drive_server();\n // Receive FIN ack, but no data ack\n pair.drive_client();\n // Check for premature finish from FIN ack\n assert_matches!(pair.client_conn_mut(client_ch).poll(), None);\n // Recover\n pair.drive();\n assert_matches!(\n pair.client_conn_mut(client_ch).poll(),\n Some(Event::Stream(StreamEvent::Finished { id })) if id == s\n );\n\n assert_matches!(\n pair.server_conn_mut(server_ch).poll(),\n Some(Event::Stream(StreamEvent::Opened { dir: Dir::Uni }))\n );\n\n assert_matches!(pair.server_streams(server_ch).accept(Dir::Uni), Some(stream) if stream == s);\n\n let mut recv = pair.server_recv(server_ch, s);\n let mut chunks = recv.read(false).unwrap();\n assert_matches!(\n chunks.next(usize::MAX),\n Ok(Some(chunk)) if chunk.offset == 0 && chunk.bytes == MSG\n );\n assert_matches!(chunks.next(usize::MAX), Ok(None));\n let _ = chunks.finalize();\n}\n```"}], "func_name": "finish_retransmit", "docstring": "Ensure that we don't yield a finish event while there's still unacknowledged data", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/tests/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/tests/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "edae4672a0b88b46797854f9e75860850d2729a01a7c74dbb89809e664292328"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect_too_low_mtu\n\nDocumentation:\nThis is mostly a sanity check to ensure our testing code is correctly dropping packets above the\npmtu\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn connect_too_low_mtu() {\n let _guard = subscribe();\n let mut pair = Pair::default();\n\n // The maximum payload size is lower than 1200, so no packages will get through!\n pair.mtu = 1000;\n\n pair.begin_connect(client_config());\n pair.drive();\n pair.server.assert_no_accept();\n}\n```"}], "func_name": "connect_too_low_mtu", "docstring": "This is mostly a sanity check to ensure our testing code is correctly dropping packets above the\npmtu", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/tests/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/tests/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e0cfa905934ec3b87cf23604ec1a5bbfdc5cc930708fdb4dec399cfe4031ade5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: step\n\nDocumentation:\nReturns whether the connection is not idle\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn step(&mut self) -> bool {\n self.drive_client();\n self.drive_server();\n if self.client.is_idle() && self.server.is_idle() {\n return false;\n }\n\n let client_t = self.client.next_wakeup();\n let server_t = self.server.next_wakeup();\n match min_opt(client_t, server_t) {\n Some(t) if Some(t) == client_t => {\n if t != self.time {\n self.time = self.time.max(t);\n trace!(\"advancing to {:?} for client\", self.time - self.epoch);\n }\n true\n }\n Some(t) if Some(t) == server_t => {\n if t != self.time {\n self.time = self.time.max(t);\n trace!(\"advancing to {:?} for server\", self.time - self.epoch);\n }\n true\n }\n Some(_) => unreachable!(),\n None => false,\n }\n }\n```"}], "func_name": "step", "docstring": "Returns whether the connection is not idle", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/tests/util.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/tests/util.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2eb5291d0af2be40c04824064a20af31cad10bf9a4f48fd8d9b9b09021b11e9f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: drive\n\nDocumentation:\nAdvance time until both connections are idle\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn drive(&mut self) {\n while self.step() {}\n }\n```"}], "func_name": "drive", "docstring": "Advance time until both connections are idle", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/tests/util.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/tests/util.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4241e99b6ee67d3236ba35509317af45a03cf3a202f9f375d5a15cc8770fcf5f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: drive_bounded\n\nDocumentation:\nAdvance time until both connections are idle, or after 100 steps have been executed\n\nReturns true if the amount of steps exceeds the bounds, because the connections never became\nidle\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn drive_bounded(&mut self) -> bool {\n for _ in 0..100 {\n if !self.step() {\n return false;\n }\n }\n\n true\n }\n```"}], "func_name": "drive_bounded", "docstring": "Advance time until both connections are idle, or after 100 steps have been executed\n\nReturns true if the amount of steps exceeds the bounds, because the connections never became\nidle", "repo": "quinn-rs/quinn", "path": "quinn-proto/src/tests/util.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-proto/src/tests/util.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "396b5a83e84a027cc7cbba9eed2f4205f75ecdad1ca5c500f355b1276e074f74"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default\n\nDocumentation:\nConstructs a value with arbitrary fields, intended to be overwritten\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn default() -> Self {\n Self {\n addr: SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), 0),\n len: 0,\n stride: 0,\n ecn: None,\n dst_ip: None,\n }\n }\n```"}], "func_name": "default", "docstring": "Constructs a value with arbitrary fields, intended to be overwritten", "repo": "quinn-rs/quinn", "path": "quinn-udp/src/lib.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-udp/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18ec322d2bde651910c347d16ea85856bd21c02e668f8a55292efb518d455d85"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: max_gso_segments\n\nDocumentation:\nChecks whether GSO support is available by checking the kernel version followed by setting\nthe UDP_SEGMENT option on a socket\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn max_gso_segments() -> usize {\n const GSO_SIZE: libc::c_int = 1500;\n\n if !SUPPORTED_BY_CURRENT_KERNEL.get_or_init(supported_by_current_kernel) {\n return 1;\n }\n\n let socket = match std::net::UdpSocket::bind(\"[::]:0\")\n .or_else(|_| std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)))\n {\n Ok(socket) => socket,\n Err(_) => return 1,\n };\n\n // As defined in linux/udp.h\n // #define UDP_MAX_SEGMENTS (1 << 6UL)\n match set_socket_option(&socket, libc::SOL_UDP, UDP_SEGMENT, GSO_SIZE) {\n Ok(()) => 64,\n Err(_e) => {\n crate::log::debug!(\n \"failed to set `UDP_SEGMENT` socket option ({_e}); setting `max_gso_segments = 1`\"\n );\n\n 1\n }\n }\n }\n```"}], "func_name": "max_gso_segments", "docstring": "Checks whether GSO support is available by checking the kernel version followed by setting\nthe UDP_SEGMENT option on a socket", "repo": "quinn-rs/quinn", "path": "quinn-udp/src/unix.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-udp/src/unix.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "875c1b34ab0f482eac2509e9441a8d85b2be56c7c11bc49b073eb93733847377"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_socket_option_supported\n\nDocumentation:\nReturns whether the given socket option is supported on the current platform\n\nYields `Ok(true)` if the option was set successfully, `Ok(false)` if setting\nthe option raised an `ENOPROTOOPT` error, and `Err` for any other error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_socket_option_supported(\n socket: &impl AsRawFd,\n level: libc::c_int,\n name: libc::c_int,\n value: libc::c_int,\n) -> io::Result {\n match set_socket_option(socket, level, name, value) {\n Ok(()) => Ok(true),\n Err(err) if err.raw_os_error() == Some(libc::ENOPROTOOPT) => Ok(false),\n Err(err) => Err(err),\n }\n}\n```"}], "func_name": "set_socket_option_supported", "docstring": "Returns whether the given socket option is supported on the current platform\n\nYields `Ok(true)` if the option was set successfully, `Ok(false)` if setting\nthe option raised an `ENOPROTOOPT` error, and `Err` for any other error.", "repo": "quinn-rs/quinn", "path": "quinn-udp/src/unix.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-udp/src/unix.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d718b6b3f071a02d15a2bd2ee1eb2a316262db44a79461d9b0ca3e7e3732987c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_gro\n\nDocumentation:\nEnable or disable receive offloading.\n\nAlso referred to as UDP Receive Segment Coalescing Offload (URO) on Windows.\n\n\n\nDisabled by default on Windows due to .\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_gro(&self, socket: UdpSockRef<'_>, enable: bool) -> io::Result<()> {\n set_socket_option(\n &*socket.0,\n WinSock::IPPROTO_UDP,\n WinSock::UDP_RECV_MAX_COALESCED_SIZE,\n match enable {\n // u32 per\n // https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-udp-socket-options.\n // Choice of 2^16 - 1 inspired by msquic.\n true => u16::MAX as u32,\n false => 0,\n },\n )\n }\n```"}], "func_name": "set_gro", "docstring": "Enable or disable receive offloading.\n\nAlso referred to as UDP Receive Segment Coalescing Offload (URO) on Windows.\n\n\n\nDisabled by default on Windows due to .", "repo": "quinn-rs/quinn", "path": "quinn-udp/src/windows.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-udp/src/windows.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "75f19afd25851909c5d8931ff800a3048d15f91abb3e57606fa47e452a1dcd9e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\n# Safety\n- `hdr` must contain a suitably aligned pointer to a big enough buffer to hold control messages\nbytes. All bytes of this buffer can be safely written.\n- The `Encoder` must be dropped before `hdr` is passed to a system call, and must not be leaked.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) unsafe fn new(hdr: &'a mut M) -> Self {\n Self {\n cmsg: hdr.cmsg_first_hdr().as_mut(),\n hdr,\n len: 0,\n }\n }\n```"}], "func_name": "new", "docstring": "# Safety\n- `hdr` must contain a suitably aligned pointer to a big enough buffer to hold control messages\nbytes. All bytes of this buffer can be safely written.\n- The `Encoder` must be dropped before `hdr` is passed to a system call, and must not be leaked.", "repo": "quinn-rs/quinn", "path": "quinn-udp/src/cmsg/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-udp/src/cmsg/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bfe31ba0597546d1dc856a430668b41f197dfbc652891b49d00097b347c0fc5f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push\n\nDocumentation:\nAppend a control message to the buffer.\n\n# Panics\n- If insufficient buffer space remains.\n- If `T` has stricter alignment requirements than `M::ControlMessage`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn push(&mut self, level: c_int, ty: c_int, value: T) {\n assert!(mem::align_of::() <= mem::align_of::());\n let space = M::ControlMessage::cmsg_space(mem::size_of_val(&value));\n assert!(\n self.hdr.control_len() >= self.len + space,\n \"control message buffer too small. Required: {}, Available: {}\",\n self.len + space,\n self.hdr.control_len()\n );\n let cmsg = self.cmsg.take().expect(\"no control buffer space remaining\");\n cmsg.set(\n level,\n ty,\n M::ControlMessage::cmsg_len(mem::size_of_val(&value)),\n );\n unsafe {\n ptr::write(cmsg.cmsg_data() as *const T as *mut T, value);\n }\n self.len += space;\n self.cmsg = unsafe { self.hdr.cmsg_nxt_hdr(cmsg).as_mut() };\n }\n```"}], "func_name": "push", "docstring": "Append a control message to the buffer.\n\n# Panics\n- If insufficient buffer space remains.\n- If `T` has stricter alignment requirements than `M::ControlMessage`", "repo": "quinn-rs/quinn", "path": "quinn-udp/src/cmsg/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-udp/src/cmsg/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c9e203dd4323b5417ae12c17b2d8cde57e9fa7fa283e9d584098c8594dfcc5e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish\n\nDocumentation:\nFinishes appending control messages to the buffer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn finish(self) {\n // Delegates to the `Drop` impl\n }\n```"}], "func_name": "finish", "docstring": "Finishes appending control messages to the buffer", "repo": "quinn-rs/quinn", "path": "quinn-udp/src/cmsg/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-udp/src/cmsg/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8b5df712598c97df04a293f132dd4f5bd71ebf152f3999ea7249a069c7cdc36f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decode\n\nDocumentation:\n# Safety\n\n`cmsg` must refer to a native cmsg containing a payload of type `T`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) unsafe fn decode(cmsg: &impl CMsgHdr) -> T {\n assert!(mem::align_of::() <= mem::align_of::());\n debug_assert_eq!(cmsg.len(), C::cmsg_len(mem::size_of::()));\n ptr::read(cmsg.cmsg_data() as *const T)\n}\n```"}], "func_name": "decode", "docstring": "# Safety\n\n`cmsg` must refer to a native cmsg containing a payload of type `T`", "repo": "quinn-rs/quinn", "path": "quinn-udp/src/cmsg/mod.rs", "url": "https://github.com/quinn-rs/quinn/blob/master/quinn-udp/src/cmsg/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bcdaacfbdec9ec0ca5e66d8a98444b49234f6b51b267a6c600ad6c2f4dbc6b38"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: register_read\n\nDocumentation:\nHelper function implementing reading registers from a HashMap.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn register_read(\n registers: &HashMap,\n addr: u16,\n cnt: u16,\n) -> Result, ExceptionCode> {\n let mut response_values = vec![0; cnt.into()];\n for i in 0..cnt {\n let reg_addr = addr + i;\n if let Some(r) = registers.get(®_addr) {\n response_values[i as usize] = *r;\n } else {\n println!(\"SERVER: Exception::IllegalDataAddress\");\n return Err(ExceptionCode::IllegalDataAddress);\n }\n }\n\n Ok(response_values)\n}\n```"}], "func_name": "register_read", "docstring": "Helper function implementing reading registers from a HashMap.", "repo": "slowtec/tokio-modbus", "path": "examples/rtu-over-tcp-server.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/examples/rtu-over-tcp-server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ce7c6bc0a35c4b8ec67385a71c40d99d2f697d032bfa891ec29869cd36e80dca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: register_write\n\nDocumentation:\nWrite a holding register. Used by both the write single register\nand write multiple registers requests.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn register_write(\n registers: &mut HashMap,\n addr: u16,\n values: &[u16],\n) -> Result<(), ExceptionCode> {\n for (i, value) in values.iter().enumerate() {\n let reg_addr = addr + i as u16;\n if let Some(r) = registers.get_mut(®_addr) {\n *r = *value;\n } else {\n println!(\"SERVER: Exception::IllegalDataAddress\");\n return Err(ExceptionCode::IllegalDataAddress);\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "register_write", "docstring": "Write a holding register. Used by both the write single register\nand write multiple registers requests.", "repo": "slowtec/tokio-modbus", "path": "examples/rtu-over-tcp-server.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/examples/rtu-over-tcp-server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c151b5f99a6540994d2bfae24a9630afc04cfa330a65a0470b1582176bb60d5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: attach\n\nDocumentation:\nConnect to no particular Modbus slave device for sending\nbroadcast messages.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn attach(transport: T) -> Context\nwhere\n T: AsyncRead + AsyncWrite + Debug + Unpin + Send + 'static,\n{\n attach_slave(transport, Slave::broadcast())\n}\n```"}], "func_name": "attach", "docstring": "Connect to no particular Modbus slave device for sending\nbroadcast messages.", "repo": "slowtec/tokio-modbus", "path": "src/client/rtu.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/rtu.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "784f0f5402a628fa59ca6221db10ea9efc9deafc46834a440abe5968a73f288b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: attach_slave\n\nDocumentation:\nConnect to any kind of Modbus slave device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn attach_slave(transport: T, slave: Slave) -> Context\nwhere\n T: AsyncRead + AsyncWrite + Debug + Unpin + Send + 'static,\n{\n let client = crate::service::rtu::Client::new(transport, slave);\n Context {\n client: Box::new(client),\n }\n}\n```"}], "func_name": "attach_slave", "docstring": "Connect to any kind of Modbus slave device.", "repo": "slowtec/tokio-modbus", "path": "src/client/rtu.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/rtu.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5973ddb921616b8d18e09de1dc1aab0846e3423759dfd78f24f97750d7d7980d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nEstablish a direct connection to a Modbus TCP coupler.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn connect(socket_addr: SocketAddr) -> io::Result {\n connect_slave(socket_addr, Slave::tcp_device()).await\n}\n```"}], "func_name": "connect", "docstring": "Establish a direct connection to a Modbus TCP coupler.", "repo": "slowtec/tokio-modbus", "path": "src/client/tcp.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/tcp.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cebd875c248bc8649da0925987e1c0e226e46c52893dfa6f5f7c292471120132"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect_slave\n\nDocumentation:\nConnect to a physical, broadcast, or custom Modbus device,\nprobably through a Modbus TCP gateway that is forwarding\nmessages to/from the corresponding slave device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn connect_slave(socket_addr: SocketAddr, slave: Slave) -> io::Result {\n let transport = TcpStream::connect(socket_addr).await?;\n let context = attach_slave(transport, slave);\n Ok(context)\n}\n```"}], "func_name": "connect_slave", "docstring": "Connect to a physical, broadcast, or custom Modbus device,\nprobably through a Modbus TCP gateway that is forwarding\nmessages to/from the corresponding slave device.", "repo": "slowtec/tokio-modbus", "path": "src/client/tcp.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/tcp.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "58e1f84deb732e65f8a169c06f3d6289882a2bf0c762cc197517f0c9181c1ef6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: attach\n\nDocumentation:\nAttach a new client context to a direct transport connection.\n\nThe connection could either be an ordinary [`TcpStream`] or a TLS connection.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn attach(transport: T) -> Context\nwhere\n T: AsyncRead + AsyncWrite + Send + Unpin + fmt::Debug + 'static,\n{\n attach_slave(transport, Slave::tcp_device())\n}\n```"}], "func_name": "attach", "docstring": "Attach a new client context to a direct transport connection.\n\nThe connection could either be an ordinary [`TcpStream`] or a TLS connection.", "repo": "slowtec/tokio-modbus", "path": "src/client/tcp.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/tcp.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3bfbfc5137882ea005b87173d1b9cd9192c76175d8499f5a149c702119c0a2d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: attach_slave\n\nDocumentation:\nAttach a new client context to a transport connection.\n\nThe connection could either be an ordinary [`TcpStream`] or a TLS connection.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn attach_slave(transport: T, slave: Slave) -> Context\nwhere\n T: AsyncRead + AsyncWrite + Send + Unpin + fmt::Debug + 'static,\n{\n let client = crate::service::tcp::Client::new(transport, slave);\n Context {\n client: Box::new(client),\n }\n}\n```"}], "func_name": "attach_slave", "docstring": "Attach a new client context to a transport connection.\n\nThe connection could either be an ordinary [`TcpStream`] or a TLS connection.", "repo": "slowtec/tokio-modbus", "path": "src/client/tcp.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/tcp.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0466df6fe8472062526531778fb7e423dd084afe4bd7d6c906e3d9fde585d4b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_timeout\n\nDocumentation:\nSets a timeout duration for all subsequent operations.\n\nThe timeout is disabled by passing `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_timeout(&mut self, duration: impl Into>) {\n self.timeout = duration.into();\n }\n```"}], "func_name": "set_timeout", "docstring": "Sets a timeout duration for all subsequent operations.\n\nThe timeout is disabled by passing `None`.", "repo": "slowtec/tokio-modbus", "path": "src/client/sync/mod.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/sync/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "349c35586435f753ca21fd5861dedb7efeccde3a609dd4362b832ab392ec9c81"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_timeout\n\nDocumentation:\nDisables the timeout for all subsequent operations.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reset_timeout(&mut self) {\n self.timeout = None;\n }\n```"}], "func_name": "reset_timeout", "docstring": "Disables the timeout for all subsequent operations.", "repo": "slowtec/tokio-modbus", "path": "src/client/sync/mod.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/sync/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "441be5fbf85ac1246801f8ec4de6f899d024086e709636d31604855add99b860"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nConnect to no particular _Modbus_ slave device for sending\nbroadcast messages.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connect(builder: &SerialPortBuilder) -> io::Result {\n connect_slave(builder, Slave::broadcast())\n}\n```"}], "func_name": "connect", "docstring": "Connect to no particular _Modbus_ slave device for sending\nbroadcast messages.", "repo": "slowtec/tokio-modbus", "path": "src/client/sync/rtu.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/sync/rtu.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5df09a3d01a154ac847eaae8fab3c0840b13c5485885781656dcec10499f94a9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect_with_timeout\n\nDocumentation:\nConnect to no particular _Modbus_ slave device for sending\nbroadcast messages with a timeout.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connect_with_timeout(\n builder: &SerialPortBuilder,\n timeout: Option,\n) -> io::Result {\n connect_slave_with_timeout(builder, Slave::broadcast(), timeout)\n}\n```"}], "func_name": "connect_with_timeout", "docstring": "Connect to no particular _Modbus_ slave device for sending\nbroadcast messages with a timeout.", "repo": "slowtec/tokio-modbus", "path": "src/client/sync/rtu.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/sync/rtu.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb4c0b73c7b134a74c30c5b1eaea679d83aab176f7dc69a1ef16360d7ccac11c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect_slave\n\nDocumentation:\nConnect to any kind of _Modbus_ slave device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connect_slave(builder: &SerialPortBuilder, slave: Slave) -> io::Result {\n connect_slave_with_timeout(builder, slave, None)\n}\n```"}], "func_name": "connect_slave", "docstring": "Connect to any kind of _Modbus_ slave device.", "repo": "slowtec/tokio-modbus", "path": "src/client/sync/rtu.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/sync/rtu.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "db062c0cda9e1a538a9b942f718b0c615277d49f7adb57865ac6d00ec316baee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect_slave_with_timeout\n\nDocumentation:\nConnect to any kind of _Modbus_ slave device with a timeout.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connect_slave_with_timeout(\n builder: &SerialPortBuilder,\n slave: Slave,\n timeout: Option,\n) -> io::Result {\n let runtime = tokio::runtime::Builder::new_current_thread()\n .enable_io()\n .enable_time()\n .build()?;\n // SerialStream::open requires a runtime at least on cfg(unix).\n let serial = block_on_with_timeout(&runtime, timeout, async { SerialStream::open(builder) })?;\n let async_ctx = crate::client::rtu::attach_slave(serial, slave);\n let sync_ctx = Context {\n runtime,\n async_ctx,\n timeout,\n };\n Ok(sync_ctx)\n}\n```"}], "func_name": "connect_slave_with_timeout", "docstring": "Connect to any kind of _Modbus_ slave device with a timeout.", "repo": "slowtec/tokio-modbus", "path": "src/client/sync/rtu.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/sync/rtu.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "99a4d961b29e786a3877a60d99a3f41c5b3ad96f09e4df0dd89ddd4988fddd43"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nEstablish a direct connection to a _Modbus_ TCP coupler.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connect(socket_addr: SocketAddr) -> io::Result {\n connect_slave(socket_addr, Slave::tcp_device())\n}\n```"}], "func_name": "connect", "docstring": "Establish a direct connection to a _Modbus_ TCP coupler.", "repo": "slowtec/tokio-modbus", "path": "src/client/sync/tcp.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/sync/tcp.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd93db5eb514be86cc37baebc2fe435be66f43caeed31bbc85c9df6a0dca3549"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect_with_timeout\n\nDocumentation:\nEstablish a direct connection to a _Modbus_ TCP coupler with a timeout.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connect_with_timeout(\n socket_addr: SocketAddr,\n timeout: Option,\n) -> io::Result {\n connect_slave_with_timeout(socket_addr, Slave::tcp_device(), timeout)\n}\n```"}], "func_name": "connect_with_timeout", "docstring": "Establish a direct connection to a _Modbus_ TCP coupler with a timeout.", "repo": "slowtec/tokio-modbus", "path": "src/client/sync/tcp.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/sync/tcp.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d9e165b6dc8d8ebc73432ef668998dc130be1d57a90b17eb00b6225c9236c2d8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect_slave\n\nDocumentation:\nConnect to any kind of _Modbus_ slave device, probably through a _Modbus_ TCP/RTU\ngateway that is forwarding messages to/from the corresponding unit identified\nby the slave parameter.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connect_slave(socket_addr: SocketAddr, slave: Slave) -> io::Result {\n connect_slave_with_timeout(socket_addr, slave, None)\n}\n```"}], "func_name": "connect_slave", "docstring": "Connect to any kind of _Modbus_ slave device, probably through a _Modbus_ TCP/RTU\ngateway that is forwarding messages to/from the corresponding unit identified\nby the slave parameter.", "repo": "slowtec/tokio-modbus", "path": "src/client/sync/tcp.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/client/sync/tcp.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "875fabe70d83cb4c404e2d467b2c4e5c70035338baaff9581027e4d527c95477"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_from_path\n\nDocumentation:\nset up a new [`Server`] instance from an interface path and baud rate\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_from_path>(p: P, baud_rate: u32) -> io::Result {\n let serial =\n SerialStream::open(&tokio_serial::new(p.as_ref().to_string_lossy(), baud_rate))?;\n Ok(Server { serial })\n }\n```"}], "func_name": "new_from_path", "docstring": "set up a new [`Server`] instance from an interface path and baud rate", "repo": "slowtec/tokio-modbus", "path": "src/server/rtu.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/server/rtu.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6de68dea136844ccd15f5e6ca537ed00d108ee7f830f7e2861e058a4baaf7b6a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: serve_until\n\nDocumentation:\nProcess Modbus RTU requests until finished or aborted.\n\nWarning: Request processing is not scoped and could be aborted at any internal await point!\nSee also: \n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn serve_until(self, service: S, abort_signal: X) -> io::Result\n where\n S: Service + Send + Sync + 'static,\n S::Request: From> + Send,\n X: Future + Sync + Send + Unpin + 'static,\n {\n let framed = Framed::new(self.serial, ServerCodec::default());\n let abort_signal = abort_signal.fuse();\n tokio::select! {\n res = process(framed, service) => {\n res.map(|()| Terminated::Finished)\n },\n () = abort_signal => {\n Ok(Terminated::Aborted)\n }\n }\n }\n```"}], "func_name": "serve_until", "docstring": "Process Modbus RTU requests until finished or aborted.\n\nWarning: Request processing is not scoped and could be aborted at any internal await point!\nSee also: ", "repo": "slowtec/tokio-modbus", "path": "src/server/rtu.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/server/rtu.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0ee9a10595859f91d5a3222f40c42a585f825274617c950d411f3e453845d4e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process\n\nDocumentation:\nframe wrapper around the underlying service's responses to forwarded requests\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn process(mut framed: Framed, service: S) -> io::Result<()>\nwhere\n S: Service + Send + Sync + 'static,\n S::Request: From> + Send,\n{\n loop {\n let Some(request_adu) = framed.next().await.transpose().inspect_err(|err| {\n log::debug!(\"Failed to receive and decode request ADU: {err}\");\n })?\n else {\n log::debug!(\"Stream has finished\");\n break;\n };\n\n let RequestAdu {\n hdr,\n pdu: RequestPdu(request),\n } = &request_adu;\n let hdr = *hdr;\n let fc = request.function_code();\n let OptionalResponsePdu(Some(response_pdu)) = service\n .call(request_adu.into())\n .await\n .map(Into::into)\n .map_err(|e| ExceptionResponse {\n function: fc,\n exception: e.into(),\n })\n .into()\n else {\n log::trace!(\"No response for request {hdr:?} (function = {fc})\");\n continue;\n };\n\n framed\n .send(ResponseAdu {\n hdr,\n pdu: response_pdu,\n })\n .await\n .inspect_err(|err| {\n log::debug!(\"Failed to send response for request {hdr:?} (function = {fc}): {err}\");\n })?;\n }\n Ok(())\n}\n```"}], "func_name": "process", "docstring": "frame wrapper around the underlying service's responses to forwarded requests", "repo": "slowtec/tokio-modbus", "path": "src/server/rtu.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/server/rtu.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3059d8ade6c8cb429c6f2d9412e3c9c79ee1bf6e7c974a002b3f6d883837d011"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: serve\n\nDocumentation:\nListens for incoming connections and starts a Modbus RTU over TCP server task for\neach connection.\n\n`OnConnected` is responsible for creating both the service and the\ntransport layer for the underlying TCP stream. If `OnConnected` returns\nwith `Err` then listening stops and [`Self::serve()`] returns with an error.\nIf `OnConnected` returns `Ok(None)` then the connection is rejected\nbut [`Self::serve()`] continues listening for new connections.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn serve(\n &self,\n on_connected: &OnConnected,\n on_process_error: OnProcessError,\n ) -> io::Result<()>\n where\n S: Service + Send + Sync + 'static,\n S::Request: From> + Send,\n T: AsyncRead + AsyncWrite + Unpin + Send + 'static,\n OnConnected: Fn(TcpStream, SocketAddr) -> F,\n F: Future>>,\n OnProcessError: FnOnce(io::Error) + Clone + Send + 'static,\n {\n loop {\n let (stream, socket_addr) = self.listener.accept().await?;\n log::debug!(\"Accepted connection from {socket_addr}\");\n\n let Some((service, transport)) = on_connected(stream, socket_addr).await? else {\n log::debug!(\"No service for connection from {socket_addr}\");\n continue;\n };\n let on_process_error = on_process_error.clone();\n\n // use RTU codec\n let framed = Framed::new(transport, ServerCodec::default());\n\n tokio::spawn(async move {\n log::debug!(\"Processing requests from {socket_addr}\");\n if let Err(err) = process(framed, service).await {\n on_process_error(err);\n }\n });\n }\n }\n```"}], "func_name": "serve", "docstring": "Listens for incoming connections and starts a Modbus RTU over TCP server task for\neach connection.\n\n`OnConnected` is responsible for creating both the service and the\ntransport layer for the underlying TCP stream. If `OnConnected` returns\nwith `Err` then listening stops and [`Self::serve()`] returns with an error.\nIf `OnConnected` returns `Ok(None)` then the connection is rejected\nbut [`Self::serve()`] continues listening for new connections.", "repo": "slowtec/tokio-modbus", "path": "src/server/rtu_over_tcp.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/server/rtu_over_tcp.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9e162ce796433a5bd3f2a18e2198aae67a5448ff62b7eecc3a8a79db569eaeed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: serve_until\n\nDocumentation:\nStart an abortable Modbus RTU over TCP server task.\n\nWarning: Request processing is not scoped and could be aborted at any internal await point!\nSee also: \n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn serve_until(\n self,\n on_connected: &OnConnected,\n on_process_error: OnProcessError,\n abort_signal: X,\n ) -> io::Result\n where\n S: Service + Send + Sync + 'static,\n S::Request: From> + Send,\n T: AsyncRead + AsyncWrite + Unpin + Send + 'static,\n X: Future + Sync + Send + Unpin + 'static,\n OnConnected: Fn(TcpStream, SocketAddr) -> F,\n F: Future>>,\n OnProcessError: FnOnce(io::Error) + Clone + Send + 'static,\n {\n let abort_signal = abort_signal.fuse();\n tokio::select! {\n res = self.serve(on_connected, on_process_error) => {\n res.map(|()| Terminated::Finished)\n },\n () = abort_signal => {\n Ok(Terminated::Aborted)\n }\n }\n }\n```"}], "func_name": "serve_until", "docstring": "Start an abortable Modbus RTU over TCP server task.\n\nWarning: Request processing is not scoped and could be aborted at any internal await point!\nSee also: ", "repo": "slowtec/tokio-modbus", "path": "src/server/rtu_over_tcp.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/server/rtu_over_tcp.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3b81d1fa0a0f30800eea7075a9bd0f8a475a88282a08928994c4d398e8686bd4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process\n\nDocumentation:\nThe request-response loop spawned by [`serve_until`] for each client\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn process(mut framed: Framed, service: S) -> io::Result<()>\nwhere\n S: Service + Send + Sync + 'static,\n S::Request: From> + Send,\n T: AsyncRead + AsyncWrite + Unpin,\n{\n loop {\n let Some(request_adu) = framed.next().await.transpose().inspect_err(|err| {\n log::debug!(\"Failed to receive and decode request ADU: {err}\");\n })?\n else {\n log::debug!(\"TCP socket has been closed\");\n break;\n };\n\n let RequestAdu {\n hdr,\n pdu: RequestPdu(request),\n } = &request_adu;\n let hdr = *hdr;\n let fc = request.function_code();\n let OptionalResponsePdu(Some(response_pdu)) = service\n .call(request_adu.into())\n .await\n .map(Into::into)\n .map_err(|e| ExceptionResponse {\n function: fc,\n exception: e.into(),\n })\n .into()\n else {\n log::trace!(\"No response for request {hdr:?} (function = {fc})\");\n continue;\n };\n\n framed\n .send(ResponseAdu {\n hdr,\n pdu: response_pdu,\n })\n .await\n .inspect_err(|err| {\n log::debug!(\"Failed to send response for request {hdr:?} (function = {fc}): {err}\");\n })?;\n }\n\n Ok(())\n}\n```"}], "func_name": "process", "docstring": "The request-response loop spawned by [`serve_until`] for each client", "repo": "slowtec/tokio-modbus", "path": "src/server/rtu_over_tcp.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/server/rtu_over_tcp.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9faa8c5cafc48b4e6fe1f842bffaeb43f4665f4e07c8120234b3e0de056f3918"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: serve\n\nDocumentation:\nListens for incoming connections and starts a Modbus TCP server task for\neach connection.\n\n`OnConnected` is responsible for creating both the service and the\ntransport layer for the underlying TCP stream. If `OnConnected` returns\nwith `Err` then listening stops and [`Self::serve()`] returns with an error.\nIf `OnConnected` returns `Ok(None)` then the connection is rejected\nbut [`Self::serve()`] continues listening for new connections.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn serve(\n &self,\n on_connected: &OnConnected,\n on_process_error: OnProcessError,\n ) -> io::Result<()>\n where\n S: Service + Send + Sync + 'static,\n S::Request: From> + Send,\n T: AsyncRead + AsyncWrite + Unpin + Send + 'static,\n OnConnected: Fn(TcpStream, SocketAddr) -> F,\n F: Future>>,\n OnProcessError: FnOnce(io::Error) + Clone + Send + 'static,\n {\n loop {\n let (stream, socket_addr) = self.listener.accept().await?;\n log::debug!(\"Accepted connection from {socket_addr}\");\n\n let Some((service, transport)) = on_connected(stream, socket_addr).await? else {\n log::debug!(\"No service for connection from {socket_addr}\");\n continue;\n };\n let on_process_error = on_process_error.clone();\n\n let framed = Framed::new(transport, ServerCodec::default());\n\n tokio::spawn(async move {\n log::debug!(\"Processing requests from {socket_addr}\");\n if let Err(err) = process(framed, service).await {\n on_process_error(err);\n }\n });\n }\n }\n```"}], "func_name": "serve", "docstring": "Listens for incoming connections and starts a Modbus TCP server task for\neach connection.\n\n`OnConnected` is responsible for creating both the service and the\ntransport layer for the underlying TCP stream. If `OnConnected` returns\nwith `Err` then listening stops and [`Self::serve()`] returns with an error.\nIf `OnConnected` returns `Ok(None)` then the connection is rejected\nbut [`Self::serve()`] continues listening for new connections.", "repo": "slowtec/tokio-modbus", "path": "src/server/tcp.rs", "url": "https://github.com/slowtec/tokio-modbus/blob/master/src/server/tcp.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d2b7d87e5f058fbf300782060d0ab6458cadcca85e2e98d5bd267db2cdcdbdcb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nBuilds AAB(s) and returns the built AAB(s) paths\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n config: &Config,\n env: &Env,\n noise_level: NoiseLevel,\n profile: Profile,\n targets: Vec<&Target>,\n split_per_abi: bool,\n) -> Result, AabError> {\n let build_ty = profile.as_str().to_upper_camel_case();\n\n let gradle_args = if split_per_abi {\n targets\n .iter()\n .map(|t| format!(\"bundle{}{}\", t.arch_upper_camel_case(), build_ty))\n .collect()\n } else {\n let mut args = vec![format!(\"bundleUniversal{}\", build_ty)];\n\n if !targets.is_empty() {\n args.extend_from_slice(&[\n format!(\n \"-PabiList={}\",\n targets.iter().map(|t| t.abi).collect::>().join(\",\")\n ),\n format!(\n \"-ParchList={}\",\n targets.iter().map(|t| t.arch).collect::>().join(\",\")\n ),\n format!(\n \"-PtargetList={}\",\n targets\n .iter()\n .map(|t| t.triple.split('-').next().unwrap())\n .collect::>()\n .join(\",\")\n ),\n ])\n }\n\n args\n };\n gradlew(config, env)\n .before_spawn(move |cmd| {\n cmd.args(&gradle_args).arg(match noise_level {\n NoiseLevel::Polite => \"--warn\",\n NoiseLevel::LoudAndProud => \"--info\",\n NoiseLevel::FranklyQuitePedantic => \"--debug\",\n });\n Ok(())\n })\n .start()\n .inspect_err(|err| {\n if err.kind() == std::io::ErrorKind::NotFound {\n log::error!(\"`gradlew` not found. Make sure you have the Android SDK installed and added to your PATH\");\n }\n })?\n .wait()?;\n\n let mut outputs = Vec::new();\n if split_per_abi {\n outputs.extend(\n targets\n .iter()\n .map(|t| dunce::simplified(&aab_path(config, profile, t.arch)).to_path_buf()),\n );\n } else {\n outputs.push(dunce::simplified(&aab_path(config, profile, \"universal\")).to_path_buf());\n }\n\n Ok(outputs)\n}\n```"}], "func_name": "build", "docstring": "Builds AAB(s) and returns the built AAB(s) paths", "repo": "tauri-apps/cargo-mobile2", "path": "src/android/aab.rs", "url": "https://github.com/tauri-apps/cargo-mobile2/blob/master/src/android/aab.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ae72b8d1376d7dde53385ef0f27b7c8d920554fdd4b9800b4d50ff7797dc559c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nBuilds APK(s) and returns the built APK(s) paths\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n config: &Config,\n env: &Env,\n noise_level: NoiseLevel,\n profile: Profile,\n targets: Vec<&Target>,\n split_per_abi: bool,\n) -> Result, ApkError> {\n JniLibs::remove_broken_links(config).map_err(ApkError::LibSymlinkCleaningFailed)?;\n\n let build_ty = profile.as_str().to_upper_camel_case();\n\n let gradle_args = if split_per_abi {\n targets\n .iter()\n .map(|t| format!(\"assemble{}{}\", t.arch_upper_camel_case(), build_ty))\n .collect()\n } else {\n let mut args = vec![format!(\"assembleUniversal{}\", build_ty)];\n\n if !targets.is_empty() {\n args.extend_from_slice(&[\n format!(\n \"-PabiList={}\",\n targets.iter().map(|t| t.abi).collect::>().join(\",\")\n ),\n format!(\n \"-ParchList={}\",\n targets.iter().map(|t| t.arch).collect::>().join(\",\")\n ),\n format!(\n \"-PtargetList={}\",\n targets\n .iter()\n .map(|t| t.triple.split('-').next().unwrap())\n .collect::>()\n .join(\",\")\n ),\n ])\n }\n\n args\n };\n\n gradlew(config, env)\n .before_spawn(move |cmd| {\n cmd.args(&gradle_args).arg(match noise_level {\n NoiseLevel::Polite => \"--warn\",\n NoiseLevel::LoudAndProud => \"--info\",\n NoiseLevel::FranklyQuitePedantic => \"--debug\",\n });\n Ok(())\n })\n .start()\n .inspect_err(|err| {\n if err.kind() == std::io::ErrorKind::NotFound {\n log::error!(\"`gradlew` not found. Make sure you have the Android SDK installed and added to your PATH\");\n }\n })?\n .wait()?;\n\n let mut outputs = Vec::new();\n if split_per_abi {\n let paths = targets\n .iter()\n .map(|t| {\n apks_paths(config, profile, t.arch)\n .into_iter()\n .reduce(last_modified)\n .unwrap()\n })\n .collect::>();\n outputs.extend(paths);\n } else {\n let path = apks_paths(config, profile, \"universal\")\n .into_iter()\n .reduce(last_modified)\n .unwrap();\n outputs.push(path);\n }\n\n Ok(outputs)\n}\n```"}], "func_name": "build", "docstring": "Builds APK(s) and returns the built APK(s) paths", "repo": "tauri-apps/cargo-mobile2", "path": "src/android/apk.rs", "url": "https://github.com/tauri-apps/cargo-mobile2/blob/master/src/android/apk.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1634b0e1f206043a80503be319a5c3d1cfa6f3c1658f33f83e6a3a550323daad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_create_directory\n\nDocumentation:\nCreate a new [`Action::CreateDirectory`].\nUses `transform_path` to transform `dest`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_create_directory(\n dest: &Path,\n transform_path: impl Fn(&Path) -> Result,\n ) -> Result {\n Ok(Self::CreateDirectory {\n dest: transform_path(dest)?,\n })\n }\n```"}], "func_name": "new_create_directory", "docstring": "Create a new [`Action::CreateDirectory`].\nUses `transform_path` to transform `dest`.", "repo": "tauri-apps/cargo-mobile2", "path": "src/bicycle/traverse.rs", "url": "https://github.com/tauri-apps/cargo-mobile2/blob/master/src/bicycle/traverse.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "670880533ecd0a7576fbfd6877efa00ba6364ec571971ba9225420ffbb2b1b17"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_copy_file\n\nDocumentation:\nCreate a new [`Action::CopyFile`].\nUses `transform_path` to transform `dest`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_copy_file(\n src: &Path,\n dest: &Path,\n transform_path: impl Fn(&Path) -> Result,\n ) -> Result {\n let dest = append_path(dest, src, false);\n Ok(Self::CopyFile {\n src: src.to_owned(),\n dest: transform_path(&dest)?,\n })\n }\n```"}], "func_name": "new_copy_file", "docstring": "Create a new [`Action::CopyFile`].\nUses `transform_path` to transform `dest`.", "repo": "tauri-apps/cargo-mobile2", "path": "src/bicycle/traverse.rs", "url": "https://github.com/tauri-apps/cargo-mobile2/blob/master/src/bicycle/traverse.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a63009f7040d758453bd243df64f7698fb546b29ffc0a8467b619ab17f55652c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_write_template\n\nDocumentation:\nCreate a new [`Action::WriteTemplate`].\nUses `transform_path` to transform `dest`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_write_template(\n src: &Path,\n dest: &Path,\n transform_path: impl Fn(&Path) -> Result,\n ) -> Result {\n let dest = append_path(dest, src, true);\n Ok(Self::WriteTemplate {\n src: src.to_owned(),\n dest: transform_path(&dest)?,\n })\n }\n```"}], "func_name": "new_write_template", "docstring": "Create a new [`Action::WriteTemplate`].\nUses `transform_path` to transform `dest`.", "repo": "tauri-apps/cargo-mobile2", "path": "src/bicycle/traverse.rs", "url": "https://github.com/tauri-apps/cargo-mobile2/blob/master/src/bicycle/traverse.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "500e9b7c6f368997121a8362e1838e8387a391a729022c5886cf5f88cdd371ed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dest\n\nDocumentation:\nGets the destination of any [`Action`] variant.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn dest(&self) -> &Path {\n match self {\n Self::CreateDirectory { dest }\n | Self::CopyFile { dest, .. }\n | Self::WriteTemplate { dest, .. } => dest,\n }\n }\n```"}], "func_name": "dest", "docstring": "Gets the destination of any [`Action`] variant.", "repo": "tauri-apps/cargo-mobile2", "path": "src/bicycle/traverse.rs", "url": "https://github.com/tauri-apps/cargo-mobile2/blob/master/src/bicycle/traverse.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ca0de3d313a4df47b63308b37c4879a4672b70408b6938d98ed09c0217b1b4c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: traverse\n\nDocumentation:\nTraverse file tree at `src` to generate an [`Action`] list.\nThe [`Action`] list specifies how to generate the `src` file tree at `dest`,\nand can be executed by [`Bicycle::process_actions`](super::Bicycle::process_actions).\n\nFile tree contents are interpreted as follows:\n- Each directory in the file tree generates an [`Action::CreateDirectory`].\nDirectories are traversed recursively.\n- Each file that doesn't end in `template_ext` generates an [`Action::CopyFile`].\n- Each file that ends in `template_ext` generates an [`Action::WriteTemplate`].\n\n`transform_path` is used to post-process destination path strings.\n[`Bicycle::transform_path`](super::Bicycle::transform_path) is one possible implementation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn traverse(\n src: impl AsRef,\n dest: impl AsRef,\n transform_path: impl Fn(&Path) -> Result,\n template_ext: Option<&str>,\n) -> Result, TraversalError> {\n let src = src.as_ref();\n let dest = dest.as_ref();\n let mut actions = VecDeque::new();\n traverse_dir(src, dest, &transform_path, template_ext, &mut actions).map(|_| actions)\n}\n```"}], "func_name": "traverse", "docstring": "Traverse file tree at `src` to generate an [`Action`] list.\nThe [`Action`] list specifies how to generate the `src` file tree at `dest`,\nand can be executed by [`Bicycle::process_actions`](super::Bicycle::process_actions).\n\nFile tree contents are interpreted as follows:\n- Each directory in the file tree generates an [`Action::CreateDirectory`].\nDirectories are traversed recursively.\n- Each file that doesn't end in `template_ext` generates an [`Action::CopyFile`].\n- Each file that ends in `template_ext` generates an [`Action::WriteTemplate`].\n\n`transform_path` is used to post-process destination path strings.\n[`Bicycle::transform_path`](super::Bicycle::transform_path) is one possible implementation.", "repo": "tauri-apps/cargo-mobile2", "path": "src/bicycle/traverse.rs", "url": "https://github.com/tauri-apps/cargo-mobile2/blob/master/src/bicycle/traverse.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93b9bce48a90e7b6f7a9a0eec92949619dec3a3da96b045a2bf2ad2b52adf591"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: find_entry_by_app_name\n\nDocumentation:\nReturns the first FreeDesktop XDG .desktop entry, found inside `dir_path`, when the\n\"Name\" atribute of that entry is `app_name`.\n\nThe return value is actually a tuple containing the entry itself, and the path at which\nit was found.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn find_entry_by_app_name(\n dir_path: &Path,\n app_name: &OsStr,\n) -> Option<(FreeDesktopEntry, PathBuf)> {\n for entry in dir_path.read_dir().ok()?.filter_map(Result::ok) {\n let entry_path = entry.path();\n // If it is a file we open it\n if entry_path.is_file() {\n if let Ok(parsed) = parse_entry(&entry_path) {\n if parsed\n .section(\"Desktop Entry\")\n .attr(\"Name\")\n .map(str::as_ref)\n == Some(app_name)\n {\n return Some((parsed, entry_path));\n }\n }\n } else if entry.path().is_dir() {\n // Recursively keep searching if it is a directory\n if let Some(result) = find_entry_by_app_name(&entry_path, app_name) {\n return Some(result);\n }\n }\n }\n None\n}\n```"}], "func_name": "find_entry_by_app_name", "docstring": "Returns the first FreeDesktop XDG .desktop entry, found inside `dir_path`, when the\n\"Name\" atribute of that entry is `app_name`.\n\nThe return value is actually a tuple containing the entry itself, and the path at which\nit was found.", "repo": "tauri-apps/cargo-mobile2", "path": "src/os/linux/xdg.rs", "url": "https://github.com/tauri-apps/cargo-mobile2/blob/master/src/os/linux/xdg.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "21b28480491ba23fd39ac02083e7c3496c2b027e1db16454a5e4761e55c0e0cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: _clear\n\nDocumentation:\nClears the buffer and returns buffered bytes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn _clear(&mut self) -> &[u8] {\n let buffered = &self.bytes[..self.flushed];\n self.written = 0;\n self.flushed = 0;\n buffered\n }\n```"}], "func_name": "_clear", "docstring": "Clears the buffer and returns buffered bytes.", "repo": "bytebeamio/rumqtt", "path": "benchmarks/parsers/nats.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/benchmarks/parsers/nats.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b16ac746489d838c0c9504d7e43a98483c3da817dd0ee1125b6f37f3f07d3046"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decode\n\nDocumentation:\nDecodes a single operation from the server.\n\nIf the connection is closed, `None` will be returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn decode(mut stream: impl BufRead) -> io::Result> {\n // Read a line, which should be human readable.\n let mut line = Vec::new();\n if stream.read_until(b'\\n', &mut line)? == 0 {\n // If zero bytes were read, the connection is closed.\n return Ok(None);\n }\n\n // Convert into a UTF8 string for simpler parsing.\n let line = String::from_utf8(line).map_err(|err| Error::new(ErrorKind::InvalidInput, err))?;\n let line_uppercase = line.trim();\n // .to_uppercase();\n\n if line_uppercase.starts_with(\"PING\") {\n return Ok(Some(ServerOp::Ping));\n }\n\n if line_uppercase.starts_with(\"PONG\") {\n return Ok(Some(ServerOp::Pong));\n }\n\n if line_uppercase.starts_with(\"MSG\") {\n // Extract whitespace-delimited arguments that come after \"MSG\".\n let args = line[\"MSG\".len()..]\n .split_whitespace()\n .filter(|s| !s.is_empty());\n let args = args.collect::>();\n\n // Parse the operation syntax: MSG [reply-to] <#bytes>\n let (subject, sid, reply_to, num_bytes) = match args[..] {\n [subject, sid, num_bytes] => (subject, sid, None, num_bytes),\n [subject, sid, reply_to, num_bytes] => (subject, sid, Some(reply_to), num_bytes),\n _ => {\n return Err(Error::new(\n ErrorKind::InvalidInput,\n \"invalid number of arguments after MSG\",\n ))\n }\n };\n\n // Convert the slice into an owned string.\n let subject = subject.to_string();\n\n // Parse the subject ID.\n let sid = u64::from_str(sid).map_err(|_| {\n Error::new(\n ErrorKind::InvalidInput,\n \"cannot parse sid argument after MSG\",\n )\n })?;\n\n // Convert the slice into an owned string.\n let reply_to = reply_to.map(ToString::to_string);\n\n // Parse the number of payload bytes.\n let num_bytes = u32::from_str(num_bytes).map_err(|_| {\n Error::new(\n ErrorKind::InvalidInput,\n \"cannot parse the number of bytes argument after MSG\",\n )\n })?;\n\n // Read the payload.\n let mut payload = vec![0; num_bytes as usize];\n stream.read_exact(&mut payload[..])?;\n // Read \"\\r\\n\".\n stream.read_exact(&mut [0_u8; 2])?;\n\n return Ok(Some(ServerOp::Msg {\n subject,\n sid,\n reply_to,\n payload,\n }));\n }\n\n if line_uppercase.starts_with(\"HMSG\") {\n // Extract whitespace-delimited arguments that come after \"HMSG\".\n let args = line[\"HMSG\".len()..]\n .split_whitespace()\n .filter(|s| !s.is_empty());\n let args = args.collect::>();\n\n // Parse the operation syntax:\n // `HMSG [reply-to] <# header bytes>\n // <# total bytes>\\r\\n\\r\\n[headers]\\r\\n\\r\\n[payload]\\r\\n`\n let (subject, sid, reply_to, num_header_bytes, num_bytes) = match args[..] {\n [subject, sid, num_header_bytes, num_bytes] => {\n (subject, sid, None, num_header_bytes, num_bytes)\n }\n [subject, sid, reply_to, num_header_bytes, num_bytes] => {\n (subject, sid, Some(reply_to), num_header_bytes, num_bytes)\n }\n _ => {\n return Err(Error::new(\n ErrorKind::InvalidInput,\n \"invalid number of arguments after HMSG\",\n ))\n }\n };\n\n // Convert the slice into an owned string.\n let subject = subject.to_string();\n\n // Parse the subject ID.\n let sid = u64::from_str(sid).map_err(|_| {\n Error::new(\n ErrorKind::InvalidInput,\n \"cannot parse sid argument after HMSG\",\n )\n })?;\n\n // Convert the slice into an owned string.\n let reply_to = reply_to.map(ToString::to_string);\n\n // Parse the number of payload bytes.\n let num_header_bytes = u32::from_str(num_header_bytes).map_err(|_| {\n Error::new(\n ErrorKind::InvalidInput,\n \"cannot parse the number of header bytes argument after HMSG\",\n )\n })?;\n\n // Parse the number of payload bytes.\n let num_bytes = u32::from_str(num_bytes).map_err(|_| {\n Error::new(\n ErrorKind::InvalidInput,\n \"cannot parse the number of bytes argument after HMSG\",\n )\n })?;\n\n if num_bytes <= num_header_bytes {\n return Err(Error::new(\n ErrorKind::InvalidInput,\n \"number of header bytes was greater than or \\\n equal to the total number of bytes after HMSG\",\n ));\n }\n\n let num_payload_bytes = num_bytes - num_header_bytes;\n\n // `HMSG [reply-to]\n // <# header bytes> <# total bytes>\\r\\n\n // \\r\\n[headers]\\r\\n\\r\\n[payload]\\r\\n`\n\n // Read the header payload.\n let mut header_payload = vec![0; num_header_bytes as usize];\n stream.read_exact(&mut header_payload[..])?;\n\n let headers = Headers::try_from(&*header_payload)?;\n\n // Read the payload.\n let mut payload = vec![0; num_payload_bytes as usize];\n stream.read_exact(&mut payload[..])?;\n // Read \"\\r\\n\".\n stream.read_exact(&mut [0_u8; 2])?;\n\n return Ok(Some(ServerOp::Hmsg {\n subject,\n headers,\n sid,\n reply_to,\n payload,\n }));\n }\n\n if line_uppercase.starts_with(\"-ERR\") {\n // Extract the message argument.\n let msg = line[\"-ERR\".len()..].trim().trim_matches('\\'').to_string();\n\n return Ok(Some(ServerOp::Err(msg)));\n }\n\n Ok(Some(ServerOp::Unknown(line)))\n}\n```"}], "func_name": "decode", "docstring": "Decodes a single operation from the server.\n\nIf the connection is closed, `None` will be returned.", "repo": "bytebeamio/rumqtt", "path": "benchmarks/parsers/nats.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/benchmarks/parsers/nats.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c010acfae75cdf2f989c77e91baa52cf41712c8264d032034cf9856249293cb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode\n\nDocumentation:\nEncodes a single operation from the client.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn encode(mut stream: impl Write, op: ClientOp<'_>) -> io::Result<()> {\n match &op {\n ClientOp::Pub {\n subject,\n reply_to,\n payload,\n } => {\n stream.write_all(b\"PUB \")?;\n stream.write_all(subject.as_bytes())?;\n stream.write_all(b\" \")?;\n\n if let Some(reply_to) = reply_to {\n stream.write_all(reply_to.as_bytes())?;\n stream.write_all(b\" \")?;\n }\n\n let mut buf = itoa::Buffer::new();\n stream.write_all(buf.format(payload.len()).as_bytes())?;\n stream.write_all(b\"\\r\\n\")?;\n\n stream.write_all(payload)?;\n stream.write_all(b\"\\r\\n\")?;\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "encode", "docstring": "Encodes a single operation from the client.", "repo": "bytebeamio/rumqtt", "path": "benchmarks/parsers/nats.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/benchmarks/parsers/nats.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9ad73929c9e96b0522ffa5655f86d170075adc9cfee0e0ae7d4169d852335010"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: valid_filter\n\nDocumentation:\nChecks if the filter is valid\n\n\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn valid_filter(filter: &str) -> bool {\n if filter.is_empty() {\n return false;\n }\n\n let hirerarchy = filter.split('/').collect::>();\n if let Some((last, remaining)) = hirerarchy.split_last() {\n for entry in remaining.iter() {\n // # is not allowed in filter except as a last entry\n // invalid: sport/tennis#/player\n // invalid: sport/tennis/#/ranking\n if entry.contains('#') {\n return false;\n }\n\n // + must occupy an entire level of the filter\n // invalid: sport+\n if entry.len() > 1 && entry.contains('+') {\n return false;\n }\n }\n\n // only single '#\" or '+' is allowed in last entry\n // invalid: sport/tennis#\n // invalid: sport/++\n if last.len() != 1 && (last.contains('#') || last.contains('+')) {\n return false;\n }\n }\n true\n}\n```"}], "func_name": "valid_filter", "docstring": "Checks if the filter is valid\n\n", "repo": "bytebeamio/rumqtt", "path": "benchmarks/simplerouter/src/protocol/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/benchmarks/simplerouter/src/protocol/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17966763eddfce22655e3f67742cfc6a5a285f6e29df6af8ce45b44217bcc1d7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check\n\nDocumentation:\nChecks if the stream has enough bytes to frame a packet and returns fixed header\nonly if a packet can be framed with existing bytes in the `stream`.\nThe passed stream doesn't modify parent stream's cursor. If this function\nreturned an error, next `check` on the same parent stream is forced start\nwith cursor at 0 again (Iter is owned. Only Iter's cursor is changed internally)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check(stream: Iter, max_packet_size: usize) -> Result {\n // Create fixed header if there are enough bytes in the stream\n // to frame full packet\n let stream_len = stream.len();\n let fixed_header = parse_fixed_header(stream)?;\n\n // Don't let rogue connections attack with huge payloads.\n // Disconnect them before reading all that data\n if fixed_header.remaining_len > max_packet_size {\n return Err(Error::PayloadSizeLimitExceeded(fixed_header.remaining_len));\n }\n\n // If the current call fails due to insufficient bytes in the stream,\n // after calculating remaining length, we extend the stream\n let frame_length = fixed_header.frame_length();\n if stream_len < frame_length {\n return Err(Error::InsufficientBytes(frame_length - stream_len));\n }\n\n Ok(fixed_header)\n}\n```"}], "func_name": "check", "docstring": "Checks if the stream has enough bytes to frame a packet and returns fixed header\nonly if a packet can be framed with existing bytes in the `stream`.\nThe passed stream doesn't modify parent stream's cursor. If this function\nreturned an error, next `check` on the same parent stream is forced start\nwith cursor at 0 again (Iter is owned. Only Iter's cursor is changed internally)", "repo": "bytebeamio/rumqtt", "path": "benchmarks/simplerouter/src/protocol/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/benchmarks/simplerouter/src/protocol/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "29b7944d89c9ec0d73c234f93caf521df39e0cd66860ba1bcca5551e022698ce"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: length\n\nDocumentation:\nParses variable byte integer in the stream and returns the length\nand number of bytes that make it. Used for remaining length calculation\nas well as for calculating property lengths\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn length(stream: Iter) -> Result<(usize, usize), Error> {\n let mut len: usize = 0;\n let mut len_len = 0;\n let mut done = false;\n let mut shift = 0;\n\n // Use continuation bit at position 7 to continue reading next\n // byte to frame 'length'.\n // Stream 0b1xxx_xxxx 0b1yyy_yyyy 0b1zzz_zzzz 0b0www_wwww will\n // be framed as number 0bwww_wwww_zzz_zzzz_yyy_yyyy_xxx_xxxx\n for byte in stream {\n len_len += 1;\n let byte = *byte as usize;\n len += (byte & 0x7F) << shift;\n\n // stop when continue bit is 0\n done = (byte & 0x80) == 0;\n if done {\n break;\n }\n\n shift += 7;\n\n // Only a max of 4 bytes allowed for remaining length\n // more than 4 shifts (0, 7, 14, 21) implies bad length\n if shift > 21 {\n return Err(Error::MalformedRemainingLength);\n }\n }\n\n // Not enough bytes to frame remaining length. wait for\n // one more byte\n if !done {\n return Err(Error::InsufficientBytes(1));\n }\n\n Ok((len_len, len))\n}\n```"}], "func_name": "length", "docstring": "Parses variable byte integer in the stream and returns the length\nand number of bytes that make it. Used for remaining length calculation\nas well as for calculating property lengths", "repo": "bytebeamio/rumqtt", "path": "benchmarks/simplerouter/src/protocol/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/benchmarks/simplerouter/src/protocol/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3879190bf7458639044d6ceec85f0a1fdc06232646e250caadd94dd677ceba2d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: view_u16\n\nDocumentation:\nReturns big endian u16 view from next 2 bytes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn view_u16(stream: &[u8]) -> Result {\n let v = stream.get(0..2).ok_or(Error::MalformedPacket)?;\n\n Ok(((v[0] as u16) << 8) | (v[1] as u16))\n}\n```"}], "func_name": "view_u16", "docstring": "Returns big endian u16 view from next 2 bytes", "repo": "bytebeamio/rumqtt", "path": "benchmarks/simplerouter/src/protocol/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/benchmarks/simplerouter/src/protocol/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2711a1254f0626619ebc202b6b3c078d4d6fcf34ae0dcd4918644d116adea2e7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_u32\n\nDocumentation:\nAfter collecting enough bytes to frame a packet (packet's frame())\n, It's possible that content itself in the stream is wrong. Like expected\npacket id or qos not being present. In cases where `read_mqtt_string` or\n`read_mqtt_bytes` exhausted remaining length but packet framing expects to\nparse qos next, these pre checks will prevent `bytes` crashes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_u32(stream: &mut Bytes) -> Result {\n if stream.len() < 4 {\n return Err(Error::MalformedPacket);\n }\n\n Ok(stream.get_u32())\n}\n```"}], "func_name": "read_u32", "docstring": "After collecting enough bytes to frame a packet (packet's frame())\n, It's possible that content itself in the stream is wrong. Like expected\npacket id or qos not being present. In cases where `read_mqtt_string` or\n`read_mqtt_bytes` exhausted remaining length but packet framing expects to\nparse qos next, these pre checks will prevent `bytes` crashes", "repo": "bytebeamio/rumqtt", "path": "benchmarks/simplerouter/src/protocol/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/benchmarks/simplerouter/src/protocol/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9afe16bb7fb5b8a3b5d1bab63770a4a723eae9b85244733b78e57c683afd5e5d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_mqtt_bytes\n\nDocumentation:\nReads a series of bytes with a length from a byte stream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_mqtt_bytes(stream: &mut Bytes) -> Result {\n let len = read_u16(stream)? as usize;\n\n // Prevent attacks with wrong remaining length. This method is used in\n // `packet.assembly()` with (enough) bytes to frame packet. Ensures that\n // reading variable len string or bytes doesn't cross promised boundary\n // with `read_fixed_header()`\n if len > stream.len() {\n return Err(Error::BoundaryCrossed(len));\n }\n\n Ok(stream.split_to(len))\n}\n```"}], "func_name": "read_mqtt_bytes", "docstring": "Reads a series of bytes with a length from a byte stream", "repo": "bytebeamio/rumqtt", "path": "benchmarks/simplerouter/src/protocol/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/benchmarks/simplerouter/src/protocol/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "295d570cac67eeed24c2c0847d229b16bd8ca32772fa461784947f6ae03dd429"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_mqtt_bytes\n\nDocumentation:\nSerializes bytes to stream (including length)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_mqtt_bytes(stream: &mut BytesMut, bytes: &[u8]) {\n stream.put_u16(bytes.len() as u16);\n stream.extend_from_slice(bytes);\n}\n```"}], "func_name": "write_mqtt_bytes", "docstring": "Serializes bytes to stream (including length)", "repo": "bytebeamio/rumqtt", "path": "benchmarks/simplerouter/src/protocol/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/benchmarks/simplerouter/src/protocol/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e030aba2f58494b96612c634b6fe715de7eb92188f27434aba61f923ff2c502"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_remaining_length\n\nDocumentation:\nWrites remaining length to stream and returns number of bytes for remaining length\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_remaining_length(stream: &mut BytesMut, len: usize) -> Result {\n if len > 268_435_455 {\n return Err(Error::PayloadTooLong);\n }\n\n let mut done = false;\n let mut x = len;\n let mut count = 0;\n\n while !done {\n let mut byte = (x % 128) as u8;\n x /= 128;\n if x > 0 {\n byte |= 128;\n }\n\n stream.put_u8(byte);\n count += 1;\n done = x == 0;\n }\n\n Ok(count)\n}\n```"}], "func_name": "write_remaining_length", "docstring": "Writes remaining length to stream and returns number of bytes for remaining length", "repo": "bytebeamio/rumqtt", "path": "benchmarks/simplerouter/src/protocol/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/benchmarks/simplerouter/src/protocol/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c923beba1469344cd616c405aea14ab6307b986d0d2aeeea4fa888b7adff2bbe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: len_len\n\nDocumentation:\nReturn number of remaining length bytes required for encoding length\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn len_len(len: usize) -> usize {\n if len >= 2_097_152 {\n 4\n } else if len >= 16_384 {\n 3\n } else if len >= 128 {\n 2\n } else {\n 1\n }\n}\n```"}], "func_name": "len_len", "docstring": "Return number of remaining length bytes required for encoding length", "repo": "bytebeamio/rumqtt", "path": "benchmarks/simplerouter/src/protocol/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/benchmarks/simplerouter/src/protocol/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "136af90185602453f71c2d604311b541a4f9da5404a035e6623278e4395d265e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_mut\n\nDocumentation:\nReads a stream of bytes and extracts next MQTT packet out of it\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_mut(stream: &mut BytesMut, max_size: usize) -> Result {\n let fixed_header = check(stream.iter(), max_size)?;\n\n // Test with a stream with exactly the size to check border panics\n let packet = stream.split_to(fixed_header.frame_length());\n let packet_type = fixed_header.packet_type()?;\n\n if fixed_header.remaining_len == 0 {\n // no payload packets\n return match packet_type {\n PacketType::PingReq => Ok(Packet::PingReq),\n PacketType::PingResp => Ok(Packet::PingResp),\n PacketType::Disconnect => Ok(Packet::Disconnect),\n _ => Err(Error::PayloadRequired),\n };\n }\n\n let packet = packet.freeze();\n let packet = match packet_type {\n PacketType::Connect => Packet::Connect(connect::Connect::read(fixed_header, packet)?),\n PacketType::ConnAck => Packet::ConnAck(connack::ConnAck::read(fixed_header, packet)?),\n PacketType::Publish => Packet::Publish(publish::Publish::read(fixed_header, packet)?),\n PacketType::PubAck => Packet::PubAck(puback::PubAck::read(fixed_header, packet)?),\n PacketType::Subscribe => {\n Packet::Subscribe(subscribe::Subscribe::read(fixed_header, packet)?)\n }\n PacketType::SubAck => Packet::SubAck(suback::SubAck::read(fixed_header, packet)?),\n PacketType::PingReq => Packet::PingReq,\n PacketType::PingResp => Packet::PingResp,\n PacketType::Disconnect => Packet::Disconnect,\n v => return Err(Error::UnsupportedPacket(v)),\n };\n\n Ok(packet)\n}\n```"}], "func_name": "read_mut", "docstring": "Reads a stream of bytes and extracts next MQTT packet out of it", "repo": "bytebeamio/rumqtt", "path": "benchmarks/simplerouter/src/protocol/v4.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/benchmarks/simplerouter/src/protocol/v4.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "487ab0e3443d747ab3df0590c9075ef566424fef856164aba9010571f6227016"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new `AsyncClient`.\n\n`cap` specifies the capacity of the bounded async channel.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(options: MqttOptions, cap: usize) -> (AsyncClient, EventLoop) {\n let eventloop = EventLoop::new(options, cap);\n let request_tx = eventloop.requests_tx.clone();\n\n let client = AsyncClient { request_tx };\n\n (client, eventloop)\n }\n```"}], "func_name": "new", "docstring": "Create a new `AsyncClient`.\n\n`cap` specifies the capacity of the bounded async channel.", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a20ca397cde629e26aba233a9dbf75ae3564e4369a3281eca7c0299651cfdc1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_senders\n\nDocumentation:\nCreate a new `AsyncClient` from a channel `Sender`.\n\nThis is mostly useful for creating a test instance where you can\nlisten on the corresponding receiver.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_senders(request_tx: Sender) -> AsyncClient {\n AsyncClient { request_tx }\n }\n```"}], "func_name": "from_senders", "docstring": "Create a new `AsyncClient` from a channel `Sender`.\n\nThis is mostly useful for creating a test instance where you can\nlisten on the corresponding receiver.", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf592cca851894aac7167dd31d6e364ea699b3a2a22a3038f737a9deee16f2d5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: publish\n\nDocumentation:\nSends a MQTT Publish to the `EventLoop`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn publish(\n &self,\n topic: S,\n qos: QoS,\n retain: bool,\n payload: V,\n ) -> Result<(), ClientError>\n where\n S: Into,\n V: Into>,\n {\n let topic = topic.into();\n let mut publish = Publish::new(&topic, qos, payload);\n publish.retain = retain;\n let publish = Request::Publish(publish);\n if !valid_topic(&topic) {\n return Err(ClientError::Request(publish));\n }\n self.request_tx.send_async(publish).await?;\n Ok(())\n }\n```"}], "func_name": "publish", "docstring": "Sends a MQTT Publish to the `EventLoop`.", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f6009341360d6b1d32190f1a6be36d115eb1d80fbe37441cfcf35755e66a45e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_publish\n\nDocumentation:\nAttempts to send a MQTT Publish to the `EventLoop`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_publish(\n &self,\n topic: S,\n qos: QoS,\n retain: bool,\n payload: V,\n ) -> Result<(), ClientError>\n where\n S: Into,\n V: Into>,\n {\n let topic = topic.into();\n let mut publish = Publish::new(&topic, qos, payload);\n publish.retain = retain;\n let publish = Request::Publish(publish);\n if !valid_topic(&topic) {\n return Err(ClientError::TryRequest(publish));\n }\n self.request_tx.try_send(publish)?;\n Ok(())\n }\n```"}], "func_name": "try_publish", "docstring": "Attempts to send a MQTT Publish to the `EventLoop`.", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ab69108c7fc7e7df157eb5a75faac53652a35f164d4d09758de6eec46571baba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ack\n\nDocumentation:\nSends a MQTT PubAck to the `EventLoop`. Only needed in if `manual_acks` flag is set.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn ack(&self, publish: &Publish) -> Result<(), ClientError> {\n let ack = get_ack_req(publish);\n\n if let Some(ack) = ack {\n self.request_tx.send_async(ack).await?;\n }\n Ok(())\n }\n```"}], "func_name": "ack", "docstring": "Sends a MQTT PubAck to the `EventLoop`. Only needed in if `manual_acks` flag is set.", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94ece2aa6762a9451527f0d74e56691d9ece7d074633442d180595742de2dcc7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_ack\n\nDocumentation:\nAttempts to send a MQTT PubAck to the `EventLoop`. Only needed in if `manual_acks` flag is set.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_ack(&self, publish: &Publish) -> Result<(), ClientError> {\n let ack = get_ack_req(publish);\n if let Some(ack) = ack {\n self.request_tx.try_send(ack)?;\n }\n Ok(())\n }\n```"}], "func_name": "try_ack", "docstring": "Attempts to send a MQTT PubAck to the `EventLoop`. Only needed in if `manual_acks` flag is set.", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "36b52d4aef869238c3b059805d50c1c1b83a16d891707c004ffb95b4c3a7be4f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: publish_bytes\n\nDocumentation:\nSends a MQTT Publish to the `EventLoop`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn publish_bytes(\n &self,\n topic: S,\n qos: QoS,\n retain: bool,\n payload: Bytes,\n ) -> Result<(), ClientError>\n where\n S: Into,\n {\n let mut publish = Publish::from_bytes(topic, qos, payload);\n publish.retain = retain;\n let publish = Request::Publish(publish);\n self.request_tx.send_async(publish).await?;\n Ok(())\n }\n```"}], "func_name": "publish_bytes", "docstring": "Sends a MQTT Publish to the `EventLoop`", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d8690cd749f1f57c1f83b649a5d056a74658ba94230024ed18be2f0c43f0a252"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: subscribe\n\nDocumentation:\nSends a MQTT Subscribe to the `EventLoop`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn subscribe>(&self, topic: S, qos: QoS) -> Result<(), ClientError> {\n let subscribe = Subscribe::new(topic, qos);\n if !subscribe_has_valid_filters(&subscribe) {\n return Err(ClientError::Request(subscribe.into()));\n }\n\n self.request_tx.send_async(subscribe.into()).await?;\n Ok(())\n }\n```"}], "func_name": "subscribe", "docstring": "Sends a MQTT Subscribe to the `EventLoop`", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bebe907c426629924629947202080ca8cbe2ba3f8f9b4dd604601c61e0d7043a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_subscribe\n\nDocumentation:\nAttempts to send a MQTT Subscribe to the `EventLoop`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_subscribe>(&self, topic: S, qos: QoS) -> Result<(), ClientError> {\n let subscribe = Subscribe::new(topic, qos);\n if !subscribe_has_valid_filters(&subscribe) {\n return Err(ClientError::TryRequest(subscribe.into()));\n }\n\n self.request_tx.try_send(subscribe.into())?;\n Ok(())\n }\n```"}], "func_name": "try_subscribe", "docstring": "Attempts to send a MQTT Subscribe to the `EventLoop`", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9cb05ffcfa0d1ed7fec0bd688647a2ce24a89a9cf597a4f2c7b5bbedf84524da"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: subscribe_many\n\nDocumentation:\nSends a MQTT Subscribe for multiple topics to the `EventLoop`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn subscribe_many(&self, topics: T) -> Result<(), ClientError>\n where\n T: IntoIterator,\n {\n let subscribe = Subscribe::new_many(topics);\n if !subscribe_has_valid_filters(&subscribe) {\n return Err(ClientError::Request(subscribe.into()));\n }\n\n self.request_tx.send_async(subscribe.into()).await?;\n Ok(())\n }\n```"}], "func_name": "subscribe_many", "docstring": "Sends a MQTT Subscribe for multiple topics to the `EventLoop`", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aed19e1efcd5d458680597c366b2fd56a6fc86f011b3e95b782dcc3f23956ac4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_subscribe_many\n\nDocumentation:\nAttempts to send a MQTT Subscribe for multiple topics to the `EventLoop`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_subscribe_many(&self, topics: T) -> Result<(), ClientError>\n where\n T: IntoIterator,\n {\n let subscribe = Subscribe::new_many(topics);\n if !subscribe_has_valid_filters(&subscribe) {\n return Err(ClientError::TryRequest(subscribe.into()));\n }\n self.request_tx.try_send(subscribe.into())?;\n Ok(())\n }\n```"}], "func_name": "try_subscribe_many", "docstring": "Attempts to send a MQTT Subscribe for multiple topics to the `EventLoop`", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "345367a43e810a3a5ac1b801dedb02b2dd4da1b681829bac218f29840a8fa045"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unsubscribe\n\nDocumentation:\nSends a MQTT Unsubscribe to the `EventLoop`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn unsubscribe>(&self, topic: S) -> Result<(), ClientError> {\n let unsubscribe = Unsubscribe::new(topic.into());\n let request = Request::Unsubscribe(unsubscribe);\n self.request_tx.send_async(request).await?;\n Ok(())\n }\n```"}], "func_name": "unsubscribe", "docstring": "Sends a MQTT Unsubscribe to the `EventLoop`", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0af61d735f8e696aceac781120da16a4922d1d1591e146206f6aa5d147fc813d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_unsubscribe\n\nDocumentation:\nAttempts to send a MQTT Unsubscribe to the `EventLoop`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_unsubscribe>(&self, topic: S) -> Result<(), ClientError> {\n let unsubscribe = Unsubscribe::new(topic.into());\n let request = Request::Unsubscribe(unsubscribe);\n self.request_tx.try_send(request)?;\n Ok(())\n }\n```"}], "func_name": "try_unsubscribe", "docstring": "Attempts to send a MQTT Unsubscribe to the `EventLoop`", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d7f6d90e1a719850afe049defd7fa6f2722a00c6a749e491728f65ad469958af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: disconnect\n\nDocumentation:\nSends a MQTT disconnect to the `EventLoop`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn disconnect(&self) -> Result<(), ClientError> {\n let request = Request::Disconnect(Disconnect);\n self.request_tx.send_async(request).await?;\n Ok(())\n }\n```"}], "func_name": "disconnect", "docstring": "Sends a MQTT disconnect to the `EventLoop`", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3d947a12b387930c84a8f32d3c7194a1089ba6dd2ff4de7bfd342f4c16b6bcbf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_disconnect\n\nDocumentation:\nAttempts to send a MQTT disconnect to the `EventLoop`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_disconnect(&self) -> Result<(), ClientError> {\n let request = Request::Disconnect(Disconnect);\n self.request_tx.try_send(request)?;\n Ok(())\n }\n```"}], "func_name": "try_disconnect", "docstring": "Attempts to send a MQTT disconnect to the `EventLoop`", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "49071a8f231db35c5c28ea2d3dd2b80559d7a64f6b3c1280c4cdcce3463005c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new `Client`\n\n`cap` specifies the capacity of the bounded async channel.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(options: MqttOptions, cap: usize) -> (Client, Connection) {\n let (client, eventloop) = AsyncClient::new(options, cap);\n let client = Client { client };\n let runtime = runtime::Builder::new_current_thread()\n .enable_all()\n .build()\n .unwrap();\n\n let connection = Connection::new(eventloop, runtime);\n (client, connection)\n }\n```"}], "func_name": "new", "docstring": "Create a new `Client`\n\n`cap` specifies the capacity of the bounded async channel.", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81d798baf7d3a0ca2f5811b08832ee628149b3ad6ca413055294ae878deeb597"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_sender\n\nDocumentation:\nCreate a new `Client` from a channel `Sender`.\n\nThis is mostly useful for creating a test instance where you can\nlisten on the corresponding receiver.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_sender(request_tx: Sender) -> Client {\n Client {\n client: AsyncClient::from_senders(request_tx),\n }\n }\n```"}], "func_name": "from_sender", "docstring": "Create a new `Client` from a channel `Sender`.\n\nThis is mostly useful for creating a test instance where you can\nlisten on the corresponding receiver.", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a360d0eafe1367d28216f5d9f203774d18951573f1b00a768c3cdc431d76fdd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: recv\n\nDocumentation:\nAttempt to fetch an incoming [`Event`] on the [`EventLoop`], returning an error\nif all clients/users have closed requests channel.\n\n[`EventLoop`]: super::EventLoop\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn recv(&mut self) -> Result, RecvError> {\n let f = self.eventloop.poll();\n let event = self.runtime.block_on(f);\n\n resolve_event(event).ok_or(RecvError)\n }\n```"}], "func_name": "recv", "docstring": "Attempt to fetch an incoming [`Event`] on the [`EventLoop`], returning an error\nif all clients/users have closed requests channel.\n\n[`EventLoop`]: super::EventLoop", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "162487d81094f1a9ce3ce422f2a40f3a2e5ded6b069c4638aece744f84cc7977"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_recv\n\nDocumentation:\nAttempt to fetch an incoming [`Event`] on the [`EventLoop`], returning an error\nif none immediately present or all clients/users have closed requests channel.\n\n[`EventLoop`]: super::EventLoop\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_recv(&mut self) -> Result, TryRecvError> {\n let f = self.eventloop.poll();\n // Enters the runtime context so we can poll the future, as required by `now_or_never()`.\n // ref: https://docs.rs/tokio/latest/tokio/runtime/struct.Runtime.html#method.enter\n let _guard = self.runtime.enter();\n let event = f.now_or_never().ok_or(TryRecvError::Empty)?;\n\n resolve_event(event).ok_or(TryRecvError::Disconnected)\n }\n```"}], "func_name": "try_recv", "docstring": "Attempt to fetch an incoming [`Event`] on the [`EventLoop`], returning an error\nif none immediately present or all clients/users have closed requests channel.\n\n[`EventLoop`]: super::EventLoop", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "33fa0b93068c854cbbd2e3ba8c7eb0609b189485b58e11820310b338a5c17065"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: recv_timeout\n\nDocumentation:\nAttempt to fetch an incoming [`Event`] on the [`EventLoop`], returning an error\nif all clients/users have closed requests channel or the timeout has expired.\n\n[`EventLoop`]: super::EventLoop\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn recv_timeout(\n &mut self,\n duration: Duration,\n ) -> Result, RecvTimeoutError> {\n let f = self.eventloop.poll();\n let event = self\n .runtime\n .block_on(async { timeout(duration, f).await })\n .map_err(|_| RecvTimeoutError::Timeout)?;\n\n resolve_event(event).ok_or(RecvTimeoutError::Disconnected)\n }\n```"}], "func_name": "recv_timeout", "docstring": "Attempt to fetch an incoming [`Event`] on the [`EventLoop`], returning an error\nif all clients/users have closed requests channel or the timeout has expired.\n\n[`EventLoop`]: super::EventLoop", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/client.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a34eb4175a2c7ad54ae49af47bd65bf0ad701e7a3b2199a53f7f03443a665186"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nNew MQTT `EventLoop`\n\nWhen connection encounters critical errors (like auth failure), user has a choice to\naccess and update `options`, `state` and `requests`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(mqtt_options: MqttOptions, cap: usize) -> EventLoop {\n let (requests_tx, requests_rx) = bounded(cap);\n let pending = VecDeque::new();\n let max_inflight = mqtt_options.inflight;\n let manual_acks = mqtt_options.manual_acks;\n\n EventLoop {\n mqtt_options,\n state: MqttState::new(max_inflight, manual_acks),\n requests_tx,\n requests_rx,\n pending,\n network: None,\n keepalive_timeout: None,\n network_options: NetworkOptions::new(),\n }\n }\n```"}], "func_name": "new", "docstring": "New MQTT `EventLoop`\n\nWhen connection encounters critical errors (like auth failure), user has a choice to\naccess and update `options`, `state` and `requests`.", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/eventloop.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/eventloop.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "07bfe228ff9e99a6cd6bb289efd329ecbeb3d9f84fc03332ec32aeae371da8ca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clean\n\nDocumentation:\nLast session might contain packets which aren't acked. MQTT says these packets should be\nrepublished in the next session. Move pending messages from state to eventloop, drops the\nunderlying network connection and clears the keepalive timeout if any.\n\n> NOTE: Use only when EventLoop is blocked on network and unable to immediately handle disconnect.\n> Also, while this helps prevent data loss, the pending list length should be managed properly.\n> For this reason we recommend setting [`AsycClient`](crate::AsyncClient)'s channel capacity to `0`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clean(&mut self) {\n self.network = None;\n self.keepalive_timeout = None;\n self.pending.extend(self.state.clean());\n\n // drain requests from channel which weren't yet received\n let mut requests_in_channel: Vec<_> = self.requests_rx.drain().collect();\n\n requests_in_channel.retain(|request| {\n match request {\n Request::PubAck(_) => false, // Wait for publish retransmission, else the broker could be confused by an unexpected ack\n _ => true,\n }\n });\n\n self.pending.extend(requests_in_channel);\n }\n```"}], "func_name": "clean", "docstring": "Last session might contain packets which aren't acked. MQTT says these packets should be\nrepublished in the next session. Move pending messages from state to eventloop, drops the\nunderlying network connection and clears the keepalive timeout if any.\n\n> NOTE: Use only when EventLoop is blocked on network and unable to immediately handle disconnect.\n> Also, while this helps prevent data loss, the pending list length should be managed properly.\n> For this reason we recommend setting [`AsycClient`](crate::AsyncClient)'s channel capacity to `0`.", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/eventloop.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/eventloop.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a825b736a2132e823926cc723d4b7149a56813b7f33050e49a1950aa8753989"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: poll\n\nDocumentation:\nYields Next notification or outgoing request and periodically pings\nthe broker. Continuing to poll will reconnect to the broker if there is\na disconnection.\n**NOTE** Don't block this while iterating\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn poll(&mut self) -> Result {\n if self.network.is_none() {\n let (network, connack) = match time::timeout(\n Duration::from_secs(self.network_options.connection_timeout()),\n connect(&self.mqtt_options, self.network_options.clone()),\n )\n .await\n {\n Ok(inner) => inner?,\n Err(_) => return Err(ConnectionError::NetworkTimeout),\n };\n // Last session might contain packets which aren't acked. If it's a new session, clear the pending packets.\n if !connack.session_present {\n self.pending.clear();\n }\n self.network = Some(network);\n\n if self.keepalive_timeout.is_none() && !self.mqtt_options.keep_alive.is_zero() {\n self.keepalive_timeout = Some(Box::pin(time::sleep(self.mqtt_options.keep_alive)));\n }\n\n return Ok(Event::Incoming(Packet::ConnAck(connack)));\n }\n\n match self.select().await {\n Ok(v) => Ok(v),\n Err(e) => {\n // MQTT requires that packets pending acknowledgement should be republished on session resume.\n // Move pending messages from state to eventloop.\n self.clean();\n Err(e)\n }\n }\n }\n```"}], "func_name": "poll", "docstring": "Yields Next notification or outgoing request and periodically pings\nthe broker. Continuing to poll will reconnect to the broker if there is\na disconnection.\n**NOTE** Don't block this while iterating", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/eventloop.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/eventloop.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "52db1659e17af4c64d4f3e03e618e8827d505ce75c073b17e9f5bae4167c8622"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: select\n\nDocumentation:\nSelect on network and requests and generate keepalive pings when necessary\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn select(&mut self) -> Result {\n let network = self.network.as_mut().unwrap();\n // let await_acks = self.state.await_acks;\n let inflight_full = self.state.inflight >= self.mqtt_options.inflight;\n let collision = self.state.collision.is_some();\n let network_timeout = Duration::from_secs(self.network_options.connection_timeout());\n\n // Read buffered events from previous polls before calling a new poll\n if let Some(event) = self.state.events.pop_front() {\n return Ok(event);\n }\n\n let mut no_sleep = Box::pin(time::sleep(Duration::ZERO));\n // this loop is necessary since self.incoming.pop_front() might return None. In that case,\n // instead of returning a None event, we try again.\n select! {\n // Pull a bunch of packets from network, reply in bunch and yield the first item\n o = network.readb(&mut self.state) => {\n o?;\n // flush all the acks and return first incoming packet\n match time::timeout(network_timeout, network.flush()).await {\n Ok(inner) => inner?,\n Err(_)=> return Err(ConnectionError::FlushTimeout),\n };\n Ok(self.state.events.pop_front().unwrap())\n },\n // Handles pending and new requests.\n // If available, prioritises pending requests from previous session.\n // Else, pulls next request from user requests channel.\n // If conditions in the below branch are for flow control.\n // The branch is disabled if there's no pending messages and new user requests\n // cannot be serviced due flow control.\n // We read next user user request only when inflight messages are < configured inflight\n // and there are no collisions while handling previous outgoing requests.\n //\n // Flow control is based on ack count. If inflight packet count in the buffer is\n // less than max_inflight setting, next outgoing request will progress. For this\n // to work correctly, broker should ack in sequence (a lot of brokers won't)\n //\n // E.g If max inflight = 5, user requests will be blocked when inflight queue\n // looks like this -> [1, 2, 3, 4, 5].\n // If broker acking 2 instead of 1 -> [1, x, 3, 4, 5].\n // This pulls next user request. But because max packet id = max_inflight, next\n // user request's packet id will roll to 1. This replaces existing packet id 1.\n // Resulting in a collision\n //\n // Eventloop can stop receiving outgoing user requests when previous outgoing\n // request collided. I.e collision state. Collision state will be cleared only\n // when correct ack is received\n // Full inflight queue will look like -> [1a, 2, 3, 4, 5].\n // If 3 is acked instead of 1 first -> [1a, 2, x, 4, 5].\n // After collision with pkid 1 -> [1b ,2, x, 4, 5].\n // 1a is saved to state and event loop is set to collision mode stopping new\n // outgoing requests (along with 1b).\n o = Self::next_request(\n &mut self.pending,\n &self.requests_rx,\n self.mqtt_options.pending_throttle\n ), if !self.pending.is_empty() || (!inflight_full && !collision) => match o {\n Ok(request) => {\n if let Some(outgoing) = self.state.handle_outgoing_packet(request)? {\n network.write(outgoing).await?;\n }\n match time::timeout(network_timeout, network.flush()).await {\n Ok(inner) => inner?,\n Err(_)=> return Err(ConnectionError::FlushTimeout),\n };\n Ok(self.state.events.pop_front().unwrap())\n }\n Err(_) => Err(ConnectionError::RequestsDone),\n },\n // We generate pings irrespective of network activity. This keeps the ping logic\n // simple. We can change this behavior in future if necessary (to prevent extra pings)\n _ = self.keepalive_timeout.as_mut().unwrap_or(&mut no_sleep),\n if self.keepalive_timeout.is_some() && !self.mqtt_options.keep_alive.is_zero() => {\n let timeout = self.keepalive_timeout.as_mut().unwrap();\n timeout.as_mut().reset(Instant::now() + self.mqtt_options.keep_alive);\n\n if let Some(outgoing) = self.state.handle_outgoing_packet(Request::PingReq(PingReq))? {\n network.write(outgoing).await?;\n }\n match time::timeout(network_timeout, network.flush()).await {\n Ok(inner) => inner?,\n Err(_)=> return Err(ConnectionError::FlushTimeout),\n };\n Ok(self.state.events.pop_front().unwrap())\n }\n }\n }\n```"}], "func_name": "select", "docstring": "Select on network and requests and generate keepalive pings when necessary", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/eventloop.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/eventloop.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "33526118579036df515ac44026237c3cc58e41ef553233680f9025f5572c4a05"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nThis stream internally processes requests from the request stream provided to the eventloop\nwhile also consuming byte stream from the network and yielding mqtt packets as the output of\nthe stream.\nThis function (for convenience) includes internal delays for users to perform internal sleeps\nbetween re-connections so that cancel semantics can be used during this sleep\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn connect(\n mqtt_options: &MqttOptions,\n network_options: NetworkOptions,\n) -> Result<(Network, ConnAck), ConnectionError> {\n // connect to the broker\n let mut network = network_connect(mqtt_options, network_options).await?;\n\n // make MQTT connection request (which internally awaits for ack)\n let connack = mqtt_connect(mqtt_options, &mut network).await?;\n\n Ok((network, connack))\n}\n```"}], "func_name": "connect", "docstring": "This stream internally processes requests from the request stream provided to the eventloop\nwhile also consuming byte stream from the network and yielding mqtt packets as the output of\nthe stream.\nThis function (for convenience) includes internal delays for users to perform internal sleeps\nbetween re-connections so that cancel semantics can be used during this sleep", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/eventloop.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/eventloop.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0a8952c14a22a2dbe5e76bb2b1cf433622ff1a5dd692a5cd98bcb47f0c4740d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read\n\nDocumentation:\nReads and returns a single packet from network\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn read(&mut self) -> Result {\n match self.framed.next().await {\n Some(Ok(packet)) => Ok(packet),\n Some(Err(mqttbytes::Error::InsufficientBytes(_))) => unreachable!(),\n Some(Err(e)) => Err(StateError::Deserialization(e)),\n None => Err(StateError::ConnectionAborted),\n }\n }\n```"}], "func_name": "read", "docstring": "Reads and returns a single packet from network", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/framed.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/framed.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0dd9d1d0d1fe8d21c051a006010d01f8dfc30237dc03d8865600117f5dc71db3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: readb\n\nDocumentation:\nRead packets in bulk. This allow replies to be in bulk. This method is used\nafter the connection is established to read a bunch of incoming packets\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn readb(&mut self, state: &mut MqttState) -> Result<(), StateError> {\n // wait for the first read\n let mut res = self.framed.next().await;\n let mut count = 1;\n loop {\n match res {\n Some(Ok(packet)) => {\n if let Some(outgoing) = state.handle_incoming_packet(packet)? {\n self.write(outgoing).await?;\n }\n\n count += 1;\n if count >= self.max_readb_count {\n break;\n }\n }\n Some(Err(mqttbytes::Error::InsufficientBytes(_))) => unreachable!(),\n Some(Err(e)) => return Err(StateError::Deserialization(e)),\n None => return Err(StateError::ConnectionAborted),\n }\n // do not wait for subsequent reads\n match self.framed.next().now_or_never() {\n Some(r) => res = r,\n _ => break,\n };\n }\n\n Ok(())\n }\n```"}], "func_name": "readb", "docstring": "Read packets in bulk. This allow replies to be in bulk. This method is used\nafter the connection is established to read a bunch of incoming packets", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/framed.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/framed.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "628dc912823e336bcffc106dc95807e0b76b7de236aed00ea555583187a53261"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate an [`MqttOptions`] object that contains default values for all settings other than\n- id: A string to identify the device connecting to a broker\n- host: The broker's domain name or IP address\n- port: The port number on which broker must be listening for incoming connections\n\n```\n# use rumqttc::MqttOptions;\nlet options = MqttOptions::new(\"123\", \"localhost\", 1883);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new, T: Into>(id: S, host: T, port: u16) -> MqttOptions {\n MqttOptions {\n broker_addr: host.into(),\n port,\n transport: Transport::tcp(),\n keep_alive: Duration::from_secs(60),\n clean_session: true,\n client_id: id.into(),\n credentials: None,\n max_incoming_packet_size: 10 * 1024,\n max_outgoing_packet_size: 10 * 1024,\n request_channel_capacity: 10,\n max_request_batch: 0,\n pending_throttle: Duration::from_micros(0),\n inflight: 100,\n last_will: None,\n manual_acks: false,\n #[cfg(feature = \"proxy\")]\n proxy: None,\n #[cfg(feature = \"websocket\")]\n request_modifier: None,\n }\n }\n```"}], "func_name": "new", "docstring": "Create an [`MqttOptions`] object that contains default values for all settings other than\n- id: A string to identify the device connecting to a broker\n- host: The broker's domain name or IP address\n- port: The port number on which broker must be listening for incoming connections\n\n```\n# use rumqttc::MqttOptions;\nlet options = MqttOptions::new(\"123\", \"localhost\", 1883);\n```", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/lib.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "26f526933c703e46d5fa07fcb933df3a3cbcf65501deeb493d5dffce7590c4fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_url\n\nDocumentation:\nCreates an [`MqttOptions`] object by parsing provided string with the [url] crate's\n[`Url::parse(url)`](url::Url::parse) method and is only enabled when run using the \"url\" feature.\n\n```\n# use rumqttc::MqttOptions;\nlet options = MqttOptions::parse_url(\"mqtt://example.com:1883?client_id=123\").unwrap();\n```\n\n**NOTE:** A url must be prefixed with one of either `tcp://`, `mqtt://`, `ssl://`,`mqtts://`,\n`ws://` or `wss://` to denote the protocol for establishing a connection with the broker.\n\n**NOTE:** Encrypted connections(i.e. `mqtts://`, `ssl://`, `wss://`) by default use the\nsystem's root certificates. To configure with custom certificates, one may use the\n[`set_transport`](MqttOptions::set_transport) method.\n\n```ignore\n# use rumqttc::{MqttOptions, Transport};\n# use tokio_rustls::rustls::ClientConfig;\n# let root_cert_store = rustls::RootCertStore::empty();\n# let client_config = ClientConfig::builder()\n# .with_root_certificates(root_cert_store)\n# .with_no_client_auth();\nlet mut options = MqttOptions::parse_url(\"mqtts://example.com?client_id=123\").unwrap();\noptions.set_transport(Transport::tls_with_config(client_config.into()));\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_url>(url: S) -> Result {\n let url = url::Url::parse(&url.into())?;\n let options = MqttOptions::try_from(url)?;\n\n Ok(options)\n }\n```"}], "func_name": "parse_url", "docstring": "Creates an [`MqttOptions`] object by parsing provided string with the [url] crate's\n[`Url::parse(url)`](url::Url::parse) method and is only enabled when run using the \"url\" feature.\n\n```\n# use rumqttc::MqttOptions;\nlet options = MqttOptions::parse_url(\"mqtt://example.com:1883?client_id=123\").unwrap();\n```\n\n**NOTE:** A url must be prefixed with one of either `tcp://`, `mqtt://`, `ssl://`,`mqtts://`,\n`ws://` or `wss://` to denote the protocol for establishing a connection with the broker.\n\n**NOTE:** Encrypted connections(i.e. `mqtts://`, `ssl://`, `wss://`) by default use the\nsystem's root certificates. To configure with custom certificates, one may use the\n[`set_transport`](MqttOptions::set_transport) method.\n\n```ignore\n# use rumqttc::{MqttOptions, Transport};\n# use tokio_rustls::rustls::ClientConfig;\n# let root_cert_store = rustls::RootCertStore::empty();\n# let client_config = ClientConfig::builder()\n# .with_root_certificates(root_cert_store)\n# .with_no_client_auth();\nlet mut options = MqttOptions::parse_url(\"mqtts://example.com?client_id=123\").unwrap();\noptions.set_transport(Transport::tls_with_config(client_config.into()));\n```", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/lib.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "670004893af0c528bc10a2b6e752e53280f513373891ba0cfce26b0e1c4302c1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_keep_alive\n\nDocumentation:\nSet number of seconds after which client should ping the broker\nif there is no other data exchange\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_keep_alive(&mut self, duration: Duration) -> &mut Self {\n assert!(\n duration.is_zero() || duration >= Duration::from_secs(1),\n \"Keep alives should be specified in seconds. Durations less than \\\n a second are not allowed, except for Duration::ZERO.\"\n );\n\n self.keep_alive = duration;\n self\n }\n```"}], "func_name": "set_keep_alive", "docstring": "Set number of seconds after which client should ping the broker\nif there is no other data exchange", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/lib.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7afa57582271951c0e9641f30633854c339d85fc8c221ed62cce0743d106aed8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_pending_throttle\n\nDocumentation:\nEnables throttling and sets outoing message rate to the specified 'rate'\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_pending_throttle(&mut self, duration: Duration) -> &mut Self {\n self.pending_throttle = duration;\n self\n }\n```"}], "func_name": "set_pending_throttle", "docstring": "Enables throttling and sets outoing message rate to the specified 'rate'", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/lib.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dc8bac2cb784e884620b99be79cdd758d283e799a1c6833cba3c34a3ca11a0da"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_inflight\n\nDocumentation:\nSet number of concurrent in flight messages\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_inflight(&mut self, inflight: u16) -> &mut Self {\n assert!(inflight != 0, \"zero in flight is not allowed\");\n\n self.inflight = inflight;\n self\n }\n```"}], "func_name": "set_inflight", "docstring": "Set number of concurrent in flight messages", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/lib.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d8c0c94d0f2664822fb0de39c61fdd85bb6bee1294bf9ee4f215f15822d63b16"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates new mqtt state. Same state should be used during a\nconnection for persistent sessions while new state should\ninstantiated for clean sessions\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(max_inflight: u16, manual_acks: bool) -> Self {\n MqttState {\n await_pingresp: false,\n collision_ping_count: 0,\n last_incoming: Instant::now(),\n last_outgoing: Instant::now(),\n last_pkid: 0,\n last_puback: 0,\n inflight: 0,\n max_inflight,\n // index 0 is wasted as 0 is not a valid packet id\n outgoing_pub: vec![None; max_inflight as usize + 1],\n outgoing_rel: FixedBitSet::with_capacity(max_inflight as usize + 1),\n incoming_pub: FixedBitSet::with_capacity(u16::MAX as usize + 1),\n collision: None,\n // TODO: Optimize these sizes later\n events: VecDeque::with_capacity(100),\n manual_acks,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates new mqtt state. Same state should be used during a\nconnection for persistent sessions while new state should\ninstantiated for clean sessions", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/state.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ab4e706dde2c7138ee34a7eaec5ca0e35f2816bc03eb5f71012979c8f729d69"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clean\n\nDocumentation:\nReturns inflight outgoing packets and clears internal queues\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clean(&mut self) -> Vec {\n let mut pending = Vec::with_capacity(100);\n let (first_half, second_half) = self\n .outgoing_pub\n .split_at_mut(self.last_puback as usize + 1);\n\n for publish in second_half.iter_mut().chain(first_half) {\n if let Some(publish) = publish.take() {\n let request = Request::Publish(publish);\n pending.push(request);\n }\n }\n\n // remove and collect pending releases\n for pkid in self.outgoing_rel.ones() {\n let request = Request::PubRel(PubRel::new(pkid as u16));\n pending.push(request);\n }\n self.outgoing_rel.clear();\n\n // remove packet ids of incoming qos2 publishes\n self.incoming_pub.clear();\n\n self.await_pingresp = false;\n self.collision_ping_count = 0;\n self.inflight = 0;\n pending\n }\n```"}], "func_name": "clean", "docstring": "Returns inflight outgoing packets and clears internal queues", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/state.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ff475c86ce5150d248d3ac6b88b5d24e7d996c1135090c65e85d2ba72422f921"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_outgoing_packet\n\nDocumentation:\nConsolidates handling of all outgoing mqtt packet logic. Returns a packet which should\nbe put on to the network by the eventloop\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn handle_outgoing_packet(\n &mut self,\n request: Request,\n ) -> Result, StateError> {\n let packet = match request {\n Request::Publish(publish) => self.outgoing_publish(publish)?,\n Request::PubRel(pubrel) => self.outgoing_pubrel(pubrel)?,\n Request::Subscribe(subscribe) => self.outgoing_subscribe(subscribe)?,\n Request::Unsubscribe(unsubscribe) => self.outgoing_unsubscribe(unsubscribe)?,\n Request::PingReq(_) => self.outgoing_ping()?,\n Request::Disconnect(_) => self.outgoing_disconnect()?,\n Request::PubAck(puback) => self.outgoing_puback(puback)?,\n Request::PubRec(pubrec) => self.outgoing_pubrec(pubrec)?,\n _ => unimplemented!(),\n };\n\n self.last_outgoing = Instant::now();\n Ok(packet)\n }\n```"}], "func_name": "handle_outgoing_packet", "docstring": "Consolidates handling of all outgoing mqtt packet logic. Returns a packet which should\nbe put on to the network by the eventloop", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/state.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "439366eb5d2bae90555f3463ce24c2a5b831a93cad9376cb020c53cb63bd4e40"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_incoming_packet\n\nDocumentation:\nConsolidates handling of all incoming mqtt packets. Returns a `Notification` which for the\nuser to consume and `Packet` which for the eventloop to put on the network\nE.g For incoming QoS1 publish packet, this method returns (Publish, Puback). Publish packet will\nbe forwarded to user and Pubck packet will be written to network\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn handle_incoming_packet(\n &mut self,\n packet: Incoming,\n ) -> Result, StateError> {\n self.events.push_back(Event::Incoming(packet.clone()));\n\n let outgoing = match &packet {\n Incoming::PingResp => self.handle_incoming_pingresp()?,\n Incoming::Publish(publish) => self.handle_incoming_publish(publish)?,\n Incoming::SubAck(_suback) => self.handle_incoming_suback()?,\n Incoming::UnsubAck(_unsuback) => self.handle_incoming_unsuback()?,\n Incoming::PubAck(puback) => self.handle_incoming_puback(puback)?,\n Incoming::PubRec(pubrec) => self.handle_incoming_pubrec(pubrec)?,\n Incoming::PubRel(pubrel) => self.handle_incoming_pubrel(pubrel)?,\n Incoming::PubComp(pubcomp) => self.handle_incoming_pubcomp(pubcomp)?,\n _ => {\n error!(\"Invalid incoming packet = {:?}\", packet);\n return Err(StateError::WrongPacket);\n }\n };\n self.last_incoming = Instant::now();\n\n Ok(outgoing)\n }\n```"}], "func_name": "handle_incoming_packet", "docstring": "Consolidates handling of all incoming mqtt packets. Returns a `Notification` which for the\nuser to consume and `Packet` which for the eventloop to put on the network\nE.g For incoming QoS1 publish packet, this method returns (Publish, Puback). Publish packet will\nbe forwarded to user and Pubck packet will be written to network", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/state.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a7f136754da7c7ef4acc364490cbf63af05f81aa62c7dd7ad47b0c4d6cc8c93"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_incoming_publish\n\nDocumentation:\nResults in a publish notification in all the QoS cases. Replys with an ack\nin case of QoS1 and Replys rec in case of QoS while also storing the message\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_incoming_publish(&mut self, publish: &Publish) -> Result, StateError> {\n let qos = publish.qos;\n\n match qos {\n QoS::AtMostOnce => Ok(None),\n QoS::AtLeastOnce => {\n if !self.manual_acks {\n let puback = PubAck::new(publish.pkid);\n return self.outgoing_puback(puback);\n }\n Ok(None)\n }\n QoS::ExactlyOnce => {\n let pkid = publish.pkid;\n self.incoming_pub.insert(pkid as usize);\n\n if !self.manual_acks {\n let pubrec = PubRec::new(pkid);\n return self.outgoing_pubrec(pubrec);\n }\n Ok(None)\n }\n }\n }\n```"}], "func_name": "handle_incoming_publish", "docstring": "Results in a publish notification in all the QoS cases. Replys with an ack\nin case of QoS1 and Replys rec in case of QoS while also storing the message", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/state.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d1aefe2b821f6b49c7922a027fa0e2c87c409fb80ac5d57247877f810d743f3a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: outgoing_publish\n\nDocumentation:\nAdds next packet identifier to QoS 1 and 2 publish packets and returns\nit buy wrapping publish in packet\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn outgoing_publish(&mut self, mut publish: Publish) -> Result, StateError> {\n if publish.qos != QoS::AtMostOnce {\n if publish.pkid == 0 {\n publish.pkid = self.next_pkid();\n }\n\n let pkid = publish.pkid;\n if self\n .outgoing_pub\n .get(publish.pkid as usize)\n .ok_or(StateError::Unsolicited(publish.pkid))?\n .is_some()\n {\n info!(\"Collision on packet id = {:?}\", publish.pkid);\n self.collision = Some(publish);\n let event = Event::Outgoing(Outgoing::AwaitAck(pkid));\n self.events.push_back(event);\n return Ok(None);\n }\n\n // if there is an existing publish at this pkid, this implies that broker hasn't acked this\n // packet yet. This error is possible only when broker isn't acking sequentially\n self.outgoing_pub[pkid as usize] = Some(publish.clone());\n self.inflight += 1;\n };\n\n debug!(\n \"Publish. Topic = {}, Pkid = {:?}, Payload Size = {:?}\",\n publish.topic,\n publish.pkid,\n publish.payload.len()\n );\n\n let event = Event::Outgoing(Outgoing::Publish(publish.pkid));\n self.events.push_back(event);\n\n Ok(Some(Packet::Publish(publish)))\n }\n```"}], "func_name": "outgoing_publish", "docstring": "Adds next packet identifier to QoS 1 and 2 publish packets and returns\nit buy wrapping publish in packet", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/state.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e0d655291894c6654656b178bba1b9a6a9a0f09b03d9c7f61aa8ff4b2a5bbfde"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: outgoing_ping\n\nDocumentation:\ncheck when the last control packet/pingreq packet is received and return\nthe status which tells if keep alive time has exceeded\nNOTE: status will be checked for zero keepalive times also\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn outgoing_ping(&mut self) -> Result, StateError> {\n let elapsed_in = self.last_incoming.elapsed();\n let elapsed_out = self.last_outgoing.elapsed();\n\n if self.collision.is_some() {\n self.collision_ping_count += 1;\n if self.collision_ping_count >= 2 {\n return Err(StateError::CollisionTimeout);\n }\n }\n\n // raise error if last ping didn't receive ack\n if self.await_pingresp {\n return Err(StateError::AwaitPingResp);\n }\n\n self.await_pingresp = true;\n\n debug!(\n \"Pingreq,\n last incoming packet before {} millisecs,\n last outgoing request before {} millisecs\",\n elapsed_in.as_millis(),\n elapsed_out.as_millis()\n );\n\n let event = Event::Outgoing(Outgoing::PingReq);\n self.events.push_back(event);\n\n Ok(Some(Packet::PingReq))\n }\n```"}], "func_name": "outgoing_ping", "docstring": "check when the last control packet/pingreq packet is received and return\nthe status which tells if keep alive time has exceeded\nNOTE: status will be checked for zero keepalive times also", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/state.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2847d617b91361cb68286db70a9be7e3f08cf51872155bf1512bf666cd3e9043"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next_pkid\n\nDocumentation:\nhttp://stackoverflow.com/questions/11115364/mqtt-messageid-practical-implementation\nPacket ids are incremented till maximum set inflight messages and reset to 1 after that.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn next_pkid(&mut self) -> u16 {\n let next_pkid = self.last_pkid + 1;\n\n // When next packet id is at the edge of inflight queue,\n // set await flag. This instructs eventloop to stop\n // processing requests until all the inflight publishes\n // are acked\n if next_pkid == self.max_inflight {\n self.last_pkid = 0;\n return next_pkid;\n }\n\n self.last_pkid = next_pkid;\n next_pkid\n }\n```"}], "func_name": "next_pkid", "docstring": "http://stackoverflow.com/questions/11115364/mqtt-messageid-practical-implementation\nPacket ids are incremented till maximum set inflight messages and reset to 1 after that.", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/state.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "422a33d6b5a2734a6719c34abb153e96702ac6e5ee4b2cfb8f811a971dc88fe3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_wildcards\n\nDocumentation:\nChecks if a topic or topic filter has wildcards\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn has_wildcards(s: &str) -> bool {\n s.contains('+') || s.contains('#')\n}\n```"}], "func_name": "has_wildcards", "docstring": "Checks if a topic or topic filter has wildcards", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/mqttbytes/topic.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/mqttbytes/topic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b83a518c447549101841c603532b82e6f2f043eb5c68868562f84bd79ec3410e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: matches\n\nDocumentation:\nChecks if topic matches a filter. topic and filter validation isn't done here.\n\n**NOTE**: 'topic' is a misnomer in the arg. this can also be used to match 2 wild subscriptions\n**NOTE**: make sure a topic is validated during a publish and filter is validated\nduring a subscribe\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn matches(topic: &str, filter: &str) -> bool {\n if !topic.is_empty() && topic[..1].contains('$') {\n return false;\n }\n\n let mut topics = topic.split('/');\n let mut filters = filter.split('/');\n\n for f in filters.by_ref() {\n // \"#\" being the last element is validated by the broker with 'valid_filter'\n if f == \"#\" {\n return true;\n }\n\n // filter still has remaining elements\n // filter = a/b/c/# should match topci = a/b/c\n // filter = a/b/c/d should not match topic = a/b/c\n let top = topics.next();\n match top {\n Some(\"#\") => return false,\n Some(_) if f == \"+\" => continue,\n Some(t) if f != t => return false,\n Some(_) => continue,\n None => return false,\n }\n }\n\n // topic has remaining elements and filter's last element isn't \"#\"\n if topics.next().is_some() {\n return false;\n }\n\n true\n}\n```"}], "func_name": "matches", "docstring": "Checks if topic matches a filter. topic and filter validation isn't done here.\n\n**NOTE**: 'topic' is a misnomer in the arg. this can also be used to match 2 wild subscriptions\n**NOTE**: make sure a topic is validated during a publish and filter is validated\nduring a subscribe", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/mqttbytes/topic.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/mqttbytes/topic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8bc6b6f9d22d1e8da151acd617aebee3894fd8131e42f3a4427b3886cfaf1bc1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write\n\nDocumentation:\nSerializes the MQTT packet into a stream of bytes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write(&self, stream: &mut BytesMut, max_size: usize) -> Result {\n if self.size() > max_size {\n return Err(Error::OutgoingPacketTooLarge {\n pkt_size: self.size(),\n max: max_size,\n });\n }\n\n match self {\n Packet::Connect(c) => c.write(stream),\n Packet::ConnAck(c) => c.write(stream),\n Packet::Publish(p) => p.write(stream),\n Packet::PubAck(p) => p.write(stream),\n Packet::PubRec(p) => p.write(stream),\n Packet::PubRel(p) => p.write(stream),\n Packet::PubComp(p) => p.write(stream),\n Packet::Subscribe(s) => s.write(stream),\n Packet::SubAck(s) => s.write(stream),\n Packet::Unsubscribe(u) => u.write(stream),\n Packet::UnsubAck(u) => u.write(stream),\n Packet::PingReq => PingReq.write(stream),\n Packet::PingResp => PingResp.write(stream),\n Packet::Disconnect => Disconnect.write(stream),\n }\n }\n```"}], "func_name": "write", "docstring": "Serializes the MQTT packet into a stream of bytes", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/mqttbytes/v4/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/mqttbytes/v4/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "085ab00e7bfe5f65d13cf42b07e27172df0743a3cea849970850bdb3ef0811f1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate an [`MqttOptions`] object that contains default values for all settings other than\n- id: A string to identify the device connecting to a broker\n- host: The broker's domain name or IP address\n- port: The port number on which broker must be listening for incoming connections\n\n```\n# use rumqttc::v5::MqttOptions;\nlet options = MqttOptions::new(\"123\", \"localhost\", 1883);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new, T: Into>(id: S, host: T, port: u16) -> MqttOptions {\n MqttOptions {\n broker_addr: host.into(),\n port,\n transport: Transport::tcp(),\n keep_alive: Duration::from_secs(60),\n clean_start: true,\n client_id: id.into(),\n credentials: None,\n request_channel_capacity: 10,\n max_request_batch: 0,\n pending_throttle: Duration::from_micros(0),\n last_will: None,\n conn_timeout: 5,\n default_max_incoming_size: 10 * 1024,\n connect_properties: None,\n manual_acks: false,\n network_options: NetworkOptions::new(),\n #[cfg(feature = \"proxy\")]\n proxy: None,\n outgoing_inflight_upper_limit: None,\n #[cfg(feature = \"websocket\")]\n request_modifier: None,\n }\n }\n```"}], "func_name": "new", "docstring": "Create an [`MqttOptions`] object that contains default values for all settings other than\n- id: A string to identify the device connecting to a broker\n- host: The broker's domain name or IP address\n- port: The port number on which broker must be listening for incoming connections\n\n```\n# use rumqttc::v5::MqttOptions;\nlet options = MqttOptions::new(\"123\", \"localhost\", 1883);\n```", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f4752e66d096d9780c7e55d05f335fd1872f3a3dc002c201f6fbc19774f3e6b3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_session_expiry_interval\n\nDocumentation:\nset session expiry interval on connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_session_expiry_interval(&mut self, interval: Option) -> &mut Self {\n if let Some(conn_props) = &mut self.connect_properties {\n conn_props.session_expiry_interval = interval;\n self\n } else {\n let mut conn_props = ConnectProperties::new();\n conn_props.session_expiry_interval = interval;\n self.set_connect_properties(conn_props)\n }\n }\n```"}], "func_name": "set_session_expiry_interval", "docstring": "set session expiry interval on connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bccdbf573106242868457f72b5da8dd6bce487c8e3949ea74a649d8c88a10570"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: session_expiry_interval\n\nDocumentation:\nget session expiry interval on connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn session_expiry_interval(&self) -> Option {\n if let Some(conn_props) = &self.connect_properties {\n conn_props.session_expiry_interval\n } else {\n None\n }\n }\n```"}], "func_name": "session_expiry_interval", "docstring": "get session expiry interval on connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "552fc820d418ade3196a5051bc0dd532e81952dc92ab75847dad0c290a8a5d14"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_receive_maximum\n\nDocumentation:\nset receive maximum on connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_receive_maximum(&mut self, recv_max: Option) -> &mut Self {\n if let Some(conn_props) = &mut self.connect_properties {\n conn_props.receive_maximum = recv_max;\n self\n } else {\n let mut conn_props = ConnectProperties::new();\n conn_props.receive_maximum = recv_max;\n self.set_connect_properties(conn_props)\n }\n }\n```"}], "func_name": "set_receive_maximum", "docstring": "set receive maximum on connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f96c733d9ffbdcbc8059c935a169de5953618428d2c1d9fad1a23592b9863cc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: receive_maximum\n\nDocumentation:\nget receive maximum from connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn receive_maximum(&self) -> Option {\n if let Some(conn_props) = &self.connect_properties {\n conn_props.receive_maximum\n } else {\n None\n }\n }\n```"}], "func_name": "receive_maximum", "docstring": "get receive maximum from connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f2a2247d31496e4b57e2686523eef50c3aeb87e4c299dd2b89c3db4a61022337"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_max_packet_size\n\nDocumentation:\nset max packet size on connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_max_packet_size(&mut self, max_size: Option) -> &mut Self {\n if let Some(conn_props) = &mut self.connect_properties {\n conn_props.max_packet_size = max_size;\n self\n } else {\n let mut conn_props = ConnectProperties::new();\n conn_props.max_packet_size = max_size;\n self.set_connect_properties(conn_props)\n }\n }\n```"}], "func_name": "set_max_packet_size", "docstring": "set max packet size on connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b632d569504a50a42d2831fd25f18815e73f20502b2a0822c8004cfc4f214b7c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: max_packet_size\n\nDocumentation:\nget max packet size from connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn max_packet_size(&self) -> Option {\n if let Some(conn_props) = &self.connect_properties {\n conn_props.max_packet_size\n } else {\n None\n }\n }\n```"}], "func_name": "max_packet_size", "docstring": "get max packet size from connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6fc92f0667c1329fe771a4fae04691d9e0d481bde8f12c33beb5069cd521cc0d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_topic_alias_max\n\nDocumentation:\nset max topic alias on connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_topic_alias_max(&mut self, topic_alias_max: Option) -> &mut Self {\n if let Some(conn_props) = &mut self.connect_properties {\n conn_props.topic_alias_max = topic_alias_max;\n self\n } else {\n let mut conn_props = ConnectProperties::new();\n conn_props.topic_alias_max = topic_alias_max;\n self.set_connect_properties(conn_props)\n }\n }\n```"}], "func_name": "set_topic_alias_max", "docstring": "set max topic alias on connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "35834dd01aa618484e25a409d2a50b46667c3aae054040e2736c455e3738e20a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: topic_alias_max\n\nDocumentation:\nget max topic alias from connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn topic_alias_max(&self) -> Option {\n if let Some(conn_props) = &self.connect_properties {\n conn_props.topic_alias_max\n } else {\n None\n }\n }\n```"}], "func_name": "topic_alias_max", "docstring": "get max topic alias from connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "816aa6f2808aecac97e8cc13b3233e2d5ad8a3a68de862b9c5dce763db7a1bcf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_request_response_info\n\nDocumentation:\nset request response info on connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_request_response_info(&mut self, request_response_info: Option) -> &mut Self {\n if let Some(conn_props) = &mut self.connect_properties {\n conn_props.request_response_info = request_response_info;\n self\n } else {\n let mut conn_props = ConnectProperties::new();\n conn_props.request_response_info = request_response_info;\n self.set_connect_properties(conn_props)\n }\n }\n```"}], "func_name": "set_request_response_info", "docstring": "set request response info on connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1940e5952db86f6fc605c6f7ddbfe1250b5fd2e0dd63194fdda44a7279e0c1dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: request_response_info\n\nDocumentation:\nget request response info from connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn request_response_info(&self) -> Option {\n if let Some(conn_props) = &self.connect_properties {\n conn_props.request_response_info\n } else {\n None\n }\n }\n```"}], "func_name": "request_response_info", "docstring": "get request response info from connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00b73df05b1933af62cbd6cc18266c31bfc39eb7fff4cb04a619e297ad80a2ef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_request_problem_info\n\nDocumentation:\nset request problem info on connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_request_problem_info(&mut self, request_problem_info: Option) -> &mut Self {\n if let Some(conn_props) = &mut self.connect_properties {\n conn_props.request_problem_info = request_problem_info;\n self\n } else {\n let mut conn_props = ConnectProperties::new();\n conn_props.request_problem_info = request_problem_info;\n self.set_connect_properties(conn_props)\n }\n }\n```"}], "func_name": "set_request_problem_info", "docstring": "set request problem info on connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "70018d05206218b5fcd34d3a40d3cf820da30b3331a7d923c2aa3eb9192845d7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: request_problem_info\n\nDocumentation:\nget request problem info from connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn request_problem_info(&self) -> Option {\n if let Some(conn_props) = &self.connect_properties {\n conn_props.request_problem_info\n } else {\n None\n }\n }\n```"}], "func_name": "request_problem_info", "docstring": "get request problem info from connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ccd64606ce458825a145748f6f0d66aaa3f76df2378b45f212b38ecc0320e3a0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_user_properties\n\nDocumentation:\nset user properties on connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_user_properties(&mut self, user_properties: Vec<(String, String)>) -> &mut Self {\n if let Some(conn_props) = &mut self.connect_properties {\n conn_props.user_properties = user_properties;\n self\n } else {\n let mut conn_props = ConnectProperties::new();\n conn_props.user_properties = user_properties;\n self.set_connect_properties(conn_props)\n }\n }\n```"}], "func_name": "set_user_properties", "docstring": "set user properties on connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1462e94b8990992e9ac3cbaf0bca835415d44e31c1b5a63fc6997b6e30eb6f58"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: user_properties\n\nDocumentation:\nget user properties from connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn user_properties(&self) -> Vec<(String, String)> {\n if let Some(conn_props) = &self.connect_properties {\n conn_props.user_properties.clone()\n } else {\n Vec::new()\n }\n }\n```"}], "func_name": "user_properties", "docstring": "get user properties from connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "13f0de046fdd572f7ddc42cc9e3c5bf6d80f862335bb71e19a33a2534dd898e7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_authentication_method\n\nDocumentation:\nset authentication method on connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_authentication_method(\n &mut self,\n authentication_method: Option,\n ) -> &mut Self {\n if let Some(conn_props) = &mut self.connect_properties {\n conn_props.authentication_method = authentication_method;\n self\n } else {\n let mut conn_props = ConnectProperties::new();\n conn_props.authentication_method = authentication_method;\n self.set_connect_properties(conn_props)\n }\n }\n```"}], "func_name": "set_authentication_method", "docstring": "set authentication method on connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ae016327c8255d982613b0f9118349f7885648b05c0a0b32e1c4e42827bb694"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: authentication_method\n\nDocumentation:\nget authentication method from connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn authentication_method(&self) -> Option {\n if let Some(conn_props) = &self.connect_properties {\n conn_props.authentication_method.clone()\n } else {\n None\n }\n }\n```"}], "func_name": "authentication_method", "docstring": "get authentication method from connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8543bddbac0a28e627e85d44c3a8ed70860b4fcc0b9d14441416868cf4992eca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_authentication_data\n\nDocumentation:\nset authentication data on connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_authentication_data(&mut self, authentication_data: Option) -> &mut Self {\n if let Some(conn_props) = &mut self.connect_properties {\n conn_props.authentication_data = authentication_data;\n self\n } else {\n let mut conn_props = ConnectProperties::new();\n conn_props.authentication_data = authentication_data;\n self.set_connect_properties(conn_props)\n }\n }\n```"}], "func_name": "set_authentication_data", "docstring": "set authentication data on connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc6a971726dd3d175786e89a4ffcb46457f9585e849d29b5809189b40df00afb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: authentication_data\n\nDocumentation:\nget authentication data from connection properties\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn authentication_data(&self) -> Option {\n if let Some(conn_props) = &self.connect_properties {\n conn_props.authentication_data.clone()\n } else {\n None\n }\n }\n```"}], "func_name": "authentication_data", "docstring": "get authentication data from connection properties", "repo": "bytebeamio/rumqtt", "path": "rumqttc/src/v5/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/src/v5/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc381e0c084b21a2fd5d2de45284e3ef0d87caeb4701bb376e6d9fd9e96967b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new broker which accepts 1 mqtt connection\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn new(port: u16, connack: u8, session_saved: bool) -> Broker {\n let addr = format!(\"127.0.0.1:{port}\");\n let listener = TcpListener::bind(&addr).await.unwrap();\n\n let (stream, _) = listener.accept().await.unwrap();\n let mut framed = Network::new(stream, 10 * 1024);\n let mut incoming = VecDeque::new();\n let (outgoing_tx, outgoing_rx) = bounded(10);\n framed.readb(&mut incoming).await.unwrap();\n\n match incoming.pop_front().unwrap() {\n Packet::Connect(connect) => {\n let connack = match connack {\n 0 => ConnAck::new(\n ConnectReturnCode::Success,\n !connect.clean_session && session_saved,\n ),\n 1 => ConnAck::new(ConnectReturnCode::BadUserNamePassword, false),\n _ => {\n return Broker {\n framed,\n incoming,\n outgoing_tx,\n outgoing_rx,\n }\n }\n };\n\n framed.connack(connack).await.unwrap();\n }\n _ => {\n panic!(\"Expecting connect packet\");\n }\n }\n\n Broker {\n framed,\n incoming: VecDeque::new(),\n outgoing_tx,\n outgoing_rx,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new broker which accepts 1 mqtt connection", "repo": "bytebeamio/rumqtt", "path": "rumqttc/tests/broker.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/tests/broker.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "92ea6a3858ed39d647b51f26b4865eb0f3652db01b1fbc110c29d3c79fa7a6d7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_packet\n\nDocumentation:\nReads next packet from the stream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn read_packet(&mut self) -> Option {\n let _ = time::timeout(Duration::from_secs(30), async {\n let p = self.framed.readb(&mut self.incoming).await;\n if p.is_err() {\n println!(\"Broker read = {p:?}\");\n }\n // Sometimes there can be a timeout on the connection so instead of unwrapping return\n // an Option\n // p.unwrap()\n })\n .await;\n\n self.incoming.pop_front()\n }\n```"}], "func_name": "read_packet", "docstring": "Reads next packet from the stream", "repo": "bytebeamio/rumqtt", "path": "rumqttc/tests/broker.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/tests/broker.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dcd1f787cb2879dfdf42d83e8bd4f7d8287f3fca5a1f636988a73b4e86b8f951"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tick\n\nDocumentation:\nSelects between outgoing and incoming packets\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn tick(&mut self) -> Event {\n select! {\n request = self.outgoing_rx.recv_async() => {\n let request = request.unwrap();\n let outgoing = self.framed.write(request).await.unwrap();\n Event::Outgoing(outgoing)\n }\n packet = self.framed.readb(&mut self.incoming) => {\n packet.unwrap();\n let incoming = self.incoming.pop_front().unwrap();\n Event::Incoming(incoming)\n }\n }\n }\n```"}], "func_name": "tick", "docstring": "Selects between outgoing and incoming packets", "repo": "bytebeamio/rumqtt", "path": "rumqttc/tests/broker.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/tests/broker.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f064707874fa9ab60a7bf6feb0c4265e406779521800ac5451f2ef0eaebbf79"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_bytes\n\nDocumentation:\nReads more than 'required' bytes to frame a packet into self.read buffer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn read_bytes(&mut self, required: usize) -> io::Result {\n let mut total_read = 0;\n loop {\n let read = self.socket.read_buf(&mut self.read).await?;\n if 0 == read {\n return if self.read.is_empty() {\n Err(io::Error::new(\n io::ErrorKind::ConnectionAborted,\n \"connection closed by peer\",\n ))\n } else {\n Err(io::Error::new(\n io::ErrorKind::ConnectionReset,\n \"connection reset by peer\",\n ))\n };\n }\n\n total_read += read;\n if total_read >= required {\n return Ok(total_read);\n }\n }\n }\n```"}], "func_name": "read_bytes", "docstring": "Reads more than 'required' bytes to frame a packet into self.read buffer", "repo": "bytebeamio/rumqtt", "path": "rumqttc/tests/broker.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttc/tests/broker.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dfa80ea55345dbae0558def2f1bde86df8dfa1e44dcb564884a1c5d0d97f4b70"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nRequires the corresponding Router to be running to complete\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(config: ConsoleSettings, router_tx: Sender<(ConnectionId, Event)>) -> ConsoleLink {\n let tx = router_tx.clone();\n let (link_tx, link_rx, _ack) = LinkBuilder::new(\"console\", tx)\n .dynamic_filters(true)\n .build()\n .unwrap();\n let connection_id = link_tx.connection_id;\n ConsoleLink {\n config,\n router_tx,\n _link_rx: link_rx,\n connection_id,\n }\n }\n```"}], "func_name": "new", "docstring": "Requires the corresponding Router to be running to complete", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/link/console.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/link/console.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cba84dd58b1245cfa248280150b3716e7f4c4ea9749e7131428106d6dc3a7567"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: publish\n\nDocumentation:\nSends a MQTT Publish to the router\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn publish(&mut self, topic: S, payload: V) -> Result\n where\n S: Into,\n V: Into,\n {\n let publish = Publish {\n dup: false,\n qos: QoS::AtMostOnce,\n retain: false,\n topic: topic.into(),\n pkid: 0,\n payload: payload.into(),\n };\n\n let len = self.push(Packet::Publish(publish, None))?;\n Ok(len)\n }\n```"}], "func_name": "publish", "docstring": "Sends a MQTT Publish to the router", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/link/local.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/link/local.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8ea55ca37af48d56e102e93b7671e746f3d0ada07d0ab92d2f959bc114955442"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: subscribe\n\nDocumentation:\nSends a MQTT Subscribe to the eventloop\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn subscribe>(&mut self, filter: S) -> Result {\n let filters = vec![Filter {\n path: filter.into(),\n qos: QoS::AtMostOnce,\n nolocal: false,\n preserve_retain: false,\n retain_forward_rule: RetainForwardRule::Never,\n }];\n\n let subscribe = Subscribe { pkid: 0, filters };\n\n let len = self.push(Packet::Subscribe(subscribe, None))?;\n Ok(len)\n }\n```"}], "func_name": "subscribe", "docstring": "Sends a MQTT Subscribe to the eventloop", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/link/local.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/link/local.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ee19a30b331bfa3af35632bbc81623c98b798fc18aa08d05a741324e312c6348"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unsubscribe\n\nDocumentation:\nSends a MQTT Unsubscribe to the eventloop\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unsubscribe>(&mut self, filter: S) -> Result {\n let unsubscribe = Unsubscribe {\n pkid: 0,\n filters: vec![filter.into()],\n };\n\n let len = self.push(Packet::Unsubscribe(unsubscribe, None))?;\n Ok(len)\n }\n```"}], "func_name": "unsubscribe", "docstring": "Sends a MQTT Unsubscribe to the eventloop", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/link/local.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/link/local.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7a1193b1d779b0b145161f00bd8a1de209187f610106203e1ef47212bb479916"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: serialize\n\nDocumentation:\nSerialization which is independent of MQTT\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn serialize(&self) -> Bytes {\n let mut o = BytesMut::with_capacity(self.len() + 5);\n let dup = self.dup as u8;\n let qos = self.qos as u8;\n let retain = self.retain as u8;\n o.put_u8(0b0011_0000 | retain | (qos << 1) | (dup << 3));\n o.put_u16(self.pkid);\n o.put_u16(self.topic.len() as u16);\n o.extend_from_slice(&self.topic[..]);\n\n // TODO: Change segments to take Buf to prevent this copying\n o.extend_from_slice(&self.payload[..]);\n o.freeze()\n }\n```"}], "func_name": "serialize", "docstring": "Serialization which is independent of MQTT", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/protocol/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/protocol/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ff8055e5d6e977403c466306e6f9165cbee5e5c061084a3128456e810315828"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_replica_router_handle\n\nDocumentation:\nAdd router handle of replicas representing other nodes of the cluster\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_replica_router_handle(&mut self, id: NodeId, replica: (LinkTx, LinkRx)) {\n self.replicas.insert(id, replica);\n }\n```"}], "func_name": "add_replica_router_handle", "docstring": "Add router handle of replicas representing other nodes of the cluster", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/replicator/local.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/replicator/local.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ef2a5f32a4b9b0bff87ddd954e3fb7ff33a967ed295ba9863018cd643dd77fd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate connection state to hold identifying information of connecting device\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n tenant_id: Option,\n client_id: String,\n clean: bool,\n dynamic_filters: bool,\n ) -> Connection {\n // Change client id to -> tenant_id.client_id and derive topic path prefix\n // to validate topics\n let (client_id, tenant_prefix) = match tenant_id {\n Some(tenant_id) => {\n let tenant_prefix = Some(\"/tenants/\".to_owned() + &tenant_id + \"/\");\n let client_id = tenant_id + \".\" + &client_id;\n (client_id, tenant_prefix)\n }\n None => (client_id, None),\n };\n\n Connection {\n client_id,\n tenant_prefix,\n dynamic_filters,\n clean,\n subscriptions: HashSet::default(),\n last_will: None,\n last_will_properties: None,\n events: ConnectionEvents::default(),\n topic_aliases: HashMap::new(),\n broker_topic_aliases: None,\n subscription_ids: HashMap::new(),\n }\n }\n```"}], "func_name": "new", "docstring": "Create connection state to hold identifying information of connecting device", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/router/connection.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/router/connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8ee18547c07d9c049a6d050ec02e9561f60a02657505fd120f78e2b4e241f0a7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_forwards\n\nDocumentation:\nPush packets to the outgoing buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn push_forwards(\n &mut self,\n publishes: impl Iterator,\n qos: u8,\n filter_idx: usize,\n ) -> (usize, usize) {\n let mut buffer = self.data_buffer.lock();\n let publishes = publishes;\n\n if qos == 0 {\n for p in publishes {\n self.meter.publish_count += 1;\n buffer.push_back(Notification::Forward(p));\n // self.meter.total_size += p.len();\n }\n\n // self.meter.update_data_rate(total_size);\n let buffer_count = buffer.len();\n let inflight_count = self.inflight_buffer.len();\n return (buffer_count, inflight_count);\n }\n\n for mut p in publishes {\n // Index and pkid of current outgoing packet\n self.last_pkid += 1;\n p.publish.pkid = self.last_pkid;\n\n self.inflight_buffer\n .push_back((self.last_pkid, filter_idx, p.cursor));\n\n // Place max pkid packet at index 0\n if self.last_pkid == MAX_PKID {\n self.last_pkid = 0;\n }\n\n self.meter.publish_count += 1;\n self.meter.total_size += p.publish.topic.len() + p.publish.payload.len();\n buffer.push_back(Notification::Forward(p));\n }\n\n let buffer_count = buffer.len();\n let inflight_count = self.inflight_buffer.len();\n\n if inflight_count > MAX_INFLIGHT {\n warn!(\n \"More inflight publishes than max allowed, inflight count = {}, max allowed = {}\",\n inflight_count, MAX_INFLIGHT\n );\n }\n\n (buffer_count, inflight_count)\n }\n```"}], "func_name": "push_forwards", "docstring": "Push packets to the outgoing buffer.", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/router/iobufs.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/router/iobufs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d53e3bf0bd071419f2f1778eb1e687d931e7196ed6651362d124f1647a56fbaf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clean\n\nDocumentation:\nCleanup a connection from all the waiters\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clean(&mut self, id: ConnectionId) -> Vec {\n let mut inflight = Vec::new();\n for (_, data) in self.native.iter_mut() {\n inflight.append(&mut data.waiters.remove(id));\n }\n\n inflight\n }\n```"}], "func_name": "clean", "docstring": "Cleanup a connection from all the waiters", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/router/logs.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/router/logs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3aac0091a96ae6b94bcec3d94587d4bfefe0283620313f91a1164d100142a3ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: append\n\nDocumentation:\nWrites to all the filters that are mapped to this publish topic\nand wakes up consumers that are matching this topic (if they exist)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn append(\n &mut self,\n item: T,\n notifications: &mut VecDeque<(ConnectionId, DataRequest)>,\n ) -> (Offset, &Filter) {\n let size = item.size();\n let offset = self.log.append(item);\n if let Some(mut parked) = self.waiters.take() {\n notifications.append(&mut parked);\n }\n\n self.meter.count += 1;\n self.meter.total_size += size;\n\n (offset, &self.filter)\n }\n```"}], "func_name": "append", "docstring": "Writes to all the filters that are mapped to this publish topic\nand wakes up consumers that are matching this topic (if they exist)", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/router/logs.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/router/logs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5e5ee0a50362c491a3cfb7d2ab9414ac28b4f10ff061e9116afb04677333003f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_device_payload\n\nDocumentation:\nHandles new incoming data on a topic\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_device_payload(&mut self, id: ConnectionId) {\n // TODO: Retun errors and move error handling to the caller\n let incoming = match self.ibufs.get_mut(id) {\n Some(v) => v,\n None => {\n error!(\"no-connection id {} is already gone\", id);\n return;\n }\n };\n\n let client_id = incoming.client_id.clone();\n let span = tracing::error_span!(\"incoming_payload\", client_id);\n let _guard = span.enter();\n\n // Instead of exchanging, we should just append new incoming packets inside cache\n let mut packets = incoming.exchange(self.cache.take().unwrap());\n\n let mut force_ack = false;\n let mut new_data = false;\n let mut disconnect = false;\n let mut disconnect_reason: Option = None;\n\n // info!(\"{:15.15}[I] {:20} count = {}\", client_id, \"packets\", packets.len());\n\n for packet in packets.drain(0..) {\n match packet {\n Packet::Publish(publish, properties) => {\n let span = tracing::error_span!(\"publish\", topic = ?publish.topic, pkid = publish.pkid);\n let _guard = span.enter();\n\n let qos = publish.qos;\n let pkid = publish.pkid;\n\n // Prepare acks for the above publish\n // If any of the publish in the batch results in force flush,\n // set global force flush flag. Force flush is triggered when the\n // router is in instant ack more or connection data is from a replica\n //\n // TODO: handle multiple offsets\n //\n // The problem with multiple offsets is that when using replication with the current\n // architecture, a single publish might get appended to multiple commit logs, resulting in\n // multiple offsets (see `append_to_commitlog` function), meaning replicas will need to\n // coordinate using multiple offsets, and we don't have any idea how to do so right now.\n // Currently as we don't have replication, we just use a single offset, even when appending to\n // multiple commit logs.\n\n match qos {\n QoS::AtLeastOnce => {\n let puback = PubAck {\n pkid,\n reason: PubAckReason::Success,\n };\n\n let ackslog = self.ackslog.get_mut(id).unwrap();\n ackslog.puback(puback);\n force_ack = true;\n }\n QoS::ExactlyOnce => {\n let pubrec = PubRec {\n pkid,\n reason: PubRecReason::Success,\n };\n\n let ackslog = self.ackslog.get_mut(id).unwrap();\n ackslog.pubrec(publish, properties, pubrec);\n force_ack = true;\n continue;\n }\n QoS::AtMostOnce => {\n // Do nothing\n }\n };\n\n self.router_meters.total_publishes += 1;\n\n // Try to append publish to commitlog\n match append_to_commitlog(\n id,\n publish.clone(),\n properties,\n &mut self.datalog,\n &mut self.notifications,\n &mut self.connections,\n ) {\n Ok(_offset) => {\n // Even if one of the data in the batch is appended to commitlog,\n // set new data. This triggers notifications to wake waiters.\n // Don't overwrite this flag to false if it is already true.\n new_data = true;\n }\n Err(e) => {\n // Disconnect on bad publishes\n error!(\n reason = ?e, \"Failed to append to commitlog\"\n );\n self.router_meters.failed_publishes += 1;\n disconnect = true;\n\n if let RouterError::Disconnect(code) = e {\n disconnect_reason = Some(code)\n }\n\n break;\n }\n };\n\n let meter = &mut self.ibufs.get_mut(id).unwrap().meter;\n if let Err(e) = meter.register_publish(&publish) {\n error!(\n reason = ?e, \"Failed to write to incoming meter\"\n );\n };\n }\n Packet::Subscribe(mut subscribe, props) => {\n let mut return_codes = Vec::new();\n let pkid = subscribe.pkid;\n // let len = s.len();\n\n for f in &mut subscribe.filters {\n let span =\n tracing::info_span!(\"subscribe\", topic = f.path, pkid = subscribe.pkid);\n let _guard = span.enter();\n\n info!(\"Adding subscription on topic {}\", f.path);\n let connection = self.connections.get_mut(id).unwrap();\n\n if let Err(e) = validate_subscription(connection, f) {\n warn!(reason = ?e,\"Subscription cannot be validated: {}\", e);\n\n disconnect = true;\n break;\n }\n\n let mut filter = f.path.clone();\n let mut group = None;\n\n if let Some((grp, filter_path)) = extract_group(&f.path) {\n group = Some(grp);\n filter = filter_path;\n };\n\n let subscription_id = props.as_ref().and_then(|p| p.id);\n\n if subscription_id == Some(0) {\n error!(\"Subscription identifier can't be 0\");\n disconnect = true;\n disconnect_reason = Some(DisconnectReasonCode::ProtocolError);\n break;\n }\n\n let (idx, cursor) = self.datalog.next_native_offset(&filter);\n\n // in case of shared sub original_filter will be $share/group/topic\n // this is because we do want to treat is as diffrent subscription\n // and create DataRequest, while using the same datalog of \"topic\"\n // NOTE: topic & $share/group/topic will have same filteridx!\n self.prepare_filter(id, cursor, idx, f, group, subscription_id);\n\n let code = match f.qos {\n QoS::AtMostOnce => SubscribeReasonCode::QoS0,\n QoS::AtLeastOnce => SubscribeReasonCode::QoS1,\n QoS::ExactlyOnce => SubscribeReasonCode::QoS2,\n };\n\n return_codes.push(code);\n }\n\n // let meter = &mut self.ibufs.get_mut(id).unwrap().meter;\n // meter.total_size += len;\n\n let suback = SubAck { pkid, return_codes };\n let ackslog = self.ackslog.get_mut(id).unwrap();\n ackslog.suback(suback);\n force_ack = true;\n }\n Packet::Unsubscribe(unsubscribe, _) => {\n let connection = self.connections.get_mut(id).unwrap();\n let pkid = unsubscribe.pkid;\n for filter in &unsubscribe.filters {\n let span = tracing::info_span!(\"unsubscribe\", topic = filter, pkid);\n let _guard = span.enter();\n\n debug!(\"Removing subscription on filter {}\", filter);\n if let Some(connection_ids) = self.subscription_map.get_mut(filter) {\n let removed = connection_ids.remove(&id);\n if !removed {\n continue;\n }\n\n let meter = &mut self.ibufs.get_mut(id).unwrap().meter;\n meter.unregister_subscription(filter);\n\n if !connection.subscriptions.remove(filter) {\n warn!(\n pkid = unsubscribe.pkid,\n \"Unsubscribe failed as filter was not subscribed previously\"\n );\n continue;\n }\n\n // Remove connections from all groups\n // discard empty group ( group with no client )\n // note: can we do this in better way?\n self.shared_subscriptions.retain(|_, group| {\n group.remove_client(&client_id);\n !group.is_empty()\n });\n\n if let Some(broker_aliases) = connection.broker_topic_aliases.as_mut() {\n broker_aliases.remove_alias(filter);\n }\n\n // remove the subscription id\n connection.subscription_ids.remove(filter);\n\n let unsuback = UnsubAck {\n pkid,\n // reasons are used in MQTTv5\n reasons: vec![UnsubAckReason::Success],\n };\n let ackslog = self.ackslog.get_mut(id).unwrap();\n ackslog.unsuback(unsuback);\n self.scheduler.untrack(id, filter);\n self.datalog.remove_waiters_for_id(id, filter);\n force_ack = true;\n }\n }\n }\n Packet::PubAck(puback, _) => {\n let span = tracing::info_span!(\"puback\", pkid = puback.pkid);\n let _guard = span.enter();\n\n let outgoing = self.obufs.get_mut(id).unwrap();\n let pkid = puback.pkid;\n if outgoing.register_ack(pkid).is_none() {\n error!(pkid, \"Unsolicited/ooo ack received for pkid {}\", pkid);\n disconnect = true;\n break;\n }\n\n self.scheduler.reschedule(id, ScheduleReason::IncomingAck);\n }\n Packet::PubRec(pubrec, _) => {\n let span = tracing::info_span!(\"pubrec\", pkid = pubrec.pkid);\n let _guard = span.enter();\n\n let outgoing = self.obufs.get_mut(id).unwrap();\n let pkid = pubrec.pkid;\n if outgoing.register_ack(pkid).is_none() {\n error!(pkid, \"Unsolicited/ooo ack received for pkid {}\", pkid);\n disconnect = true;\n break;\n }\n\n let ackslog = self.ackslog.get_mut(id).unwrap();\n let pubrel = PubRel {\n pkid: pubrec.pkid,\n reason: PubRelReason::Success,\n };\n\n outgoing.register_pubrec(pubrel.pkid);\n ackslog.pubrel(pubrel);\n self.scheduler.reschedule(id, ScheduleReason::IncomingAck);\n }\n Packet::PubRel(pubrel, None) => {\n let span = tracing::info_span!(\"pubrel\", pkid = pubrel.pkid);\n let _guard = span.enter();\n\n let ackslog = self.ackslog.get_mut(id).unwrap();\n let pubcomp = PubComp {\n pkid: pubrel.pkid,\n reason: PubCompReason::Success,\n };\n\n // NOTE: client can try to resend previously unacked pubrels\n // on reconnection ( with clean session false )\n // we try to retrive publish assuming broker saved the previous state\n // successfully in graveyard.\n let (publish, props) = match ackslog.pubcomp(pubcomp) {\n Some(v) => v,\n None => {\n disconnect = true;\n break;\n }\n };\n\n // Try to append publish to commitlog\n match append_to_commitlog(\n id,\n publish,\n props,\n &mut self.datalog,\n &mut self.notifications,\n &mut self.connections,\n ) {\n Ok(_offset) => {\n // Even if one of the data in the batch is appended to commitlog,\n // set new data. This triggers notifications to wake waiters.\n // Don't overwrite this flag to false if it is already true.\n new_data = true;\n }\n Err(e) => {\n // Disconnect on bad publishes\n error!(\n reason = ?e, \"Failed to append to commitlog\"\n );\n self.router_meters.failed_publishes += 1;\n disconnect = true;\n break;\n }\n };\n self.scheduler.reschedule(id, ScheduleReason::IncomingAck);\n }\n Packet::PubComp(pubcomp, _) => {\n let span = tracing::info_span!(\"pubcomp\", pkid = pubcomp.pkid);\n let _guard = span.enter();\n\n let outgoing = self.obufs.get_mut(id).unwrap();\n let pkid = pubcomp.pkid;\n if outgoing.register_pubcomp(pkid).is_none() {\n error!(\n pkid,\n \"ack received for pkid {}, but the pkid didn't exists!\", pkid\n );\n disconnect = true;\n break;\n }\n }\n Packet::PingReq(_) => {\n let ackslog = self.ackslog.get_mut(id).unwrap();\n ackslog.pingresp(PingResp);\n\n force_ack = true;\n }\n Packet::Disconnect(_, _) => {\n let span = tracing::info_span!(\"disconnect\");\n let _guard = span.enter();\n disconnect = true;\n // delete the last will message\n self.last_wills.remove(&client_id);\n break;\n }\n incoming => {\n warn!(packet=?incoming, \"Unexpected packet received, ignoring the packet.\" );\n }\n }\n }\n\n self.cache = Some(packets);\n\n // Prepare AcksRequest in tracker if router is operating in a\n // single node mode or force ack request for subscriptions\n if force_ack {\n self.scheduler.reschedule(id, ScheduleReason::FreshData);\n }\n\n // Notify waiting consumers only if there is publish data. During\n // subscription, data request is added to data waiter. With out this\n // if condition, connection will be woken up even during subscription\n if new_data {\n // Prepare all the consumers which are waiting for new data\n while let Some((id, request)) = self.notifications.pop_front() {\n self.scheduler.track(id, request);\n self.scheduler.reschedule(id, ScheduleReason::FreshData);\n }\n }\n\n // Incase BytesMut represents 10 packets, publish error/diconnect event\n // on say 5th packet should not block new data notifications for packets\n // 1 - 4. Hence we use a flag instead of diconnecting immediately\n if disconnect {\n self.handle_disconnection(id, disconnect_reason);\n }\n }\n```"}], "func_name": "handle_device_payload", "docstring": "Handles new incoming data on a topic", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/router/routing.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/router/routing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e360b06d31a248ea7aea3ce8f6f5a1292b2db460751e52c6ad292cdf456410d7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prepare_filter\n\nDocumentation:\nApply filter and prepare this connection to receive subscription data\nHandle retained messages as per subscription options!\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn prepare_filter(\n &mut self,\n id: ConnectionId,\n cursor: Offset,\n filter_idx: FilterIdx,\n filter: &protocol::Filter,\n group: Option,\n subscription_id: Option,\n ) {\n let filter_path = &filter.path;\n\n // Add connection id to subscription list\n match self.subscription_map.get_mut(filter_path) {\n Some(connections) => {\n connections.insert(id);\n }\n None => {\n let mut connections = HashSet::new();\n connections.insert(id);\n self.subscription_map\n .insert(filter_path.clone(), connections);\n }\n }\n\n // Prepare consumer to pull data in case of subscription\n let connection = self.connections.get_mut(id).unwrap();\n\n // Add/Create shared group\n if let Some(group_name) = &group {\n let client_id = connection.client_id.clone();\n\n let shared_group = self\n .shared_subscriptions\n .entry(group_name.to_string())\n .or_insert(SharedGroup::new(\n cursor,\n self.config.shared_subscriptions_strategy.clone(),\n ));\n\n shared_group.add_client(client_id);\n };\n\n if let Some(subscription_id) = subscription_id {\n connection\n .subscription_ids\n .insert(filter_path.clone(), subscription_id);\n }\n\n // check is group is None because retained messages aren't sent\n // for shared subscriptions\n // TODO: use retain forward rules\n let forward_retained = group.is_none();\n\n // call to `insert(_)` returns `true` if it didn't contain the filter_path already\n // i.e. its a new subscription\n if connection.subscriptions.insert(filter_path.clone()) {\n let request = DataRequest {\n filter: filter_path.clone(),\n filter_idx,\n qos: filter.qos as u8,\n cursor,\n read_count: 0,\n max_count: 100,\n // set true for new subscriptions\n forward_retained,\n group,\n };\n\n self.scheduler.track(id, request);\n self.scheduler.reschedule(id, ScheduleReason::NewFilter);\n debug_assert!(self.scheduler.check_tracker_duplicates(id).is_none())\n }\n\n // TODO: figure out how we can update existing DataRequest\n // helpful in re-subscriptions and forwarding retained messages on\n // every subscribe\n\n let meter = &mut self.ibufs.get_mut(id).unwrap().meter;\n meter.register_subscription(filter_path.clone());\n }\n```"}], "func_name": "prepare_filter", "docstring": "Apply filter and prepare this connection to receive subscription data\nHandle retained messages as per subscription options!", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/router/routing.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/router/routing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80924e802a4f8d7bc613a76bb7ca3b601059aafac038ddafd847346426f37403"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: consume\n\nDocumentation:\nWhen a connection is ready, it should sweep native data from 'datalog',\nsend data and notifications to consumer.\nTo activate a connection, first connection's tracker is fetched and\nall the requests are handled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn consume(&mut self) -> Option<()> {\n let (id, mut requests) = self.scheduler.poll()?;\n\n let span = tracing::info_span!(\"[<] outgoing\", connection_id = id);\n let _guard = span.enter();\n\n let outgoing = match self.obufs.get_mut(id) {\n Some(v) => v,\n None => {\n error!(\"Connection is already disconnected\");\n return Some(());\n }\n };\n\n let ackslog = self.ackslog.get_mut(id).unwrap();\n let datalog = &mut self.datalog;\n let alertlog = &mut self.alertlog;\n\n trace!(\"Consuming requests\");\n\n // We always try to ack when ever a connection is scheduled\n ack_device_data(ackslog, outgoing);\n\n let connection = &mut self.connections[id];\n\n // Keep track of temporarily skipped DataRequest\n // NOTE: VecDeque::new() doesn't allocate memory until elements are pushed\n let mut skipped_requests: VecDeque = VecDeque::new();\n\n // A new connection's tracker is always initialized with acks request.\n // A subscribe will register data request.\n // So a new connection is always scheduled with at least one request\n for _ in 0..MAX_SCHEDULE_ITERATIONS {\n let mut request = match requests.pop_front() {\n // Handle next data or acks request\n Some(request) => request,\n // No requests in the queue. This implies that consumer data and\n // acks are completely caught up. Pending requests are registered\n // in waiters and awaiting new notifications (device or replica data)\n None => {\n if skipped_requests.is_empty() {\n // if no requests is in skip list, that means\n // we have nothing left to process, i.e. we caughtup\n self.scheduler.pause(id, PauseReason::Caughtup);\n }\n // add back the skipped requests!\n self.scheduler.trackv(id, skipped_requests);\n return Some(());\n }\n };\n\n let shared_group = request\n .group\n .as_ref()\n .and_then(|name| self.shared_subscriptions.get_mut(name));\n\n match forward_device_data(\n &mut request,\n datalog,\n outgoing,\n alertlog,\n connection,\n shared_group,\n ) {\n ConsumeStatus::BufferFull => {\n requests.push_back(request);\n self.scheduler.pause(id, PauseReason::Busy);\n break;\n }\n ConsumeStatus::InflightFull => {\n requests.push_back(request);\n self.scheduler.pause(id, PauseReason::InflightFull);\n break;\n }\n ConsumeStatus::FilterCaughtup => {\n let filter = &request.filter;\n trace!(filter, \"Filter caughtup {filter}, parking connection\");\n\n // When all the data in the log is caught up, current request is\n // registered in waiters and not added back to the tracker. This\n // ensures that tracker.next() stops when all the requests are done\n datalog.park(id, request);\n }\n ConsumeStatus::PartialRead => {\n requests.push_back(request);\n }\n ConsumeStatus::SkipRequest => {\n skipped_requests.push_back(request);\n }\n }\n }\n\n // Add requests back to the tracker if there are any\n requests.extend(skipped_requests);\n self.scheduler.trackv(id, requests);\n Some(())\n }\n```"}], "func_name": "consume", "docstring": "When a connection is ready, it should sweep native data from 'datalog',\nsend data and notifications to consumer.\nTo activate a connection, first connection's tracker is fetched and\nall the requests are handled.", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/router/routing.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/router/routing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be076649f719acee917cb8a3b1a85f14ee115d797d4567aa2f7ae9d8f321cce5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ack_device_data\n\nDocumentation:\nSweep ackslog for all the pending acks.\nWe write everything to outgoing buf with out worrying about buffer size\nbecause acks most certainly won't cause memory bloat\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn ack_device_data(ackslog: &mut AckLog, outgoing: &mut Outgoing) -> bool {\n let span = tracing::info_span!(\"outgoing_ack\", client_id = outgoing.client_id);\n let _guard = span.enter();\n\n let acks = ackslog.readv();\n if acks.is_empty() {\n debug!(\"No acks pending\");\n return false;\n }\n\n let mut count = 0;\n let mut buffer = outgoing.data_buffer.lock();\n\n // Unlike forwards, we are reading all the pending acks for a given connection.\n // At any given point of time, there can be a max of connection's buffer size\n for ack in acks.drain(..) {\n let pkid = packetid(&ack);\n trace!(pkid, \"Ack added for pkid {}\", pkid);\n let message = Notification::DeviceAck(ack);\n buffer.push_back(message);\n count += 1;\n }\n\n debug!(acks_count = count, \"Acks sent to device\");\n outgoing.handle.try_send(()).ok();\n true\n}\n```"}], "func_name": "ack_device_data", "docstring": "Sweep ackslog for all the pending acks.\nWe write everything to outgoing buf with out worrying about buffer size\nbecause acks most certainly won't cause memory bloat", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/router/routing.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/router/routing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3433c8fbb4a3f563d6f3c521ba99b621fb21de2cedb2d7da7bded5e9ed9a3e29"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: forward_device_data\n\nDocumentation:\nSweep datalog from offset in DataRequest and updates DataRequest\nfor next sweep. Returns (busy, caughtup) status\nReturned arguments:\n1. `busy`: whether the data request was completed or not.\n2. `done`: whether the connection was busy or not.\n3. `inflight_full`: whether the inflight requests were completely filled\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn forward_device_data(\n request: &mut DataRequest,\n datalog: &mut DataLog,\n outgoing: &mut Outgoing,\n alertlog: &mut AlertLog,\n connection: &mut Connection,\n shared_group: Option<&mut SharedGroup>,\n) -> ConsumeStatus {\n let span = tracing::info_span!(\"outgoing_publish\", client_id = outgoing.client_id);\n let _guard = span.enter();\n\n if let Some(ref shared_group) = shared_group {\n // update the request cursor to use shared cursor\n request.cursor = shared_group.cursor;\n }\n\n trace!(\n \"Reading from datalog: {}[{}, {}]\",\n request.filter,\n request.cursor.0,\n request.cursor.1\n );\n\n let mut inflight_slots = if request.qos != 0 {\n // for qos 1 & 2\n let len = outgoing.free_slots();\n if len == 0 {\n trace!(\"Aborting read from datalog: inflight capacity reached\");\n return ConsumeStatus::InflightFull;\n }\n\n len as u64\n } else {\n datalog.config.max_outgoing_packet_count\n };\n\n if shared_group\n .as_ref()\n .is_some_and(|g| g.strategy == Strategy::RoundRobin)\n {\n // only read one message in case of round robin\n // so that messages get equally distributed!\n inflight_slots = 1;\n }\n\n let mut publishes = Vec::new();\n\n if request.forward_retained {\n // NOTE: ideally we want to limit the number of read messages\n // and skip the messages previously read while reading next time.\n // but for now, we just try to read all messages and drop the excess ones\n let mut retained_publishes = datalog.read_retained_messages(&request.filter);\n retained_publishes.truncate(inflight_slots as usize);\n\n publishes.extend(retained_publishes.into_iter().map(|p| (p, None)));\n inflight_slots -= publishes.len() as u64;\n\n // we only want to forward retained messages once\n request.forward_retained = false;\n }\n\n let (next, publishes_from_datalog) =\n match datalog.native_readv(request.filter_idx, request.cursor, inflight_slots) {\n Ok(v) => v,\n Err(e) => {\n error!(error = ?e, \"Failed to read from commitlog {}\", e);\n return ConsumeStatus::FilterCaughtup;\n }\n };\n\n publishes.extend(\n publishes_from_datalog\n .into_iter()\n .map(|(p, offset)| (p, Some(offset))),\n );\n\n let (start, next, caughtup) = match next {\n Position::Next { start, end } => (start, end, false),\n Position::Done { start, end } => (start, end, true),\n };\n\n if let Some(ref shared_group) = shared_group {\n let skip_current_client = Some(&outgoing.client_id) != shared_group.current_client();\n\n if skip_current_client {\n return if caughtup {\n ConsumeStatus::FilterCaughtup\n } else {\n ConsumeStatus::SkipRequest\n };\n }\n }\n\n if start != request.cursor {\n let error = format!(\n \"Read cursor start jumped from {:?} to {:?} on {}\",\n request.cursor, start, request.filter\n );\n\n warn!(\n request_cursor = ?request.cursor,\n start_cursor = ?start,\n error\n );\n\n let alert = alert::cursorjump(&outgoing.client_id, &request.filter, 0);\n alertlog.log(alert);\n }\n\n trace!(\n \"Read from commitlog, cursor = {}[{}, {}), read count = {}\",\n request.filter,\n next.0,\n next.1,\n publishes.len()\n );\n\n let qos = request.qos;\n let filter_idx = request.filter_idx;\n request.read_count += publishes.len();\n request.cursor = next;\n // println!(\"{:?} {:?} {}\", start, next, request.read_count);\n\n if publishes.is_empty() {\n return ConsumeStatus::FilterCaughtup;\n }\n\n let broker_topic_aliases = &mut connection.broker_topic_aliases;\n let mut topic_alias = broker_topic_aliases\n .as_ref()\n .and_then(|aliases| aliases.get_alias(&request.filter));\n\n let topic_alias_already_exists = topic_alias.is_some();\n\n // if topic alias doesn't exists, try creating new one!\n if !topic_alias_already_exists {\n topic_alias = broker_topic_aliases\n .as_mut()\n .and_then(|broker_aliases| broker_aliases.set_new_alias(&request.filter))\n }\n\n let subscription_id = connection.subscription_ids.get(&request.filter);\n\n // Fill and notify device data\n let forwards = publishes\n .into_iter()\n .map(|((mut publish, mut properties), offset)| {\n publish.qos = protocol::qos(qos).unwrap();\n\n // if there is some topic alias to use, set it in publish properties\n if topic_alias.is_some() {\n let mut props = properties.unwrap_or_default();\n props.topic_alias = topic_alias;\n properties = Some(props);\n }\n\n // We want to clear topic if we are using an existing alias\n if topic_alias_already_exists {\n publish.topic.clear()\n }\n\n if let Some(&subscription_id) = subscription_id {\n // create new props if not already exists\n let mut props = properties.unwrap_or_default();\n props.subscription_identifiers.push(subscription_id);\n properties = Some(props);\n }\n\n Forward {\n cursor: offset,\n size: 0,\n publish,\n properties,\n }\n });\n\n let (len, inflight) = outgoing.push_forwards(forwards, qos, filter_idx);\n\n debug!(\n inflight_count = inflight,\n forward_count = len,\n \"Forwarding publishes, cursor = {}[{}, {}) forward count = {}\",\n request.filter,\n request.cursor.0,\n request.cursor.1,\n len\n );\n\n if len >= MAX_CHANNEL_CAPACITY - 1 {\n debug!(\"Outgoing channel reached its capacity\");\n outgoing.push_notification(Notification::Unschedule);\n outgoing.handle.try_send(()).ok();\n return ConsumeStatus::BufferFull;\n }\n\n outgoing.handle.try_send(()).ok();\n\n // update the state of shared subscription\n if let Some(share) = shared_group {\n share.update_next_client();\n // update the shared cursor\n share.cursor = request.cursor;\n }\n\n if caughtup {\n ConsumeStatus::FilterCaughtup\n } else {\n ConsumeStatus::PartialRead\n }\n}\n```"}], "func_name": "forward_device_data", "docstring": "Sweep datalog from offset in DataRequest and updates DataRequest\nfor next sweep. Returns (busy, caughtup) status\nReturned arguments:\n1. `busy`: whether the data request was completed or not.\n2. `done`: whether the connection was busy or not.\n3. `inflight_full`: whether the inflight requests were completely filled", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/router/routing.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/router/routing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "617c94f1e9cec31aa42a3f506691477bbf136d0765a942c7e748322bd1b1bdb7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: poll\n\nDocumentation:\nNext connection which is ready to make progress\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn poll(&mut self) -> Option<(ConnectionId, VecDeque)> {\n let id = self.readyqueue.pop_front()?;\n let tracker = self.trackers.get_mut(id)?;\n\n // drain will clear all DataRequest but will keep the allocated memory of our VecDeque.\n let data_requests = tracker.data_requests.drain(..).collect();\n\n // Implicitly reschedule the connection. Router will take care of explicitly pausing if\n // required (it has the state necessary to determine if pausing is required)\n self.readyqueue.push_back(id);\n Some((id, data_requests))\n }\n```"}], "func_name": "poll", "docstring": "Next connection which is ready to make progress", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/router/scheduler.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/router/scheduler.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f8e5c7e9ff333b5dec615b04783d66915a0661511bb229581e6d44801c4f981c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_ready\n\nDocumentation:\nSets the state to ready if correct event to bring out of paused state\nis received.\n\nDoesn't change the state to ready if counter event is not received or\nif already in ready state\n\nReturns Some(previous state) if status is changed to ready.\nNone return implies either the connection is already ready of the\nstate cannot be changed to ready\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_ready(&mut self, reason: ScheduleReason) -> Option {\n let previous = match self.status {\n Status::Ready => return None,\n Status::Paused(p) => p,\n };\n\n match reason {\n ScheduleReason::Init => {\n debug_assert!(self.status == Status::Paused(PauseReason::Busy));\n self.status = Status::Ready;\n Some(previous)\n }\n ScheduleReason::NewFilter if previous == PauseReason::Caughtup => {\n self.status = Status::Ready;\n Some(previous)\n }\n ScheduleReason::FreshData if previous == PauseReason::Caughtup => {\n self.status = Status::Ready;\n Some(previous)\n }\n // There might be a case where we got IncomingAck but our inflight wasn't full\n // In case of QoS2, we need to send back PubRel ASAP,\n // So we set status to Ready in case of IncomingAck unless reason in Busy\n ScheduleReason::IncomingAck if previous != PauseReason::Busy => {\n self.status = Status::Ready;\n Some(previous)\n }\n ScheduleReason::Ready => {\n debug_assert!(self.status == Status::Paused(PauseReason::Busy));\n self.status = Status::Ready;\n Some(previous)\n }\n _ => None,\n }\n }\n```"}], "func_name": "try_ready", "docstring": "Sets the state to ready if correct event to bring out of paused state\nis received.\n\nDoesn't change the state to ready if counter event is not received or\nif already in ready state\n\nReturns Some(previous state) if status is changed to ready.\nNone return implies either the connection is already ready of the\nstate cannot be changed to ready", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/router/scheduler.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/router/scheduler.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "86e25c66c0fc0c84520e8af8817d5e3edc20bf17cb77227c32842ce6ab4daea1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: register\n\nDocumentation:\nPushes a request to current wait queue\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn register(&mut self, id: ConnectionId, request: T) {\n let request = (id, request);\n self.current.push_back(request);\n }\n```"}], "func_name": "register", "docstring": "Pushes a request to current wait queue", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/router/waiters.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/router/waiters.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a30a7e875db85505a2c2db2e451fee4bd34fed1be2996e5d3f097327ee0c64b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: take\n\nDocumentation:\nSwaps next wait queue with current wait queue\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn take(&mut self) -> Option> {\n if self.current.is_empty() {\n return None;\n }\n\n let next = VecDeque::new();\n Some(std::mem::replace(&mut self.current, next))\n }\n```"}], "func_name": "take", "docstring": "Swaps next wait queue with current wait queue", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/router/waiters.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/router/waiters.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7df2a3f7f7aedbc252b72383645440ec42466d7eba8a923824d78f1c91d19fef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: readv\n\nDocumentation:\nRead `len` Ts at once. More efficient than reading 1 at a time. Returns\nthe next offset to read data from. The Position::start returned need not\nbe a valid index if the start given is not valid either.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn readv(\n &self,\n mut start: (u64, u64),\n mut len: u64,\n out: &mut Vec<(T, Offset)>,\n ) -> io::Result {\n let mut cursor = start;\n let _orig_cursor = cursor;\n\n if cursor.0 > self.tail {\n return Ok(Position::Done { start, end: start });\n }\n\n if cursor.0 < self.head {\n let head_absolute_offset = self.segments.front().unwrap().absolute_offset;\n warn!(\n \"given index {} less than head {}, jumping to head\",\n cursor.0, head_absolute_offset\n );\n cursor = (self.head, head_absolute_offset);\n start = cursor;\n }\n\n let mut idx = (cursor.0 - self.head) as usize;\n let mut curr_segment = &self.segments[idx];\n\n if curr_segment.absolute_offset > cursor.1 {\n warn!(\n \"offset specified {} if less than actual {}, jumping\",\n cursor.1, curr_segment.absolute_offset\n );\n start.1 = curr_segment.absolute_offset;\n cursor.1 = curr_segment.absolute_offset;\n }\n\n while cursor.0 < self.tail {\n // `Segment::readv` handles the conversion from absolute index to relative\n // index and it returns the absolute offset.\n // absolute cursor not to be confused with absolute offset\n match curr_segment.readv(cursor, len, out)? {\n // an offset returned -> we didn't read till end -> len fulfilled -> return\n SegmentPosition::Next(offset) => {\n return Ok(Position::Next {\n start,\n end: (cursor.0, offset),\n });\n }\n // no offset returned -> we reached end\n // if len unfulfilled -> try next segment with remaining length\n SegmentPosition::Done(next_offset) => {\n // This condition is needed in case cursor.1 > 0 (when the user provies cursor.1\n // beyond segment's last offset which can happen due to next readv offset\n // being off by 1 before jumping to next segment or while manually reading\n // from a particular cursor). In such case, the no. of read data points is\n // 0 and hence we don't decrement len.\n if next_offset >= cursor.1 {\n len -= next_offset - cursor.1;\n }\n cursor = (cursor.0 + 1, next_offset);\n }\n }\n\n if len == 0 {\n // debug!(\"start: {:?}, end: ({}, {})\", orig_cursor, cursor.0, cursor.1 - 1);\n return Ok(Position::Next { start, end: cursor });\n }\n\n idx += 1;\n curr_segment = &self.segments[idx];\n }\n\n if curr_segment.next_offset() <= cursor.1 {\n return Ok(Position::Done { start, end: cursor });\n }\n\n // We need to read seperately from active segment because if `None` is returned for active\n // segment's `readv`, then we should return `None` as well as it is not possible to read\n // further, whereas for older segments we simply jump on to the new one to read more.\n\n match curr_segment.readv(cursor, len, out)? {\n SegmentPosition::Next(v) => {\n // debug!(\"start: {:?}, end: ({}, {})\", orig_cursor, cursor.0, cursor.1 + v - 1);\n Ok(Position::Next {\n start,\n end: (cursor.0, v),\n })\n }\n SegmentPosition::Done(absolute_offset) => {\n // debug!(\"start: {:?}, end: ({}, {}) done\", orig_cursor, cursor.0, absolute_offset);\n Ok(Position::Done {\n start,\n end: (cursor.0, absolute_offset),\n })\n }\n }\n }\n```"}], "func_name": "readv", "docstring": "Read `len` Ts at once. More efficient than reading 1 at a time. Returns\nthe next offset to read data from. The Position::start returned need not\nbe a valid index if the start given is not valid either.", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/segments/mod.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/segments/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e5644db6d6b7e726bf6d66b5f4795f2267930294002f06855396eb1c1a67f7a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: readv\n\nDocumentation:\nTakes in the abosolute index to start reading from. Internally handles the conversion from\nrelative offset to absolute offset and vice-versa.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn readv(\n &self,\n cursor: Cursor,\n len: u64,\n out: &mut Vec<(T, Offset)>,\n ) -> io::Result {\n // This substraction can never overflow as checking of offset happens at\n // `CommitLog::readv`.\n let idx = cursor.1 - self.absolute_offset;\n\n let mut ret: Option;\n\n if idx >= self.len() {\n ret = None;\n } else {\n let mut limit = idx + len;\n\n ret = Some(limit);\n\n if limit >= self.len() {\n ret = None;\n limit = self.len();\n }\n let offsets = std::iter::repeat(cursor.0).zip(cursor.1..cursor.1 + limit);\n let o = self.data[idx as usize..limit as usize]\n .iter()\n .cloned()\n .zip(offsets);\n out.extend(o);\n }\n\n match ret {\n Some(relative_offset) => Ok(SegmentPosition::Next(\n self.absolute_offset + relative_offset,\n )),\n None => Ok(SegmentPosition::Done(self.next_offset())),\n }\n }\n```"}], "func_name": "readv", "docstring": "Takes in the abosolute index to start reading from. Internally handles the conversion from\nrelative offset to absolute offset and vice-versa.", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/segments/segment.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/segments/segment.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bffc6be7d37cea60a3984ac90ec464706ff494e21947dd3d2dc826db32dc14d6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_tenant_id\n\nDocumentation:\nExtract uid from certificate's subject organization field\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extract_tenant_id(der: &[u8]) -> Result, Error> {\n let (_, cert) =\n x509_parser::parse_x509_certificate(der).map_err(|_| Error::CertificateParse)?;\n let tenant_id = match cert.subject().iter_organization().next() {\n Some(org) => match org.as_str() {\n Ok(val) => val.to_string(),\n Err(_) => return Err(Error::InvalidTenant),\n },\n None => {\n #[cfg(feature = \"validate-tenant-prefix\")]\n return Err(Error::MissingTenantId);\n #[cfg(not(feature = \"validate-tenant-prefix\"))]\n return Ok(None);\n }\n };\n\n if tenant_id.chars().any(|c| !c.is_alphanumeric()) {\n return Err(Error::InvalidTenantId(tenant_id));\n }\n\n Ok(Some(tenant_id))\n}\n```"}], "func_name": "extract_tenant_id", "docstring": "Extract uid from certificate's subject organization field", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/server/tls.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/server/tls.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "43248e16026bbca77a1f870d0be405e661f0f9aa3c75e8fad758c2b154271e65"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: first_private_key_in_pemfile\n\nDocumentation:\nGet the first private key in a PEM file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn first_private_key_in_pemfile(key_path: &String) -> Result, Error> {\n // Get private key\n let key_file = File::open(key_path);\n let key_file = key_file.map_err(|_| Error::ServerKeyNotFound(key_path.clone()))?;\n\n let rd = &mut BufReader::new(key_file);\n\n // keep reading Items one by one to find a Key, return error if none found.\n loop {\n let item = rustls_pemfile::read_one(rd).map_err(|err| {\n error!(\"Error reading key file: {:?}\", err);\n Error::InvalidServerKey(key_path.clone())\n })?;\n\n match item {\n Some(Item::Sec1Key(key)) => {\n return Ok(key.into());\n }\n Some(Item::Pkcs1Key(key)) => {\n return Ok(key.into());\n }\n Some(Item::Pkcs8Key(key)) => {\n return Ok(key.into());\n }\n None => {\n error!(\"No private key found in {:?}\", key_path);\n return Err(Error::InvalidServerKey(key_path.clone()));\n }\n _ => {}\n }\n }\n}\n```"}], "func_name": "first_private_key_in_pemfile", "docstring": "Get the first private key in a PEM file", "repo": "bytebeamio/rumqtt", "path": "rumqttd/src/server/tls.rs", "url": "https://github.com/bytebeamio/rumqtt/blob/master/rumqttd/src/server/tls.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a0be7529486b146caed971e3f37ba9fae8f4cc6fd5749159300d4f8870d229d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: optimize_cache\n\nDocumentation:\nUpdates the cache according to the IP address successfully connected.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn optimize_cache(&self, address: String, connected_ip: IpAddr) {\n match connected_ip {\n IpAddr::V4(..) => self.optimize_cache_ipv4(address, connected_ip).await,\n IpAddr::V6(..) => self.optimize_cache_ipv6(address, connected_ip).await,\n }\n }\n```"}], "func_name": "optimize_cache", "docstring": "Updates the cache according to the IP address successfully connected.", "repo": "eycorsican/leaf", "path": "leaf/src/app/dns_client.rs", "url": "https://github.com/eycorsican/leaf/blob/master/leaf/src/app/dns_client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0f6e9b1471b40f1484071b3fe36f6e3519880fb1561fddc24a712d2bb554d77"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decrypt\n\nDocumentation:\nDecrypts a message. On success, returns the plaintext.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn decrypt(&self, mut buf: BytesMut) -> io::Result {\n let salt_size = self.cipher.key_len();\n let tag_len = self.cipher.tag_len();\n let buf_len = buf.len();\n\n if buf.len() < salt_size {\n return Err(short_packet());\n }\n\n let salt = buf.split_to(salt_size);\n\n let key = hkdf_sha1(\n &self.psk,\n &salt,\n String::from(\"ss-subkey\").as_bytes().to_vec(),\n self.cipher.key_len(),\n )\n .map_err(|_| crypto_err())?;\n let nonce = ShadowsocksNonceSequence::new(self.cipher.nonce_len());\n let mut dec = self\n .cipher\n .decryptor(&key, nonce)\n .map_err(|_| crypto_err())?;\n\n if buf.len() < tag_len {\n debug!(\"buffer size {}\", buf.len());\n return Err(short_packet());\n }\n\n dec.decrypt(&mut buf).map_err(|_| crypto_err())?;\n\n let _ = buf.split_off(buf_len - salt_size - tag_len);\n\n Ok(buf.freeze())\n }\n```"}], "func_name": "decrypt", "docstring": "Decrypts a message. On success, returns the plaintext.", "repo": "eycorsican/leaf", "path": "leaf/src/proxy/shadowsocks/shadow.rs", "url": "https://github.com/eycorsican/leaf/blob/master/leaf/src/proxy/shadowsocks/shadow.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a54d2d01d88482bc6cd7d026f94871f420f291485ae6051af3847050f8a70e57"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encrypt\n\nDocumentation:\nEncrypts a message. On success, returns the ciphertext.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn encrypt(&self, mut buf: BytesMut) -> io::Result {\n if buf.is_empty() {\n return Ok(Bytes::new());\n }\n\n let salt_size = self.cipher.key_len();\n\n let mut buffer = BytesMut::new(); // TODO optimize\n buffer.resize(salt_size, 0);\n\n // generate random salt\n let mut rng = StdRng::from_entropy();\n for i in 0..salt_size {\n buffer[i] = rng.gen();\n }\n\n let key = hkdf_sha1(\n &self.psk,\n &buffer[..salt_size],\n String::from(\"ss-subkey\").as_bytes().to_vec(),\n self.cipher.key_len(),\n )\n .map_err(|_| crypto_err())?;\n let nonce = ShadowsocksNonceSequence::new(self.cipher.nonce_len());\n let mut enc = self\n .cipher\n .encryptor(&key, nonce)\n .map_err(|_| crypto_err())?;\n\n enc.encrypt(&mut buf).map_err(|_| crypto_err())?;\n\n buffer.extend_from_slice(&buf[..]);\n\n Ok(buffer.freeze())\n }\n```"}], "func_name": "encrypt", "docstring": "Encrypts a message. On success, returns the ciphertext.", "repo": "eycorsican/leaf", "path": "leaf/src/proxy/shadowsocks/shadow.rs", "url": "https://github.com/eycorsican/leaf/blob/master/leaf/src/proxy/shadowsocks/shadow.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c16c612accf71ce6d0c48fb4ff2bcb7fec09a305f8b267bd38719e5e7dacefdb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_spirv\n\nDocumentation:\nSafely read SPIR-V\n\nConverts to native endianness and returns correctly aligned storage without unnecessary\ncopying. Returns an `InvalidData` error if the input is trivially not SPIR-V.\n\nThis function can also be used to convert an already in-memory `&[u8]` to a valid `Vec`,\nbut prefer working with `&[u32]` from the start whenever possible.\n\n# Examples\n```no_run\nlet mut file = std::fs::File::open(\"/path/to/shader.spv\").unwrap();\nlet words = gfx_auxil::read_spirv(&mut file).unwrap();\n```\n```\nconst SPIRV: &[u8] = &[\n0x03, 0x02, 0x23, 0x07, // ...\n];\nlet words = gfx_auxil::read_spirv(std::io::Cursor::new(&SPIRV[..])).unwrap();\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_spirv(mut x: R) -> io::Result> {\n let size = x.seek(io::SeekFrom::End(0))?;\n if size % 4 != 0 {\n return Err(io::Error::new(\n io::ErrorKind::InvalidData,\n \"input length not divisible by 4\",\n ));\n }\n if size > usize::MAX as u64 {\n return Err(io::Error::new(io::ErrorKind::InvalidData, \"input too long\"));\n }\n let words = (size / 4) as usize;\n let mut result = Vec::::with_capacity(words);\n x.seek(io::SeekFrom::Start(0))?;\n unsafe {\n // Writing all bytes through a pointer with less strict alignment when our type has no\n // invalid bitpatterns is safe.\n x.read_exact(slice::from_raw_parts_mut(\n result.as_mut_ptr() as *mut u8,\n words * 4,\n ))?;\n result.set_len(words);\n }\n const MAGIC_NUMBER: u32 = 0x07230203;\n if result.len() > 0 && result[0] == MAGIC_NUMBER.swap_bytes() {\n for word in &mut result {\n *word = word.swap_bytes();\n }\n }\n if result.len() == 0 || result[0] != MAGIC_NUMBER {\n return Err(io::Error::new(\n io::ErrorKind::InvalidData,\n \"input missing SPIR-V magic number\",\n ));\n }\n Ok(result)\n}\n```"}], "func_name": "read_spirv", "docstring": "Safely read SPIR-V\n\nConverts to native endianness and returns correctly aligned storage without unnecessary\ncopying. Returns an `InvalidData` error if the input is trivially not SPIR-V.\n\nThis function can also be used to convert an already in-memory `&[u8]` to a valid `Vec`,\nbut prefer working with `&[u32]` from the start whenever possible.\n\n# Examples\n```no_run\nlet mut file = std::fs::File::open(\"/path/to/shader.spv\").unwrap();\nlet words = gfx_auxil::read_spirv(&mut file).unwrap();\n```\n```\nconst SPIRV: &[u8] = &[\n0x03, 0x02, 0x23, 0x07, // ...\n];\nlet words = gfx_auxil::read_spirv(std::io::Cursor::new(&SPIRV[..])).unwrap();\n```", "repo": "gfx-rs/gfx", "path": "src/auxil/auxil/src/lib.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/auxil/auxil/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a29658c13cfa528d5995e46f06a2fec87ac2bb7c558d2725213dd2839e1527b8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: external_memory_type\n\nDocumentation:\nGet the [ExternalMemoryType][ExternalMemoryType] from this enum.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn external_memory_type(&self) -> ExternalMemoryType {\n match self {\n #[cfg(unix)]\n Self::OpaqueFd(_) => ExternalMemoryType::OpaqueFd,\n #[cfg(windows)]\n Self::OpaqueWin32(_) => ExternalMemoryType::OpaqueWin32,\n #[cfg(windows)]\n Self::OpaqueWin32Kmt(_) => ExternalMemoryType::OpaqueWin32Kmt,\n #[cfg(windows)]\n Self::D3D11Texture(_) => ExternalMemoryType::D3D11Texture,\n #[cfg(windows)]\n Self::D3D11TextureKmt(_) => ExternalMemoryType::D3D11TextureKmt,\n #[cfg(windows)]\n Self::D3D12Heap(_) => ExternalMemoryType::D3D12Heap,\n #[cfg(windows)]\n Self::D3D12Resource(_) => ExternalMemoryType::D3D12Resource,\n #[cfg(any(target_os = \"linux\", target_os = \"android\"))]\n Self::DmaBuf(_) => ExternalMemoryType::DmaBuf,\n #[cfg(target_os = \"android\")]\n Self::AndroidHardwareBuffer(_) => ExternalMemoryType::AndroidHardwareBuffer,\n Self::HostAllocation(_) => ExternalMemoryType::HostAllocation,\n Self::HostMappedForeignMemory(_) => ExternalMemoryType::HostMappedForeignMemory,\n }\n }\n```"}], "func_name": "external_memory_type", "docstring": "Get the [ExternalMemoryType][ExternalMemoryType] from this enum.", "repo": "gfx-rs/gfx", "path": "src/auxil/external-memory/src/lib.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/auxil/external-memory/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "698c9b861a0039a5a0f22b4baed22f9cabcbfc830d5f1c5588fdc074c704e828"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: platform_memory_type\n\nDocumentation:\nGet the [PlatformMemoryType][PlatformMemoryType] from this enum.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn platform_memory_type(&self) -> PlatformMemoryType {\n match self {\n #[cfg(unix)]\n Self::OpaqueFd(_) => PlatformMemoryType::Fd,\n #[cfg(windows)]\n Self::OpaqueWin32(_) => PlatformMemoryType::Handle,\n #[cfg(windows)]\n Self::OpaqueWin32Kmt(_) => PlatformMemoryType::Handle,\n #[cfg(windows)]\n Self::D3D11Texture(_) => PlatformMemoryType::Handle,\n #[cfg(windows)]\n Self::D3D11TextureKmt(_) => PlatformMemoryType::Handle,\n #[cfg(windows)]\n Self::D3D12Heap(_) => PlatformMemoryType::Handle,\n #[cfg(windows)]\n Self::D3D12Resource(_) => PlatformMemoryType::Handle,\n #[cfg(any(target_os = \"linux\", target_os = \"android\"))]\n Self::DmaBuf(_) => PlatformMemoryType::Fd,\n #[cfg(target_os = \"android\")]\n Self::AndroidHardwareBuffer(_) => PlatformMemoryType::Fd,\n Self::HostAllocation(_) => PlatformMemoryType::Ptr,\n Self::HostMappedForeignMemory(_) => PlatformMemoryType::Ptr,\n }\n }\n```"}], "func_name": "platform_memory_type", "docstring": "Get the [PlatformMemoryType][PlatformMemoryType] from this enum.", "repo": "gfx-rs/gfx", "path": "src/auxil/external-memory/src/lib.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/auxil/external-memory/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "808c05aa97681be438ad78373bf7fd0f1766a1e75dfe6f8c99621cd6ff2b6a45"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fd\n\nDocumentation:\nGet the associated unix file descriptor as ([Fd][Fd]).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fd(&self) -> Option<&Fd> {\n match self {\n Self::OpaqueFd(fd) => Some(fd),\n #[cfg(any(target_os = \"linux\", target_os = \"android\"))]\n Self::DmaBuf(fd) => Some(fd),\n #[cfg(target_os = \"android\")]\n Self::AndroidHardwareBuffer(fd) => Some(fd),\n _ => None,\n }\n }\n```"}], "func_name": "fd", "docstring": "Get the associated unix file descriptor as ([Fd][Fd]).", "repo": "gfx-rs/gfx", "path": "src/auxil/external-memory/src/lib.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/auxil/external-memory/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2851212172b6fde655a2754dc8d66a1035d8e3418aced4ffc725da80d4bf4ccf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle\n\nDocumentation:\nGet the associated windows handle as ([Handle][Handle]).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn handle(&self) -> Option<&Handle> {\n match self {\n Self::OpaqueWin32(handle) => Some(handle),\n Self::OpaqueWin32Kmt(handle) => Some(handle),\n Self::D3D11Texture(handle) => Some(handle),\n Self::D3D11TextureKmt(handle) => Some(handle),\n Self::D3D12Heap(handle) => Some(handle),\n Self::D3D12Resource(handle) => Some(handle),\n _ => None,\n }\n }\n```"}], "func_name": "handle", "docstring": "Get the associated windows handle as ([Handle][Handle]).", "repo": "gfx-rs/gfx", "path": "src/auxil/external-memory/src/lib.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/auxil/external-memory/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3d5a50f2837605d10e4902094c4e4470ed51952ad634f95873431cdf01a79d66"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ptr\n\nDocumentation:\nGet the associated host pointer as ([Ptr][Ptr]).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ptr(&self) -> Option<&Ptr> {\n match self {\n Self::HostAllocation(ptr) => Some(ptr),\n Self::HostMappedForeignMemory(ptr) => Some(ptr),\n // Without this on non unix or windows platform, this will trigger error for unreachable pattern\n #[allow(unreachable_patterns)]\n _ => None,\n }\n }\n```"}], "func_name": "ptr", "docstring": "Get the associated host pointer as ([Ptr][Ptr]).", "repo": "gfx-rs/gfx", "path": "src/auxil/external-memory/src/lib.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/auxil/external-memory/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4efa27df357701bc9d05059fbcf7a92e0568d68309e6740d58ba0007e5afeac2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: allocated_ranges\n\nDocumentation:\nReturns an iterator over allocated non-empty ranges\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn allocated_ranges<'a>(&'a self) -> impl 'a + Iterator> {\n let first = match self.free_ranges.first() {\n Some(Range { ref start, .. }) if *start > self.initial_range.start => {\n Some(self.initial_range.start..*start)\n }\n None => Some(self.initial_range.clone()),\n _ => None,\n };\n\n let last = match self.free_ranges.last() {\n Some(Range { end, .. }) if *end < self.initial_range.end => {\n Some(*end..self.initial_range.end)\n }\n _ => None,\n };\n\n let mid = self\n .free_ranges\n .iter()\n .zip(self.free_ranges.iter().skip(1))\n .map(|(ra, rb)| ra.end..rb.start);\n\n first.into_iter().chain(mid).chain(last)\n }\n```"}], "func_name": "allocated_ranges", "docstring": "Returns an iterator over allocated non-empty ranges", "repo": "gfx-rs/gfx", "path": "src/auxil/range-alloc/src/lib.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/auxil/range-alloc/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fbe9663dbb8ff3516804c7e49bdcf1435f40d05795ba07b8fc1659bc7a9c2e5e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_debug_name\n\nDocumentation:\nSet the debug name of a resource.\n\nMust be ASCII.\n\nSetPrivateData will copy the data internally so the data doesn't need to live.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_debug_name(resource: &d3d11::ID3D11DeviceChild, name: &str) {\n unsafe {\n resource.SetPrivateData(\n (&d3dcommon::WKPDID_D3DDebugObjectName) as *const _,\n name.len() as _,\n name.as_ptr() as *const _,\n );\n }\n}\n```"}], "func_name": "set_debug_name", "docstring": "Set the debug name of a resource.\n\nMust be ASCII.\n\nSetPrivateData will copy the data internally so the data doesn't need to live.", "repo": "gfx-rs/gfx", "path": "src/backend/dx11/src/debug.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/dx11/src/debug.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7d273b530b6eba3ccc2b37a0d1471a197624b2e197fe06f1187595f21c70d974"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_debug_name_with_suffix\n\nDocumentation:\nSet the debug name of a resource with a given suffix.\n\nMust be ASCII.\n\nThe given string will be mutated to add the suffix, then restored to it's original state.\nThis saves an allocation. SetPrivateData will copy the data internally so the data doesn't need to live.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_debug_name_with_suffix(\n resource: &d3d11::ID3D11DeviceChild,\n name: &mut String,\n suffix: &str,\n) {\n name.push_str(suffix);\n unsafe {\n resource.SetPrivateData(\n (&d3dcommon::WKPDID_D3DDebugObjectName) as *const _,\n name.len() as _,\n name.as_ptr() as *const _,\n );\n }\n name.drain((name.len() - suffix.len())..);\n}\n```"}], "func_name": "set_debug_name_with_suffix", "docstring": "Set the debug name of a resource with a given suffix.\n\nMust be ASCII.\n\nThe given string will be mutated to add the suffix, then restored to it's original state.\nThis saves an allocation. SetPrivateData will copy the data internally so the data doesn't need to live.", "repo": "gfx-rs/gfx", "path": "src/backend/dx11/src/debug.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/dx11/src/debug.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c10fb0cc033d3855b27402e6b52b7b897fa0c78bfce99d76d5aa34edb4cd41e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: introspect_spirv_vertex_semantic_remapping\n\nDocumentation:\nIntrospects the input attributes of given SPIR-V shader and returns an optional vertex semantic remapping.\n\nThe returned hashmap has attribute location as a key and an Optional remapping to a two part semantic.\n\neg.\n`2 -> None` means use default semantic `TEXCOORD2`\n`2 -> Some((0, 2))` means use two part semantic `TEXCOORD0_2`. This is how matrices are represented by spirv-cross.\n\nThis is a temporary workaround for https://github.com/KhronosGroup/SPIRV-Cross/issues/1512.\n\nThis workaround also exists under the same name in the DX12 backend.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn introspect_spirv_vertex_semantic_remapping(\n raw_data: &[u32],\n) -> Result>, pso::CreationError> {\n const SHADER_STAGE: ShaderStage = ShaderStage::Vertex;\n // This is inefficient as we already parse it once before. This is a temporary workaround only called\n // on vertex shaders. If this becomes permanent or shows up in profiles, deduplicate these as first course of action.\n let ast = parse_spirv(SHADER_STAGE, raw_data)?;\n\n let mut map = auxil::FastHashMap::default();\n\n let inputs = ast\n .get_shader_resources()\n .map_err(|err| gen_query_error(SHADER_STAGE, err))?\n .stage_inputs;\n for input in inputs {\n let idx = ast\n .get_decoration(input.id, spirv::Decoration::Location)\n .map_err(|err| gen_query_error(SHADER_STAGE, err))?;\n\n let ty = ast\n .get_type(input.type_id)\n .map_err(|err| gen_query_error(SHADER_STAGE, err))?;\n\n match ty {\n spirv::Type::Boolean { columns, .. }\n | spirv::Type::Int { columns, .. }\n | spirv::Type::UInt { columns, .. }\n | spirv::Type::Half { columns, .. }\n | spirv::Type::Float { columns, .. }\n | spirv::Type::Double { columns, .. }\n if columns > 1 =>\n {\n for col in 0..columns {\n if let Some(_) = map.insert(idx + col, Some((idx, col))) {\n let error = format!(\n \"Shader has overlapping input attachments at location {}\",\n idx\n );\n return Err(pso::CreationError::ShaderCreationError(\n SHADER_STAGE.to_flag(),\n error,\n ));\n }\n }\n }\n _ => {\n if let Some(_) = map.insert(idx, None) {\n let error = format!(\n \"Shader has overlapping input attachments at location {}\",\n idx\n );\n return Err(pso::CreationError::ShaderCreationError(\n SHADER_STAGE.to_flag(),\n error,\n ));\n }\n }\n }\n }\n\n Ok(map)\n}\n```"}], "func_name": "introspect_spirv_vertex_semantic_remapping", "docstring": "Introspects the input attributes of given SPIR-V shader and returns an optional vertex semantic remapping.\n\nThe returned hashmap has attribute location as a key and an Optional remapping to a two part semantic.\n\neg.\n`2 -> None` means use default semantic `TEXCOORD2`\n`2 -> Some((0, 2))` means use two part semantic `TEXCOORD0_2`. This is how matrices are represented by spirv-cross.\n\nThis is a temporary workaround for https://github.com/KhronosGroup/SPIRV-Cross/issues/1512.\n\nThis workaround also exists under the same name in the DX12 backend.", "repo": "gfx-rs/gfx", "path": "src/backend/dx11/src/shader.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/dx11/src/shader.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "039df47884540ae50d232494301bb124f354a871bb7f071ab404b3b7e1494c5f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_constants\n\nDocumentation:\nWrite root constant values into the user data, overwriting virtual memory\nrange [offset..offset + data.len()]. Changes are marked as dirty.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_constants(&mut self, offset: usize, data: &[u32]) {\n assert!(offset + data.len() <= ROOT_SIGNATURE_SIZE);\n // Each root constant occupies one DWORD\n for (i, val) in data.iter().enumerate() {\n self.data[offset + i] = RootElement::Constant(*val);\n self.dirty_mask |= 1u64 << (offset + i);\n }\n }\n```"}], "func_name": "set_constants", "docstring": "Write root constant values into the user data, overwriting virtual memory\nrange [offset..offset + data.len()]. Changes are marked as dirty.", "repo": "gfx-rs/gfx", "path": "src/backend/dx12/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/dx12/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "05408c535858b18308d1be4b7d87d2037491d5470056a1fcf82a5b06a7237257"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_srv_cbv_uav_table\n\nDocumentation:\nWrite a SRV/CBV/UAV descriptor table into the user data, overwriting virtual\nmemory range [offset..offset + 1]. Changes are marked as dirty.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_srv_cbv_uav_table(&mut self, offset: usize, table_start: u32) {\n assert!(offset < ROOT_SIGNATURE_SIZE);\n // A descriptor table occupies one DWORD\n self.data[offset] = RootElement::TableSrvCbvUav(table_start);\n self.dirty_mask |= 1u64 << offset;\n }\n```"}], "func_name": "set_srv_cbv_uav_table", "docstring": "Write a SRV/CBV/UAV descriptor table into the user data, overwriting virtual\nmemory range [offset..offset + 1]. Changes are marked as dirty.", "repo": "gfx-rs/gfx", "path": "src/backend/dx12/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/dx12/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bd407277b39bedd43f9d751b97930686d39946e87c87d6ceb42985bbf7c8837f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_sampler_table\n\nDocumentation:\nWrite a sampler descriptor table into the user data, overwriting virtual\nmemory range [offset..offset + 1]. Changes are marked as dirty.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_sampler_table(&mut self, offset: usize, table_start: u32) {\n assert!(offset < ROOT_SIGNATURE_SIZE);\n // A descriptor table occupies one DWORD\n self.data[offset] = RootElement::TableSampler(table_start);\n self.dirty_mask |= 1u64 << offset;\n }\n```"}], "func_name": "set_sampler_table", "docstring": "Write a sampler descriptor table into the user data, overwriting virtual\nmemory range [offset..offset + 1]. Changes are marked as dirty.", "repo": "gfx-rs/gfx", "path": "src/backend/dx12/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/dx12/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "78a03f019894e1d59fa489d5012894f0f2588f2a6656fc8af62dc498cd65ceb6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_descriptor_dynamic\n\nDocumentation:\nWrite a dynamic buffer root descriptor into the user data, overwriting virtual\nmemory range [offset..offset + 2]. Changes are marked as dirty.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_descriptor_dynamic(&mut self, offset: usize, buffer: u64, kind: DynamicBuffer) {\n assert!(offset + 1 < ROOT_SIGNATURE_SIZE);\n // A root descriptor occupies two DWORDs\n self.data[offset] = RootElement::DescriptorDynamic { buffer, kind };\n self.data[offset + 1] = RootElement::DescriptorPlaceholder;\n self.dirty_mask |= 1u64 << offset;\n self.dirty_mask |= 1u64 << offset + 1;\n }\n```"}], "func_name": "set_descriptor_dynamic", "docstring": "Write a dynamic buffer root descriptor into the user data, overwriting virtual\nmemory range [offset..offset + 2]. Changes are marked as dirty.", "repo": "gfx-rs/gfx", "path": "src/backend/dx12/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/dx12/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a1a35706d8ca51bbddd8670d78b4d1eba5f71372b3c1ebe1a45416b09449659c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clear_up_to\n\nDocumentation:\nMark all entries as clear up to the given i.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn clear_up_to(&mut self, i: u32) {\n self.dirty_mask &= !((1 << i) - 1);\n }\n```"}], "func_name": "clear_up_to", "docstring": "Mark all entries as clear up to the given i.", "repo": "gfx-rs/gfx", "path": "src/backend/dx12/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/dx12/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fba2747d24572f244d2b7002090a79d4ae70475b17bdc23a881fd7f92c5b2c36"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: derive_immutable_image_states\n\nDocumentation:\nDerive the combination of read-only states from the access flags.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn derive_immutable_image_states(access: image::Access) -> D3D12_RESOURCE_STATES {\n let mut state = D3D12_RESOURCE_STATE_COMMON;\n\n if access.contains(image::Access::TRANSFER_READ) {\n state |= D3D12_RESOURCE_STATE_COPY_SOURCE;\n }\n if access.contains(image::Access::INPUT_ATTACHMENT_READ) {\n state |= D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;\n }\n if access.contains(image::Access::DEPTH_STENCIL_ATTACHMENT_READ) {\n state |= D3D12_RESOURCE_STATE_DEPTH_READ;\n }\n if access.contains(image::Access::SHADER_READ) {\n state |= D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE\n | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;\n }\n\n state\n}\n```"}], "func_name": "derive_immutable_image_states", "docstring": "Derive the combination of read-only states from the access flags.", "repo": "gfx-rs/gfx", "path": "src/backend/dx12/src/conv.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/dx12/src/conv.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "895f95d4d4f8109cd7c8f140b089f5ad7b75cd27c6df59baedb4b39154d6063d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: derive_mutable_image_states\n\nDocumentation:\nDerive the mutable or read-only states from the access flags.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn derive_mutable_image_states(access: image::Access) -> D3D12_RESOURCE_STATES {\n if access.contains(image::Access::SHADER_WRITE) {\n return D3D12_RESOURCE_STATE_UNORDERED_ACCESS;\n }\n if access.contains(image::Access::COLOR_ATTACHMENT_WRITE) {\n return D3D12_RESOURCE_STATE_RENDER_TARGET;\n }\n if access.contains(image::Access::DEPTH_STENCIL_ATTACHMENT_WRITE) {\n return D3D12_RESOURCE_STATE_DEPTH_WRITE;\n }\n if access.contains(image::Access::TRANSFER_WRITE) {\n return D3D12_RESOURCE_STATE_COPY_DEST;\n }\n\n derive_immutable_image_states(access)\n}\n```"}], "func_name": "derive_mutable_image_states", "docstring": "Derive the mutable or read-only states from the access flags.", "repo": "gfx-rs/gfx", "path": "src/backend/dx12/src/conv.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/dx12/src/conv.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bd8d6ce6c391033337523faa1dc7a49454f99cc7dadda852ee353e581faa4736"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_shader\n\nDocumentation:\nCompile a single shader entry point from a HLSL text shader\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn compile_shader(\n stage: ShaderStage,\n shader_model: hlsl::ShaderModel,\n features: &hal::Features,\n entry: &str,\n code: &[u8],\n) -> Result {\n let stage_str = match stage {\n ShaderStage::Vertex => \"vs\",\n ShaderStage::Fragment => \"ps\",\n ShaderStage::Compute => \"cs\",\n _ => unimplemented!(),\n };\n let model_str = match shader_model {\n hlsl::ShaderModel::V5_0 => \"5_0\",\n hlsl::ShaderModel::V5_1 => \"5_1\",\n hlsl::ShaderModel::V6_0 => \"6_0\",\n _ => unimplemented!(),\n };\n let full_stage = format!(\"{}_{}\\0\", stage_str, model_str);\n\n let mut shader_data = native::Blob::null();\n let mut error = native::Blob::null();\n let entry = ffi::CString::new(entry).unwrap();\n let mut compile_flags = d3dcompiler::D3DCOMPILE_ENABLE_STRICTNESS;\n if cfg!(debug_assertions) {\n compile_flags |= d3dcompiler::D3DCOMPILE_DEBUG;\n }\n if features.contains(hal::Features::UNSIZED_DESCRIPTOR_ARRAY) {\n compile_flags |= d3dcompiler::D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES;\n }\n let hr = unsafe {\n d3dcompiler::D3DCompile(\n code.as_ptr() as *const _,\n code.len(),\n ptr::null(),\n ptr::null(),\n ptr::null_mut(),\n entry.as_ptr() as *const _,\n full_stage.as_ptr() as *const i8,\n compile_flags,\n 0,\n shader_data.mut_void() as *mut *mut _,\n error.mut_void() as *mut *mut _,\n )\n };\n if !winerror::SUCCEEDED(hr) {\n let message = unsafe {\n let pointer = error.GetBufferPointer();\n let size = error.GetBufferSize();\n let slice = slice::from_raw_parts(pointer as *const u8, size as usize);\n String::from_utf8_lossy(slice).into_owned()\n };\n unsafe {\n error.destroy();\n }\n let error = format!(\"D3DCompile error {:x}: {}\", hr, message);\n Err(pso::CreationError::ShaderCreationError(\n stage.to_flag(),\n error,\n ))\n } else {\n Ok(shader_data)\n }\n}\n```"}], "func_name": "compile_shader", "docstring": "Compile a single shader entry point from a HLSL text shader", "repo": "gfx-rs/gfx", "path": "src/backend/dx12/src/device.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/dx12/src/device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d2359d6368b7de809be9fe75a51c4fcb6cf60b65afe0708b4a1dbb4c7af60bcd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: introspect_spirv_vertex_semantic_remapping\n\nDocumentation:\nIntrospects the input attributes of given SPIR-V shader and returns an optional vertex semantic remapping.\n\nThe returned hashmap has attribute location as a key and an Optional remapping to a two part semantic.\n\neg.\n`2 -> None` means use default semantic `TEXCOORD2`\n`2 -> Some((0, 2))` means use two part semantic `TEXCOORD0_2`. This is how matrices are represented by spirv-cross.\n\nThis is a temporary workaround for https://github.com/KhronosGroup/SPIRV-Cross/issues/1512.\n\nThis workaround also exists under the same name in the DX11 backend.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn introspect_spirv_vertex_semantic_remapping(\n raw_data: &[u32],\n ) -> Result>, pso::CreationError> {\n const SHADER_STAGE: ShaderStage = ShaderStage::Vertex;\n // This is inefficient as we already parse it once before. This is a temporary workaround only called\n // on vertex shaders. If this becomes permanent or shows up in profiles, deduplicate these as first course of action.\n let ast = Self::parse_spirv(SHADER_STAGE, raw_data)?;\n\n let mut map = auxil::FastHashMap::default();\n\n let inputs = ast\n .get_shader_resources()\n .map_err(|err| gen_query_error(SHADER_STAGE, err))?\n .stage_inputs;\n for input in inputs {\n let idx = ast\n .get_decoration(input.id, spirv::Decoration::Location)\n .map_err(|err| gen_query_error(SHADER_STAGE, err))?;\n\n let ty = ast\n .get_type(input.type_id)\n .map_err(|err| gen_query_error(SHADER_STAGE, err))?;\n\n match ty {\n spirv::Type::Boolean { columns, .. }\n | spirv::Type::Int { columns, .. }\n | spirv::Type::UInt { columns, .. }\n | spirv::Type::Half { columns, .. }\n | spirv::Type::Float { columns, .. }\n | spirv::Type::Double { columns, .. }\n if columns > 1 =>\n {\n for col in 0..columns {\n if let Some(_) = map.insert(idx + col, Some((idx, col))) {\n let error = format!(\n \"Shader has overlapping input attachments at location {}\",\n idx\n );\n return Err(pso::CreationError::ShaderCreationError(\n SHADER_STAGE.to_flag(),\n error,\n ));\n }\n }\n }\n _ => {\n if let Some(_) = map.insert(idx, None) {\n let error = format!(\n \"Shader has overlapping input attachments at location {}\",\n idx\n );\n return Err(pso::CreationError::ShaderCreationError(\n SHADER_STAGE.to_flag(),\n error,\n ));\n }\n }\n }\n }\n\n Ok(map)\n }\n```"}], "func_name": "introspect_spirv_vertex_semantic_remapping", "docstring": "Introspects the input attributes of given SPIR-V shader and returns an optional vertex semantic remapping.\n\nThe returned hashmap has attribute location as a key and an Optional remapping to a two part semantic.\n\neg.\n`2 -> None` means use default semantic `TEXCOORD2`\n`2 -> Some((0, 2))` means use two part semantic `TEXCOORD0_2`. This is how matrices are represented by spirv-cross.\n\nThis is a temporary workaround for https://github.com/KhronosGroup/SPIRV-Cross/issues/1512.\n\nThis workaround also exists under the same name in the DX11 backend.", "repo": "gfx-rs/gfx", "path": "src/backend/dx12/src/device.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/dx12/src/device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "49ecdeaccdc26819e207f0c3548a1afdcd3a656434eaac6f8bab2ca9a0186ac9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: free_handles\n\nDocumentation:\nFree handles previously given out by this `DescriptorHeapSlice`.\nDo not use this with handles not given out by this `DescriptorHeapSlice`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn free_handles(&mut self, handle: DualHandle) {\n let start = (handle.gpu.ptr - self.start.gpu.ptr) / self.handle_size;\n let handle_range = start..start + handle.size;\n self.range_allocator.free_range(handle_range);\n }\n```"}], "func_name": "free_handles", "docstring": "Free handles previously given out by this `DescriptorHeapSlice`.\nDo not use this with handles not given out by this `DescriptorHeapSlice`.", "repo": "gfx-rs/gfx", "path": "src/backend/dx12/src/resource.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/dx12/src/resource.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d052c5f75978314d0839370e8e0a2d0ba36e3ccf2b7f80c81cedf5ec5a584af9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add\n\nDocumentation:\nCopy a given vector slice into the data buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add(&mut self, data: &[T]) -> BufferSlice {\n self.add_raw(unsafe {\n slice::from_raw_parts(data.as_ptr() as *const _, data.len() * mem::size_of::())\n })\n }\n```"}], "func_name": "add", "docstring": "Copy a given vector slice into the data buffer.", "repo": "gfx-rs/gfx", "path": "src/backend/gl/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/gl/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48efd2a74fd694c9cfccd3f72ea355027306a97cd5dd695c8ce71349d9e27aaa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_raw\n\nDocumentation:\nCopy a given u8 slice into the data buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_raw(&mut self, data: &[u8]) -> BufferSlice {\n let mut memory = self\n .memory\n .try_lock()\n .expect(\"Trying to record a command buffers, while memory is in-use.\");\n\n let data_buffer = &mut match *memory {\n BufferMemory::Linear(ref mut buffer) => buffer,\n BufferMemory::Individual {\n ref mut storage, ..\n } => storage.get_mut(&self.id).unwrap(),\n }\n .data;\n data_buffer.extend_from_slice(data);\n let slice = BufferSlice {\n offset: (data_buffer.len() - data.len()) as u32,\n size: data.len() as u32,\n };\n slice\n }\n```"}], "func_name": "add_raw", "docstring": "Copy a given u8 slice into the data buffer.", "repo": "gfx-rs/gfx", "path": "src/backend/gl/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/gl/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94efdea2dedfe50f18bf6461ce481a60cc2fad52fd1d60fc115b008e0d4f7701"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_embedded\n\nDocumentation:\nCreate a new OpenGL ES version number\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_embedded(major: u32, minor: u32, vendor_info: String) -> Self {\n Version {\n major,\n minor,\n is_embedded: true,\n revision: None,\n vendor_info,\n }\n }\n```"}], "func_name": "new_embedded", "docstring": "Create a new OpenGL ES version number", "repo": "gfx-rs/gfx", "path": "src/backend/gl/src/info.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/gl/src/info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dce8986b29a381f8c9348153736419b52ca5d3e170fb3a67c2833acbfaa53a53"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tuple\n\nDocumentation:\nGet a tuple of (major, minor) versions\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn tuple(&self) -> (u32, u32) {\n (self.major, self.minor)\n }\n```"}], "func_name": "tuple", "docstring": "Get a tuple of (major, minor) versions", "repo": "gfx-rs/gfx", "path": "src/backend/gl/src/info.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/gl/src/info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ec0ffee7bf262b977becf0493f45948bc735b0408b5c40b9fea879c63f880190"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse\n\nDocumentation:\nAccording to the OpenGL specification, the version information is\nexpected to follow the following syntax:\n\n~~~bnf\n ::= \n ::= \n ::= \n ::= \n ::= \".\" [\".\" ]\n ::= [\" \" ]\n~~~\n\nNote that this function is intentionally lenient in regards to parsing,\nand will try to recover at least the first two version numbers without\nresulting in an `Err`.\n# Notes\n`WebGL 2` version returned as `OpenGL ES 3.0`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse(mut src: &str) -> Result {\n let webgl_sig = \"WebGL \";\n // According to the WebGL specification\n // VERSION\tWebGL1.0\n // SHADING_LANGUAGE_VERSION\tWebGLGLSLES1.0\n let is_webgl = src.starts_with(webgl_sig);\n let is_es = if is_webgl {\n let pos = src.rfind(webgl_sig).unwrap_or(0);\n src = &src[pos + webgl_sig.len()..];\n true\n } else {\n let es_sig = \" ES \";\n match src.rfind(es_sig) {\n Some(pos) => {\n src = &src[pos + es_sig.len()..];\n true\n }\n None => false,\n }\n };\n\n let glsl_es_sig = \"GLSL ES \";\n let is_glsl = match src.find(glsl_es_sig) {\n Some(pos) => {\n src = &src[pos + glsl_es_sig.len()..];\n true\n }\n None => false,\n };\n\n let (version, vendor_info) = match src.find(' ') {\n Some(i) => (&src[..i], src[i + 1..].to_string()),\n None => (src, String::new()),\n };\n\n // TODO: make this even more lenient so that we can also accept\n // ` \".\" []`\n let mut it = version.split('.');\n let major = it.next().and_then(|s| s.parse().ok());\n let minor = it.next().and_then(|s| {\n let trimmed = if s.starts_with('0') {\n \"0\"\n } else {\n s.trim_end_matches('0')\n };\n trimmed.parse().ok()\n });\n let revision = if is_webgl {\n None\n } else {\n it.next().and_then(|s| s.parse().ok())\n };\n\n match (major, minor, revision) {\n (Some(major), Some(minor), revision) => Ok(Version {\n // Return WebGL 2.0 version as OpenGL ES 3.0\n major: if is_webgl && !is_glsl {\n major + 1\n } else {\n major\n },\n minor,\n is_embedded: is_es,\n revision,\n vendor_info,\n }),\n (_, _, _) => Err(src),\n }\n }\n```"}], "func_name": "parse", "docstring": "According to the OpenGL specification, the version information is\nexpected to follow the following syntax:\n\n~~~bnf\n ::= \n ::= \n ::= \n ::= \n ::= \".\" [\".\" ]\n ::= [\" \" ]\n~~~\n\nNote that this function is intentionally lenient in regards to parsing,\nand will try to recover at least the first two version numbers without\nresulting in an `Err`.\n# Notes\n`WebGL 2` version returned as `OpenGL ES 3.0`", "repo": "gfx-rs/gfx", "path": "src/backend/gl/src/info.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/gl/src/info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8cc01f16b8753a517deca50db6c5239cbea325b3f2dea70b313ec70bb793b048"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_es3\n\nDocumentation:\nCreates a new filter for OpenGL ES 3.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_es3() -> Self {\n Self::Whitelist {\n whitelist: {\n let mut whitelist = HashSet::<(u32, u32, u32)>::default();\n whitelist.extend(Self::ES3_TABLE);\n\n whitelist\n },\n }\n }\n```"}], "func_name": "new_es3", "docstring": "Creates a new filter for OpenGL ES 3.", "repo": "gfx-rs/gfx", "path": "src/backend/gl/src/info.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/gl/src/info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d2173d50fe7f0305666d64ccd1acc9d2da7900fde87589161a2b612b26344982"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_es1_es2\n\nDocumentation:\nCreates a new filter for OpenGL ES 2 and OpenGL ES 1.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_es1_es2() -> Self {\n Self::Whitelist {\n whitelist: {\n let mut whitelist = HashSet::<(u32, u32, u32)>::default();\n whitelist.extend(Self::ES1_ES2_TABLE);\n\n whitelist\n },\n }\n }\n```"}], "func_name": "new_es1_es2", "docstring": "Creates a new filter for OpenGL ES 2 and OpenGL ES 1.", "repo": "gfx-rs/gfx", "path": "src/backend/gl/src/info.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/gl/src/info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "79bc8709d4b22a6c748769b2d3f82d175aba24e8432089e90cfafbfc25c79b85"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check\n\nDocumentation:\nThis function checks whether a given format description is allowed by\nthis filter.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check(&self, internal_format: u32, format: u32, type_: u32) -> bool {\n match self {\n Self::Whitelist { whitelist } => whitelist.contains(&(internal_format, format, type_)),\n Self::Permissive => true,\n }\n }\n```"}], "func_name": "check", "docstring": "This function checks whether a given format description is allowed by\nthis filter.", "repo": "gfx-rs/gfx", "path": "src/backend/gl/src/info.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/gl/src/info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ce8140f4fb67fe2da8845f666925f04aa728e7070bdca469f392915475a9a27c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: query_all\n\nDocumentation:\nLoad the information pertaining to the driver and the corresponding device\ncapabilities.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn query_all(\n gl: &GlContainer,\n) -> (\n Info,\n Features,\n LegacyFeatures,\n PhysicalDeviceProperties,\n PrivateCaps,\n TextureFormatFilter,\n) {\n use self::Requirement::*;\n let info = Info::get(gl);\n let max_texture_size = get_usize(gl, glow::MAX_TEXTURE_SIZE).unwrap_or(64) as u32;\n let max_samples = get_usize(gl, glow::MAX_SAMPLES).unwrap_or(8);\n let max_samples_mask = (max_samples * 2 - 1) as u8;\n let max_texel_elements = if crate::is_webgl() {\n 0\n } else {\n get_usize(gl, glow::MAX_TEXTURE_BUFFER_SIZE).unwrap_or(0)\n };\n let min_storage_buffer_offset_alignment = if crate::is_webgl() {\n 256\n } else {\n get_u64(gl, glow::SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT).unwrap_or(256)\n };\n\n let mut limits = Limits {\n max_image_1d_size: max_texture_size,\n max_image_2d_size: max_texture_size,\n max_image_3d_size: max_texture_size,\n max_image_cube_size: max_texture_size,\n max_image_array_layers: get_usize(gl, glow::MAX_ARRAY_TEXTURE_LAYERS).unwrap_or(1) as u16,\n max_texel_elements,\n max_viewports: 1,\n optimal_buffer_copy_offset_alignment: 1,\n optimal_buffer_copy_pitch_alignment: 1,\n min_texel_buffer_offset_alignment: 1,\n min_uniform_buffer_offset_alignment: get_u64(gl, glow::UNIFORM_BUFFER_OFFSET_ALIGNMENT)\n .unwrap_or(1024),\n min_storage_buffer_offset_alignment,\n framebuffer_color_sample_counts: max_samples_mask,\n non_coherent_atom_size: 1,\n max_color_attachments: get_usize(gl, glow::MAX_COLOR_ATTACHMENTS)\n .unwrap_or(1)\n .min(MAX_COLOR_ATTACHMENTS),\n ..Limits::default()\n };\n\n if info.is_supported(&[Core(4, 0), Ext(\"GL_ARB_tessellation_shader\")]) {\n limits.max_patch_size = get_usize(gl, glow::MAX_PATCH_VERTICES).unwrap_or(0) as _;\n }\n if info.is_supported(&[Core(4, 1)]) {\n // TODO: extension\n limits.max_viewports = get_usize(gl, glow::MAX_VIEWPORTS).unwrap_or(0);\n }\n\n //TODO: technically compute is exposed in Es(3, 1), but GLES requires 3.2\n // for any storage buffers. We need to investigate if this requirement\n // can be lowered.\n if info.is_supported(&[Core(4, 3), Es(3, 2), Ext(\"GL_ARB_compute_shader\")]) {\n for (i, (count, size)) in limits\n .max_compute_work_group_count\n .iter_mut()\n .zip(limits.max_compute_work_group_size.iter_mut())\n .enumerate()\n {\n unsafe {\n *count =\n gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_COUNT, i as _) as u32;\n *size =\n gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_SIZE, i as _) as u32;\n }\n }\n }\n\n let mut features = Features::NDC_Y_UP | Features::MUTABLE_COMPARISON_SAMPLER;\n // TODO: Fill out downlevel features correctly.\n let mut downlevel = hal::DownlevelProperties::all_enabled();\n // TODO: Merge downlevel/legacy features?\n let mut legacy = LegacyFeatures::empty();\n\n if info.is_supported(&[\n Core(4, 6),\n Ext(\"GL_ARB_texture_filter_anisotropic\"),\n Ext(\"GL_EXT_texture_filter_anisotropic\"),\n ]) {\n features |= Features::SAMPLER_ANISOTROPY;\n }\n if info.is_supported(&[Core(4, 2), Es(3, 1)]) {\n legacy |= LegacyFeatures::EXPLICIT_LAYOUTS_IN_SHADER;\n }\n if info.is_supported(&[Core(3, 3), Es(3, 0), Ext(\"GL_ARB_instanced_arrays\")]) {\n features |= Features::INSTANCE_RATE;\n }\n if info.is_supported(&[Core(3, 3)]) {\n // TODO: extension\n features |= Features::SAMPLER_MIP_LOD_BIAS;\n }\n if info.is_supported(&[Core(2, 1)]) {\n features |= Features::SAMPLER_BORDER_COLOR;\n }\n if info.is_supported(&[Core(4, 4), Ext(\"ARB_texture_mirror_clamp_to_edge\")]) {\n features |= Features::SAMPLER_MIRROR_CLAMP_EDGE;\n }\n if info.is_supported(&[Core(4, 0), Es(3, 2), Ext(\"GL_EXT_draw_buffers2\")]) && !crate::is_webgl()\n {\n features |= Features::INDEPENDENT_BLENDING;\n }\n\n // TODO\n if false && info.is_supported(&[Core(4, 3), Es(3, 1)]) {\n // TODO: extension\n legacy |= LegacyFeatures::INDIRECT_EXECUTION;\n }\n if info.is_supported(&[Core(3, 1), Es(3, 0), Ext(\"GL_ARB_draw_instanced\")]) {\n legacy |= LegacyFeatures::DRAW_INSTANCED;\n }\n if info.is_supported(&[Core(4, 2), Ext(\"GL_ARB_base_instance\")]) {\n legacy |= LegacyFeatures::DRAW_INSTANCED_BASE;\n }\n if info.is_supported(&[Core(3, 2)]) {\n // TODO: extension\n legacy |= LegacyFeatures::DRAW_INDEXED_BASE;\n }\n if info.is_supported(&[Core(3, 1), Es(3, 0)]) {\n // TODO: extension\n legacy |= LegacyFeatures::DRAW_INDEXED_INSTANCED;\n }\n if info.is_supported(&[Core(3, 2)]) {\n // TODO: extension\n legacy |= LegacyFeatures::DRAW_INDEXED_INSTANCED_BASE_VERTEX;\n }\n if info.is_supported(&[\n Core(3, 2),\n Es(3, 2),\n Ext(\"GL_ARB_draw_elements_base_vertex\"),\n ]) {\n legacy |= LegacyFeatures::VERTEX_BASE;\n }\n if info.is_supported(&[\n Core(3, 1),\n Es(3, 0),\n Ext(\"GL_ARB_framebuffer_sRGB\"),\n Ext(\"GL_EXT_sRGB\"),\n ]) {\n legacy |= LegacyFeatures::SRGB_COLOR;\n }\n if info.is_supported(&[Core(3, 1), Es(3, 0), Ext(\"GL_ARB_uniform_buffer_object\")]) {\n legacy |= LegacyFeatures::CONSTANT_BUFFER;\n }\n if info.is_supported(&[Core(4, 0)]) {\n // TODO: extension\n legacy |= LegacyFeatures::UNORDERED_ACCESS_VIEW;\n }\n if info.is_supported(&[\n Core(3, 1),\n Es(3, 0),\n Ext(\"GL_ARB_copy_buffer\"),\n Ext(\"GL_NV_copy_buffer\"),\n ]) {\n legacy |= LegacyFeatures::COPY_BUFFER;\n }\n if info.is_supported(&[Core(3, 3), Es(3, 0), Ext(\"GL_ARB_sampler_objects\")]) {\n legacy |= LegacyFeatures::SAMPLER_OBJECTS;\n }\n if info.is_supported(&[Core(3, 3), Es(3, 0)]) {\n legacy |= LegacyFeatures::INSTANCED_ATTRIBUTE_BINDING;\n }\n\n let mut performance_caveats = PerformanceCaveats::empty();\n //TODO: extension\n if !info.is_supported(&[Core(4, 2)]) {\n performance_caveats |= PerformanceCaveats::BASE_VERTEX_INSTANCE_DRAWING;\n }\n let properties = PhysicalDeviceProperties {\n limits,\n performance_caveats,\n dynamic_pipeline_states: DynamicStates::all(),\n ..PhysicalDeviceProperties::default()\n };\n\n let buffer_storage = info.is_supported(&[\n Core(4, 4),\n Ext(\"GL_ARB_buffer_storage\"),\n Ext(\"GL_EXT_buffer_storage\"),\n ]);\n // See https://github.com/gfx-rs/gfx/issues/3453\n let emulate_map = crate::is_webgl() || !buffer_storage;\n\n let private = PrivateCaps {\n vertex_array: info.is_supported(&[Core(3, 0), Es(3, 0), Ext(\"GL_ARB_vertex_array_object\")]),\n // TODO && gl.GenVertexArrays.is_loaded(),\n framebuffer: info.is_supported(&[Core(3, 0), Es(2, 0), Ext(\"GL_ARB_framebuffer_object\")]),\n // TODO && gl.GenFramebuffers.is_loaded(),\n framebuffer_texture: info.is_supported(&[Core(3, 0)]), //TODO: double check\n // `WebGL` Note: buffers bound to non ELEMENT_ARRAY_BUFFER targets can not be bound to ELEMENT_ARRAY_BUFFER target\n index_buffer_role_change: info.is_supported(&[Core(2, 0), Es(2, 0)]) && !crate::is_webgl(),\n image_storage: info.is_supported(&[Core(4, 2), Es(3, 0), Ext(\"GL_ARB_texture_storage\")]),\n buffer_storage,\n clear_buffer: info.is_supported(&[Core(3, 0), Es(3, 0)]),\n program_interface: info.is_supported(&[Core(4, 3), Ext(\"GL_ARB_program_interface_query\")]),\n frag_data_location: !info.version.is_embedded,\n sync: info.is_supported(&[Core(3, 2), Es(3, 0), Ext(\"GL_ARB_sync\")]), // TODO\n emulate_map,\n depth_range_f64_precision: !info.version.is_embedded, // TODO\n draw_buffers: info.is_supported(&[Core(2, 0), Es(3, 0)]),\n per_slot_color_mask: info.is_supported(&[Core(3, 0)]),\n get_tex_image: !info.version.is_embedded,\n memory_barrier: info.is_supported(&[Core(4, 2), Es(3, 1)]),\n };\n\n let filter = if info.is_supported(&[Es(3, 0)]) {\n /* Use the OpenGL ES 3 format filter. */\n TextureFormatFilter::new_es3()\n } else if info.is_supported(&[Es(1, 0)]) {\n /* Use the OpenGL ES 1 and OpenGL ES 2 format filter. */\n TextureFormatFilter::new_es1_es2()\n } else {\n /* We're using the core specification. We can assume all of the\n * combinations are valid, provided the OpenGL enums values are also\n * valid for textures. */\n TextureFormatFilter::new_permissive()\n };\n\n (info, features, legacy, properties, private, filter)\n}\n```"}], "func_name": "query_all", "docstring": "Load the information pertaining to the driver and the corresponding device\ncapabilities.", "repo": "gfx-rs/gfx", "path": "src/backend/gl/src/info.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/gl/src/info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "498eb8e5057f49de1b883fcd3546fbeab8f901f4b5ba1cc9873959b2c88f7167"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check\n\nDocumentation:\nFails during a debug build if the implementation's error flag was set.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check(&self) -> Result<(), Error> {\n if cfg!(debug_assertions) {\n let gl = &self.context;\n let err = Error::from_error_code(unsafe { gl.get_error() });\n if err != Error::NoError {\n return Err(err);\n }\n }\n Ok(())\n }\n```"}], "func_name": "check", "docstring": "Fails during a debug build if the implementation's error flag was set.", "repo": "gfx-rs/gfx", "path": "src/backend/gl/src/lib.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/gl/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4478b741574d9b47e544d211111167750b85d2ceb79397be53721731282fb64e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: _attachment_using\n\nDocumentation:\nCheck if an attachment is used by this sub-pass.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn _attachment_using(&self, at_id: pass::AttachmentId) -> Option {\n if self.depth_stencil == Some(at_id) {\n Some(glow::DEPTH_STENCIL_ATTACHMENT)\n } else {\n self.color_attachments\n .iter()\n .position(|id| *id == at_id)\n .map(|p| glow::COLOR_ATTACHMENT0 + p as u32)\n }\n }\n```"}], "func_name": "_attachment_using", "docstring": "Check if an attachment is used by this sub-pass.", "repo": "gfx-rs/gfx", "path": "src/backend/gl/src/native.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/gl/src/native.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e2ee1a18e453104dbdda8e413b57e51e49442543ab5f99552d7c4d3154a093c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_gl\n\nDocumentation:\nAccess the OpenGL directly via a closure. OpenGL types and enumerations\ncan be found in the `gl` crate.\n\n> Note: Calling this function can have a noticeable impact on the performance\nbecause the internal state cache will flushed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub unsafe fn with_gl(&mut self, mut fun: F) {\n self.reset_state();\n fun(&self.share.context);\n // Flush the state to enforce a reset once a new command buffer\n // is execute because we have no control of the called functions.\n self.state.flush();\n }\n```"}], "func_name": "with_gl", "docstring": "Access the OpenGL directly via a closure. OpenGL types and enumerations\ncan be found in the `gl` crate.\n\n> Note: Calling this function can have a noticeable impact on the performance\nbecause the internal state cache will flushed.", "repo": "gfx-rs/gfx", "path": "src/backend/gl/src/queue.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/gl/src/queue.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4348dd079ce5eac837d89e3337256dad03ec2b36601f7cd7e48b04b830af3368"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturn a reference to a stored data object.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get(data: &[u8], ptr: com::BufferSlice) -> &[T] {\n let u32_size = mem::size_of::();\n assert_eq!(ptr.size % u32_size as u32, 0);\n let raw = Self::get_raw(data, ptr);\n unsafe { slice::from_raw_parts(raw.as_ptr() as *const _, raw.len() / u32_size) }\n }\n```"}], "func_name": "get", "docstring": "Return a reference to a stored data object.", "repo": "gfx-rs/gfx", "path": "src/backend/gl/src/queue.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/gl/src/queue.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3edf3a071a65c0c16970bff16fd8f49b0c88850dabb73bfc59e42892c8e5dc15"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn\n\nDocumentation:\nSpawns a command buffer from a virtual pool.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn spawn(&mut self) -> (metal::CommandBuffer, Token) {\n self.reserve.start += 1;\n let cmd_buf = autoreleasepool(|| self.spawn_temp().to_owned());\n (cmd_buf, Token { active: true })\n }\n```"}], "func_name": "spawn", "docstring": "Spawns a command buffer from a virtual pool.", "repo": "gfx-rs/gfx", "path": "src/backend/metal/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/metal/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54fe3b5d40085a4620cda63a564fce9ab3e11951e56c2132e275dd1ea1f15a12"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: release\n\nDocumentation:\nReturns a command buffer to a virtual pool.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn release(&mut self, mut token: Token) {\n token.active = false;\n self.reserve.start -= 1;\n }\n```"}], "func_name": "release", "docstring": "Returns a command buffer to a virtual pool.", "repo": "gfx-rs/gfx", "path": "src/backend/metal/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/metal/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e436b6ed4f2040b5ab87eef58e64d400044a87611f398d161a5b5a360078e5d1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pre_render\n\nDocumentation:\nStart issuing pre-render commands. Those can be rejected, so the caller is responsible\nfor updating the state cache accordingly, so that it's set upon the start of a next pass.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn pre_render(&mut self) -> PreRender {\n match *self {\n CommandSink::Immediate {\n encoder_state: EncoderState::Render(ref encoder),\n ..\n } => PreRender::Immediate(encoder),\n CommandSink::Deferred {\n is_encoding: true,\n ref mut journal,\n ..\n } => match journal.passes.last() {\n Some(&(soft::Pass::Render(_), _, _)) => {\n PreRender::Deferred(&mut journal.resources, &mut journal.render_commands)\n }\n _ => PreRender::Void,\n },\n #[cfg(feature = \"dispatch\")]\n CommandSink::Remote {\n pass: Some(EncodePass::Render(ref mut list, ref mut resources, _, _)),\n ..\n } => PreRender::Deferred(resources, list),\n _ => PreRender::Void,\n }\n }\n```"}], "func_name": "pre_render", "docstring": "Start issuing pre-render commands. Those can be rejected, so the caller is responsible\nfor updating the state cache accordingly, so that it's set upon the start of a next pass.", "repo": "gfx-rs/gfx", "path": "src/backend/metal/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/metal/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "16867c261a98ad6dc84979ccd3f0ea0c6367165601b99a829c92ab18cfe78bb9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: switch_render\n\nDocumentation:\nSwitch the active encoder to render by starting a render pass.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn switch_render(\n &mut self,\n descriptor: metal::RenderPassDescriptor,\n pool_shared: &Arc,\n ) -> PreRender {\n //assert!(AutoReleasePool::is_active());\n self.stop_encoding();\n\n match *self {\n CommandSink::Immediate {\n ref cmd_buffer,\n ref mut encoder_state,\n ref mut num_passes,\n ref label,\n ..\n } => {\n *num_passes += 1;\n let encoder = cmd_buffer.new_render_command_encoder(&descriptor);\n pool_shared.render_pass_descriptors.lock().free(descriptor);\n if !label.is_empty() {\n encoder.set_label(label);\n }\n *encoder_state = EncoderState::Render(encoder.to_owned());\n PreRender::Immediate(encoder)\n }\n CommandSink::Deferred {\n ref mut is_encoding,\n ref mut journal,\n is_inheriting,\n ref label,\n ..\n } => {\n assert!(!is_inheriting);\n *is_encoding = true;\n journal.passes.alloc().init((\n soft::Pass::Render(descriptor),\n journal.render_commands.len()..0,\n label.clone(),\n ));\n PreRender::Deferred(&mut journal.resources, &mut journal.render_commands)\n }\n #[cfg(feature = \"dispatch\")]\n CommandSink::Remote {\n ref mut pass,\n ref capacity,\n ref label,\n ..\n } => {\n let list = Vec::with_capacity(capacity.render);\n *pass = Some(EncodePass::Render(\n list,\n soft::Own::default(),\n descriptor,\n label.clone(),\n ));\n match *pass {\n Some(EncodePass::Render(ref mut list, ref mut resources, _, _)) => {\n PreRender::Deferred(resources, list)\n }\n _ => unreachable!(),\n }\n }\n }\n }\n```"}], "func_name": "switch_render", "docstring": "Switch the active encoder to render by starting a render pass.", "repo": "gfx-rs/gfx", "path": "src/backend/metal/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/metal/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9cc01b362a06573dde1e4342f34db1a05b53da69a935741fef9fdc91443562a3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: blit_commands\n\nDocumentation:\nIssue provided blit commands. This function doesn't expect an active blit pass,\nit will automatically start one when needed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn blit_commands(&mut self, commands: I)\n where\n I: Iterator,\n {\n enum PreBlit<'b> {\n Immediate(&'b metal::BlitCommandEncoderRef),\n Deferred(&'b mut Vec),\n }\n\n let pre = match *self {\n CommandSink::Immediate {\n encoder_state: EncoderState::Blit(ref encoder),\n ..\n } => PreBlit::Immediate(encoder),\n CommandSink::Immediate {\n ref cmd_buffer,\n ref mut encoder_state,\n ref mut num_passes,\n ..\n } => {\n *num_passes += 1;\n encoder_state.end();\n let encoder = cmd_buffer.new_blit_command_encoder();\n *encoder_state = EncoderState::Blit(encoder.to_owned());\n PreBlit::Immediate(encoder)\n }\n CommandSink::Deferred {\n ref mut is_encoding,\n is_inheriting,\n ref mut journal,\n ref label,\n ..\n } => {\n assert!(!is_inheriting);\n *is_encoding = true;\n if let Some(&(soft::Pass::Blit, _, _)) = journal.passes.last() {\n } else {\n journal.stop();\n journal.passes.alloc().init((\n soft::Pass::Blit,\n journal.blit_commands.len()..0,\n label.clone(),\n ));\n }\n PreBlit::Deferred(&mut journal.blit_commands)\n }\n #[cfg(feature = \"dispatch\")]\n CommandSink::Remote {\n pass: Some(EncodePass::Blit(ref mut list, _)),\n ..\n } => PreBlit::Deferred(list),\n #[cfg(feature = \"dispatch\")]\n CommandSink::Remote {\n queue: NoDebug(ref queue),\n ref cmd_buffer,\n ref mut pass,\n ref mut capacity,\n ref label,\n ref pool_shared,\n ..\n } => {\n if let Some(pass) = pass.take() {\n pass.update(capacity);\n pass.schedule(queue, cmd_buffer, pool_shared);\n }\n let list = Vec::with_capacity(capacity.blit);\n *pass = Some(EncodePass::Blit(list, label.clone()));\n match *pass {\n Some(EncodePass::Blit(ref mut list, _)) => PreBlit::Deferred(list),\n _ => unreachable!(),\n }\n }\n };\n\n match pre {\n PreBlit::Immediate(encoder) => {\n for com in commands {\n exec_blit(encoder, com);\n }\n }\n PreBlit::Deferred(list) => {\n list.extend(commands);\n }\n }\n }\n```"}], "func_name": "blit_commands", "docstring": "Issue provided blit commands. This function doesn't expect an active blit pass,\nit will automatically start one when needed.", "repo": "gfx-rs/gfx", "path": "src/backend/metal/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/metal/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e44140e22c9e58a6b681171937509071a3ef8a8891be45b9b2e04546e7d80aa8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pre_compute\n\nDocumentation:\nStart issuing pre-compute commands. Those can be rejected, so the caller is responsible\nfor updating the state cache accordingly, so that it's set upon the start of a next pass.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn pre_compute(&mut self) -> PreCompute {\n match *self {\n CommandSink::Immediate {\n encoder_state: EncoderState::Compute(ref encoder),\n ..\n } => PreCompute::Immediate(encoder),\n CommandSink::Deferred {\n is_encoding: true,\n is_inheriting: false,\n ref mut journal,\n ..\n } => match journal.passes.last() {\n Some(&(soft::Pass::Compute, _, _)) => {\n PreCompute::Deferred(&mut journal.resources, &mut journal.compute_commands)\n }\n _ => PreCompute::Void,\n },\n #[cfg(feature = \"dispatch\")]\n CommandSink::Remote {\n pass: Some(EncodePass::Compute(ref mut list, ref mut resources, _)),\n ..\n } => PreCompute::Deferred(resources, list),\n _ => PreCompute::Void,\n }\n }\n```"}], "func_name": "pre_compute", "docstring": "Start issuing pre-compute commands. Those can be rejected, so the caller is responsible\nfor updating the state cache accordingly, so that it's set upon the start of a next pass.", "repo": "gfx-rs/gfx", "path": "src/backend/metal/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/metal/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e21f14afaf67aa96651403b8a654a9ec017726befd99a91ccda6e32840334a87"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: switch_compute\n\nDocumentation:\nSwitch the active encoder to compute.\nSecond returned value is `true` if the switch has just happened.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn switch_compute(&mut self) -> (PreCompute, bool) {\n match *self {\n CommandSink::Immediate {\n encoder_state: EncoderState::Compute(ref encoder),\n ..\n } => (PreCompute::Immediate(encoder), false),\n CommandSink::Immediate {\n ref cmd_buffer,\n ref mut encoder_state,\n ref mut num_passes,\n ..\n } => {\n *num_passes += 1;\n encoder_state.end();\n let encoder = cmd_buffer.new_compute_command_encoder();\n *encoder_state = EncoderState::Compute(encoder.to_owned());\n (PreCompute::Immediate(encoder), true)\n }\n CommandSink::Deferred {\n ref mut is_encoding,\n is_inheriting,\n ref mut journal,\n ref label,\n ..\n } => {\n assert!(!is_inheriting);\n *is_encoding = true;\n let switch = if let Some(&(soft::Pass::Compute, _, _)) = journal.passes.last() {\n false\n } else {\n journal.stop();\n journal.passes.alloc().init((\n soft::Pass::Compute,\n journal.compute_commands.len()..0,\n label.clone(),\n ));\n true\n };\n (\n PreCompute::Deferred(&mut journal.resources, &mut journal.compute_commands),\n switch,\n )\n }\n #[cfg(feature = \"dispatch\")]\n CommandSink::Remote {\n pass: Some(EncodePass::Compute(ref mut list, ref mut resources, _)),\n ..\n } => (PreCompute::Deferred(resources, list), false),\n #[cfg(feature = \"dispatch\")]\n CommandSink::Remote {\n queue: NoDebug(ref queue),\n ref cmd_buffer,\n ref mut pass,\n ref mut capacity,\n ref label,\n ref pool_shared,\n ..\n } => {\n if let Some(pass) = pass.take() {\n pass.update(capacity);\n pass.schedule(queue, cmd_buffer, pool_shared);\n }\n let list = Vec::with_capacity(capacity.compute);\n *pass = Some(EncodePass::Compute(\n list,\n soft::Own::default(),\n label.clone(),\n ));\n match *pass {\n Some(EncodePass::Compute(ref mut list, ref mut resources, _)) => {\n (PreCompute::Deferred(resources, list), true)\n }\n _ => unreachable!(),\n }\n }\n }\n }\n```"}], "func_name": "switch_compute", "docstring": "Switch the active encoder to compute.\nSecond returned value is `true` if the switch has just happened.", "repo": "gfx-rs/gfx", "path": "src/backend/metal/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/metal/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "600233dacc517dd4da68c1fa08a59b9572d6c86fd475685c1e86c0d8fe94456f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: record_empty\n\nDocumentation:\nThis is a hack around Metal System Trace logic that ignores empty command buffers entirely.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn record_empty(&self, command_buf: &metal::CommandBufferRef) {\n if self.insert_dummy_encoders {\n command_buf.new_blit_command_encoder().end_encoding();\n }\n }\n```"}], "func_name": "record_empty", "docstring": "This is a hack around Metal System Trace logic that ignores empty command buffers entirely.", "repo": "gfx-rs/gfx", "path": "src/backend/metal/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/metal/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d590a78da6cb88dbc245f81758059cbac18735acaa5adc68f8627f008b5f17b8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: free\n\nDocumentation:\nFree command buffers which are allocated from this pool.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn free(&mut self, cmd_buffers: I)\n where\n I: Iterator,\n {\n use hal::command::CommandBuffer as _;\n for mut cmd_buf in cmd_buffers {\n cmd_buf.reset(true);\n match self\n .allocated\n .iter_mut()\n .position(|b| Arc::ptr_eq(b, &cmd_buf.inner))\n {\n Some(index) => {\n self.allocated.swap_remove(index);\n }\n None => error!(\"Unable to free a command buffer!\"),\n }\n }\n }\n```"}], "func_name": "free", "docstring": "Free command buffers which are allocated from this pool.", "repo": "gfx-rs/gfx", "path": "src/backend/metal/src/command.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/metal/src/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8220e6eb590132378f79dbb975de60b4d3677727df502cce424291cb62b4bdcc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: supports_swizzle\n\nDocumentation:\nReturn true if the specified format-swizzle pair is supported natively.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn supports_swizzle(&self, format: format::Format, swizzle: format::Swizzle) -> bool {\n self.shared\n .private_caps\n .map_format_with_swizzle(format, swizzle)\n .is_some()\n }\n```"}], "func_name": "supports_swizzle", "docstring": "Return true if the specified format-swizzle pair is supported natively.", "repo": "gfx-rs/gfx", "path": "src/backend/metal/src/device.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/metal/src/device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e4ab5a763965cf280991b511b355938fc550efd73453f6940f7deb81bccbe31c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: view_cube_as_2d\n\nDocumentation:\nView this cube texture as a 2D array.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn view_cube_as_2d(&self) -> Option {\n match self.mtl_type {\n metal::MTLTextureType::Cube | metal::MTLTextureType::CubeArray => {\n let raw = self.like.as_texture();\n Some(raw.new_texture_view_from_slice(\n self.mtl_format,\n metal::MTLTextureType::D2Array,\n metal::NSRange {\n location: 0,\n length: raw.mipmap_level_count(),\n },\n metal::NSRange {\n location: 0,\n length: self.kind.num_layers() as _,\n },\n ))\n }\n _ => None,\n }\n }\n```"}], "func_name": "view_cube_as_2d", "docstring": "View this cube texture as a 2D array.", "repo": "gfx-rs/gfx", "path": "src/backend/metal/src/native.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/metal/src/native.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "22a701a6af216fb47bb578244d7a8ea70d5f3bee391bcb28efafc79ccef8d089"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: filter_memory_requirements\n\nDocumentation:\nWe only work with a subset of Ash-exposed memory types that we know.\nThis function filters an ash mask into our mask.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn filter_memory_requirements(&self, ash_mask: u32) -> u32 {\n let mut hal_index = 0;\n let mut mask = 0;\n for ash_index in 0..32 {\n if self.valid_ash_memory_types & (1 << ash_index) != 0 {\n if ash_mask & (1 << ash_index) != 0 {\n mask |= 1 << hal_index;\n }\n hal_index += 1;\n }\n }\n mask\n }\n```"}], "func_name": "filter_memory_requirements", "docstring": "We only work with a subset of Ash-exposed memory types that we know.\nThis function filters an ash mask into our mask.", "repo": "gfx-rs/gfx", "path": "src/backend/vulkan/src/device.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/vulkan/src/device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac2fcdbc69e954a0b088de6641c195d40c9584212d284240e7251a75eea37319"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_raw\n\nDocumentation:\n# Safety\n`raw_instance` must be created using at least the extensions provided by `Instance::required_extensions()`\nand the layers provided by `Instance::required_extensions()`.\n`driver_api_version` must match the version used to create `raw_instance`.\n`extensions` must match the extensions used to create `raw_instance`.\n`raw_instance` must be manually destroyed *after* gfx-hal Instance has been dropped.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub unsafe fn from_raw(\n entry: Entry,\n raw_instance: ash::Instance,\n driver_api_version: Version,\n extensions: Vec<&'static CStr>,\n ) -> Result {\n Instance::inner_create(entry, raw_instance, true, driver_api_version, extensions)\n }\n```"}], "func_name": "from_raw", "docstring": "# Safety\n`raw_instance` must be created using at least the extensions provided by `Instance::required_extensions()`\nand the layers provided by `Instance::required_extensions()`.\n`driver_api_version` must match the version used to create `raw_instance`.\n`extensions` must match the extensions used to create `raw_instance`.\n`raw_instance` must be manually destroyed *after* gfx-hal Instance has been dropped.", "repo": "gfx-rs/gfx", "path": "src/backend/vulkan/src/lib.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/vulkan/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c1cfe8f06caec946d06ab3d0caaa7e7920d94ae59515cb545e6036a4f01efd84"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: adapter_from_raw\n\nDocumentation:\n# Safety\n`raw_physical_device` must be created from `self` (or from the inner raw handle)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub unsafe fn adapter_from_raw(\n &self,\n raw_physical_device: vk::PhysicalDevice,\n ) -> adapter::Adapter {\n physical_device::load_adapter(&self.raw, raw_physical_device)\n }\n```"}], "func_name": "adapter_from_raw", "docstring": "# Safety\n`raw_physical_device` must be created from `self` (or from the inner raw handle)", "repo": "gfx-rs/gfx", "path": "src/backend/vulkan/src/lib.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/vulkan/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e9bd2587a4316fcf274091406f4d385b44f0fe873d58de08d042a966a62dee3c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unwrap_extension\n\nDocumentation:\nExpect `self` to be `ExtensionFn::Extension` and return the inner value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn unwrap_extension(&self) -> &T {\n if let ExtensionFn::Extension(t) = self {\n t\n } else {\n panic!()\n }\n }\n```"}], "func_name": "unwrap_extension", "docstring": "Expect `self` to be `ExtensionFn::Extension` and return the inner value.", "repo": "gfx-rs/gfx", "path": "src/backend/vulkan/src/lib.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/vulkan/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bfe6518f762acc8036512839a996cea89d3418a1d1d77f871a54955e1e5267a0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_to_device_create_builder\n\nDocumentation:\nAdd the members of `self` into `info.enabled_features` and its `p_next` chain.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_to_device_create_builder<'a>(\n &'a mut self,\n mut info: vk::DeviceCreateInfoBuilder<'a>,\n ) -> vk::DeviceCreateInfoBuilder<'a> {\n info = info.enabled_features(&self.core);\n\n if let Some(ref mut feature) = self.vulkan_1_2 {\n info = info.push_next(feature);\n }\n if let Some(ref mut feature) = self.descriptor_indexing {\n info = info.push_next(feature);\n }\n if let Some(ref mut feature) = self.mesh_shader {\n info = info.push_next(feature);\n }\n if let Some(ref mut feature) = self.imageless_framebuffer {\n info = info.push_next(feature);\n }\n\n info\n }\n```"}], "func_name": "add_to_device_create_builder", "docstring": "Add the members of `self` into `info.enabled_features` and its `p_next` chain.", "repo": "gfx-rs/gfx", "path": "src/backend/vulkan/src/physical_device.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/vulkan/src/physical_device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "211c51a047023121bf2766170dc8a8daf87fad511c02d02767a927790f7ac25f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_extensions_and_requested_features\n\nDocumentation:\nCreate a `PhysicalDeviceFeatures` that will be used to create a logical device.\n\n`requested_features` should be the same as what was used to generate `enabled_extensions`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_extensions_and_requested_features(\n api_version: Version,\n enabled_extensions: &[&'static CStr],\n requested_features: Features,\n supports_vulkan12_imageless_framebuffer: bool,\n ) -> PhysicalDeviceFeatures {\n // This must follow the \"Valid Usage\" requirements of [`VkDeviceCreateInfo`](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkDeviceCreateInfo.html).\n let features = requested_features;\n PhysicalDeviceFeatures {\n // vk::PhysicalDeviceFeatures is a struct composed of Bool32's while\n // Features is a bitfield so we need to map everything manually\n core: vk::PhysicalDeviceFeatures::builder()\n .robust_buffer_access(features.contains(Features::ROBUST_BUFFER_ACCESS))\n .full_draw_index_uint32(features.contains(Features::FULL_DRAW_INDEX_U32))\n .image_cube_array(features.contains(Features::IMAGE_CUBE_ARRAY))\n .independent_blend(features.contains(Features::INDEPENDENT_BLENDING))\n .geometry_shader(features.contains(Features::GEOMETRY_SHADER))\n .tessellation_shader(features.contains(Features::TESSELLATION_SHADER))\n .sample_rate_shading(features.contains(Features::SAMPLE_RATE_SHADING))\n .dual_src_blend(features.contains(Features::DUAL_SRC_BLENDING))\n .logic_op(features.contains(Features::LOGIC_OP))\n .multi_draw_indirect(features.contains(Features::MULTI_DRAW_INDIRECT))\n .draw_indirect_first_instance(\n features.contains(Features::DRAW_INDIRECT_FIRST_INSTANCE),\n )\n .depth_clamp(features.contains(Features::DEPTH_CLAMP))\n .depth_bias_clamp(features.contains(Features::DEPTH_BIAS_CLAMP))\n .fill_mode_non_solid(features.contains(Features::NON_FILL_POLYGON_MODE))\n .depth_bounds(features.contains(Features::DEPTH_BOUNDS))\n .wide_lines(features.contains(Features::LINE_WIDTH))\n .large_points(features.contains(Features::POINT_SIZE))\n .alpha_to_one(features.contains(Features::ALPHA_TO_ONE))\n .multi_viewport(features.contains(Features::MULTI_VIEWPORTS))\n .sampler_anisotropy(features.contains(Features::SAMPLER_ANISOTROPY))\n .texture_compression_etc2(features.contains(Features::FORMAT_ETC2))\n .texture_compression_astc_ldr(features.contains(Features::FORMAT_ASTC_LDR))\n .texture_compression_bc(features.contains(Features::FORMAT_BC))\n .occlusion_query_precise(features.contains(Features::PRECISE_OCCLUSION_QUERY))\n .pipeline_statistics_query(features.contains(Features::PIPELINE_STATISTICS_QUERY))\n .vertex_pipeline_stores_and_atomics(\n features.contains(Features::VERTEX_STORES_AND_ATOMICS),\n )\n .fragment_stores_and_atomics(\n features.contains(Features::FRAGMENT_STORES_AND_ATOMICS),\n )\n .shader_tessellation_and_geometry_point_size(\n features.contains(Features::SHADER_TESSELLATION_AND_GEOMETRY_POINT_SIZE),\n )\n .shader_image_gather_extended(\n features.contains(Features::SHADER_IMAGE_GATHER_EXTENDED),\n )\n .shader_storage_image_extended_formats(\n features.contains(Features::SHADER_STORAGE_IMAGE_EXTENDED_FORMATS),\n )\n .shader_storage_image_multisample(\n features.contains(Features::SHADER_STORAGE_IMAGE_MULTISAMPLE),\n )\n .shader_storage_image_read_without_format(\n features.contains(Features::SHADER_STORAGE_IMAGE_READ_WITHOUT_FORMAT),\n )\n .shader_storage_image_write_without_format(\n features.contains(Features::SHADER_STORAGE_IMAGE_WRITE_WITHOUT_FORMAT),\n )\n .shader_uniform_buffer_array_dynamic_indexing(\n features.contains(Features::SHADER_UNIFORM_BUFFER_ARRAY_DYNAMIC_INDEXING),\n )\n .shader_sampled_image_array_dynamic_indexing(\n features.contains(Features::SHADER_SAMPLED_IMAGE_ARRAY_DYNAMIC_INDEXING),\n )\n .shader_storage_buffer_array_dynamic_indexing(\n features.contains(Features::SHADER_STORAGE_BUFFER_ARRAY_DYNAMIC_INDEXING),\n )\n .shader_storage_image_array_dynamic_indexing(\n features.contains(Features::SHADER_STORAGE_IMAGE_ARRAY_DYNAMIC_INDEXING),\n )\n .shader_clip_distance(features.contains(Features::SHADER_CLIP_DISTANCE))\n .shader_cull_distance(features.contains(Features::SHADER_CULL_DISTANCE))\n .shader_float64(features.contains(Features::SHADER_FLOAT64))\n .shader_int64(features.contains(Features::SHADER_INT64))\n .shader_int16(features.contains(Features::SHADER_INT16))\n .shader_resource_residency(features.contains(Features::SHADER_RESOURCE_RESIDENCY))\n .shader_resource_min_lod(features.contains(Features::SHADER_RESOURCE_MIN_LOD))\n .sparse_binding(features.contains(Features::SPARSE_BINDING))\n .sparse_residency_buffer(features.contains(Features::SPARSE_RESIDENCY_BUFFER))\n .sparse_residency_image2_d(features.contains(Features::SPARSE_RESIDENCY_IMAGE_2D))\n .sparse_residency_image3_d(features.contains(Features::SPARSE_RESIDENCY_IMAGE_3D))\n .sparse_residency2_samples(features.contains(Features::SPARSE_RESIDENCY_2_SAMPLES))\n .sparse_residency4_samples(features.contains(Features::SPARSE_RESIDENCY_4_SAMPLES))\n .sparse_residency8_samples(features.contains(Features::SPARSE_RESIDENCY_8_SAMPLES))\n .sparse_residency16_samples(\n features.contains(Features::SPARSE_RESIDENCY_16_SAMPLES),\n )\n .sparse_residency_aliased(features.contains(Features::SPARSE_RESIDENCY_ALIASED))\n .variable_multisample_rate(features.contains(Features::VARIABLE_MULTISAMPLE_RATE))\n .inherited_queries(features.contains(Features::INHERITED_QUERIES))\n .build(),\n vulkan_1_2: if api_version >= Version::V1_2 {\n Some(\n vk::PhysicalDeviceVulkan12Features::builder()\n .sampler_mirror_clamp_to_edge(\n features.contains(Features::SAMPLER_MIRROR_CLAMP_EDGE),\n )\n .draw_indirect_count(features.contains(Features::DRAW_INDIRECT_COUNT))\n .descriptor_indexing(\n features.intersects(Features::DESCRIPTOR_INDEXING_MASK),\n )\n .shader_sampled_image_array_non_uniform_indexing(\n features.contains(Features::SAMPLED_TEXTURE_DESCRIPTOR_INDEXING),\n )\n .shader_storage_image_array_non_uniform_indexing(\n features.contains(Features::STORAGE_TEXTURE_DESCRIPTOR_INDEXING),\n )\n .shader_storage_buffer_array_non_uniform_indexing(\n features.contains(Features::STORAGE_BUFFER_DESCRIPTOR_INDEXING),\n )\n .shader_uniform_buffer_array_non_uniform_indexing(\n features.contains(Features::UNIFORM_BUFFER_DESCRIPTOR_INDEXING),\n )\n .runtime_descriptor_array(\n features.contains(Features::UNSIZED_DESCRIPTOR_ARRAY),\n )\n .sampler_filter_minmax(features.contains(Features::SAMPLER_REDUCTION))\n .imageless_framebuffer(supports_vulkan12_imageless_framebuffer)\n .build(),\n )\n } else {\n None\n },\n descriptor_indexing: if enabled_extensions\n .contains(&vk::ExtDescriptorIndexingFn::name())\n {\n Some(\n vk::PhysicalDeviceDescriptorIndexingFeaturesEXT::builder()\n .shader_sampled_image_array_non_uniform_indexing(\n features.contains(Features::SAMPLED_TEXTURE_DESCRIPTOR_INDEXING),\n )\n .shader_storage_image_array_non_uniform_indexing(\n features.contains(Features::STORAGE_TEXTURE_DESCRIPTOR_INDEXING),\n )\n .shader_storage_buffer_array_non_uniform_indexing(\n features.contains(Features::STORAGE_BUFFER_DESCRIPTOR_INDEXING),\n )\n .shader_uniform_buffer_array_non_uniform_indexing(\n features.contains(Features::UNIFORM_BUFFER_DESCRIPTOR_INDEXING),\n )\n .runtime_descriptor_array(\n features.contains(Features::UNSIZED_DESCRIPTOR_ARRAY),\n )\n .build(),\n )\n } else {\n None\n },\n mesh_shader: if enabled_extensions.contains(&vk::NvMeshShaderFn::name()) {\n Some(\n vk::PhysicalDeviceMeshShaderFeaturesNV::builder()\n .task_shader(features.contains(Features::TASK_SHADER))\n .mesh_shader(features.contains(Features::MESH_SHADER))\n .build(),\n )\n } else {\n None\n },\n imageless_framebuffer: if enabled_extensions\n .contains(&vk::KhrImagelessFramebufferFn::name())\n {\n Some(\n vk::PhysicalDeviceImagelessFramebufferFeaturesKHR::builder()\n .imageless_framebuffer(true)\n .build(),\n )\n } else {\n None\n },\n }\n }\n```"}], "func_name": "from_extensions_and_requested_features", "docstring": "Create a `PhysicalDeviceFeatures` that will be used to create a logical device.\n\n`requested_features` should be the same as what was used to generate `enabled_extensions`.", "repo": "gfx-rs/gfx", "path": "src/backend/vulkan/src/physical_device.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/vulkan/src/physical_device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "633e5cd506aec1a3bad2953d07b3b0c4cce71e1bc8cf7d82a53bc43986eb6b61"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_hal_features\n\nDocumentation:\nGet the `hal::Features` corresponding to the raw physical device's features and properties.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn to_hal_features(&self, info: &PhysicalDeviceInfo) -> Features {\n let mut bits = Features::empty()\n | Features::TRIANGLE_FAN\n | Features::SEPARATE_STENCIL_REF_VALUES\n | Features::SAMPLER_MIP_LOD_BIAS\n | Features::SAMPLER_BORDER_COLOR\n | Features::MUTABLE_COMPARISON_SAMPLER\n | Features::MUTABLE_UNNORMALIZED_SAMPLER\n | Features::TEXTURE_DESCRIPTOR_ARRAY\n | Features::BUFFER_DESCRIPTOR_ARRAY;\n\n if self.core.robust_buffer_access != 0 {\n bits |= Features::ROBUST_BUFFER_ACCESS;\n }\n if self.core.full_draw_index_uint32 != 0 {\n bits |= Features::FULL_DRAW_INDEX_U32;\n }\n if self.core.image_cube_array != 0 {\n bits |= Features::IMAGE_CUBE_ARRAY;\n }\n if self.core.independent_blend != 0 {\n bits |= Features::INDEPENDENT_BLENDING;\n }\n if self.core.geometry_shader != 0 {\n bits |= Features::GEOMETRY_SHADER;\n }\n if self.core.tessellation_shader != 0 {\n bits |= Features::TESSELLATION_SHADER;\n }\n if self.core.sample_rate_shading != 0 {\n bits |= Features::SAMPLE_RATE_SHADING;\n }\n if self.core.dual_src_blend != 0 {\n bits |= Features::DUAL_SRC_BLENDING;\n }\n if self.core.logic_op != 0 {\n bits |= Features::LOGIC_OP;\n }\n if self.core.multi_draw_indirect != 0 {\n bits |= Features::MULTI_DRAW_INDIRECT;\n }\n if self.core.draw_indirect_first_instance != 0 {\n bits |= Features::DRAW_INDIRECT_FIRST_INSTANCE;\n }\n if self.core.depth_clamp != 0 {\n bits |= Features::DEPTH_CLAMP;\n }\n if self.core.depth_bias_clamp != 0 {\n bits |= Features::DEPTH_BIAS_CLAMP;\n }\n if self.core.fill_mode_non_solid != 0 {\n bits |= Features::NON_FILL_POLYGON_MODE;\n }\n if self.core.depth_bounds != 0 {\n bits |= Features::DEPTH_BOUNDS;\n }\n if self.core.wide_lines != 0 {\n bits |= Features::LINE_WIDTH;\n }\n if self.core.large_points != 0 {\n bits |= Features::POINT_SIZE;\n }\n if self.core.alpha_to_one != 0 {\n bits |= Features::ALPHA_TO_ONE;\n }\n if self.core.multi_viewport != 0 {\n bits |= Features::MULTI_VIEWPORTS;\n }\n if self.core.sampler_anisotropy != 0 {\n bits |= Features::SAMPLER_ANISOTROPY;\n }\n if self.core.texture_compression_etc2 != 0 {\n bits |= Features::FORMAT_ETC2;\n }\n if self.core.texture_compression_astc_ldr != 0 {\n bits |= Features::FORMAT_ASTC_LDR;\n }\n if self.core.texture_compression_bc != 0 {\n bits |= Features::FORMAT_BC;\n }\n if self.core.occlusion_query_precise != 0 {\n bits |= Features::PRECISE_OCCLUSION_QUERY;\n }\n if self.core.pipeline_statistics_query != 0 {\n bits |= Features::PIPELINE_STATISTICS_QUERY;\n }\n if self.core.vertex_pipeline_stores_and_atomics != 0 {\n bits |= Features::VERTEX_STORES_AND_ATOMICS;\n }\n if self.core.fragment_stores_and_atomics != 0 {\n bits |= Features::FRAGMENT_STORES_AND_ATOMICS;\n }\n if self.core.shader_tessellation_and_geometry_point_size != 0 {\n bits |= Features::SHADER_TESSELLATION_AND_GEOMETRY_POINT_SIZE;\n }\n if self.core.shader_image_gather_extended != 0 {\n bits |= Features::SHADER_IMAGE_GATHER_EXTENDED;\n }\n if self.core.shader_storage_image_extended_formats != 0 {\n bits |= Features::SHADER_STORAGE_IMAGE_EXTENDED_FORMATS;\n }\n if self.core.shader_storage_image_multisample != 0 {\n bits |= Features::SHADER_STORAGE_IMAGE_MULTISAMPLE;\n }\n if self.core.shader_storage_image_read_without_format != 0 {\n bits |= Features::SHADER_STORAGE_IMAGE_READ_WITHOUT_FORMAT;\n }\n if self.core.shader_storage_image_write_without_format != 0 {\n bits |= Features::SHADER_STORAGE_IMAGE_WRITE_WITHOUT_FORMAT;\n }\n if self.core.shader_uniform_buffer_array_dynamic_indexing != 0 {\n bits |= Features::SHADER_UNIFORM_BUFFER_ARRAY_DYNAMIC_INDEXING;\n }\n if self.core.shader_sampled_image_array_dynamic_indexing != 0 {\n bits |= Features::SHADER_SAMPLED_IMAGE_ARRAY_DYNAMIC_INDEXING;\n }\n if self.core.shader_storage_buffer_array_dynamic_indexing != 0 {\n bits |= Features::SHADER_STORAGE_BUFFER_ARRAY_DYNAMIC_INDEXING;\n }\n if self.core.shader_storage_image_array_dynamic_indexing != 0 {\n bits |= Features::SHADER_STORAGE_IMAGE_ARRAY_DYNAMIC_INDEXING;\n }\n if self.core.shader_clip_distance != 0 {\n bits |= Features::SHADER_CLIP_DISTANCE;\n }\n if self.core.shader_cull_distance != 0 {\n bits |= Features::SHADER_CULL_DISTANCE;\n }\n if self.core.shader_float64 != 0 {\n bits |= Features::SHADER_FLOAT64;\n }\n if self.core.shader_int64 != 0 {\n bits |= Features::SHADER_INT64;\n }\n if self.core.shader_int16 != 0 {\n bits |= Features::SHADER_INT16;\n }\n if self.core.shader_resource_residency != 0 {\n bits |= Features::SHADER_RESOURCE_RESIDENCY;\n }\n if self.core.shader_resource_min_lod != 0 {\n bits |= Features::SHADER_RESOURCE_MIN_LOD;\n }\n if self.core.sparse_binding != 0 {\n bits |= Features::SPARSE_BINDING;\n }\n if self.core.sparse_residency_buffer != 0 {\n bits |= Features::SPARSE_RESIDENCY_BUFFER;\n }\n if self.core.sparse_residency_image2_d != 0 {\n bits |= Features::SPARSE_RESIDENCY_IMAGE_2D;\n }\n if self.core.sparse_residency_image3_d != 0 {\n bits |= Features::SPARSE_RESIDENCY_IMAGE_3D;\n }\n if self.core.sparse_residency2_samples != 0 {\n bits |= Features::SPARSE_RESIDENCY_2_SAMPLES;\n }\n if self.core.sparse_residency4_samples != 0 {\n bits |= Features::SPARSE_RESIDENCY_4_SAMPLES;\n }\n if self.core.sparse_residency8_samples != 0 {\n bits |= Features::SPARSE_RESIDENCY_8_SAMPLES;\n }\n if self.core.sparse_residency16_samples != 0 {\n bits |= Features::SPARSE_RESIDENCY_16_SAMPLES;\n }\n if self.core.sparse_residency_aliased != 0 {\n bits |= Features::SPARSE_RESIDENCY_ALIASED;\n }\n if self.core.variable_multisample_rate != 0 {\n bits |= Features::VARIABLE_MULTISAMPLE_RATE;\n }\n if self.core.inherited_queries != 0 {\n bits |= Features::INHERITED_QUERIES;\n }\n\n if info.supports_extension(vk::AmdNegativeViewportHeightFn::name())\n || info.supports_extension(vk::KhrMaintenance1Fn::name())\n || info.api_version() >= Version::V1_1\n {\n bits |= Features::NDC_Y_UP;\n }\n\n if info.supports_extension(vk::KhrSamplerMirrorClampToEdgeFn::name()) {\n bits |= Features::SAMPLER_MIRROR_CLAMP_EDGE;\n }\n\n if info.supports_extension(vk::ExtSamplerFilterMinmaxFn::name()) {\n bits |= Features::SAMPLER_REDUCTION;\n }\n\n if info.supports_extension(DrawIndirectCount::name()) {\n bits |= Features::DRAW_INDIRECT_COUNT\n }\n\n if info.supports_extension(vk::ExtConservativeRasterizationFn::name()) {\n bits |= Features::CONSERVATIVE_RASTERIZATION\n }\n\n if info.api_version() >= Version::V1_1\n || (info.supports_extension(vk::KhrGetPhysicalDeviceProperties2Fn::name())\n && info.supports_extension(vk::KhrExternalMemoryFn::name()))\n {\n bits |= Features::EXTERNAL_MEMORY\n }\n\n if let Some(ref vulkan_1_2) = self.vulkan_1_2 {\n if vulkan_1_2.shader_sampled_image_array_non_uniform_indexing != 0 {\n bits |= Features::SAMPLED_TEXTURE_DESCRIPTOR_INDEXING;\n }\n if vulkan_1_2.shader_storage_image_array_non_uniform_indexing != 0 {\n bits |= Features::STORAGE_TEXTURE_DESCRIPTOR_INDEXING;\n }\n if vulkan_1_2.shader_storage_buffer_array_non_uniform_indexing != 0 {\n bits |= Features::STORAGE_BUFFER_DESCRIPTOR_INDEXING;\n }\n if vulkan_1_2.shader_uniform_buffer_array_non_uniform_indexing != 0 {\n bits |= Features::UNIFORM_BUFFER_DESCRIPTOR_INDEXING;\n }\n if vulkan_1_2.runtime_descriptor_array != 0 {\n bits |= Features::UNSIZED_DESCRIPTOR_ARRAY;\n }\n if vulkan_1_2.sampler_mirror_clamp_to_edge != 0 {\n bits |= Features::SAMPLER_MIRROR_CLAMP_EDGE;\n }\n if vulkan_1_2.sampler_filter_minmax != 0 {\n bits |= Features::SAMPLER_REDUCTION\n }\n if vulkan_1_2.draw_indirect_count != 0 {\n bits |= Features::DRAW_INDIRECT_COUNT\n }\n }\n\n if let Some(ref descriptor_indexing) = self.descriptor_indexing {\n if descriptor_indexing.shader_sampled_image_array_non_uniform_indexing != 0 {\n bits |= Features::SAMPLED_TEXTURE_DESCRIPTOR_INDEXING;\n }\n if descriptor_indexing.shader_storage_image_array_non_uniform_indexing != 0 {\n bits |= Features::STORAGE_TEXTURE_DESCRIPTOR_INDEXING;\n }\n if descriptor_indexing.shader_storage_buffer_array_non_uniform_indexing != 0 {\n bits |= Features::STORAGE_BUFFER_DESCRIPTOR_INDEXING;\n }\n if descriptor_indexing.shader_uniform_buffer_array_non_uniform_indexing != 0 {\n bits |= Features::UNIFORM_BUFFER_DESCRIPTOR_INDEXING;\n }\n if descriptor_indexing.runtime_descriptor_array != 0 {\n bits |= Features::UNSIZED_DESCRIPTOR_ARRAY;\n }\n }\n\n if let Some(ref mesh_shader) = self.mesh_shader {\n if mesh_shader.task_shader != 0 {\n bits |= Features::TASK_SHADER;\n }\n if mesh_shader.mesh_shader != 0 {\n bits |= Features::MESH_SHADER;\n }\n }\n\n bits\n }\n```"}], "func_name": "to_hal_features", "docstring": "Get the `hal::Features` corresponding to the raw physical device's features and properties.", "repo": "gfx-rs/gfx", "path": "src/backend/vulkan/src/physical_device.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/vulkan/src/physical_device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "052bb4bded74faf78db4180ac68cf302468af0aa0f38846fc04266234ccab2f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_required_extensions\n\nDocumentation:\nMap `requested_features` to the list of Vulkan extension strings required to create the logical device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_required_extensions(&self, requested_features: Features) -> Vec<&'static CStr> {\n let mut requested_extensions = Vec::new();\n\n requested_extensions.push(Swapchain::name());\n\n if self.api_version() < Version::V1_1 {\n requested_extensions.push(vk::KhrMaintenance1Fn::name());\n requested_extensions.push(vk::KhrMaintenance2Fn::name());\n }\n\n if requested_features.contains(Features::NDC_Y_UP) {\n // `VK_AMD_negative_viewport_height` is obsoleted by `VK_KHR_maintenance1` and must not be enabled alongside `VK_KHR_maintenance1` or a 1.1+ device.\n if self.api_version() < Version::V1_1\n && !self.supports_extension(vk::KhrMaintenance1Fn::name())\n {\n requested_extensions.push(vk::AmdNegativeViewportHeightFn::name());\n }\n }\n\n if self.api_version() < Version::V1_2\n && self.supports_extension(vk::KhrImagelessFramebufferFn::name())\n {\n requested_extensions.push(vk::KhrImagelessFramebufferFn::name());\n requested_extensions.push(vk::KhrImageFormatListFn::name()); // Required for `KhrImagelessFramebufferFn`\n }\n\n if self.api_version() < Version::V1_2 {\n requested_extensions.push(vk::ExtSamplerFilterMinmaxFn::name());\n }\n\n if self.api_version() < Version::V1_2\n && requested_features.intersects(Features::DESCRIPTOR_INDEXING_MASK)\n {\n requested_extensions.push(vk::ExtDescriptorIndexingFn::name());\n\n if self.api_version() < Version::V1_1 {\n requested_extensions.push(vk::KhrMaintenance3Fn::name());\n }\n }\n\n if self.api_version() < Version::V1_2\n && requested_features.intersects(Features::SAMPLER_MIRROR_CLAMP_EDGE)\n {\n requested_extensions.push(vk::KhrSamplerMirrorClampToEdgeFn::name());\n }\n\n if self.api_version() < Version::V1_2\n && requested_features.contains(Features::SAMPLER_REDUCTION)\n {\n requested_extensions.push(vk::ExtSamplerFilterMinmaxFn::name());\n }\n\n if requested_features.intersects(Features::MESH_SHADER_MASK) {\n requested_extensions.push(MeshShader::name());\n }\n\n if self.api_version() < Version::V1_2\n && requested_features.contains(Features::DRAW_INDIRECT_COUNT)\n {\n requested_extensions.push(DrawIndirectCount::name());\n }\n\n if requested_features.contains(Features::CONSERVATIVE_RASTERIZATION) {\n requested_extensions.push(vk::ExtConservativeRasterizationFn::name());\n requested_extensions.push(vk::KhrGetDisplayProperties2Fn::name()); // TODO NOT NEEDED, RIGHT?\n }\n\n if self.supports_extension(vk::ExtDisplayControlFn::name()) {\n requested_extensions.push(vk::ExtDisplayControlFn::name());\n }\n\n if requested_features.contains(Features::EXTERNAL_MEMORY) {\n if self.api_version() < Version::V1_1 {\n requested_extensions.push(vk::KhrGetPhysicalDeviceProperties2Fn::name());\n requested_extensions.push(vk::KhrExternalMemoryFn::name());\n\n // External memory interact with DedicatedAllocation extension, but it is not a strict dependency.\n requested_extensions.push(vk::KhrGetMemoryRequirements2Fn::name()); // TODO Functions should be added because they are useful\n requested_extensions.push(vk::KhrDedicatedAllocationFn::name());\n }\n\n requested_extensions.push(vk::ExtExternalMemoryHostFn::name());\n #[cfg(window)]\n requested_extensions.push(vk::KhrExternalMemoryWin32Fn::name());\n #[cfg(unix)]\n {\n requested_extensions.push(vk::KhrExternalMemoryFdFn::name());\n requested_extensions.push(vk::ExtExternalMemoryDmaBufFn::name());\n\n requested_extensions.push(vk::KhrBindMemory2Fn::name());\n\n requested_extensions.push(vk::KhrImageFormatListFn::name());\n requested_extensions.push(vk::KhrSamplerYcbcrConversionFn::name());\n requested_extensions.push(vk::ExtImageDrmFormatModifierFn::name());\n }\n }\n requested_extensions\n }\n```"}], "func_name": "get_required_extensions", "docstring": "Map `requested_features` to the list of Vulkan extension strings required to create the logical device.", "repo": "gfx-rs/gfx", "path": "src/backend/vulkan/src/physical_device.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/vulkan/src/physical_device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "532bad8003151fc93eaade4292efb5f4c1944d0a1d9c8c83453b97686fd1b485"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: null_p_next\n\nDocumentation:\n# Safety\n`T` must be a struct bigger than `vk::BaseOutStructure`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn null_p_next(features: &mut Option) {\n if let Some(features) = features {\n // This is technically invalid since `vk::BaseOutStructure` and `T` will probably never have the same size.\n mem::transmute::<_, &mut vk::BaseOutStructure>(features).p_next = ptr::null_mut();\n }\n }\n```"}], "func_name": "null_p_next", "docstring": "# Safety\n`T` must be a struct bigger than `vk::BaseOutStructure`.", "repo": "gfx-rs/gfx", "path": "src/backend/vulkan/src/physical_device.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/vulkan/src/physical_device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2620a15baa7b0d43d7b906b64f17f4530d9030a09cba5201fb6d8d47937e3d26"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: gpu_from_raw\n\nDocumentation:\n# Safety\n`raw_device` must be created from `self` (or from the inner raw handle)\n`raw_device` must be created with `requested_features`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub unsafe fn gpu_from_raw(\n &self,\n raw_device: ash::Device,\n families: &[(&QueueFamily, &[queue::QueuePriority])],\n requested_features: Features,\n ) -> Result, CreationError> {\n let enabled_extensions = self.enabled_extensions(requested_features)?;\n Ok(self.inner_create_gpu(\n raw_device,\n true,\n families,\n requested_features,\n enabled_extensions,\n ))\n }\n```"}], "func_name": "gpu_from_raw", "docstring": "# Safety\n`raw_device` must be created from `self` (or from the inner raw handle)\n`raw_device` must be created with `requested_features`", "repo": "gfx-rs/gfx", "path": "src/backend/vulkan/src/physical_device.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/vulkan/src/physical_device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9682a4d28b8585369b9900a04b074cc4530401d7aeb57d1c715a68a157ff0709"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: enumerate_adapters_async\n\nDocumentation:\nEnumerates the adapters available from this backend.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn enumerate_adapters_async(&self) -> Vec> {\n let mut options = web_sys::GpuRequestAdapterOptions::new();\n\n // Request the high-performance dedicated GPU\n options.power_preference(web_sys::GpuPowerPreference::HighPerformance);\n let high_performance_adapter_promise = self.0.request_adapter_with_options(&options);\n\n // Request the low-power integrated GPU\n options.power_preference(web_sys::GpuPowerPreference::LowPower);\n let low_power_adapter_promise = self.0.request_adapter_with_options(&options);\n\n let high_performance_adapter = JsFuture::from(high_performance_adapter_promise).await;\n let low_power_adapter = JsFuture::from(low_power_adapter_promise).await;\n\n let high_performance_adapter = future_request_adapter(high_performance_adapter);\n let low_power_adapter = future_request_adapter(low_power_adapter);\n\n // If the system has at least two **different** graphics adapters,\n // we can return them and let the application choose.\n if high_performance_adapter != low_power_adapter {\n high_performance_adapter\n .chain(low_power_adapter)\n .map(map_wgpu_adapter_to_hal_adapter)\n .collect()\n } else {\n high_performance_adapter\n .map(map_wgpu_adapter_to_hal_adapter)\n .collect()\n }\n }\n```"}], "func_name": "enumerate_adapters_async", "docstring": "Enumerates the adapters available from this backend.", "repo": "gfx-rs/gfx", "path": "src/backend/webgpu/src/lib.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/backend/webgpu/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ae095f5a78c5e9c25dd25861bed6e5f834820f1b3a4cba63fd88c80367235597"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: can_transfer\n\nDocumentation:\nReturns if the buffer can be used in transfer operations.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn can_transfer(&self) -> bool {\n self.intersects(Usage::TRANSFER_SRC | Usage::TRANSFER_DST)\n }\n```"}], "func_name": "can_transfer", "docstring": "Returns if the buffer can be used in transfer operations.", "repo": "gfx-rs/gfx", "path": "src/hal/src/buffer.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b58a5d96af10871815e4d7219fcec12b462e8b5e3fbe9cc8f81421c3a4b33d33"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_shader_module_from_naga\n\nDocumentation:\nCreate a new shader module from the `naga` module.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn create_shader_module_from_naga(\n &self,\n shader: NagaShader,\n ) -> Result {\n Err((ShaderError::Unsupported, shader))\n }\n```"}], "func_name": "create_shader_module_from_naga", "docstring": "Create a new shader module from the `naga` module.", "repo": "gfx-rs/gfx", "path": "src/hal/src/device.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c07f25974f269ceb0f887933198ff9772a7f328e561f813944d9a346e1044a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait_for_fence\n\nDocumentation:\nBlocks until the given fence is signaled.\nReturns true if the fence was signaled before the timeout.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn wait_for_fence(&self, fence: &B::Fence, timeout_ns: u64) -> Result {\n self.wait_for_fences(iter::once(fence), WaitFor::All, timeout_ns)\n }\n```"}], "func_name": "wait_for_fence", "docstring": "Blocks until the given fence is signaled.\nReturns true if the fence was signaled before the timeout.", "repo": "gfx-rs/gfx", "path": "src/hal/src/device.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7f839dbb79eefe4c6639f50abd2dbfb593ca256e81144181eb6972a91fa95c43"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait_for_fences\n\nDocumentation:\nBlocks until all or one of the given fences are signaled.\nReturns true if fences were signaled before the timeout.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn wait_for_fences<'a, I>(\n &self,\n fences: I,\n wait: WaitFor,\n timeout_ns: u64,\n ) -> Result\n where\n I: Iterator,\n {\n use std::{thread, time};\n fn to_ns(duration: time::Duration) -> u64 {\n duration.as_secs() * 1_000_000_000 + duration.subsec_nanos() as u64\n }\n\n let start = time::Instant::now();\n match wait {\n WaitFor::All => {\n for fence in fences {\n if !self.wait_for_fence(fence, 0)? {\n let elapsed_ns = to_ns(start.elapsed());\n if elapsed_ns > timeout_ns {\n return Ok(false);\n }\n if !self.wait_for_fence(fence, timeout_ns - elapsed_ns)? {\n return Ok(false);\n }\n }\n }\n Ok(true)\n }\n WaitFor::Any => {\n let fences: Vec<_> = fences.collect();\n loop {\n for &fence in &fences {\n if self.wait_for_fence(fence, 0)? {\n return Ok(true);\n }\n }\n if to_ns(start.elapsed()) >= timeout_ns {\n return Ok(false);\n }\n thread::sleep(time::Duration::from_millis(1));\n }\n }\n }\n }\n```"}], "func_name": "wait_for_fences", "docstring": "Blocks until all or one of the given fences are signaled.\nReturns true if fences were signaled before the timeout.", "repo": "gfx-rs/gfx", "path": "src/hal/src/device.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc4a761ec3f37d90f443ef6a529c7fd660d95eb51e1675c581eba8469b5a105a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_compressed\n\nDocumentation:\nCheck if the format is compressed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_compressed(&self) -> bool {\n self.dim != (1, 1)\n }\n```"}], "func_name": "is_compressed", "docstring": "Check if the format is compressed.", "repo": "gfx-rs/gfx", "path": "src/hal/src/format.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/format.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00ba5d0d385854306bd82a66215d5bbabdcca9c056bea51ef2146e9dc76b19b8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: base_format\n\nDocumentation:\nGet base format.\n\nReturns `None` if format is `Undefined`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn base_format(self) -> BaseFormat {\n assert!(self as usize != 0 && NUM_FORMATS > self as usize);\n BASE_FORMATS[self as usize - 1]\n }\n```"}], "func_name": "base_format", "docstring": "Get base format.\n\nReturns `None` if format is `Undefined`.", "repo": "gfx-rs/gfx", "path": "src/hal/src/format.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/format.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "033b71662462a47c5a1495f16fd4f5316d501acfb7b0677b4d9882b999f72787"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_empty\n\nDocumentation:\nReturn true if one of the dimensions is zero.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_empty(&self) -> bool {\n self.width == 0 || self.height == 0 || self.depth == 0\n }\n```"}], "func_name": "is_empty", "docstring": "Return true if one of the dimensions is zero.", "repo": "gfx-rs/gfx", "path": "src/hal/src/image.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93260ae0de26b799bb8bfb25184f9122ffcb20c9c0b540b72f39d21fae1573fc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: at_level\n\nDocumentation:\nGet the extent at a particular mipmap level.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn at_level(&self, level: Level) -> Self {\n Extent {\n width: 1.max(self.width >> level),\n height: 1.max(self.height >> level),\n depth: 1.max(self.depth >> level),\n }\n }\n```"}], "func_name": "at_level", "docstring": "Get the extent at a particular mipmap level.", "repo": "gfx-rs/gfx", "path": "src/hal/src/image.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d6b082732c3f3a8884a77d38cd45b224d0941788c0c5a59d582f467c2a542608"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rect\n\nDocumentation:\nGet a rectangle for the full area of extent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn rect(&self) -> Rect {\n Rect {\n x: 0,\n y: 0,\n w: self.width as i16,\n h: self.height as i16,\n }\n }\n```"}], "func_name": "rect", "docstring": "Get a rectangle for the full area of extent.", "repo": "gfx-rs/gfx", "path": "src/hal/src/image.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "26b4901ec60ae3b6778cf238a048fac66f404bc93764dfdd2905fcc142f710da"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_bounds\n\nDocumentation:\nConvert the offset into 2-sided bounds given the extent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_bounds(self, extent: &Extent) -> Range {\n let end = Offset {\n x: self.x + extent.width as i32,\n y: self.y + extent.height as i32,\n z: self.z + extent.depth as i32,\n };\n self..end\n }\n```"}], "func_name": "into_bounds", "docstring": "Convert the offset into 2-sided bounds given the extent.", "repo": "gfx-rs/gfx", "path": "src/hal/src/image.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ed3dc3d576e78ddf5e88e9e929ede0ee0dfc98ed5649f2e3ad01d4726116b5c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: level_extent\n\nDocumentation:\nGet the extent of a particular mipmap level.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn level_extent(&self, level: Level) -> Extent {\n use std::cmp::{max, min};\n // must be at least 1\n let map = |val| max(min(val, 1), val >> min(level, MAX_LEVEL));\n match *self {\n Kind::D1(w, _) => Extent {\n width: map(w),\n height: 1,\n depth: 1,\n },\n Kind::D2(w, h, _, _) => Extent {\n width: map(w),\n height: map(h),\n depth: 1,\n },\n Kind::D3(w, h, d) => Extent {\n width: map(w),\n height: map(h),\n depth: map(d),\n },\n }\n }\n```"}], "func_name": "level_extent", "docstring": "Get the extent of a particular mipmap level.", "repo": "gfx-rs/gfx", "path": "src/hal/src/image.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81a1930322cbdab5278e27235060864869a4b94e05b3596900bff1dae3eb5bbb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compute_num_levels\n\nDocumentation:\nCount the number of mipmap levels.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compute_num_levels(&self) -> Level {\n use std::cmp::max;\n match *self {\n Kind::D2(_, _, _, s) if s > 1 => {\n // anti-aliased images can't have mipmaps\n 1\n }\n _ => {\n let extent = self.extent();\n let dominant = max(max(extent.width, extent.height), extent.depth);\n (1..).find(|level| dominant >> level == 0).unwrap()\n }\n }\n }\n```"}], "func_name": "compute_num_levels", "docstring": "Count the number of mipmap levels.", "repo": "gfx-rs/gfx", "path": "src/hal/src/image.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "af2095f1d708854194417cba79da34dc6654512627ba6f9d234e6f965e571bdb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: num_layers\n\nDocumentation:\nReturn the number of layers in an array type.\n\nEach cube face counts as separate layer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn num_layers(&self) -> Layer {\n match *self {\n Kind::D1(_, a) | Kind::D2(_, _, a, _) => a,\n Kind::D3(..) => 1,\n }\n }\n```"}], "func_name": "num_layers", "docstring": "Return the number of layers in an array type.\n\nEach cube face counts as separate layer.", "repo": "gfx-rs/gfx", "path": "src/hal/src/image.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2d4b8cf00884f02d317e096c279f2e75bac463f8ef7a5391ba19be9c8f1e579b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: num_samples\n\nDocumentation:\nReturn the number of MSAA samples for the kind.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn num_samples(&self) -> NumSamples {\n match *self {\n Kind::D1(..) => 1,\n Kind::D2(_, _, _, s) => s,\n Kind::D3(..) => 1,\n }\n }\n```"}], "func_name": "num_samples", "docstring": "Return the number of MSAA samples for the kind.", "repo": "gfx-rs/gfx", "path": "src/hal/src/image.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "79417df9b40fa1121b062f67a8c5df1db6b9ff64ff3b780811631af88c1bc548"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: can_target\n\nDocumentation:\nReturns true if this image can be used as a target.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn can_target(&self) -> bool {\n self.intersects(Usage::COLOR_ATTACHMENT | Usage::DEPTH_STENCIL_ATTACHMENT)\n }\n```"}], "func_name": "can_target", "docstring": "Returns true if this image can be used as a target.", "repo": "gfx-rs/gfx", "path": "src/hal/src/image.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "05334649267ebdec00f579f5fe93b2cea57015b8cd8a6882e49e06184729a582"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new sampler description with a given filter method for all filtering operations\nand a wrapping mode, using no LOD modifications.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(filter: Filter, wrap: WrapMode) -> Self {\n SamplerDesc {\n min_filter: filter,\n mag_filter: filter,\n mip_filter: filter,\n reduction_mode: ReductionMode::WeightedAverage,\n wrap_mode: (wrap, wrap, wrap),\n lod_bias: Lod(0.0),\n lod_range: Lod::RANGE.clone(),\n comparison: None,\n border: BorderColor::TransparentBlack,\n normalized: true,\n anisotropy_clamp: None,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new sampler description with a given filter method for all filtering operations\nand a wrapping mode, using no LOD modifications.", "repo": "gfx-rs/gfx", "path": "src/hal/src/image.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ec214fb92861cb9ef9936d58f81428a9f4ebee28496420eb70e0039ab28951e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve_level_count\n\nDocumentation:\nResolve the concrete level count based on the total number of layers in an image.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn resolve_level_count(&self, total: Level) -> Level {\n self.level_count.unwrap_or(total - self.level_start)\n }\n```"}], "func_name": "resolve_level_count", "docstring": "Resolve the concrete level count based on the total number of layers in an image.", "repo": "gfx-rs/gfx", "path": "src/hal/src/image.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2558a211de41dfb6d2c1e1d6028e855c2e2a9b709158748ed396ae93b44c8710"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve_layer_count\n\nDocumentation:\nResolve the concrete layer count based on the total number of layer in an image.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn resolve_layer_count(&self, total: Layer) -> Layer {\n self.layer_count.unwrap_or(total - self.layer_start)\n }\n```"}], "func_name": "resolve_layer_count", "docstring": "Resolve the concrete layer count based on the total number of layer in an image.", "repo": "gfx-rs/gfx", "path": "src/hal/src/image.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44b5cf43d3e6c35fc2cba6b707a019b6e1436f3a072e2734e854a2590726130c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_tile_size\n\nDocumentation:\nTile or block size for sparse binding\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_tile_size(tile_kind: TileKind, texel_bits: u16) -> (u16, u16, u16) {\n match tile_kind {\n TileKind::Flat(samples) => {\n let sizes = match texel_bits {\n 8 => (256, 256, 1),\n 16 => (256, 128, 1),\n 32 => (128, 128, 1),\n 64 => (128, 64, 1),\n 128 => (64, 64, 1),\n _ => unimplemented!(),\n };\n match samples {\n 1 => sizes,\n 2 => (sizes.0 / 2, sizes.1, 1),\n 4 => (sizes.0 / 2, sizes.1 / 2, 1),\n 8 => (sizes.0 / 4, sizes.1 / 2, 1),\n 16 => (sizes.0 / 4, sizes.1 / 4, 1),\n _ => unimplemented!(),\n }\n }\n TileKind::Volume => match texel_bits {\n 8 => (64, 32, 32),\n 16 => (32, 32, 32),\n 32 => (32, 32, 16),\n 64 => (32, 16, 16),\n 128 => (16, 16, 16),\n _ => unimplemented!(),\n },\n }\n}\n```"}], "func_name": "get_tile_size", "docstring": "Tile or block size for sparse binding", "repo": "gfx-rs/gfx", "path": "src/hal/src/image.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "42937959adef06805922c2cf0854c7482a364559bd3f0cfc6cc75a1068c49292"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: all_enabled\n\nDocumentation:\nEnables all properties for a vulkan-complient backend.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn all_enabled() -> Self {\n Self {\n compute_shaders: true,\n shader_model: DownlevelShaderModel::ShaderModel5,\n storage_images: true,\n read_only_depth_stencil: true,\n device_local_image_copies: true,\n non_power_of_two_mipmapped_textures: true,\n }\n }\n```"}], "func_name": "all_enabled", "docstring": "Enables all properties for a vulkan-complient backend.", "repo": "gfx-rs/gfx", "path": "src/hal/src/lib.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f08fad9405aaf857081e718c38f0668e5753f8279eeb05441eb7bf6a130ac535"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: whole_buffer\n\nDocumentation:\nCreate a barrier for the whole buffer between the given states.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn whole_buffer(target: &'a B::Buffer, states: Range) -> Self {\n Barrier::Buffer {\n states,\n target,\n families: None,\n range: buffer::SubRange::WHOLE,\n }\n }\n```"}], "func_name": "whole_buffer", "docstring": "Create a barrier for the whole buffer between the given states.", "repo": "gfx-rs/gfx", "path": "src/hal/src/memory.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/memory.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0f15ed588a8a1163f01a0cd8937cc55580f06d9ae350d00949a4266b220eb87"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConvenience function to create a new `AttachmentOps`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(load: AttachmentLoadOp, store: AttachmentStoreOp) -> Self {\n AttachmentOps { load, store }\n }\n```"}], "func_name": "new", "docstring": "Convenience function to create a new `AttachmentOps`.", "repo": "gfx-rs/gfx", "path": "src/hal/src/pass.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/pass.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd77755ad2065742bc7e1046704c15a0d05cabc8e4a82bd70fb3868e3044e6d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_clears\n\nDocumentation:\nReturns true if this attachment has some clear operations.\n\nUseful when starting a render pass, since there has to be a clear value provided.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn has_clears(&self) -> bool {\n self.ops.load == AttachmentLoadOp::Clear || self.stencil_ops.load == AttachmentLoadOp::Clear\n }\n```"}], "func_name": "has_clears", "docstring": "Returns true if this attachment has some clear operations.\n\nUseful when starting a render pass, since there has to be a clear value provided.", "repo": "gfx-rs/gfx", "path": "src/hal/src/pass.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/pass.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d03bea82ac5550a5d6d97db86539022f962f6f67c37c0fb666bcb6b8da01e25"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: allocate_one\n\nDocumentation:\nAllocate a single [command buffer][crate::command::CommandBuffer] from the pool.\n\n# Arguments\n\n* `level` - whether this command buffer is primary or secondary.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn allocate_one(&mut self, level: Level) -> B::CommandBuffer {\n let mut result = PseudoVec(None);\n self.allocate(1, level, &mut result);\n result.0.unwrap()\n }\n```"}], "func_name": "allocate_one", "docstring": "Allocate a single [command buffer][crate::command::CommandBuffer] from the pool.\n\n# Arguments\n\n* `level` - whether this command buffer is primary or secondary.", "repo": "gfx-rs/gfx", "path": "src/hal/src/pool.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/pool.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0aaf897042a1f24ac4a762c74c88dfa35c277d63fedc99e4afe9c2a2ff711abb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: allocate\n\nDocumentation:\nAllocate new [command buffers][crate::command::CommandBuffer] from the pool.\n\n# Arguments\n\n* `num` - how many buffers to return\n* `level` - whether to allocate primary or secondary command buffers.\n* `list` - an extendable list of command buffers into which to allocate.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn allocate(&mut self, num: usize, level: Level, list: &mut E)\n where\n E: Extend,\n {\n list.extend((0..num).map(|_| self.allocate_one(level)));\n }\n```"}], "func_name": "allocate", "docstring": "Allocate new [command buffers][crate::command::CommandBuffer] from the pool.\n\n# Arguments\n\n* `num` - how many buffers to return\n* `level` - whether to allocate primary or secondary command buffers.\n* `list` - an extendable list of command buffers into which to allocate.", "repo": "gfx-rs/gfx", "path": "src/hal/src/pool.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/pool.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9b7d0e11b67de78628617ec09dcfa6f617b9ae9e33150713107aaccb61eb995"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new default configuration (color images only).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(width: u32, height: u32, format: Format, image_count: SwapImageIndex) -> Self {\n SwapchainConfig {\n present_mode: PresentMode::FIFO,\n composite_alpha_mode: CompositeAlphaMode::OPAQUE,\n format,\n extent: Extent2D { width, height },\n image_count,\n image_layers: 1,\n image_usage: DEFAULT_USAGE,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new default configuration (color images only).", "repo": "gfx-rs/gfx", "path": "src/hal/src/window.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/window.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f50059e77cd656226d2608adfeb9e8a7ced26ed9fff91d28a2350637c6f86f8d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: framebuffer_attachment\n\nDocumentation:\nReturn the framebuffer attachment corresponding to the swapchain image views.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn framebuffer_attachment(&self) -> image::FramebufferAttachment {\n image::FramebufferAttachment {\n usage: self.image_usage,\n view_caps: image::ViewCapabilities::empty(),\n format: self.format,\n }\n }\n```"}], "func_name": "framebuffer_attachment", "docstring": "Return the framebuffer attachment corresponding to the swapchain image views.", "repo": "gfx-rs/gfx", "path": "src/hal/src/window.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/window.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7fc849d9609159f11cfb59827cc5a062ab940004e678f4d831bdf922ea5ebe29"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_caps\n\nDocumentation:\nCreate a swapchain configuration based on the capabilities\nreturned from a physical device query. If the surface does not\nspecify a current size, default_extent is clamped and used instead.\n\nThe default values are taken from `DEFAULT_USAGE` and `DEFAULT_IMAGE_COUNT`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_caps(caps: &SurfaceCapabilities, format: Format, default_extent: Extent2D) -> Self {\n let composite_alpha_mode = if caps\n .composite_alpha_modes\n .contains(CompositeAlphaMode::INHERIT)\n {\n CompositeAlphaMode::INHERIT\n } else if caps\n .composite_alpha_modes\n .contains(CompositeAlphaMode::OPAQUE)\n {\n CompositeAlphaMode::OPAQUE\n } else {\n panic!(\"neither INHERIT or OPAQUE CompositeAlphaMode(s) are supported\")\n };\n let present_mode = if caps.present_modes.contains(PresentMode::MAILBOX) {\n PresentMode::MAILBOX\n } else if caps.present_modes.contains(PresentMode::FIFO) {\n PresentMode::FIFO\n } else {\n panic!(\"FIFO PresentMode is not supported\")\n };\n\n SwapchainConfig {\n present_mode,\n composite_alpha_mode,\n format,\n extent: caps.clamped_extent(default_extent),\n image_count: DEFAULT_IMAGE_COUNT\n .max(*caps.image_count.start())\n .min(*caps.image_count.end()),\n image_layers: 1,\n image_usage: DEFAULT_USAGE,\n }\n }\n```"}], "func_name": "from_caps", "docstring": "Create a swapchain configuration based on the capabilities\nreturned from a physical device query. If the surface does not\nspecify a current size, default_extent is clamped and used instead.\n\nThe default values are taken from `DEFAULT_USAGE` and `DEFAULT_IMAGE_COUNT`.", "repo": "gfx-rs/gfx", "path": "src/hal/src/window.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/window.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb12713c3f829e4e4a2645a9872b49bfd238cd0b69b3fe5d9e8a19e9e5167867"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_image_usage\n\nDocumentation:\nSpecify the usage of backbuffer images.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_image_usage(mut self, usage: image::Usage) -> Self {\n self.image_usage = usage;\n self\n }\n```"}], "func_name": "with_image_usage", "docstring": "Specify the usage of backbuffer images.", "repo": "gfx-rs/gfx", "path": "src/hal/src/window.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/window.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8f4505199b098bdf8855ed372a3d7d9d0bb083f2c84632760610106c9a4e5bae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_image_count\n\nDocumentation:\nSpecify the count of backbuffer image.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_image_count(mut self, count: SwapImageIndex) -> Self {\n self.image_count = count;\n self\n }\n```"}], "func_name": "with_image_count", "docstring": "Specify the count of backbuffer image.", "repo": "gfx-rs/gfx", "path": "src/hal/src/window.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/window.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d3b6e92f53015b0bef5d87cdda94c822872815b4df80a44ee121411090a737f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: begin_primary\n\nDocumentation:\nBegins recording a primary command buffer\n(that has no inheritance information).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn begin_primary(&mut self, flags: CommandBufferFlags) {\n self.begin(flags, CommandBufferInheritanceInfo::default());\n }\n```"}], "func_name": "begin_primary", "docstring": "Begins recording a primary command buffer\n(that has no inheritance information).", "repo": "gfx-rs/gfx", "path": "src/hal/src/command/mod.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/command/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "38ee74ba7cde4c72722b4e38c7ef1939360cf2f69808810eca9330a8db4b212d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: allocate_one\n\nDocumentation:\nAllocate a descriptor set from the pool.\n\nThe descriptor set will be allocated from the pool according to the corresponding set layout. However,\nspecific descriptors must still be written to the set before use using a [`DescriptorSetWrite`] or\n[`DescriptorSetCopy`].\n\nDescriptors will become invalid once the pool is reset. Usage of invalidated descriptor sets results\nin undefined behavior.\n\n[`DescriptorSetWrite`]: struct.DescriptorSetWrite.html\n[`DescriptorSetCopy`]: struct.DescriptorSetCopy.html\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn allocate_one(\n &mut self,\n layout: &B::DescriptorSetLayout,\n ) -> Result {\n let mut result = PseudoVec(None);\n self.allocate(iter::once(layout), &mut result)?;\n Ok(result.0.unwrap())\n }\n```"}], "func_name": "allocate_one", "docstring": "Allocate a descriptor set from the pool.\n\nThe descriptor set will be allocated from the pool according to the corresponding set layout. However,\nspecific descriptors must still be written to the set before use using a [`DescriptorSetWrite`] or\n[`DescriptorSetCopy`].\n\nDescriptors will become invalid once the pool is reset. Usage of invalidated descriptor sets results\nin undefined behavior.\n\n[`DescriptorSetWrite`]: struct.DescriptorSetWrite.html\n[`DescriptorSetCopy`]: struct.DescriptorSetCopy.html", "repo": "gfx-rs/gfx", "path": "src/hal/src/pso/descriptor.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/pso/descriptor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f708c739680b5182dceae7964b4761750e7cee4ffb7b496bffabd920c3956b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: allocate\n\nDocumentation:\nAllocate multiple descriptor sets from the pool.\n\nThe descriptor set will be allocated from the pool according to the corresponding set layout. However,\nspecific descriptors must still be written to the set before use using a [`DescriptorSetWrite`] or\n[`DescriptorSetCopy`].\n\nEach descriptor set will be allocated from the pool according to the corresponding set layout.\nDescriptors will become invalid once the pool is reset. Usage of invalidated descriptor sets results\nin undefined behavior.\n\n[`DescriptorSetWrite`]: struct.DescriptorSetWrite.html\n[`DescriptorSetCopy`]: struct.DescriptorSetCopy.html\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn allocate<'a, I, E>(&mut self, layouts: I, list: &mut E) -> Result<(), AllocationError>\n where\n I: Iterator,\n E: Extend,\n {\n for layout in layouts {\n let set = self.allocate_one(layout)?;\n list.extend(iter::once(set));\n }\n Ok(())\n }\n```"}], "func_name": "allocate", "docstring": "Allocate multiple descriptor sets from the pool.\n\nThe descriptor set will be allocated from the pool according to the corresponding set layout. However,\nspecific descriptors must still be written to the set before use using a [`DescriptorSetWrite`] or\n[`DescriptorSetCopy`].\n\nEach descriptor set will be allocated from the pool according to the corresponding set layout.\nDescriptors will become invalid once the pool is reset. Usage of invalidated descriptor sets results\nin undefined behavior.\n\n[`DescriptorSetWrite`]: struct.DescriptorSetWrite.html\n[`DescriptorSetCopy`]: struct.DescriptorSetCopy.html", "repo": "gfx-rs/gfx", "path": "src/hal/src/pso/descriptor.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/pso/descriptor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82655db562804ad26c0a1522606a5932ce5efbf4b935bca76f22e35953868dee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_uint\n\nDocumentation:\nGet the numeric representation of the rate\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_uint(&self) -> u8 {\n match *self {\n VertexInputRate::Vertex => 0,\n VertexInputRate::Instance(divisor) => divisor,\n }\n }\n```"}], "func_name": "as_uint", "docstring": "Get the numeric representation of the rate", "repo": "gfx-rs/gfx", "path": "src/hal/src/pso/input_assembler.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/pso/input_assembler.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "934fd1092b582e291a00fd4c23afa1c02a3e50c836ceb7bbaa6cdbb59dec2683"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: static_or\n\nDocumentation:\nReturns the static value or a default.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn static_or(self, default: T) -> T {\n match self {\n State::Static(v) => v,\n State::Dynamic => default,\n }\n }\n```"}], "func_name": "static_or", "docstring": "Returns the static value or a default.", "repo": "gfx-rs/gfx", "path": "src/hal/src/pso/mod.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/pso/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a813c1a3d4fb8fba121098df7fb4bbbe1b03d17620b51d46802783fa71cf7c0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new `Sided` structure with both `front` and `back` holding\nthe same value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(value: T) -> Self {\n Sided {\n front: value,\n back: value,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new `Sided` structure with both `front` and `back` holding\nthe same value.", "repo": "gfx-rs/gfx", "path": "src/hal/src/pso/output_merger.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/pso/output_merger.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c8e19a96f7609359d1369e2c071095f2a87c5d5115d6dc6489f3ca621f553fb5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: uses_depth\n\nDocumentation:\nReturns true if the descriptor assumes the depth attachment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn uses_depth(&self) -> bool {\n self.depth.is_some() || self.depth_bounds\n }\n```"}], "func_name": "uses_depth", "docstring": "Returns true if the descriptor assumes the depth attachment.", "repo": "gfx-rs/gfx", "path": "src/hal/src/pso/output_merger.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/pso/output_merger.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4390fb41f64e6d60267a03b604e2df50c013859ea4d4904143368e085a62cbac"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new, empty queue group for a queue family.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(family: QueueFamilyId) -> Self {\n QueueGroup {\n family,\n queues: Vec::new(),\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new, empty queue group for a queue family.", "repo": "gfx-rs/gfx", "path": "src/hal/src/queue/family.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/queue/family.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27043039b34a7b6b5e2155cb5709e9873388635adf1c09f493d51da92da74125"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: supports_graphics\n\nDocumentation:\nReturns true if the queue supports graphics operations.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn supports_graphics(&self) -> bool {\n match *self {\n QueueType::General | QueueType::Graphics => true,\n QueueType::Compute | QueueType::Transfer => false,\n }\n }\n```"}], "func_name": "supports_graphics", "docstring": "Returns true if the queue supports graphics operations.", "repo": "gfx-rs/gfx", "path": "src/hal/src/queue/mod.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/queue/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d611207adc5b45720084841120c6bd4ac03b8da34dd8ceda69d93300c615f4a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: supports_compute\n\nDocumentation:\nReturns true if the queue supports compute operations.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn supports_compute(&self) -> bool {\n match *self {\n QueueType::General | QueueType::Graphics | QueueType::Compute => true,\n QueueType::Transfer => false,\n }\n }\n```"}], "func_name": "supports_compute", "docstring": "Returns true if the queue supports compute operations.", "repo": "gfx-rs/gfx", "path": "src/hal/src/queue/mod.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/queue/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a96bb6f1c2366a3b37f9f1a0f8b9501bbf158e7cd4114bf9942aaca613d778fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bind_sparse\n\nDocumentation:\nSparse memory bind operation.\n\n# Arguments\n\n* `info` - information about the memory bindings.\n\n# Safety\n\n- Defining memory as `None` will cause undefined behaviour when the\ntile is read or written from in some hardware.\n- The memory regions provided are not checked to be valid and matching\nof the sparse resource type.\n- If extents are not a multiple of the block size, additional space will be\nbound, and accessing memory is unsafe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn bind_sparse<'a, Iw, Is, Ibi, Ib, Iii, Io, Ii>(\n &mut self,\n _wait_semaphores: Iw,\n _signal_semaphores: Is,\n _buffer_memory_binds: Ib,\n _image_opaque_memory_binds: Io,\n _image_memory_binds: Ii,\n _device: &B::Device,\n _fence: Option<&B::Fence>,\n ) where\n Ibi: Iterator>,\n Ib: Iterator,\n Iii: Iterator>,\n Io: Iterator,\n Ii: Iterator,\n Iw: Iterator,\n Is: Iterator,\n {\n unimplemented!()\n }\n```"}], "func_name": "bind_sparse", "docstring": "Sparse memory bind operation.\n\n# Arguments\n\n* `info` - information about the memory bindings.\n\n# Safety\n\n- Defining memory as `None` will cause undefined behaviour when the\ntile is read or written from in some hardware.\n- The memory regions provided are not checked to be valid and matching\nof the sparse resource type.\n- If extents are not a multiple of the block size, additional space will be\nbound, and accessing memory is unsafe.", "repo": "gfx-rs/gfx", "path": "src/hal/src/queue/mod.rs", "url": "https://github.com/gfx-rs/gfx/blob/master/src/hal/src/queue/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1fe184b2e6764a84a037c28421a2b89be25e307c90f0c5fb595625385836713f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nread version at compile time from env variables\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new() -> Self {\n let mut res = Self::default();\n let major_str = env!(\"CARGO_PKG_VERSION_MAJOR\");\n if let Ok(major) = major_str.parse::() {\n res.major = major;\n }\n let minor_str = env!(\"CARGO_PKG_VERSION_MINOR\");\n if let Ok(minor) = minor_str.parse::() {\n res.minor = minor;\n }\n let patch_str = env!(\"CARGO_PKG_VERSION_PATCH\");\n if let Ok(patch) = patch_str.parse::() {\n res.patch = patch;\n }\n let pre_str = env!(\"CARGO_PKG_VERSION_PRE\");\n res.pre = if pre_str.is_empty() {\n None\n } else {\n Some(pre_str.to_string())\n };\n res\n }\n```"}], "func_name": "new", "docstring": "read version at compile time from env variables", "repo": "TaKO8Ki/gobang", "path": "src/version.rs", "url": "https://github.com/TaKO8Ki/gobang/blob/master/src/version.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5a5084fec31a157d3f96aeb0df5d4862f4f94b8087f6bc6523028ee293af4670"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: debug_delay\n\nDocumentation:\nThis function is useful for inducing random jitter into\nour atomic operations, shaking out more possible\ninterleavings quickly. It gets fully eliminated by the\ncompiler in non-test code.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn debug_delay() {\n #[cfg(feature = \"runtime_validation\")]\n {\n use std::thread;\n use std::time::Duration;\n\n use rand::{thread_rng, Rng};\n\n let mut rng = thread_rng();\n\n match rng.gen_range(0..100) {\n 0..=90 => thread::yield_now(),\n _ => thread::sleep(Duration::from_millis(5)),\n }\n }\n}\n```"}], "func_name": "debug_delay", "docstring": "This function is useful for inducing random jitter into\nour atomic operations, shaking out more possible\ninterleavings quickly. It gets fully eliminated by the\ncompiler in non-test code.", "repo": "komora-io/marble", "path": "src/debug_delay.rs", "url": "https://github.com/komora-io/marble/blob/master/src/debug_delay.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1955b9eb5689933cf495bb03fcb25ab7b123489c7f6b04ac302211d7251980d6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stats\n\nDocumentation:\nReturns the counts of (files, total file size, total stored objects, live objects)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn stats(&self) -> (usize, u64, u64, u64) {\n let mut live_objects = 0;\n let mut stored_objects = 0;\n\n let mut fams_len = 0;\n let mut total_file_size = 0;\n for (_, fam) in &self.fams {\n if let Some(metadata) = fam.metadata() {\n fams_len += 1;\n total_file_size += metadata.file_size;\n live_objects += fam.live_objects.load(SeqCst);\n stored_objects += metadata.present_objects;\n }\n }\n\n (fams_len, total_file_size, stored_objects, live_objects)\n }\n```"}], "func_name": "stats", "docstring": "Returns the counts of (files, total file size, total stored objects, live objects)", "repo": "komora-io/marble", "path": "src/file_map.rs", "url": "https://github.com/komora-io/marble/blob/master/src/file_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be63a330a9110f948dd6d04f995e26cc9be5a33180674c4bc34604ed4e93d0af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: maintenance\n\nDocumentation:\nDefragments backing storage files, blocking\nconcurrent calls to `write_batch` but not\nblocking concurrent calls to `read`. Returns the\nnumber of rewritten objects.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn maintenance(&self) -> io::Result {\n log::debug!(\"performing maintenance\");\n\n let (files_to_defrag, claims): (Map>, _) =\n self.file_map.files_to_defrag(&self.config)?;\n\n // use this old_locations Map in the outer loop to reuse the\n // allocation and avoid resizing as often.\n let mut old_locations: Map = Map::default();\n\n let mut rewritten_objects = 0;\n\n // rewrite the live objects\n for (generation, file_to_defrag) in files_to_defrag {\n log::trace!(\n \"compacting files {:?} with generation {}\",\n file_to_defrag,\n generation\n );\n\n if file_to_defrag.len() < self.config.min_compaction_files {\n // skip batch with too few files (claims\n // auto-released by Drop of DeferUnclaim\n continue;\n }\n\n let mut batch = Map::default();\n let mut rewritten_fam_locations = vec![];\n\n for fam in file_to_defrag {\n log::trace!(\n \"rewriting any surviving objects in file at location {:?}\",\n fam.location\n );\n rewritten_fam_locations.push(fam.location);\n let metadata: &crate::Metadata = fam\n .metadata()\n .expect(\"anything being defragged should have metadata already set\");\n\n let path: &std::path::PathBuf = fam.path().unwrap();\n\n // TODO handle trailer read using full buf\n let file_buf = read_range_at(&fam.file, 0, metadata.file_size)?;\n\n let trailer = read_trailer_from_buf(\n &file_buf[usize::try_from(metadata.trailer_offset).unwrap()..],\n )?;\n\n let mut buf_reader = std::io::Cursor::new(file_buf);\n\n let mut offset = 0_u64;\n\n while offset < metadata.trailer_offset {\n let mut header = [0_u8; HEADER_LEN];\n buf_reader.read_exact(&mut header)?;\n\n let crc_expected: [u8; 4] = header[0..4].try_into().unwrap();\n let pid_buf = header[4..12].try_into().unwrap();\n let object_id = u64::from_le_bytes(pid_buf);\n let len_buf = header[12..20].try_into().unwrap();\n let len = usize::try_from(u64::from_le_bytes(len_buf)).unwrap();\n\n if len >= self.config.max_object_size {\n log::warn!(\"corrupt object size detected: {} bytes\", len);\n return Err(io::Error::new(\n io::ErrorKind::InvalidData,\n \"corrupt object size or configured max_object_size has gone down \\\n since this object was written\",\n ));\n }\n\n let current_location = self\n .location_table\n .load(object_id)\n .expect(\"anything being rewritten should exist in the location table\");\n\n let rewritten_location =\n RelativeDiskLocation::new(offset, false).to_absolute(fam.location.lsn());\n\n // all objects present before the trailer are not deletes\n let mut object_buf = uninit_boxed_slice(len);\n\n buf_reader.read_exact(&mut object_buf)?;\n\n let crc_actual = hash(len_buf, pid_buf, &object_buf);\n\n if crc_expected != crc_actual {\n log::error!(\n \"crc mismatch when reading object {} at offset {} in file {:?} - \\\n expected {:?} actual {:?}\",\n object_id,\n offset,\n path,\n crc_expected,\n crc_actual,\n );\n return Err(annotate!(io::Error::new(\n io::ErrorKind::InvalidData,\n \"crc mismatch in maintenance routine\",\n )));\n }\n\n if rewritten_location == current_location {\n // can attempt to rewrite\n log::trace!(\n \"rewriting object {object_id} at rewritten location \\\n {rewritten_location:?}\"\n );\n batch.insert(object_id, Some(object_buf));\n old_locations.insert(object_id, rewritten_location);\n } else {\n log::trace!(\n \"not rewriting object {object_id}, as the location being defragmented \\\n {rewritten_location:?} does not match the current location in the \\\n location table {current_location:?}\"\n );\n }\n\n offset += (HEADER_LEN + len) as u64;\n }\n\n log::trace!(\n \"trying to read trailer at file for lsn {} offset {} items\",\n metadata.trailer_offset,\n fam.location.lsn(),\n );\n\n for (object_id, relative_location) in trailer {\n if relative_location.is_delete() {\n let rewritten_location = relative_location.to_absolute(fam.location.lsn());\n let current_location = self\n .location_table\n .load(object_id)\n .expect(\"anything being rewritten should exist in the location table\");\n\n if rewritten_location == current_location {\n // can attempt to rewrite\n log::trace!(\n \"rewriting object {object_id} at rewritten location \\\n {rewritten_location:?}\"\n );\n batch.insert(object_id, None);\n old_locations.insert(object_id, rewritten_location);\n } else {\n log::trace!(\n \"not rewriting object {object_id}, as the location being \\\n defragmented {rewritten_location:?} does not match the current \\\n location in the location table {current_location:?}\"\n );\n }\n }\n }\n }\n\n rewritten_objects += batch.len();\n\n log::trace!(\"{rewritten_objects}, {}\", batch.len());\n\n self.shard_batch(batch, generation, &old_locations)?;\n old_locations.clear();\n\n self.file_map\n .verify_files_uninhabited(&rewritten_fam_locations, &self.location_table);\n }\n\n drop(claims);\n\n self.prune_empty_files()?;\n\n Ok(rewritten_objects)\n }\n```"}], "func_name": "maintenance", "docstring": "Defragments backing storage files, blocking\nconcurrent calls to `write_batch` but not\nblocking concurrent calls to `read`. Returns the\nnumber of rewritten objects.", "repo": "komora-io/marble", "path": "src/gc.rs", "url": "https://github.com/komora-io/marble/blob/master/src/gc.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e35e831ec1be7725ba18b0cdfc8aff74ee767609da00c887e27dfc4a7d8ee8bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_partition_function\n\nDocumentation:\nShard based on rough size ranges corresponding to SSD\npage and block sizes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn default_partition_function(_object_id: u64, size: usize) -> u8 {\n const SUBPAGE_MAX: usize = PAGE_MIN - 1;\n const PAGE_MIN: usize = 2048;\n const PAGE_MAX: usize = 16 * 1024;\n const BLOCK_MIN: usize = PAGE_MAX + 1;\n const BLOCK_MAX: usize = 4 * 1024 * 1024;\n\n match size {\n // items smaller than known SSD page sizes go to shard 0\n 0..=SUBPAGE_MAX => 0,\n // items that fall roughly within the range of SSD page sizes go to shard 1\n PAGE_MIN..=PAGE_MAX => 1,\n // items that fall roughly within the size of an SSD block go to shard 2\n BLOCK_MIN..=BLOCK_MAX => 2,\n // large items that are larger than typical SSD block sizes go to shard 3\n _ => 3,\n }\n}\n```"}], "func_name": "default_partition_function", "docstring": "Shard based on rough size ranges corresponding to SSD\npage and block sizes", "repo": "komora-io/marble", "path": "src/lib.rs", "url": "https://github.com/komora-io/marble/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e0f9390b82833a73693bb8c9e3b56d7007e411f727e27484e723edf29974be6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open\n\nDocumentation:\nOpen the system with default configuration at the\nprovided path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn open>(path: P) -> io::Result {\n let config = Config {\n path: path.as_ref().into(),\n ..Config::default()\n };\n\n config.open()\n}\n```"}], "func_name": "open", "docstring": "Open the system with default configuration at the\nprovided path.", "repo": "komora-io/marble", "path": "src/lib.rs", "url": "https://github.com/komora-io/marble/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fb80b108d55e31318a8b14fd1fc6ea577efcaf794f0d46f6a67ae0acbffe7542"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sync_all\n\nDocumentation:\nIf `Config::fsync_each_batch` is `false`, this\nmethod can be called at a desired interval to\nensure that the written batches are durable on\ndisk.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sync_all(&self) -> io::Result<()> {\n let synced_files = self.file_map.sync_all()?;\n if synced_files {\n fallible!(self.directory_lock.sync_all());\n }\n Ok(())\n }\n```"}], "func_name": "sync_all", "docstring": "If `Config::fsync_each_batch` is `false`, this\nmethod can be called at a desired interval to\nensure that the written batches are durable on\ndisk.", "repo": "komora-io/marble", "path": "src/lib.rs", "url": "https://github.com/komora-io/marble/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d64d24ef43c497b25d54de7a2152d88c88b2c5a2fb575de12fe81dc2f9b6fd1c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: free_object_ids\n\nDocumentation:\nIntended for use in recovery, to bootstrap a higher level object ID allocator.\n\nReturns a tuple of 1 higher than the current max allocated object ID,\nand an iterator over all object IDs beneath that which are\ncurrently deleted (due to being stored as a `None` in a write batch).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn free_object_ids<'a>(&'a self) -> (u64, impl 'a + Iterator) {\n let max = self.max_object_id.load(Acquire);\n\n let iter = (0..=max).filter_map(|oid| {\n if self.location_table.load(oid).is_none() {\n Some(oid)\n } else {\n None\n }\n });\n (max + 1, iter)\n }\n```"}], "func_name": "free_object_ids", "docstring": "Intended for use in recovery, to bootstrap a higher level object ID allocator.\n\nReturns a tuple of 1 higher than the current max allocated object ID,\nand an iterator over all object IDs beneath that which are\ncurrently deleted (due to being stored as a `None` in a write batch).", "repo": "komora-io/marble", "path": "src/lib.rs", "url": "https://github.com/komora-io/marble/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f63976db3d1e356504f0abbc623e2a047c191442e978573ac41e23559dd61ea7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: allocated_object_ids\n\nDocumentation:\nReturns an Iterator over all currently allocated object IDs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn allocated_object_ids<'a>(&'a self) -> impl 'a + Iterator {\n let max = self.max_object_id.load(Acquire);\n (0..=max).filter_map(|oid| {\n if self.location_table.load(oid).is_some() {\n Some(oid)\n } else {\n None\n }\n })\n }\n```"}], "func_name": "allocated_object_ids", "docstring": "Returns an Iterator over all currently allocated object IDs.", "repo": "komora-io/marble", "path": "src/lib.rs", "url": "https://github.com/komora-io/marble/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0a76db80206a25de28360f3845755a9fe27ad5dffd8bb87b2638817d3062c71c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read\n\nDocumentation:\nRead a object out of storage. If this object is\nunknown or has been removed, returns `Ok(None)`.\nIf there is an IO problem, returns Err.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read(&self, object_id: ObjectId) -> io::Result>> {\n let location = if let Some(location) = self.location_table.load(object_id) {\n location\n } else {\n return Ok(None);\n };\n\n if location.is_delete() {\n return Ok(None);\n }\n\n let fam = self.file_map.fam_for_location(location);\n\n let file_offset = location.lsn() - fam.location.lsn();\n\n let mut header_buf = [0_u8; HEADER_LEN];\n fallible!(fam.file.read_exact_at(&mut header_buf, file_offset));\n\n let crc_expected: [u8; 4] = header_buf[0..4].try_into().unwrap();\n let pid_buf: [u8; 8] = header_buf[4..12].try_into().unwrap();\n let len_buf: [u8; 8] = header_buf[12..].try_into().unwrap();\n\n let len: usize = if let Ok(len) = u64::from_le_bytes(len_buf).try_into() {\n len\n } else {\n return Err(io::Error::new(\n io::ErrorKind::Other,\n \"corrupted length detected\",\n ));\n };\n\n let mut read_buf: Box<[u8]> = uninit_boxed_slice(len);\n\n let object_offset = file_offset + HEADER_LEN as u64;\n fallible!(fam.file.read_exact_at(&mut read_buf, object_offset));\n\n let crc_actual = hash(len_buf, pid_buf, &read_buf);\n\n if crc_expected != crc_actual {\n log::warn!(\n \"crc mismatch when reading object at offset {} in file {:?}\",\n object_offset,\n file_offset\n );\n return Err(annotate!(io::Error::new(\n io::ErrorKind::InvalidData,\n \"crc mismatch\",\n )));\n }\n\n let read_pid = u64::from_le_bytes(pid_buf);\n\n assert_eq!(object_id, read_pid);\n\n self.bytes_read\n .fetch_add(read_buf.len() as u64, Ordering::Relaxed);\n\n Ok(Some(read_buf))\n }\n```"}], "func_name": "read", "docstring": "Read a object out of storage. If this object is\nunknown or has been removed, returns `Ok(None)`.\nIf there is an IO problem, returns Err.", "repo": "komora-io/marble", "path": "src/readpath.rs", "url": "https://github.com/komora-io/marble/blob/master/src/readpath.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b26d04dc41fc2a8d802aa63bb23326d2c84d82e400ae687285df35a1d2db3ed9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: verify_batches\n\nDocumentation:\nVerifies that the keys in the tree are correctly\nrecovered (i.e., equal). Panics if they don't match up.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn verify_batches(m: &Marble) {\n let values: Vec>> = (0..BATCH_SIZE as u64)\n .chain(once(u64::MAX))\n .map(|i| {\n let object_id = i;\n m.read(object_id).unwrap()\n })\n .collect();\n let equal = values.windows(2).all(|w| w[0] == w[1]);\n log::debug!(\"values: {:?}\", values);\n\n assert!(equal, \"values not equal: {:?}\", values);\n}\n```"}], "func_name": "verify_batches", "docstring": "Verifies that the keys in the tree are correctly\nrecovered (i.e., equal). Panics if they don't match up.", "repo": "komora-io/marble", "path": "tests/crash_atomicity.rs", "url": "https://github.com/komora-io/marble/blob/master/tests/crash_atomicity.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f0a77842ace0af448945c30a2950ed08b3af8a8f8ec4c8c03bcaf0825ee9e65"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: magic_replacer\n\nDocumentation:\nReplaces `Context` and `ServerConfig` with a correct code.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn magic_replacer(\n req_var: Ident,\n reply_var: Ident,\n imports: Arc,\n) -> impl VisitMut {\n MagicReplacer {\n req_var,\n reply_var,\n imports,\n }\n}\n```"}], "func_name": "magic_replacer", "docstring": "Replaces `Context` and `ServerConfig` with a correct code.", "repo": "fnapi/fnapi", "path": "crates/fnapi-compiler/src/file_compiler/magic_replacer.rs", "url": "https://github.com/fnapi/fnapi/blob/master/crates/fnapi-compiler/src/file_compiler/magic_replacer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "725f672de2e7c0ccb67f79e0b4530bba2eacf7da9b3afe9a10dcd983dd2866cb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start\n\nDocumentation:\nCreate a [TypeServer] for valid typescript types using typescript files\nin tests/type_server/valid\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn start() -> Arc {\n TypeServer::start(&InputFiles::Files(vec![\"tests/type_server/valid/simple.\\\n ts\"\n .into()]))\n .await\n .unwrap()\n }\n```"}], "func_name": "start", "docstring": "Create a [TypeServer] for valid typescript types using typescript files\nin tests/type_server/valid", "repo": "fnapi/fnapi", "path": "crates/fnapi-compiler/src/type_server/tests.rs", "url": "https://github.com/fnapi/fnapi/blob/master/crates/fnapi-compiler/src/type_server/tests.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a9067c791c1d3245f1230cb03854bbd2af63ae54532a2935836c4e794de769a2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: api_pkg_src_dir\n\nDocumentation:\nCompiles `@fnapi/api` package and returns the path to it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn api_pkg_src_dir() -> Arc {\n static DIR: Lazy> = Lazy::new(|| {\n let dir = PathBuf::from(env::var(\"CARGO_MANIFEST_DIR\").unwrap())\n .parent()\n .unwrap()\n .parent()\n .unwrap()\n .join(\"packages\")\n .join(\"api\");\n\n let mut cmd = std::process::Command::new(\"yarn\");\n cmd.current_dir(&dir).arg(\"run\").arg(\"build:tsc\");\n let _status = cmd.status().expect(\"failed to compile api package\");\n // assert!(status.success());\n\n Arc::new(dir.join(\"src\"))\n });\n\n DIR.clone()\n}\n```"}], "func_name": "api_pkg_src_dir", "docstring": "Compiles `@fnapi/api` package and returns the path to it.", "repo": "fnapi/fnapi", "path": "crates/fnapi-compiler/tests/project.rs", "url": "https://github.com/fnapi/fnapi/blob/master/crates/fnapi-compiler/tests/project.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c331f4fc41d8b6edc6372ee12dfe7ddd5b1d9a88b2565ff2e08207a4c65daa6b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_unchecked\n\nDocumentation:\nGet the reference to the underlying value, without checking if the cell\nis initialized.\n\n# Safety\n\nCaller must ensure that the cell is in initialized state, and that\nthe contents are acquired by (synchronized to) this thread.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) unsafe fn get_unchecked(&self) -> &T {\n debug_assert!(self.is_initialized());\n // SAFETY: The caller ensures that the value is initialized and access synchronized.\n self.value.borrow(CriticalSection::new()).get().unwrap_unchecked()\n }\n```"}], "func_name": "get_unchecked", "docstring": "Get the reference to the underlying value, without checking if the cell\nis initialized.\n\n# Safety\n\nCaller must ensure that the cell is in initialized state, and that\nthe contents are acquired by (synchronized to) this thread.", "repo": "matklad/once_cell", "path": "src/imp_cs.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/imp_cs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc7a9c9acbf4d339469041811df123de9699fa1df43cf1a99118f1ca3ff0deed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_mut\n\nDocumentation:\nGets the mutable reference to the underlying value.\nReturns `None` if the cell is empty.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn get_mut(&mut self) -> Option<&mut T> {\n // Safe b/c we have an exclusive access\n let slot: &mut Option = unsafe { &mut *self.value.get() };\n slot.as_mut()\n }\n```"}], "func_name": "get_mut", "docstring": "Gets the mutable reference to the underlying value.\nReturns `None` if the cell is empty.", "repo": "matklad/once_cell", "path": "src/imp_pl.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/imp_pl.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "30163e36443299123aedd1d44530d811ba225c6855279319a10db89ae03ff330"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set\n\nDocumentation:\nSets the contents of this cell to `value`.\n\nReturns `Ok(())` if the cell was empty and `Err(value)` if it was\nfull.\n\n# Example\n```\nuse once_cell::unsync::OnceCell;\n\nlet cell = OnceCell::new();\nassert!(cell.get().is_none());\n\nassert_eq!(cell.set(92), Ok(()));\nassert_eq!(cell.set(62), Err(62));\n\nassert!(cell.get().is_some());\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set(&self, value: T) -> Result<(), T> {\n match self.try_insert(value) {\n Ok(_) => Ok(()),\n Err((_, value)) => Err(value),\n }\n }\n```"}], "func_name": "set", "docstring": "Sets the contents of this cell to `value`.\n\nReturns `Ok(())` if the cell was empty and `Err(value)` if it was\nfull.\n\n# Example\n```\nuse once_cell::unsync::OnceCell;\n\nlet cell = OnceCell::new();\nassert!(cell.get().is_none());\n\nassert_eq!(cell.set(92), Ok(()));\nassert_eq!(cell.set(62), Err(62));\n\nassert!(cell.get().is_some());\n```", "repo": "matklad/once_cell", "path": "src/lib.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "692c90cee69a5db27cb81a0279984a0613ddf42cc9513c3063c5a0f27a79bc41"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_insert\n\nDocumentation:\nLike [`set`](Self::set), but also returns a reference to the final cell value.\n\n# Example\n```\nuse once_cell::unsync::OnceCell;\n\nlet cell = OnceCell::new();\nassert!(cell.get().is_none());\n\nassert_eq!(cell.try_insert(92), Ok(&92));\nassert_eq!(cell.try_insert(62), Err((&92, 62)));\n\nassert!(cell.get().is_some());\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {\n if let Some(old) = self.get() {\n return Err((old, value));\n }\n\n let slot = unsafe { &mut *self.inner.get() };\n // This is the only place where we set the slot, no races\n // due to reentrancy/concurrency are possible, and we've\n // checked that slot is currently `None`, so this write\n // maintains the `inner`'s invariant.\n *slot = Some(value);\n Ok(unsafe { slot.as_ref().unwrap_unchecked() })\n }\n```"}], "func_name": "try_insert", "docstring": "Like [`set`](Self::set), but also returns a reference to the final cell value.\n\n# Example\n```\nuse once_cell::unsync::OnceCell;\n\nlet cell = OnceCell::new();\nassert!(cell.get().is_none());\n\nassert_eq!(cell.try_insert(92), Ok(&92));\nassert_eq!(cell.try_insert(62), Err((&92, 62)));\n\nassert!(cell.get().is_some());\n```", "repo": "matklad/once_cell", "path": "src/lib.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "781dc43e8e30a47ce845c611fea65c2487bd242f1560edd02785a8cda0e1c659"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_or_init\n\nDocumentation:\nGets the contents of the cell, initializing it with `f`\nif the cell was empty.\n\n# Panics\n\nIf `f` panics, the panic is propagated to the caller, and the cell\nremains uninitialized.\n\nIt is an error to reentrantly initialize the cell from `f`. Doing\nso results in a panic.\n\n# Example\n```\nuse once_cell::unsync::OnceCell;\n\nlet cell = OnceCell::new();\nlet value = cell.get_or_init(|| 92);\nassert_eq!(value, &92);\nlet value = cell.get_or_init(|| unreachable!());\nassert_eq!(value, &92);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_or_init(&self, f: F) -> &T\n where\n F: FnOnce() -> T,\n {\n enum Void {}\n match self.get_or_try_init(|| Ok::(f())) {\n Ok(val) => val,\n Err(void) => match void {},\n }\n }\n```"}], "func_name": "get_or_init", "docstring": "Gets the contents of the cell, initializing it with `f`\nif the cell was empty.\n\n# Panics\n\nIf `f` panics, the panic is propagated to the caller, and the cell\nremains uninitialized.\n\nIt is an error to reentrantly initialize the cell from `f`. Doing\nso results in a panic.\n\n# Example\n```\nuse once_cell::unsync::OnceCell;\n\nlet cell = OnceCell::new();\nlet value = cell.get_or_init(|| 92);\nassert_eq!(value, &92);\nlet value = cell.get_or_init(|| unreachable!());\nassert_eq!(value, &92);\n```", "repo": "matklad/once_cell", "path": "src/lib.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a245ec266c91a660bcb06553a1187bfecb6d054344c395b945908af031d8aa3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_or_try_init\n\nDocumentation:\nGets the contents of the cell, initializing it with `f` if\nthe cell was empty. If the cell was empty and `f` failed, an\nerror is returned.\n\n# Panics\n\nIf `f` panics, the panic is propagated to the caller, and the cell\nremains uninitialized.\n\nIt is an error to reentrantly initialize the cell from `f`. Doing\nso results in a panic.\n\n# Example\n```\nuse once_cell::unsync::OnceCell;\n\nlet cell = OnceCell::new();\nassert_eq!(cell.get_or_try_init(|| Err(())), Err(()));\nassert!(cell.get().is_none());\nlet value = cell.get_or_try_init(|| -> Result {\nOk(92)\n});\nassert_eq!(value, Ok(&92));\nassert_eq!(cell.get(), Some(&92))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_or_try_init(&self, f: F) -> Result<&T, E>\n where\n F: FnOnce() -> Result,\n {\n if let Some(val) = self.get() {\n return Ok(val);\n }\n let val = f()?;\n // Note that *some* forms of reentrant initialization might lead to\n // UB (see `reentrant_init` test). I believe that just removing this\n // `assert`, while keeping `set/get` would be sound, but it seems\n // better to panic, rather than to silently use an old value.\n assert!(self.set(val).is_ok(), \"reentrant init\");\n Ok(unsafe { self.get().unwrap_unchecked() })\n }\n```"}], "func_name": "get_or_try_init", "docstring": "Gets the contents of the cell, initializing it with `f` if\nthe cell was empty. If the cell was empty and `f` failed, an\nerror is returned.\n\n# Panics\n\nIf `f` panics, the panic is propagated to the caller, and the cell\nremains uninitialized.\n\nIt is an error to reentrantly initialize the cell from `f`. Doing\nso results in a panic.\n\n# Example\n```\nuse once_cell::unsync::OnceCell;\n\nlet cell = OnceCell::new();\nassert_eq!(cell.get_or_try_init(|| Err(())), Err(()));\nassert!(cell.get().is_none());\nlet value = cell.get_or_try_init(|| -> Result {\nOk(92)\n});\nassert_eq!(value, Ok(&92));\nassert_eq!(cell.get(), Some(&92))\n```", "repo": "matklad/once_cell", "path": "src/lib.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7805e6dacda3ce4e93ccbaffc69d3f16843465200b85ac7c1c47f21d67a187c3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_inner\n\nDocumentation:\nConsumes the `OnceCell`, returning the wrapped value.\n\nReturns `None` if the cell was empty.\n\n# Examples\n\n```\nuse once_cell::unsync::OnceCell;\n\nlet cell: OnceCell = OnceCell::new();\nassert_eq!(cell.into_inner(), None);\n\nlet cell = OnceCell::new();\ncell.set(\"hello\".to_string()).unwrap();\nassert_eq!(cell.into_inner(), Some(\"hello\".to_string()));\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_inner(self) -> Option {\n // Because `into_inner` takes `self` by value, the compiler statically verifies\n // that it is not currently borrowed. So it is safe to move out `Option`.\n self.inner.into_inner()\n }\n```"}], "func_name": "into_inner", "docstring": "Consumes the `OnceCell`, returning the wrapped value.\n\nReturns `None` if the cell was empty.\n\n# Examples\n\n```\nuse once_cell::unsync::OnceCell;\n\nlet cell: OnceCell = OnceCell::new();\nassert_eq!(cell.into_inner(), None);\n\nlet cell = OnceCell::new();\ncell.set(\"hello\".to_string()).unwrap();\nassert_eq!(cell.into_inner(), Some(\"hello\".to_string()));\n```", "repo": "matklad/once_cell", "path": "src/lib.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f6a06f7b9a89c0931a982e9441508cda5207f8302339feb156f9209ca8a5a55a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new lazy value with the given initializing function.\n\n# Example\n```\n# fn main() {\nuse once_cell::unsync::Lazy;\n\nlet hello = \"Hello, World!\".to_string();\n\nlet lazy = Lazy::new(|| hello.to_uppercase());\n\nassert_eq!(&*lazy, \"HELLO, WORLD!\");\n# }\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn new(init: F) -> Lazy {\n Lazy { cell: OnceCell::new(), init: Cell::new(Some(init)) }\n }\n```"}], "func_name": "new", "docstring": "Creates a new lazy value with the given initializing function.\n\n# Example\n```\n# fn main() {\nuse once_cell::unsync::Lazy;\n\nlet hello = \"Hello, World!\".to_string();\n\nlet lazy = Lazy::new(|| hello.to_uppercase());\n\nassert_eq!(&*lazy, \"HELLO, WORLD!\");\n# }\n```", "repo": "matklad/once_cell", "path": "src/lib.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18826fef83f8f64cc31f2ddd91e0a7a2abc4f52232aa04e9092ba82a95117d17"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_value\n\nDocumentation:\nConsumes this `Lazy` returning the stored value.\n\nReturns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_value(this: Lazy) -> Result {\n let cell = this.cell;\n let init = this.init;\n cell.into_inner().ok_or_else(|| {\n init.take().unwrap_or_else(|| panic!(\"Lazy instance has previously been poisoned\"))\n })\n }\n```"}], "func_name": "into_value", "docstring": "Consumes this `Lazy` returning the stored value.\n\nReturns `Ok(value)` if `Lazy` is initialized and `Err(f)` otherwise.", "repo": "matklad/once_cell", "path": "src/lib.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ed978096b3f3560636c6a6752d8d1052b9a1c8ecfc2e1ccc4aed2238e48e704"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: force\n\nDocumentation:\nForces the evaluation of this lazy value and returns a reference to\nthe result.\n\nThis is equivalent to the `Deref` impl, but is explicit.\n\n# Example\n```\nuse once_cell::unsync::Lazy;\n\nlet lazy = Lazy::new(|| 92);\n\nassert_eq!(Lazy::force(&lazy), &92);\nassert_eq!(&*lazy, &92);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn force(this: &Lazy) -> &T {\n this.cell.get_or_init(|| match this.init.take() {\n Some(f) => f(),\n None => panic!(\"Lazy instance has previously been poisoned\"),\n })\n }\n```"}], "func_name": "force", "docstring": "Forces the evaluation of this lazy value and returns a reference to\nthe result.\n\nThis is equivalent to the `Deref` impl, but is explicit.\n\n# Example\n```\nuse once_cell::unsync::Lazy;\n\nlet lazy = Lazy::new(|| 92);\n\nassert_eq!(Lazy::force(&lazy), &92);\nassert_eq!(&*lazy, &92);\n```", "repo": "matklad/once_cell", "path": "src/lib.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3ac083e81c9fc6815981fff5855ad5cafa14bcd5c97b57d7d5bdd33c88d32bf2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: force_mut\n\nDocumentation:\nForces the evaluation of this lazy value and returns a mutable reference to\nthe result.\n\nThis is equivalent to the `DerefMut` impl, but is explicit.\n\n# Example\n```\nuse once_cell::unsync::Lazy;\n\nlet mut lazy = Lazy::new(|| 92);\n\nassert_eq!(Lazy::force_mut(&mut lazy), &92);\nassert_eq!(*lazy, 92);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn force_mut(this: &mut Lazy) -> &mut T {\n if this.cell.get_mut().is_none() {\n let value = match this.init.get_mut().take() {\n Some(f) => f(),\n None => panic!(\"Lazy instance has previously been poisoned\"),\n };\n this.cell = OnceCell::with_value(value);\n }\n this.cell.get_mut().unwrap_or_else(|| unreachable!())\n }\n```"}], "func_name": "force_mut", "docstring": "Forces the evaluation of this lazy value and returns a mutable reference to\nthe result.\n\nThis is equivalent to the `DerefMut` impl, but is explicit.\n\n# Example\n```\nuse once_cell::unsync::Lazy;\n\nlet mut lazy = Lazy::new(|| 92);\n\nassert_eq!(Lazy::force_mut(&mut lazy), &92);\nassert_eq!(*lazy, 92);\n```", "repo": "matklad/once_cell", "path": "src/lib.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3246f195301456682dd2c2430cf2bbe428b625428d09abf702e6ee21f1a2c779"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nGets the reference to the underlying value.\n\nReturns `None` if the cell is empty, or being initialized. This\nmethod never blocks.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(&self) -> Option<&T> {\n if self.0.is_initialized() {\n // Safe b/c value is initialized.\n Some(unsafe { self.get_unchecked() })\n } else {\n None\n }\n }\n```"}], "func_name": "get", "docstring": "Gets the reference to the underlying value.\n\nReturns `None` if the cell is empty, or being initialized. This\nmethod never blocks.", "repo": "matklad/once_cell", "path": "src/lib.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc69bb34662937c0c26d8d504938d6bd186ad083e03251cd5fd7e52b3dd862d5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_insert\n\nDocumentation:\nLike [`set`](Self::set), but also returns a reference to the final cell value.\n\n# Example\n\n```\nuse once_cell::unsync::OnceCell;\n\nlet cell = OnceCell::new();\nassert!(cell.get().is_none());\n\nassert_eq!(cell.try_insert(92), Ok(&92));\nassert_eq!(cell.try_insert(62), Err((&92, 62)));\n\nassert!(cell.get().is_some());\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_insert(&self, value: T) -> Result<&T, (&T, T)> {\n let mut value = Some(value);\n let res = self.get_or_init(|| unsafe { value.take().unwrap_unchecked() });\n match value {\n None => Ok(res),\n Some(value) => Err((res, value)),\n }\n }\n```"}], "func_name": "try_insert", "docstring": "Like [`set`](Self::set), but also returns a reference to the final cell value.\n\n# Example\n\n```\nuse once_cell::unsync::OnceCell;\n\nlet cell = OnceCell::new();\nassert!(cell.get().is_none());\n\nassert_eq!(cell.try_insert(92), Ok(&92));\nassert_eq!(cell.try_insert(62), Err((&92, 62)));\n\nassert!(cell.get().is_some());\n```", "repo": "matklad/once_cell", "path": "src/lib.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b3ce2073103a47bfd8ebfae524900809e2c7ec221de20469f728a5e0841bb7f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_or_try_init\n\nDocumentation:\nGets the contents of the cell, initializing it with `f` if\nthe cell was empty. If the cell was empty and `f` failed, an\nerror is returned.\n\n# Panics\n\nIf `f` panics, the panic is propagated to the caller, and\nthe cell remains uninitialized.\n\nIt is an error to reentrantly initialize the cell from `f`.\nThe exact outcome is unspecified. Current implementation\ndeadlocks, but this may be changed to a panic in the future.\n\n# Example\n```\nuse once_cell::sync::OnceCell;\n\nlet cell = OnceCell::new();\nassert_eq!(cell.get_or_try_init(|| Err(())), Err(()));\nassert!(cell.get().is_none());\nlet value = cell.get_or_try_init(|| -> Result {\nOk(92)\n});\nassert_eq!(value, Ok(&92));\nassert_eq!(cell.get(), Some(&92))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_or_try_init(&self, f: F) -> Result<&T, E>\n where\n F: FnOnce() -> Result,\n {\n // Fast path check\n if let Some(value) = self.get() {\n return Ok(value);\n }\n\n self.0.initialize(f)?;\n\n // Safe b/c value is initialized.\n debug_assert!(self.0.is_initialized());\n Ok(unsafe { self.get_unchecked() })\n }\n```"}], "func_name": "get_or_try_init", "docstring": "Gets the contents of the cell, initializing it with `f` if\nthe cell was empty. If the cell was empty and `f` failed, an\nerror is returned.\n\n# Panics\n\nIf `f` panics, the panic is propagated to the caller, and\nthe cell remains uninitialized.\n\nIt is an error to reentrantly initialize the cell from `f`.\nThe exact outcome is unspecified. Current implementation\ndeadlocks, but this may be changed to a panic in the future.\n\n# Example\n```\nuse once_cell::sync::OnceCell;\n\nlet cell = OnceCell::new();\nassert_eq!(cell.get_or_try_init(|| Err(())), Err(()));\nassert!(cell.get().is_none());\nlet value = cell.get_or_try_init(|| -> Result {\nOk(92)\n});\nassert_eq!(value, Ok(&92));\nassert_eq!(cell.get(), Some(&92))\n```", "repo": "matklad/once_cell", "path": "src/lib.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b30fb11cc66eecd3caff81062cf1d1bc767a11463eebd490f97aab5961da4f86"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new lazy value with the given initializing\nfunction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn new(f: F) -> Lazy {\n Lazy { cell: OnceCell::new(), init: Cell::new(Some(f)) }\n }\n```"}], "func_name": "new", "docstring": "Creates a new lazy value with the given initializing\nfunction.", "repo": "matklad/once_cell", "path": "src/lib.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9f5f593d82a6bdcb51b130ff604033635fb8249d72830ab32cd30372bd54c083"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_or_init\n\nDocumentation:\nGets the contents of the cell, initializing it with `f` if the cell was\nempty.\n\nIf several threads concurrently run `get_or_init`, more than one `f` can\nbe called. However, all threads will return the same value, produced by\nsome `f`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_or_init(&self, f: F) -> NonZeroUsize\n where\n F: FnOnce() -> NonZeroUsize,\n {\n enum Void {}\n match self.get_or_try_init(|| Ok::(f())) {\n Ok(val) => val,\n Err(void) => match void {},\n }\n }\n```"}], "func_name": "get_or_init", "docstring": "Gets the contents of the cell, initializing it with `f` if the cell was\nempty.\n\nIf several threads concurrently run `get_or_init`, more than one `f` can\nbe called. However, all threads will return the same value, produced by\nsome `f`.", "repo": "matklad/once_cell", "path": "src/race.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/race.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "510d063a1bb561209564025df6fdf50553c45f7824436bef55c3065f94861ff1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_or_try_init\n\nDocumentation:\nGets the contents of the cell, initializing it with `f` if\nthe cell was empty. If the cell was empty and `f` failed, an\nerror is returned.\n\nIf several threads concurrently run `get_or_init`, more than one `f` can\nbe called. However, all threads will return the same value, produced by\nsome `f`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_or_try_init(&self, f: F) -> Result\n where\n F: FnOnce() -> Result,\n {\n match self.get() {\n Some(it) => Ok(it),\n None => self.init(f),\n }\n }\n```"}], "func_name": "get_or_try_init", "docstring": "Gets the contents of the cell, initializing it with `f` if\nthe cell was empty. If the cell was empty and `f` failed, an\nerror is returned.\n\nIf several threads concurrently run `get_or_init`, more than one `f` can\nbe called. However, all threads will return the same value, produced by\nsome `f`.", "repo": "matklad/once_cell", "path": "src/race.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/race.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1fc14b4c03b56e19da0cc990a49e05212843ec302cd881f52cb9bed650fd4a1f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nGets a reference to the underlying value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(&self) -> Option<&'a T> {\n let ptr = self.inner.load(Ordering::Acquire);\n unsafe { ptr.as_ref() }\n }\n```"}], "func_name": "get", "docstring": "Gets a reference to the underlying value.", "repo": "matklad/once_cell", "path": "src/race.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/race.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f95708b98ea441e4784fa424d5e5a1f9fdb866c27ef56fceb16103cb8c38d2e3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set\n\nDocumentation:\nSets the contents of this cell to `value`.\n\nReturns `Ok(())` if the cell was empty and `Err(value)` if it was\nfull.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set(&self, value: &'a T) -> Result<(), ()> {\n match self.compare_exchange(value) {\n Ok(_) => Ok(()),\n Err(_) => Err(()),\n }\n }\n```"}], "func_name": "set", "docstring": "Sets the contents of this cell to `value`.\n\nReturns `Ok(())` if the cell was empty and `Err(value)` if it was\nfull.", "repo": "matklad/once_cell", "path": "src/race.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/race.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd367300aac3c7f958fed1b91c00bdaa5c1e50f55aaaab629dabd8f8b5eb6698"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_value\n\nDocumentation:\nCreates a new cell with the given value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_value(value: Box) -> Self {\n Self { inner: AtomicPtr::new(Box::into_raw(value)), ghost: PhantomData }\n }\n```"}], "func_name": "with_value", "docstring": "Creates a new cell with the given value.", "repo": "matklad/once_cell", "path": "src/race.rs", "url": "https://github.com/matklad/once_cell/blob/master/src/race.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a4dd07e9955671bc817f72847b3a469f10d4d81b16c53066529f6385c8ad6e25"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new suffix table for `text` in `O(n)` time and `O(kn)`\nspace, where `k` is the size of the alphabet in the text.\n\nThe table stores either `S` or a `&S` and a lexicographically sorted\nlist of suffixes. Each suffix is represented by a 32 bit integer and\nis a **byte index** into `text`.\n\n# Panics\n\nPanics if the `text` contains more than `2^32 - 1` bytes. This\nrestriction is mostly artificial; there's no fundamental reason why\nsuffix array construction algorithm can't use a `u64`. Nevertheless,\n`u64` was chosen for performance reasons. The performance of the\nconstruction algorithm is highly dependent on cache performance, which\nis degraded with a bigger number type. `u64` strikes a nice balance; it\ngets good performance while allowing most reasonably sized documents\n(~4GB).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(text: S) -> SuffixTable<'s, 't>\n where\n S: Into>,\n {\n let text = text.into();\n let table = Cow::Owned(sais_table(&text));\n SuffixTable { text: text, table: table }\n }\n```"}], "func_name": "new", "docstring": "Creates a new suffix table for `text` in `O(n)` time and `O(kn)`\nspace, where `k` is the size of the alphabet in the text.\n\nThe table stores either `S` or a `&S` and a lexicographically sorted\nlist of suffixes. Each suffix is represented by a 32 bit integer and\nis a **byte index** into `text`.\n\n# Panics\n\nPanics if the `text` contains more than `2^32 - 1` bytes. This\nrestriction is mostly artificial; there's no fundamental reason why\nsuffix array construction algorithm can't use a `u64`. Nevertheless,\n`u64` was chosen for performance reasons. The performance of the\nconstruction algorithm is highly dependent on cache performance, which\nis degraded with a bigger number type. `u64` strikes a nice balance; it\ngets good performance while allowing most reasonably sized documents\n(~4GB).", "repo": "google-research/deduplicate-text-datasets", "path": "src/table.rs", "url": "https://github.com/google-research/deduplicate-text-datasets/blob/master/src/table.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d6bba2710d804dc344f279e0fe8c9992d6d66294ab64d26cedca746b89411296"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_parts\n\nDocumentation:\nExtract the parts of a suffix table.\n\nThis is useful to avoid copying when the suffix table is part of an\nintermediate computation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_parts(self) -> (Cow<'s, [u8]>, Cow<'t, [u64]>) {\n (self.text, self.table)\n }\n```"}], "func_name": "into_parts", "docstring": "Extract the parts of a suffix table.\n\nThis is useful to avoid copying when the suffix table is part of an\nintermediate computation.", "repo": "google-research/deduplicate-text-datasets", "path": "src/table.rs", "url": "https://github.com/google-research/deduplicate-text-datasets/blob/master/src/table.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e1cb1db12448302a0900033ad1d400fab160d2affe7e9a7ea661f551e718224"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build_tab_airplanes\n\nDocumentation:\nRender Airplanes tab for tui display\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build_tab_airplanes(\n f: &mut ratatui::Frame,\n chunks: &[Rect],\n adsb_airplanes: &Airplanes,\n airplanes_state: &mut TableState,\n) {\n let mut rows = vec![];\n // make a vec of all strings to get a total amount of airplanes with\n // position information\n let empty = \"\".to_string();\n for key in adsb_airplanes.keys() {\n let state = adsb_airplanes.get(*key).unwrap();\n let aircraft_details = adsb_airplanes.aircraft_details(*key);\n let mut lat = empty.clone();\n let mut lon = empty.clone();\n let mut alt = empty.clone();\n let mut s_kilo_distance = empty.clone();\n if let Some(AirplaneDetails { position, altitude, kilo_distance, .. }) = aircraft_details {\n lat = format!(\"{:.DEFAULT_PRECISION$}\", position.latitude);\n lon = format!(\"{:.DEFAULT_PRECISION$}\", position.longitude);\n s_kilo_distance = format!(\"{kilo_distance:.DEFAULT_PRECISION$}\");\n alt = altitude.to_string();\n }\n\n let heading =\n state.heading.map_or_else(|| \"\".to_string(), |heading| format!(\"{heading:>7.1}\"));\n\n rows.push(Row::new(vec![\n format!(\"{key}\"),\n state.callsign.as_ref().unwrap_or(&empty).clone(),\n lat,\n lon,\n heading,\n format!(\"{alt:>8}\"),\n state.vert_speed.map_or_else(|| \"\".into(), |v| format!(\"{v:>6}\")),\n state.speed.map_or_else(|| \"\".into(), |v| format!(\"{v:>5.0}\")),\n format!(\"{s_kilo_distance:>8}\"),\n format!(\"{:>4}\", state.num_messages),\n ]));\n }\n\n let rows_len = rows.len();\n\n // check the length of selected airplanes\n if let Some(selected) = airplanes_state.selected() {\n if selected > rows_len - 1 {\n airplanes_state.select(Some(rows_len - 1));\n }\n }\n\n // draw table\n let widths = &[\n Constraint::Length(6),\n Constraint::Length(9),\n Constraint::Length(7),\n Constraint::Length(7),\n Constraint::Length(7),\n Constraint::Length(8),\n Constraint::Length(6),\n Constraint::Length(5),\n Constraint::Length(8),\n Constraint::Length(6),\n ];\n let table = Table::new(rows, widths)\n .style(Style::default().fg(Color::White))\n .header(\n Row::new(vec![\n \"ICAO\",\n \"Call sign\",\n \"Lat\",\n \"Long\",\n \"Heading\",\n \"Altitude\",\n \" FPM\",\n \"Speed\",\n \"Distance\",\n \"Msgs\",\n ])\n .bottom_margin(1),\n )\n .block(Block::bordered().title(format!(\"Airplanes({rows_len})\")))\n .column_spacing(1)\n .highlight_style(Style::default().add_modifier(Modifier::BOLD))\n .highlight_symbol(\">> \");\n f.render_stateful_widget(table, chunks[1], &mut airplanes_state.clone());\n}\n```"}], "func_name": "build_tab_airplanes", "docstring": "Render Airplanes tab for tui display", "repo": "rsadsb/adsb_deku", "path": "apps/src/radar/airplanes.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/apps/src/radar/airplanes.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d21c4ea081f9d7b24c3e55ea8f4efe003ac8950dfe1f901de020663102b8987c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build_tab_coverage\n\nDocumentation:\nRender Coverage tab for tui display\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build_tab_coverage(\n f: &mut ratatui::Frame,\n chunks: &[Rect],\n settings: &Settings,\n coverage_airplanes: &[(f64, f64, u32, ICAO)],\n) {\n let canvas = Canvas::default()\n .block(Block::bordered().title(\"Coverage\"))\n .x_bounds([MAX_PLOT_LOW, MAX_PLOT_HIGH])\n .y_bounds([MAX_PLOT_LOW, MAX_PLOT_HIGH])\n .paint(|ctx| {\n // draw locations\n draw_locations(ctx, settings);\n\n // draw range circles\n draw_range_circles(ctx, settings);\n\n // draw ADSB tab airplanes\n for (lat, long, seen_number, _) in coverage_airplanes.iter() {\n let (x, y) = settings.to_xy(*lat, *long);\n\n let number: u32 = 100 + *seen_number * 50;\n let color_number: u8 =\n if number > u32::from(u8::MAX) { u8::MAX } else { number as u8 };\n\n // draw dot on location\n ctx.draw(&Points {\n coords: &[(x, y)],\n color: Color::Rgb(color_number, color_number, color_number),\n });\n }\n });\n f.render_widget(canvas, chunks[1]);\n}\n```"}], "func_name": "build_tab_coverage", "docstring": "Render Coverage tab for tui display", "repo": "rsadsb/adsb_deku", "path": "apps/src/radar/coverage.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/apps/src/radar/coverage.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "412b68eff1b7d35bbbe88506188f3ea25d74992c308c582b29de6e8306d3e544"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build_tab_help\n\nDocumentation:\nRender Help tab for tui display\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build_tab_help(f: &mut ratatui::Frame, chunks: &[Rect]) {\n let horizontal_chunks = Layout::default()\n .direction(Direction::Horizontal)\n .constraints([\n Constraint::Percentage(2),\n Constraint::Percentage(96),\n Constraint::Percentage(2),\n ])\n .split(chunks[1]);\n\n let vertical_chunks = Layout::default()\n .direction(Direction::Vertical)\n .constraints([\n Constraint::Percentage(2),\n Constraint::Percentage(35),\n Constraint::Percentage(35),\n Constraint::Percentage(10),\n Constraint::Percentage(10),\n Constraint::Percentage(2),\n ])\n .split(horizontal_chunks[1]);\n\n // First help section\n let rows = vec![\n Row::new(vec![\"F1\", \"Move to Radar screen\"]),\n Row::new(vec![\"F2\", \"Move to Coverage screen\"]),\n Row::new(vec![\"F3\", \"Move to Airplanes screen\"]),\n Row::new(vec![\"F4\", \"Move to Stats screen\"]),\n Row::new(vec![\"F5\", \"Move to Help screen\"]),\n Row::new(vec![\"l\", \"control --disable-lat-long\"]),\n Row::new(vec![\"i\", \"control --disable-icao\"]),\n Row::new(vec![\"h\", \"control --disable-heading\"]),\n Row::new(vec![\"t\", \"control --disable-track\"]),\n Row::new(vec![\"n\", \"toggle --disable-callsign\"]),\n Row::new(vec![\"r\", \"toggle --disable-range-circles\"]),\n Row::new(vec![\"TAB\", \"Move to Next screen\"]),\n Row::new(vec![\"q\", \"Quit this app\"]),\n Row::new(vec![\"ctrl+c\", \"Quit this app\"]),\n ];\n let widths = &[Constraint::Percentage(10), Constraint::Percentage(90)];\n let table = Table::new(rows, widths)\n .style(Style::default().fg(Color::White))\n .header(Row::new(vec![\"Key\", \"Action\"]).bottom_margin(1))\n .column_spacing(1)\n .block(Block::bordered().title(\"Key Bindings - Any Tab\"));\n f.render_widget(table, vertical_chunks[1]);\n\n // Second help section\n let rows = vec![\n Row::new(vec![\"-\", \"Zoom out\"]),\n Row::new(vec![\"+\", \"Zoom in\"]),\n Row::new(vec![\"Up\", \"Move map up\"]),\n Row::new(vec![\"Down\", \"Move map down\"]),\n Row::new(vec![\"Left\", \"Move map left\"]),\n Row::new(vec![\"Right\", \"Move map right\"]),\n Row::new(vec![\"Enter\", \"Map position reset\"]),\n ];\n let table = Table::new(rows, widths)\n .style(Style::default().fg(Color::White))\n .header(Row::new(vec![\"Key\", \"Action\"]).bottom_margin(1))\n .column_spacing(1)\n .block(Block::bordered().title(\"Key Bindings - Map or Coverage\"));\n f.render_widget(table, vertical_chunks[2]);\n\n // Third help section\n let rows = [\n Row::new(vec![\"Up\", \"Move selection upward\"]),\n Row::new(vec![\"Down\", \"Move selection downward\"]),\n Row::new(vec![\"Enter\", \"Center Map tab on selected aircraft\"]),\n ];\n let table = Table::new(rows, widths)\n .style(Style::default().fg(Color::White))\n .header(Row::new(vec![\"Key\", \"Action\"]).bottom_margin(1))\n .column_spacing(1)\n .block(Block::bordered().title(\"Key Bindings - Airplanes\"));\n f.render_widget(table, vertical_chunks[3]);\n\n // Range circles help section\n let rows = [\n Row::new(vec![\"--range-circles\", \"Set range circles (km) as comma-separated values\"]),\n Row::new(vec![\"--disable-range-circles\", \"Hide range circles\"]),\n Row::new(vec![\"r\", \"Toggle range circles visibility\"]),\n ];\n let table = Table::new(rows, widths)\n .style(Style::default().fg(Color::White))\n .header(Row::new(vec![\"Option\", \"Description\"]).bottom_margin(1))\n .column_spacing(1)\n .block(Block::bordered().title(\"Range Circles\"));\n f.render_widget(table, vertical_chunks[4]);\n}\n```"}], "func_name": "build_tab_help", "docstring": "Render Help tab for tui display", "repo": "rsadsb/adsb_deku", "path": "apps/src/radar/help.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/apps/src/radar/help.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "06081cf6d145a8a9c724834001512da2f1d45ec1c160c9de8275bd0c3e15c6d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build_tab_map\n\nDocumentation:\nRender Map tab for tui display\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build_tab_map(\n f: &mut ratatui::Frame,\n chunks: &[Rect],\n settings: &Settings,\n adsb_airplanes: &Airplanes,\n) {\n let canvas = Canvas::default()\n .block(Block::bordered().title(\"Map\"))\n .x_bounds([MAX_PLOT_LOW, MAX_PLOT_HIGH])\n .y_bounds([MAX_PLOT_LOW, MAX_PLOT_HIGH])\n .paint(|ctx| {\n draw_lines(ctx);\n\n // draw locations\n draw_locations(ctx, settings);\n\n // draw range circles\n draw_range_circles(ctx, settings);\n\n // draw ADSB tab airplanes\n for (key, value) in adsb_airplanes.iter() {\n let aircraft_details = adsb_airplanes.aircraft_details(*key);\n if let Some(AirplaneDetails { position, heading, track, .. }) = aircraft_details {\n let (x, y) = settings.to_xy(position.latitude, position.longitude);\n\n // draw previous positions (\"track\")\n if !settings.opts.disable_track {\n if let Some(track) = track {\n for coor in track {\n if let Some(position) = coor.position {\n let (x, y) =\n settings.to_xy(position.latitude, position.longitude);\n\n // draw dot on location\n ctx.draw(&Points { coords: &[(x, y)], color: Color::White });\n }\n }\n }\n }\n\n // make wings for the angle directions facing toward the heading. This tried to\n // account for the angles not showing up around the 90 degree mark, of which I\n // add degrees of the angle before displaying\n if !settings.opts.disable_heading {\n if let Some(heading) = heading {\n const ANGLE: f32 = 20.0;\n const LENGTH: f32 = 8.0;\n\n let addition_heading = (heading % 90.0) / 10.0;\n let angle: f32 = ANGLE + addition_heading;\n\n let heading = heading + 180.0 % 360.0;\n // wrap around the angle since we are are subtracting\n let n_heading = if heading > angle {\n heading - angle\n } else {\n (360.0 + heading) - angle\n };\n\n // move the first point out, so that the green point of the aircraft\n // _usually_ shows.\n let y_1 = y + f64::from(2.0 * (n_heading.to_radians()).cos());\n let x_1 = x + f64::from(2.0 * (n_heading.to_radians()).sin());\n\n // draw the line out from the aircraft at an angle\n let y_2 = y + f64::from(LENGTH * (n_heading.to_radians()).cos());\n let x_2 = x + f64::from(LENGTH * (n_heading.to_radians()).sin());\n\n ctx.draw(&Line {\n x1: x_1,\n x2: x_2,\n y1: y_1,\n y2: y_2,\n color: Color::Blue,\n });\n\n // repeat for the other side (addition, so just modding)\n let n_heading = (heading + angle) % 360.0;\n let y_1 = y + f64::from(2.0 * (n_heading.to_radians()).cos());\n let x_1 = x + f64::from(2.0 * (n_heading.to_radians()).sin());\n let y_2 = y + f64::from(LENGTH * (n_heading.to_radians()).cos());\n let x_2 = x + f64::from(LENGTH * (n_heading.to_radians()).sin());\n\n ctx.draw(&Line {\n x1: x_1,\n x2: x_2,\n y1: y_1,\n y2: y_2,\n color: Color::Blue,\n });\n }\n }\n\n let call_sign = if settings.opts.disable_callsign {\n format!(\"{key}\").into_boxed_str()\n } else if let Some(callsign) = &value.callsign {\n callsign.to_string().into_boxed_str()\n } else {\n format!(\"{key}\").into_boxed_str()\n };\n\n let name = if settings.opts.disable_lat_long {\n format!(\"{call_sign}\").into_boxed_str()\n } else {\n format!(\n \"{call_sign} ({:.DEFAULT_PRECISION$}, {:.DEFAULT_PRECISION$})\",\n position.latitude, position.longitude\n )\n .into_boxed_str()\n };\n\n if !settings.opts.disable_icao {\n // draw plane ICAO name\n ctx.print(\n x,\n y + 20.0,\n Span::styled(name.to_string(), Style::default().fg(Color::White)),\n );\n }\n\n // draw dot on actual lat/lon\n ctx.draw(&Points { coords: &[(x, y)], color: Color::Blue });\n }\n }\n });\n f.render_widget(canvas, chunks[1]);\n}\n```"}], "func_name": "build_tab_map", "docstring": "Render Map tab for tui display", "repo": "rsadsb/adsb_deku", "path": "apps/src/radar/map.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/apps/src/radar/map.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "818c8c85cbfe1b17e5d7cf62542cde12b3d50c852c53c5fa5c2ae7a336b28c52"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_xy\n\nDocumentation:\nConvert new lat/long into mercator using current location from `Settings`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn to_xy(&self, latitude: f64, longitude: f64) -> (f64, f64) {\n // TODO save before, it's kinda costly\n let (local_x, local_y) = self.local_lat_lon();\n let (x, y) = self.to_mercator(latitude, longitude);\n let (x, y) = (x - local_x, y - local_y);\n (x, y * -1.0)\n }\n```"}], "func_name": "to_xy", "docstring": "Convert new lat/long into mercator using current location from `Settings`", "repo": "rsadsb/adsb_deku", "path": "apps/src/radar/radar.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/apps/src/radar/radar.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a0d5e6306e6b1e6badcc8f4fac0a94b9b03dc710b50259756cd571c9ce0ba006"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: local_lat_lon\n\nDocumentation:\nCalculate mercator for local lat/long\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn local_lat_lon(&self) -> (f64, f64) {\n let lat = self.custom_lat.map_or(self.lat, |lat| lat);\n let long = self.custom_long.map_or(self.long, |long| long);\n self.to_mercator(lat, long)\n }\n```"}], "func_name": "local_lat_lon", "docstring": "Calculate mercator for local lat/long", "repo": "rsadsb/adsb_deku", "path": "apps/src/radar/radar.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/apps/src/radar/radar.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e00b47c4add9c6f2501935898e6fe301460278c8cf2791594da975853921968f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_mercator\n\nDocumentation:\nConvert lat/long to mercator coordinates\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn to_mercator(&self, lat: f64, long: f64) -> (f64, f64) {\n let scale: f64 = self.scale * scale::DEFAULT;\n\n let x = (long + 180.0) * (scale / 360.0);\n let lat_rad = lat.to_radians();\n let merc_n = f64::ln(f64::tan((std::f64::consts::PI / 4.0) + (lat_rad / 2.0)));\n let y = (scale / 2.0) - (scale * merc_n / (2.0 * std::f64::consts::PI));\n\n (x, y)\n }\n```"}], "func_name": "to_mercator", "docstring": "Convert lat/long to mercator coordinates", "repo": "rsadsb/adsb_deku", "path": "apps/src/radar/radar.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/apps/src/radar/radar.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5073b329d97e50014f386602117e21d34c0ecc64b161bbc0ff92be219ede3eb5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init_tcp_reader\n\nDocumentation:\nTry and connect to a dump1090 instance while showing a tui display.\n\nReturns:\n`Ok(Some(tcp_reader))`: Success, new tcp connection wrapped in a `BufReader`\n`Ok(None)`: User quit method has been used\n`Err()`: Some other system error has occurred\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn init_tcp_reader(\n terminal: &mut Terminal>,\n settings: &mut Settings,\n socket: SocketAddr,\n) -> Result>> {\n let ip = socket.ip();\n let port = socket.port();\n\n // display a tui display\n terminal.draw(|f| {\n let chunks = Layout::default()\n .direction(Direction::Vertical)\n .margin(1)\n .constraints([Constraint::Min(3), Constraint::Percentage(100)].as_ref())\n .split(f.area());\n\n let paragraph = Paragraph::new(format!(\"radar: Waiting for connection to {ip}:{port}\"))\n .alignment(Alignment::Left);\n\n f.render_widget(paragraph, chunks[0]);\n })?;\n\n loop {\n // handle keyboard events\n if poll(Duration::from_millis(10))? {\n if let Ok(Event::Key(key_event)) = read() {\n let modifiers = key_event.modifiers;\n let code = key_event.code;\n match code {\n KeyCode::Char('q') => {\n settings.quit = Some(QuitReason::UserRequested);\n return Ok(None);\n }\n KeyCode::Char('c') => {\n if modifiers == crossterm::event::KeyModifiers::CONTROL {\n settings.quit = Some(QuitReason::UserRequested);\n return Ok(None);\n }\n }\n // unknown key\n _ => (),\n }\n }\n }\n\n // try and connect to initial dump1090 instance\n if let Ok(stream) = TcpStream::connect_timeout(&socket, Duration::from_secs(10)) {\n stream.set_read_timeout(Some(std::time::Duration::from_millis(50))).unwrap();\n return Ok(Some(BufReader::new(stream)));\n }\n }\n}\n```"}], "func_name": "init_tcp_reader", "docstring": "Try and connect to a dump1090 instance while showing a tui display.\n\nReturns:\n`Ok(Some(tcp_reader))`: Success, new tcp connection wrapped in a `BufReader`\n`Ok(None)`: User quit method has been used\n`Err()`: Some other system error has occurred", "repo": "rsadsb/adsb_deku", "path": "apps/src/radar/radar.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/apps/src/radar/radar.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e994565bfcb28066738bec4ce0e0af0b56704afadabf0c3b2b19504e2513131"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: gpsd_thread\n\nDocumentation:\nfunction ran within a thread for updating `gps_lat_long` when the gpsd shows a new `lat_long`\nposition.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn gpsd_thread(gpsd_ip: &str, gps_lat_long: Arc>>) {\n let gpsd_port = 2947;\n if let Ok(stream) = TcpStream::connect((gpsd_ip, gpsd_port))\n .with_context(|| format!(\"unable to connect to gpsd server @ {gpsd_ip}:{gpsd_port}\"))\n {\n let mut reader = BufReader::new(&stream);\n let mut writer = BufWriter::new(&stream);\n handshake(&mut reader, &mut writer).unwrap();\n info!(\"[gpsd] connected\");\n\n // keep looping while reading new messages looking for GGA messages which are the\n // normal GPS messages from the NMEA messages.\n loop {\n if let Ok(ResponseData::Tpv(data)) = get_data(&mut reader) {\n // only update if the operator hasn't set a lat/long position already\n if let Ok(mut lat_long) = gps_lat_long.lock() {\n if let (Some(lat), Some(lon)) = (data.lat, data.lon) {\n info!(\"[gpsd] lat: {lat}, long:{lon}\");\n *lat_long = Some((lat, lon));\n }\n }\n }\n }\n } else {\n error!(\"could not connect to gpsd\");\n }\n}\n```"}], "func_name": "gpsd_thread", "docstring": "function ran within a thread for updating `gps_lat_long` when the gpsd shows a new `lat_long`\nposition.", "repo": "rsadsb/adsb_deku", "path": "apps/src/radar/radar.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/apps/src/radar/radar.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "522b633e2013ecf3a306ccf55603cd875b4828f63f361a49f9ec9266f841aad1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: draw_range_circles\n\nDocumentation:\nDraw range circles around the receiver location\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn draw_range_circles(ctx: &mut Context<'_>, settings: &Settings) {\n // Skip drawing if disabled\n if settings.opts.disable_range_circles {\n return;\n }\n\n // Get the range circles from the command line options\n let ranges = &settings.opts.range_circles.0;\n\n // Get the receiver location (0,0) in the canvas coordinates\n let (x, y) = settings.to_xy(settings.lat, settings.long);\n\n // Draw each range circle\n for &range in ranges {\n let lat_offset = range / 111.0;\n let point_at_range = settings.to_xy(settings.lat + lat_offset, settings.long);\n\n // Calculate the radius in canvas units\n let radius = ((point_at_range.1 - y).powi(2) + (point_at_range.0 - x).powi(2)).sqrt();\n\n // Draw the circle\n ctx.draw(&Circle { x, y, radius, color: Color::DarkGray });\n\n let label_x = x;\n let label_y = y - radius;\n ctx.print(\n label_x,\n label_y,\n ratatui::text::Span::styled(\n format!(\"{}km\", range),\n ratatui::style::Style::default().fg(Color::DarkGray),\n ),\n );\n }\n}\n```"}], "func_name": "draw_range_circles", "docstring": "Draw range circles around the receiver location", "repo": "rsadsb/adsb_deku", "path": "apps/src/radar/range_circles.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/apps/src/radar/range_circles.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6a97180b8300a4730fa307b2b449987013f9998963a77ba922aef84665a7dc22"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cpr_nl\n\nDocumentation:\nThe NL function uses the precomputed table from 1090-WP-9-14\nThis code is translated from \n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn cpr_nl(lat: f64) -> u64 {\n let mut lat = lat;\n if lat < 0.0 {\n // Table is symmetric about the equator\n lat = -lat;\n }\n if lat < 29.911_356_86 {\n if lat < 10.470_471_30 {\n return 59;\n }\n if lat < 14.828_174_37 {\n return 58;\n }\n if lat < 18.186_263_57 {\n return 57;\n }\n if lat < 21.029_394_93 {\n return 56;\n }\n if lat < 23.545_044_87 {\n return 55;\n }\n if lat < 25.829_247_07 {\n return 54;\n }\n if lat < 27.938_987_10 {\n return 53;\n }\n // < 29.91135686\n return 52;\n }\n if lat < 44.194_549_51 {\n if lat < 31.772_097_08 {\n return 51;\n }\n if lat < 33.539_934_36 {\n return 50;\n }\n if lat < 35.228_995_98 {\n return 49;\n }\n if lat < 36.850_251_08 {\n return 48;\n }\n if lat < 38.412_418_92 {\n return 47;\n }\n if lat < 39.922_566_84 {\n return 46;\n }\n if lat < 41.386_518_32 {\n return 45;\n }\n if lat < 42.809_140_12 {\n return 44;\n }\n // < 44.19454951\n return 43;\n }\n if lat < 59.954_592_77 {\n if lat < 45.546_267_23 {\n return 42;\n }\n if lat < 46.867_332_52 {\n return 41;\n }\n if lat < 48.160_391_28 {\n return 40;\n }\n if lat < 49.427_764_39 {\n return 39;\n }\n if lat < 50.671_501_66 {\n return 38;\n }\n if lat < 51.893_424_69 {\n return 37;\n }\n if lat < 53.095_161_53 {\n return 36;\n }\n if lat < 54.278_174_72 {\n return 35;\n }\n if lat < 55.443_784_44 {\n return 34;\n }\n if lat < 56.593_187_56 {\n return 33;\n }\n if lat < 57.727_473_54 {\n return 32;\n }\n if lat < 58.847_637_76 {\n return 31;\n }\n // < 59.95459277\n return 30;\n }\n if lat < 61.049_177_74 {\n return 29;\n }\n if lat < 62.132_166_59 {\n return 28;\n }\n if lat < 63.204_274_79 {\n return 27;\n }\n if lat < 64.266_165_23 {\n return 26;\n }\n if lat < 65.318_453_10 {\n return 25;\n }\n if lat < 66.361_710_08 {\n return 24;\n }\n if lat < 67.396_467_74 {\n return 23;\n }\n if lat < 68.423_220_22 {\n return 22;\n }\n if lat < 69.442_426_31 {\n return 21;\n }\n if lat < 70.454_510_75 {\n return 20;\n }\n if lat < 71.459_864_73 {\n return 19;\n }\n if lat < 72.458_845_45 {\n return 18;\n }\n if lat < 73.451_774_42 {\n return 17;\n }\n if lat < 74.438_934_16 {\n return 16;\n }\n if lat < 75.420_562_57 {\n return 15;\n }\n if lat < 76.396_843_91 {\n return 14;\n }\n if lat < 77.367_894_61 {\n return 13;\n }\n if lat < 78.333_740_83 {\n return 12;\n }\n if lat < 79.294_282_25 {\n return 11;\n }\n if lat < 80.249_232_13 {\n return 10;\n }\n if lat < 81.198_013_49 {\n return 9;\n }\n if lat < 82.139_569_81 {\n return 8;\n }\n if lat < 83.071_994_45 {\n return 7;\n }\n if lat < 83.991_735_63 {\n return 6;\n }\n if lat < 84.891_661_91 {\n return 5;\n }\n if lat < 85.755_416_21 {\n return 4;\n }\n if lat < 86.535_369_98 {\n return 3;\n }\n if lat < 87.000_000_00 {\n return 2;\n }\n 1\n}\n```"}], "func_name": "cpr_nl", "docstring": "The NL function uses the precomputed table from 1090-WP-9-14\nThis code is translated from ", "repo": "rsadsb/adsb_deku", "path": "libadsb_deku/src/cpr.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/libadsb_deku/src/cpr.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7aa8ed108b945672340a1b722aca8f7da9a89e375525b153a55e83be254d8c73"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: action\n\nDocumentation:\nUpdate `Airplanes` with new `Frame`\n\nTake parsed `Frame` and read the `DF::ADSB` type and act upon the parsed message. This\nupdates the field that the `ME` value equates to within [`Self`]. This also adds\nairplanes (`ICAO` and `AirplaneState`) when a new aircraft is detected.\n\n`lat_long`: (latitude, longitude) of current receiver location\n\n`max_range`: max range of the receiver\n\nReturn true if entry was added into `Airplanes`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn action(&mut self, frame: Frame, lat_long: (f64, f64), max_rang: f64) -> Added {\n let mut airplane_added = Added::No;\n match frame.df {\n DF::ADSB(ref adsb) => {\n airplane_added = match &adsb.me {\n ME::AircraftIdentification { id: _id, identification } => {\n self.add_identification(adsb.icao, identification)\n }\n ME::AirborneVelocity(vel) => self.add_airborne_velocity(adsb.icao, vel),\n ME::AirbornePositionGNSSAltitude { id: _id, altitude }\n | ME::AirbornePositionBaroAltitude { id: _id, altitude } => {\n self.update_position(adsb.icao, altitude, lat_long, max_rang)\n }\n _ => Added::No,\n };\n let incr_airplane_added = self.incr_messages(adsb.icao);\n airplane_added =\n if incr_airplane_added == Added::Yes || airplane_added == Added::Yes {\n Added::Yes\n } else {\n Added::No\n };\n }\n DF::TisB { cf, pi } => {\n info!(\"TISB: {cf:?}, {pi:?}\");\n airplane_added = match cf.me {\n ME::AircraftIdentification { id: _id, identification } => {\n self.add_identification(pi, &identification)\n }\n ME::AirborneVelocity(vel) => self.add_airborne_velocity(pi, &vel),\n ME::AirbornePositionGNSSAltitude { id: _id, altitude }\n | ME::AirbornePositionBaroAltitude { id: _id, altitude } => {\n self.update_position(pi, &altitude, lat_long, max_rang)\n }\n _ => Added::No,\n };\n let incr_airplane_added = self.incr_messages(pi);\n airplane_added =\n if incr_airplane_added == Added::Yes || airplane_added == Added::Yes {\n Added::Yes\n } else {\n Added::No\n };\n }\n _ => (),\n }\n\n airplane_added\n }\n```"}], "func_name": "action", "docstring": "Update `Airplanes` with new `Frame`\n\nTake parsed `Frame` and read the `DF::ADSB` type and act upon the parsed message. This\nupdates the field that the `ME` value equates to within [`Self`]. This also adds\nairplanes (`ICAO` and `AirplaneState`) when a new aircraft is detected.\n\n`lat_long`: (latitude, longitude) of current receiver location\n\n`max_range`: max range of the receiver\n\nReturn true if entry was added into `Airplanes`", "repo": "rsadsb/adsb_deku", "path": "rsadsb_common/src/lib.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/rsadsb_common/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba82ca326f1b2c4e1683adc0bff64ec9bbd943d73d8f2a69174ce8e271391ea2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: incr_messages\n\nDocumentation:\nIncrement message count of `ICAO`. If feature: `std`, set `last_time` to current time.\n\nReturn true if entry was added into `Airplanes`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn incr_messages(&mut self, icao: ICAO) -> Added {\n let (state, airplane_added) = self.entry_or_insert(icao);\n state.num_messages += 1;\n #[cfg(feature = \"std\")]\n {\n state.last_time = std::time::SystemTime::now();\n }\n\n airplane_added\n }\n```"}], "func_name": "incr_messages", "docstring": "Increment message count of `ICAO`. If feature: `std`, set `last_time` to current time.\n\nReturn true if entry was added into `Airplanes`", "repo": "rsadsb/adsb_deku", "path": "rsadsb_common/src/lib.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/rsadsb_common/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f2fc243317e4a2d538c74cf1c3df04c5bc27373fff6664ddac189e60ad5ad562"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_identification\n\nDocumentation:\nupdate from `ME::AircraftIdentification`\n\nReturn true if entry was added into `Airplanes`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_identification(&mut self, icao: ICAO, identification: &Identification) -> Added {\n let (state, airplane_added) = self.entry_or_insert(icao);\n state.callsign = Some(identification.cn.clone());\n info!(\"[{icao}] with identification: {}\", identification.cn);\n\n airplane_added\n }\n```"}], "func_name": "add_identification", "docstring": "update from `ME::AircraftIdentification`\n\nReturn true if entry was added into `Airplanes`", "repo": "rsadsb/adsb_deku", "path": "rsadsb_common/src/lib.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/rsadsb_common/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3dcbfb30827af674511a22c6be7201fdd552eddb7609dd6987c42710c6be6a9e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_airborne_velocity\n\nDocumentation:\nupdate from `ME::AirborneVelocity`\n\nReturn true if entry was added into `Airplanes`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_airborne_velocity(&mut self, icao: ICAO, vel: &AirborneVelocity) -> Added {\n let (state, airplane_added) = self.entry_or_insert(icao);\n if let Some((heading, ground_speed, vert_speed)) = vel.calculate() {\n info!(\"[{icao}] with airborne velocity: heading: {heading}, speed: {ground_speed}, vertical speed: {vert_speed}\");\n state.heading = Some(heading);\n state.speed = Some(ground_speed as f32);\n state.vert_speed = Some(vert_speed);\n }\n\n airplane_added\n }\n```"}], "func_name": "add_airborne_velocity", "docstring": "update from `ME::AirborneVelocity`\n\nReturn true if entry was added into `Airplanes`", "repo": "rsadsb/adsb_deku", "path": "rsadsb_common/src/lib.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/rsadsb_common/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8cfd25064edf8389c7eb5b53707d78b22f89ea516a04047be3430844b708ecf1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_position\n\nDocumentation:\nupdate from `ME::AirbornePosition{GNSSAltitude, BaroAltitude}`\n\nReturn true if entry was added into `Airplanes`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn update_position(\n &mut self,\n icao: ICAO,\n altitude: &Altitude,\n lat_long: (f64, f64),\n max_range: f64,\n ) -> Added {\n let (state, airplane_added) = self.entry_or_insert(icao);\n info!(\n \"[{icao}] with: {:?}, cpr lat: {}, cpr long: {}\",\n altitude.alt, altitude.lat_cpr, altitude.lon_cpr\n );\n let mut temp_coords = match altitude.odd_flag {\n CPRFormat::Odd => AirplaneCoor {\n altitudes: [state.coords.altitudes[0], Some(*altitude)],\n ..state.coords\n },\n CPRFormat::Even => AirplaneCoor {\n altitudes: [Some(*altitude), state.coords.altitudes[1]],\n ..state.coords\n },\n };\n // update the position from the new even/odd message if it's a good new position\n if temp_coords.update_position(lat_long, max_range) {\n // don't bother updating if it's the same coords\n if state.coords != temp_coords {\n // update track\n if let Some(track) = &mut state.track {\n track.push(state.coords);\n } else {\n state.track = Some(vec![state.coords]);\n }\n // update new position\n state.coords = temp_coords;\n }\n } else {\n // clear record\n state.coords = AirplaneCoor::default();\n }\n\n airplane_added\n }\n```"}], "func_name": "update_position", "docstring": "update from `ME::AirbornePosition{GNSSAltitude, BaroAltitude}`\n\nReturn true if entry was added into `Airplanes`", "repo": "rsadsb/adsb_deku", "path": "rsadsb_common/src/lib.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/rsadsb_common/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aed077501edaa23090cc9eb8b494a6d06c6ba6731f3b3c20cb7a71d931f2e47a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_position\n\nDocumentation:\nAfter checking the range of the new lat / long, new position from last position, update the\nposition of an aircraft\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn update_position(&mut self, lat_long: (f64, f64), max_range: f64) -> bool {\n if let [Some(odd), Some(even)] = self.altitudes {\n let test_position = cpr::get_position((&odd, &even));\n\n // Check kilometer range from receiver\n if let Some(test_position) = test_position {\n let kilo_distance = Self::haversine_distance(\n lat_long,\n (test_position.latitude, test_position.longitude),\n );\n if kilo_distance > max_range {\n warn!(\"range: {kilo_distance} - old: {lat_long:?} new: {test_position:?}\");\n return false;\n }\n self.kilo_distance = Some(kilo_distance);\n debug!(\"range: {kilo_distance}\");\n }\n\n // if previous position, check against for range. This is a non-great way of doing\n // this, but maybe in the future we can check against the speed of the aircraft\n if let (Some(current_position), Some(test_position)) = (self.position, test_position) {\n let distance = Self::haversine_distance_position(current_position, test_position);\n if distance > MAX_AIRCRAFT_DISTANCE {\n warn!(\"distance: {distance} old: {current_position:?}, invalid: {test_position:?}\");\n return false;\n }\n debug!(\"distance: {distance}\");\n }\n\n // Good new position!\n self.position = test_position;\n debug!(\"update_position: odd: (lat: {}, long: {}), even: (lat: {}, long: {}), position: {:?}\",\n odd.lat_cpr,\n odd.lon_cpr,\n even.lat_cpr,\n even.lat_cpr,\n self.position);\n #[cfg(feature = \"std\")]\n {\n self.last_time = Some(SystemTime::now());\n }\n }\n true\n }\n```"}], "func_name": "update_position", "docstring": "After checking the range of the new lat / long, new position from last position, update the\nposition of an aircraft", "repo": "rsadsb/adsb_deku", "path": "rsadsb_common/src/lib.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/rsadsb_common/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9fba49909b3156a5fb7a9e81b47c1258ffec872526d8b88474b500a9a285378a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: haversine_distance_position\n\nDocumentation:\nCalculate the kilometers between two lat/long points\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn haversine_distance_position(position: cpr::Position, other: cpr::Position) -> f64 {\n let lat1 = position.latitude;\n let lat2 = other.latitude;\n let long1 = position.longitude;\n let long2 = other.longitude;\n Self::haversine_distance((lat1, long1), (lat2, long2))\n }\n```"}], "func_name": "haversine_distance_position", "docstring": "Calculate the kilometers between two lat/long points", "repo": "rsadsb/adsb_deku", "path": "rsadsb_common/src/lib.rs", "url": "https://github.com/rsadsb/adsb_deku/blob/master/rsadsb_common/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b04e9ea23a28b14f3fa4ad02911c4d7d8a677c2aba4284188848fb712384189f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_closed\n\nDocumentation:\nDetermines if the error was associated with closed connection.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_closed(&self) -> bool {\n matches!(self.kind, ErrorKind::ConnectionClosed)\n }\n```"}], "func_name": "is_closed", "docstring": "Determines if the error was associated with closed connection.", "repo": "prisma/quaint", "path": "src/error.rs", "url": "https://github.com/prisma/quaint/blob/master/src/error.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf3e299fae0fc7f32cdb58be869eac215b965657db0fd80bc3c46dfd78673123"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_postgres_flavour\n\nDocumentation:\nSets whether the URL points to a Postgres, Cockroach or Unknown database.\nThis is used to avoid a network roundtrip at connection to set the search path.\n\nThe different behaviours are:\n- Postgres: Always avoid a network roundtrip by setting the search path through client connection parameters.\n- Cockroach: Avoid a network roundtrip if the schema name is deemed \"safe\" (i.e. no escape quoting required). Otherwise, set the search path through a database query.\n- Unknown: Always add a network roundtrip by setting the search path through a database query.\n\n- Defaults to `PostgresFlavour::Unknown`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_postgres_flavour(&mut self, flavour: PostgresFlavour) {\n if let ConnectionInfo::Postgres(ref mut url) = self.connection_info {\n url.set_flavour(flavour);\n }\n\n if let QuaintManager::Postgres { ref mut url } = self.manager {\n url.set_flavour(flavour);\n }\n }\n```"}], "func_name": "set_postgres_flavour", "docstring": "Sets whether the URL points to a Postgres, Cockroach or Unknown database.\nThis is used to avoid a network roundtrip at connection to set the search path.\n\nThe different behaviours are:\n- Postgres: Always avoid a network roundtrip by setting the search path through client connection parameters.\n- Cockroach: Avoid a network roundtrip if the schema name is deemed \"safe\" (i.e. no escape quoting required). Otherwise, set the search path through a database query.\n- Unknown: Always add a network roundtrip by setting the search path through a database query.\n\n- Defaults to `PostgresFlavour::Unknown`.", "repo": "prisma/quaint", "path": "src/pooled.rs", "url": "https://github.com/prisma/quaint/blob/master/src/pooled.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ee85428a050c310a55e728d233f5f20aa9cfc0d2b544145ad6c2825059ded9eb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder for a Quaint connection pool with the given\nconnection string. See the [module level documentation] for details.\n\n[module level documentation]: index.html\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder(url_str: &str) -> crate::Result {\n match url_str {\n #[cfg(feature = \"sqlite\")]\n s if s.starts_with(\"file\") => {\n let params = crate::connector::SqliteParams::try_from(s)?;\n\n let manager = QuaintManager::Sqlite {\n url: s.to_string(),\n db_name: params.db_name,\n };\n\n let mut builder = Builder::new(s, manager)?;\n\n if let Some(limit) = params.connection_limit {\n builder.connection_limit(limit);\n }\n\n if let Some(max_lifetime) = params.max_connection_lifetime {\n builder.max_lifetime(max_lifetime);\n }\n\n if let Some(max_idle_lifetime) = params.max_idle_connection_lifetime {\n builder.max_idle_lifetime(max_idle_lifetime);\n }\n\n Ok(builder)\n }\n #[cfg(feature = \"mysql\")]\n s if s.starts_with(\"mysql\") => {\n let url = crate::connector::MysqlUrl::new(url::Url::parse(s)?)?;\n let connection_limit = url.connection_limit();\n let pool_timeout = url.pool_timeout();\n let max_connection_lifetime = url.max_connection_lifetime();\n let max_idle_connection_lifetime = url.max_idle_connection_lifetime();\n\n let manager = QuaintManager::Mysql { url };\n let mut builder = Builder::new(s, manager)?;\n\n if let Some(limit) = connection_limit {\n builder.connection_limit(limit);\n }\n\n if let Some(timeout) = pool_timeout {\n builder.pool_timeout(timeout);\n }\n\n if let Some(max_lifetime) = max_connection_lifetime {\n builder.max_lifetime(max_lifetime);\n }\n\n if let Some(max_idle_lifetime) = max_idle_connection_lifetime {\n builder.max_idle_lifetime(max_idle_lifetime);\n }\n\n Ok(builder)\n }\n #[cfg(feature = \"postgresql\")]\n s if s.starts_with(\"postgres\") || s.starts_with(\"postgresql\") => {\n let url = crate::connector::PostgresUrl::new(url::Url::parse(s)?)?;\n let connection_limit = url.connection_limit();\n let pool_timeout = url.pool_timeout();\n let max_connection_lifetime = url.max_connection_lifetime();\n let max_idle_connection_lifetime = url.max_idle_connection_lifetime();\n\n let manager = QuaintManager::Postgres { url };\n let mut builder = Builder::new(s, manager)?;\n\n if let Some(limit) = connection_limit {\n builder.connection_limit(limit);\n }\n\n if let Some(timeout) = pool_timeout {\n builder.pool_timeout(timeout);\n }\n\n if let Some(max_lifetime) = max_connection_lifetime {\n builder.max_lifetime(max_lifetime);\n }\n\n if let Some(max_idle_lifetime) = max_idle_connection_lifetime {\n builder.max_idle_lifetime(max_idle_lifetime);\n }\n\n Ok(builder)\n }\n #[cfg(feature = \"mssql\")]\n s if s.starts_with(\"jdbc:sqlserver\") || s.starts_with(\"sqlserver\") => {\n let url = crate::connector::MssqlUrl::new(s)?;\n let connection_limit = url.connection_limit();\n let pool_timeout = url.pool_timeout();\n let max_connection_lifetime = url.max_connection_lifetime();\n let max_idle_connection_lifetime = url.max_idle_connection_lifetime();\n\n let manager = QuaintManager::Mssql { url };\n let mut builder = Builder::new(s, manager)?;\n\n if let Some(limit) = connection_limit {\n builder.connection_limit(limit);\n }\n\n if let Some(timeout) = pool_timeout {\n builder.pool_timeout(timeout);\n }\n\n if let Some(max_lifetime) = max_connection_lifetime {\n builder.max_lifetime(max_lifetime);\n }\n\n if let Some(max_idle_lifetime) = max_idle_connection_lifetime {\n builder.max_idle_lifetime(max_idle_lifetime);\n }\n\n Ok(builder)\n }\n _ => unimplemented!(\"Supported url schemes: file or sqlite, mysql, postgres or postgresql.\"),\n }\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder for a Quaint connection pool with the given\nconnection string. See the [module level documentation] for details.\n\n[module level documentation]: index.html", "repo": "prisma/quaint", "path": "src/pooled.rs", "url": "https://github.com/prisma/quaint/blob/master/src/pooled.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "410ac98ccfd8f42cd42fb4339d04f3ffbc629293b467ba3cd4f89d4ac055c431"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_rows\n\nDocumentation:\nDeserialize each row of a [`ResultSet`](../connector/struct.ResultSet.html).\n\nFor an example, see the docs for [`from_row`](fn.from_row.html).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_rows(result_set: ResultSet) -> crate::Result> {\n let mut deserialized_rows = Vec::with_capacity(result_set.len());\n\n for row in result_set {\n deserialized_rows.push(from_row(row)?)\n }\n\n Ok(deserialized_rows)\n}\n```"}], "func_name": "from_rows", "docstring": "Deserialize each row of a [`ResultSet`](../connector/struct.ResultSet.html).\n\nFor an example, see the docs for [`from_row`](fn.from_row.html).", "repo": "prisma/quaint", "path": "src/serde.rs", "url": "https://github.com/prisma/quaint/blob/master/src/serde.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "77a25820cdfc62ab70128add6e3fb4a023ef5af2edab93a261a137483372dbaa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_row\n\nDocumentation:\nDeserialize a row into any type implementing `Deserialize`.\n\n```\n# use serde::Deserialize;\n# use quaint::ast::Value;\n#\n# #[derive(Deserialize, Debug, PartialEq)]\n# struct User {\n# id: u64,\n# name: String,\n# }\n#\n# fn main() -> Result<(), Box> {\n#\n# let row = quaint::serde::make_row(vec![\n# (\"id\", Value::from(12)),\n# (\"name\", \"Georgina\".into()),\n# ]);\n#\n#\nlet user: User = quaint::serde::from_row(row)?;\n\nassert_eq!(user, User { name: \"Georgina\".to_string(), id: 12 });\n# Ok(())\n# }\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_row(row: ResultRow) -> crate::Result {\n let deserializer = RowDeserializer(row);\n\n T::deserialize(deserializer).map_err(|e| Error::builder(ErrorKind::FromRowError(e)).build())\n}\n```"}], "func_name": "from_row", "docstring": "Deserialize a row into any type implementing `Deserialize`.\n\n```\n# use serde::Deserialize;\n# use quaint::ast::Value;\n#\n# #[derive(Deserialize, Debug, PartialEq)]\n# struct User {\n# id: u64,\n# name: String,\n# }\n#\n# fn main() -> Result<(), Box> {\n#\n# let row = quaint::serde::make_row(vec![\n# (\"id\", Value::from(12)),\n# (\"name\", \"Georgina\".into()),\n# ]);\n#\n#\nlet user: User = quaint::serde::from_row(row)?;\n\nassert_eq!(user, User { name: \"Georgina\".to_string(), id: 12 });\n# Ok(())\n# }\n```", "repo": "prisma/quaint", "path": "src/serde.rs", "url": "https://github.com/prisma/quaint/blob/master/src/serde.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0aa634c152f1e2f5fc08cb92d77ca360180b7ae103436b232421032a0243bac9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_in_memory\n\nDocumentation:\nOpen a new SQLite database in memory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_in_memory() -> crate::Result {\n Ok(Quaint {\n inner: Arc::new(connector::Sqlite::new_in_memory()?),\n connection_info: Arc::new(ConnectionInfo::InMemorySqlite {\n db_name: DEFAULT_SQLITE_SCHEMA_NAME.to_owned(),\n }),\n })\n }\n```"}], "func_name": "new_in_memory", "docstring": "Open a new SQLite database in memory.", "repo": "prisma/quaint", "path": "src/single.rs", "url": "https://github.com/prisma/quaint/blob/master/src/single.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a5c55502fb4da78a840a6c436e5e138e4688603bba0d0b6a541abc3b48baab32"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: visit_joins\n\nDocumentation:\nThe join statements in the query\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn visit_joins(&mut self, joins: Vec>) -> Result {\n for j in joins {\n match j {\n Join::Inner(data) => {\n self.write(\" INNER JOIN \")?;\n self.visit_join_data(data)?;\n }\n Join::Left(data) => {\n self.write(\" LEFT JOIN \")?;\n self.visit_join_data(data)?;\n }\n Join::Right(data) => {\n self.write(\" RIGHT JOIN \")?;\n self.visit_join_data(data)?;\n }\n Join::Full(data) => {\n self.write(\" FULL JOIN \")?;\n self.visit_join_data(data)?;\n }\n }\n }\n\n Ok(())\n }\n```"}], "func_name": "visit_joins", "docstring": "The join statements in the query", "repo": "prisma/quaint", "path": "src/visitor.rs", "url": "https://github.com/prisma/quaint/blob/master/src/visitor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d57c4f387e0e3b7d2dfc16dcdc6a59e269cd2ead7a9aea6cfab380d2de48965d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: visit_expression\n\nDocumentation:\nA visit to a value used in an expression\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn visit_expression(&mut self, value: Expression<'a>) -> Result {\n match value.kind {\n ExpressionKind::Value(value) => self.visit_expression(*value)?,\n ExpressionKind::ConditionTree(tree) => self.visit_conditions(tree)?,\n ExpressionKind::Compare(compare) => self.visit_compare(compare)?,\n ExpressionKind::Parameterized(val) => self.visit_parameterized(val)?,\n ExpressionKind::RawValue(val) => self.visit_raw_value(val.0)?,\n ExpressionKind::Column(column) => self.visit_column(*column)?,\n ExpressionKind::Row(row) => self.visit_row(row)?,\n ExpressionKind::Selection(selection) => {\n self.surround_with(\"(\", \")\", |ref mut s| s.visit_sub_selection(selection))?\n }\n ExpressionKind::Function(function) => self.visit_function(*function)?,\n ExpressionKind::Op(op) => self.visit_operation(*op)?,\n ExpressionKind::Values(values) => self.visit_values(*values)?,\n ExpressionKind::Asterisk(table) => match table {\n Some(table) => {\n self.visit_table(*table, false)?;\n self.write(\".*\")?\n }\n None => self.write(\"*\")?,\n },\n ExpressionKind::Default => self.write(\"DEFAULT\")?,\n }\n\n if let Some(alias) = value.alias {\n self.write(\" AS \")?;\n\n self.delimited_identifiers(&[&*alias])?;\n };\n\n Ok(())\n }\n```"}], "func_name": "visit_expression", "docstring": "A visit to a value used in an expression", "repo": "prisma/quaint", "path": "src/visitor.rs", "url": "https://github.com/prisma/quaint/blob/master/src/visitor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba1d3b70ce3f8d00f6c8926a3fee610504c220dbb73a67ccbc16bbac2ec4846c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_table\n\nDocumentation:\nCreates a new `DELETE` statement for the given table.\n\n```rust\n# use quaint::{ast::*, visitor::{Visitor, Sqlite}};\n# fn main() -> Result<(), quaint::error::Error> {\nlet query = Delete::from_table(\"users\");\nlet (sql, _) = Sqlite::build(query)?;\n\nassert_eq!(\"DELETE FROM `users`\", sql);\n# Ok(())\n# }\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_table(table: T) -> Self\n where\n T: Into>,\n {\n Self {\n table: table.into(),\n conditions: None,\n comment: None,\n }\n }\n```"}], "func_name": "from_table", "docstring": "Creates a new `DELETE` statement for the given table.\n\n```rust\n# use quaint::{ast::*, visitor::{Visitor, Sqlite}};\n# fn main() -> Result<(), quaint::error::Error> {\nlet query = Delete::from_table(\"users\");\nlet (sql, _) = Sqlite::build(query)?;\n\nassert_eq!(\"DELETE FROM `users`\", sql);\n# Ok(())\n# }\n```", "repo": "prisma/quaint", "path": "src/ast/delete.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/delete.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dd48593256d8d0d64a5513d5bafc1234638ee3bfcb4f4c29c93eb888210aad99"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: multi_into\n\nDocumentation:\nCreates a new multi row `INSERT` statement for the given table.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn multi_into(table: T, columns: I) -> MultiRowInsert<'a>\n where\n T: Into>,\n K: Into>,\n I: IntoIterator,\n {\n MultiRowInsert {\n table: Some(table.into()),\n columns: columns.into_iter().map(|c| c.into()).collect(),\n values: Vec::new(),\n }\n }\n```"}], "func_name": "multi_into", "docstring": "Creates a new multi row `INSERT` statement for the given table.", "repo": "prisma/quaint", "path": "src/ast/insert.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/insert.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d1effbcbc72f53b7d004bd200c835b59d63848101f36bf30e4e208c09221727"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: named_selection\n\nDocumentation:\nA list of item names in the query, skipping the anonymous values or\ncolumns.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn named_selection(&self) -> Vec {\n // Empty vector marks selection of everything.\n if self.columns.len() == 1 && self.columns.first().map(|c| c.is_asterisk()).unwrap_or(false) {\n return Vec::new();\n }\n\n self.columns\n .iter()\n .filter_map(|expr| match &expr.kind {\n ExpressionKind::Column(c) => c\n .alias\n .as_ref()\n .map(|a| a.to_string())\n .or_else(|| expr.alias.as_ref().map(|a| a.to_string()))\n .or_else(|| Some(c.name.to_string())),\n ExpressionKind::Parameterized(_) => expr.alias.as_ref().map(|a| a.to_string()),\n _ => None,\n })\n .collect()\n }\n```"}], "func_name": "named_selection", "docstring": "A list of item names in the query, skipping the anonymous values or\ncolumns.", "repo": "prisma/quaint", "path": "src/ast/select.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/select.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80b1df81fa5224e608916df37810fef22e6f66e7badee46d0371a262561289b5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: table\n\nDocumentation:\nCreates the basis for an `UPDATE` statement to the given table.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn table(table: T) -> Self\n where\n T: Into>,\n {\n Self {\n table: table.into(),\n columns: Vec::new(),\n values: Vec::new(),\n conditions: None,\n comment: None,\n }\n }\n```"}], "func_name": "table", "docstring": "Creates the basis for an `UPDATE` statement to the given table.", "repo": "prisma/quaint", "path": "src/ast/update.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/update.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ff53ebab4afa6a76c75f2acb8dae7c1bfb87de3fd9c7088279fc8c0a7c78cc4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_null\n\nDocumentation:\n`true` if the `Value` is null.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn is_null(&self) -> bool {\n match self {\n Value::Int32(i) => i.is_none(),\n Value::Int64(i) => i.is_none(),\n Value::Float(i) => i.is_none(),\n Value::Double(i) => i.is_none(),\n Value::Text(t) => t.is_none(),\n Value::Enum(e) => e.is_none(),\n Value::Bytes(b) => b.is_none(),\n Value::Boolean(b) => b.is_none(),\n Value::Char(c) => c.is_none(),\n Value::Array(v) => v.is_none(),\n Value::Xml(s) => s.is_none(),\n #[cfg(feature = \"bigdecimal\")]\n Value::Numeric(r) => r.is_none(),\n #[cfg(feature = \"uuid\")]\n Value::Uuid(u) => u.is_none(),\n #[cfg(feature = \"chrono\")]\n Value::DateTime(dt) => dt.is_none(),\n #[cfg(feature = \"chrono\")]\n Value::Date(d) => d.is_none(),\n #[cfg(feature = \"chrono\")]\n Value::Time(t) => t.is_none(),\n #[cfg(feature = \"json\")]\n Value::Json(json) => json.is_none(),\n }\n }\n```"}], "func_name": "is_null", "docstring": "`true` if the `Value` is null.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "66b05c5041b87be65b1b1966f6c3829be9f42f35b1cb60adfc876d5615e2fc02"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_text\n\nDocumentation:\n`true` if the `Value` is text.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn is_text(&self) -> bool {\n matches!(self, Value::Text(_))\n }\n```"}], "func_name": "is_text", "docstring": "`true` if the `Value` is text.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a77dc3e6401de6460ddc8a4a031f2e31814f843123eeb2d270a54a46bbe99ef4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_str\n\nDocumentation:\nReturns a &str if the value is text, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_str(&self) -> Option<&str> {\n match self {\n Value::Text(Some(cow)) => Some(cow.borrow()),\n Value::Bytes(Some(cow)) => std::str::from_utf8(cow.as_ref()).ok(),\n _ => None,\n }\n }\n```"}], "func_name": "as_str", "docstring": "Returns a &str if the value is text, otherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef043fee0627aea417dafcf7f598f991c6cc773bdf996530c52ab1cd206f0a65"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_char\n\nDocumentation:\nReturns a char if the value is a char, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn as_char(&self) -> Option {\n match self {\n Value::Char(c) => *c,\n _ => None,\n }\n }\n```"}], "func_name": "as_char", "docstring": "Returns a char if the value is a char, otherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a6160403e66e73fe874ae0a148406414e432b6a83cb35912799aeb25d8951644"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_string\n\nDocumentation:\nReturns a cloned String if the value is text, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_string(&self) -> Option {\n match self {\n Value::Text(Some(cow)) => Some(cow.to_string()),\n Value::Bytes(Some(cow)) => std::str::from_utf8(cow.as_ref()).map(|s| s.to_owned()).ok(),\n _ => None,\n }\n }\n```"}], "func_name": "to_string", "docstring": "Returns a cloned String if the value is text, otherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "471b27c41033060868e410fccdaf55b8afa734a015b7b54943c383ab7629bdf6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_string\n\nDocumentation:\nTransforms the `Value` to a `String` if it's text,\notherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_string(self) -> Option {\n match self {\n Value::Text(Some(cow)) => Some(cow.into_owned()),\n Value::Bytes(Some(cow)) => String::from_utf8(cow.into_owned()).ok(),\n _ => None,\n }\n }\n```"}], "func_name": "into_string", "docstring": "Transforms the `Value` to a `String` if it's text,\notherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "364f8a627f87e0eadc50547cdbf557d67628817171864e48fe67a1dfc163abb4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_bytes\n\nDocumentation:\nReturns whether this value is the `Bytes` variant.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn is_bytes(&self) -> bool {\n matches!(self, Value::Bytes(_))\n }\n```"}], "func_name": "is_bytes", "docstring": "Returns whether this value is the `Bytes` variant.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea9880fc08e5114370368f80b0b5fe443a38beb5e71e244e76e7bd74200feb27"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_bytes\n\nDocumentation:\nReturns a bytes slice if the value is text or a byte slice, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_bytes(&self) -> Option<&[u8]> {\n match self {\n Value::Text(Some(cow)) => Some(cow.as_ref().as_bytes()),\n Value::Bytes(Some(cow)) => Some(cow.as_ref()),\n _ => None,\n }\n }\n```"}], "func_name": "as_bytes", "docstring": "Returns a bytes slice if the value is text or a byte slice, otherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "abb9957316d104b272467fe143c3877ffa694fa4f9d336f21072e6fc864006be"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_bytes\n\nDocumentation:\nReturns a cloned `Vec` if the value is text or a byte slice, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_bytes(&self) -> Option> {\n match self {\n Value::Text(Some(cow)) => Some(cow.to_string().into_bytes()),\n Value::Bytes(Some(cow)) => Some(cow.to_vec()),\n _ => None,\n }\n }\n```"}], "func_name": "to_bytes", "docstring": "Returns a cloned `Vec` if the value is text or a byte slice, otherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e7e2361b79054925a6954fd34bbd48da86a899ba67456231e09ffa816054c36b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_i32\n\nDocumentation:\n`true` if the `Value` is a 32-bit signed integer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn is_i32(&self) -> bool {\n matches!(self, Value::Int32(_))\n }\n```"}], "func_name": "is_i32", "docstring": "`true` if the `Value` is a 32-bit signed integer.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f058fb0648d5c62f4beab827b92fb5c586185e58ae81f681e23f2a13fee7002a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_i64\n\nDocumentation:\n`true` if the `Value` is a 64-bit signed integer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn is_i64(&self) -> bool {\n matches!(self, Value::Int64(_))\n }\n```"}], "func_name": "is_i64", "docstring": "`true` if the `Value` is a 64-bit signed integer.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f9309b4d9fb50d6f93c190282d1a9ad469b75133001fd673c0bdb30be88a6ff7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_integer\n\nDocumentation:\n`true` if the `Value` is a signed integer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn is_integer(&self) -> bool {\n matches!(self, Value::Int32(_) | Value::Int64(_))\n }\n```"}], "func_name": "is_integer", "docstring": "`true` if the `Value` is a signed integer.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7f3cfbb357e0833c0d42c94f120e6c8408ba2cde5ce47f7dc8b8cb4d590103f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_i64\n\nDocumentation:\nReturns an `i64` if the value is a 64-bit signed integer, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn as_i64(&self) -> Option {\n match self {\n Value::Int64(i) => *i,\n _ => None,\n }\n }\n```"}], "func_name": "as_i64", "docstring": "Returns an `i64` if the value is a 64-bit signed integer, otherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "89442df621f0d960d2de14395bc9a7d6b896f7b191a2aec8db8a5dc1eb0429af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_i32\n\nDocumentation:\nReturns an `i32` if the value is a 32-bit signed integer, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn as_i32(&self) -> Option {\n match self {\n Value::Int32(i) => *i,\n _ => None,\n }\n }\n```"}], "func_name": "as_i32", "docstring": "Returns an `i32` if the value is a 32-bit signed integer, otherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a1cfa8457804a08715fbaf4d30f298f3f91c541156e18b7afce456fb1a085400"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_integer\n\nDocumentation:\nReturns an `i64` if the value is a signed integer, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_integer(&self) -> Option {\n match self {\n Value::Int32(i) => i.map(|i| i as i64),\n Value::Int64(i) => *i,\n _ => None,\n }\n }\n```"}], "func_name": "as_integer", "docstring": "Returns an `i64` if the value is a signed integer, otherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d0455d20ed3bf5f4888ddb2422e1d56391770cbb24f12ec17dd58151dd717bc7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_f64\n\nDocumentation:\nReturns a `f64` if the value is a double, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn as_f64(&self) -> Option {\n match self {\n Value::Double(Some(f)) => Some(*f),\n _ => None,\n }\n }\n```"}], "func_name": "as_f64", "docstring": "Returns a `f64` if the value is a double, otherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0041fc96775fbb480fc9e1d03ea88e007825a8fa4737a8bb544d2aa017ea5faa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_f32\n\nDocumentation:\nReturns a `f32` if the value is a double, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn as_f32(&self) -> Option {\n match self {\n Value::Float(Some(f)) => Some(*f),\n _ => None,\n }\n }\n```"}], "func_name": "as_f32", "docstring": "Returns a `f32` if the value is a double, otherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "714dad6d1c5fcfe11b6615e2bee72c3154ae114227cf5f0584b25e9b8629de28"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_bool\n\nDocumentation:\n`true` if the `Value` is a boolean value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn is_bool(&self) -> bool {\n match self {\n Value::Boolean(_) => true,\n // For schemas which don't tag booleans\n Value::Int32(Some(i)) if *i == 0 || *i == 1 => true,\n Value::Int64(Some(i)) if *i == 0 || *i == 1 => true,\n _ => false,\n }\n }\n```"}], "func_name": "is_bool", "docstring": "`true` if the `Value` is a boolean value.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a336d56a5a2f31496488fe8c5d40bb98d8785f006e26ab42ff66f6ecf7aa83b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_bool\n\nDocumentation:\nReturns a bool if the value is a boolean, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn as_bool(&self) -> Option {\n match self {\n Value::Boolean(b) => *b,\n // For schemas which don't tag booleans\n Value::Int32(Some(i)) if *i == 0 || *i == 1 => Some(*i == 1),\n Value::Int64(Some(i)) if *i == 0 || *i == 1 => Some(*i == 1),\n _ => None,\n }\n }\n```"}], "func_name": "as_bool", "docstring": "Returns a bool if the value is a boolean, otherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6eef03fa4ad19fd3c26437ffb2e0ad1e86798915630884ba6ac56e1e49389394"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_array\n\nDocumentation:\n`true` if the `Value` is an Array.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn is_array(&self) -> bool {\n matches!(self, Value::Array(_))\n }\n```"}], "func_name": "is_array", "docstring": "`true` if the `Value` is an Array.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ec544c1d1503285c0b198a9e81a8c0d9273784c387394a066d47716ec6208f97"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_vec\n\nDocumentation:\nReturns a `Vec` if the value is an array of `T`, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_vec(self) -> Option>\n where\n // Implement From\n T: TryFrom>,\n {\n match self {\n Value::Array(Some(vec)) => {\n let rslt: Result, _> = vec.into_iter().map(T::try_from).collect();\n match rslt {\n Err(_) => None,\n Ok(values) => Some(values),\n }\n }\n _ => None,\n }\n }\n```"}], "func_name": "into_vec", "docstring": "Returns a `Vec` if the value is an array of `T`, otherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b4333b388a70ae53f6fc50f1d4efc5103f05f79f97c1e9e4b3c771475064b876"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_vec\n\nDocumentation:\nReturns a cloned Vec if the value is an array of T, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_vec(&self) -> Option>\n where\n T: TryFrom>,\n {\n match self {\n Value::Array(Some(vec)) => {\n let rslt: Result, _> = vec.clone().into_iter().map(T::try_from).collect();\n match rslt {\n Err(_) => None,\n Ok(values) => Some(values),\n }\n }\n _ => None,\n }\n }\n```"}], "func_name": "to_vec", "docstring": "Returns a cloned Vec if the value is an array of T, otherwise `None`.", "repo": "prisma/quaint", "path": "src/ast/values.rs", "url": "https://github.com/prisma/quaint/blob/master/src/ast/values.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cfc26cb0795e13675af1d4f6dc559d86babfe510cdc2fefb4208b94d298f2cf9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_url\n\nDocumentation:\nParse `ConnectionInfo` out from an SQL connection string.\n\nWill fail if URI is invalid or the scheme points to an unsupported\ndatabase.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_url(url_str: &str) -> crate::Result {\n let url_result: Result = url_str.parse();\n\n // Non-URL database strings are interpreted as SQLite file paths.\n match url_str {\n #[cfg(feature = \"sqlite\")]\n s if s.starts_with(\"file\") => {\n if url_result.is_err() {\n let params = SqliteParams::try_from(s)?;\n\n return Ok(ConnectionInfo::Sqlite {\n file_path: params.file_path,\n db_name: params.db_name,\n });\n }\n }\n #[cfg(feature = \"mssql\")]\n s if s.starts_with(\"jdbc:sqlserver\") || s.starts_with(\"sqlserver\") => {\n return Ok(ConnectionInfo::Mssql(MssqlUrl::new(url_str)?));\n }\n _ => (),\n }\n\n let url = url_result?;\n\n let sql_family = SqlFamily::from_scheme(url.scheme()).ok_or_else(|| {\n let kind =\n ErrorKind::DatabaseUrlIsInvalid(format!(\"{} is not a supported database URL scheme.\", url.scheme()));\n\n Error::builder(kind).build()\n })?;\n\n match sql_family {\n #[cfg(feature = \"mysql\")]\n SqlFamily::Mysql => Ok(ConnectionInfo::Mysql(MysqlUrl::new(url)?)),\n #[cfg(feature = \"sqlite\")]\n SqlFamily::Sqlite => {\n let params = SqliteParams::try_from(url_str)?;\n\n Ok(ConnectionInfo::Sqlite {\n file_path: params.file_path,\n db_name: params.db_name,\n })\n }\n #[cfg(feature = \"postgresql\")]\n SqlFamily::Postgres => Ok(ConnectionInfo::Postgres(PostgresUrl::new(url)?)),\n #[allow(unreachable_patterns)]\n _ => unreachable!(),\n }\n }\n```"}], "func_name": "from_url", "docstring": "Parse `ConnectionInfo` out from an SQL connection string.\n\nWill fail if URI is invalid or the scheme points to an unsupported\ndatabase.", "repo": "prisma/quaint", "path": "src/connector/connection_info.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/connection_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a9103c0ec1e2a830098ad75572c253747bf147b2f750e22f98ca074a6ef2e1b8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dbname\n\nDocumentation:\nThe provided database name. This will be `None` on SQLite.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn dbname(&self) -> Option<&str> {\n match self {\n #[cfg(feature = \"postgresql\")]\n ConnectionInfo::Postgres(url) => Some(url.dbname()),\n #[cfg(feature = \"mysql\")]\n ConnectionInfo::Mysql(url) => Some(url.dbname()),\n #[cfg(feature = \"mssql\")]\n ConnectionInfo::Mssql(url) => Some(url.dbname()),\n #[cfg(feature = \"sqlite\")]\n ConnectionInfo::Sqlite { .. } | ConnectionInfo::InMemorySqlite { .. } => None,\n }\n }\n```"}], "func_name": "dbname", "docstring": "The provided database name. This will be `None` on SQLite.", "repo": "prisma/quaint", "path": "src/connector/connection_info.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/connection_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dbe4b44799849fb6430f5be6d5dbf0db4fcb85e07c012dcb2f3b5440112fbf60"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: schema_name\n\nDocumentation:\nThis is what item names are prefixed with in queries.\n\n- In SQLite, this is the schema name that the database file was attached as.\n- In Postgres, it is the selected schema inside the current database.\n- In MySQL, it is the database name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn schema_name(&self) -> &str {\n match self {\n #[cfg(feature = \"postgresql\")]\n ConnectionInfo::Postgres(url) => url.schema(),\n #[cfg(feature = \"mysql\")]\n ConnectionInfo::Mysql(url) => url.dbname(),\n #[cfg(feature = \"mssql\")]\n ConnectionInfo::Mssql(url) => url.schema(),\n #[cfg(feature = \"sqlite\")]\n ConnectionInfo::Sqlite { db_name, .. } => db_name,\n #[cfg(feature = \"sqlite\")]\n ConnectionInfo::InMemorySqlite { db_name } => db_name,\n }\n }\n```"}], "func_name": "schema_name", "docstring": "This is what item names are prefixed with in queries.\n\n- In SQLite, this is the schema name that the database file was attached as.\n- In Postgres, it is the selected schema inside the current database.\n- In MySQL, it is the database name.", "repo": "prisma/quaint", "path": "src/connector/connection_info.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/connection_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d72788ff7a7a1d113c7c949e6dadcafa1a6d90225b0c85a372f9d86d843a4ed6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: host\n\nDocumentation:\nThe provided database host. This will be `\"localhost\"` on SQLite.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn host(&self) -> &str {\n match self {\n #[cfg(feature = \"postgresql\")]\n ConnectionInfo::Postgres(url) => url.host(),\n #[cfg(feature = \"mysql\")]\n ConnectionInfo::Mysql(url) => url.host(),\n #[cfg(feature = \"mssql\")]\n ConnectionInfo::Mssql(url) => url.host(),\n #[cfg(feature = \"sqlite\")]\n ConnectionInfo::Sqlite { .. } | ConnectionInfo::InMemorySqlite { .. } => \"localhost\",\n }\n }\n```"}], "func_name": "host", "docstring": "The provided database host. This will be `\"localhost\"` on SQLite.", "repo": "prisma/quaint", "path": "src/connector/connection_info.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/connection_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e0d38b998839a7fe1723a4242fa35be36063f11c9bd3372a8296a2e0508d7aa6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: username\n\nDocumentation:\nThe provided database user name. This will be `None` on SQLite.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn username(&self) -> Option> {\n match self {\n #[cfg(feature = \"postgresql\")]\n ConnectionInfo::Postgres(url) => Some(url.username()),\n #[cfg(feature = \"mysql\")]\n ConnectionInfo::Mysql(url) => Some(url.username()),\n #[cfg(feature = \"mssql\")]\n ConnectionInfo::Mssql(url) => url.username().map(Cow::from),\n #[cfg(feature = \"sqlite\")]\n ConnectionInfo::Sqlite { .. } | ConnectionInfo::InMemorySqlite { .. } => None,\n }\n }\n```"}], "func_name": "username", "docstring": "The provided database user name. This will be `None` on SQLite.", "repo": "prisma/quaint", "path": "src/connector/connection_info.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/connection_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dffc1831d65ab139a4b58ada400a7956ddaefa0d122c0ba246deb254c624dfc0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: file_path\n\nDocumentation:\nThe database file for SQLite, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn file_path(&self) -> Option<&str> {\n match self {\n #[cfg(feature = \"postgresql\")]\n ConnectionInfo::Postgres(_) => None,\n #[cfg(feature = \"mysql\")]\n ConnectionInfo::Mysql(_) => None,\n #[cfg(feature = \"mssql\")]\n ConnectionInfo::Mssql(_) => None,\n #[cfg(feature = \"sqlite\")]\n ConnectionInfo::Sqlite { file_path, .. } => Some(file_path),\n #[cfg(feature = \"sqlite\")]\n ConnectionInfo::InMemorySqlite { .. } => None,\n }\n }\n```"}], "func_name": "file_path", "docstring": "The database file for SQLite, otherwise `None`.", "repo": "prisma/quaint", "path": "src/connector/connection_info.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/connection_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "111891b6182f882e344d18e13daf73178bfca51873608e8e810011348d00501f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: port\n\nDocumentation:\nThe provided database port, if applicable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn port(&self) -> Option {\n match self {\n #[cfg(feature = \"postgresql\")]\n ConnectionInfo::Postgres(url) => Some(url.port()),\n #[cfg(feature = \"mysql\")]\n ConnectionInfo::Mysql(url) => Some(url.port()),\n #[cfg(feature = \"mssql\")]\n ConnectionInfo::Mssql(url) => Some(url.port()),\n #[cfg(feature = \"sqlite\")]\n ConnectionInfo::Sqlite { .. } | ConnectionInfo::InMemorySqlite { .. } => None,\n }\n }\n```"}], "func_name": "port", "docstring": "The provided database port, if applicable.", "repo": "prisma/quaint", "path": "src/connector/connection_info.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/connection_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb27dc69c3bbe84d62fa3e31f20aea9370dbbc62cda398e6198fc8d87e8354aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pg_bouncer\n\nDocumentation:\nWhether the pgbouncer mode is enabled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pg_bouncer(&self) -> bool {\n #[allow(unreachable_patterns)]\n match self {\n #[cfg(feature = \"postgresql\")]\n ConnectionInfo::Postgres(url) => url.pg_bouncer(),\n _ => false,\n }\n }\n```"}], "func_name": "pg_bouncer", "docstring": "Whether the pgbouncer mode is enabled.", "repo": "prisma/quaint", "path": "src/connector/connection_info.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/connection_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "689ffa36e29fd9d3a28850cd3d037cc5daf7b8c2628348aa3c6626b5347375fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: database_location\n\nDocumentation:\nA string describing the database location, meant for error messages. It will be the host\nand port on MySQL/Postgres, and the file path on SQLite.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn database_location(&self) -> String {\n match self {\n #[cfg(feature = \"postgresql\")]\n ConnectionInfo::Postgres(url) => format!(\"{}:{}\", url.host(), url.port()),\n #[cfg(feature = \"mysql\")]\n ConnectionInfo::Mysql(url) => format!(\"{}:{}\", url.host(), url.port()),\n #[cfg(feature = \"mssql\")]\n ConnectionInfo::Mssql(url) => format!(\"{}:{}\", url.host(), url.port()),\n #[cfg(feature = \"sqlite\")]\n ConnectionInfo::Sqlite { file_path, .. } => file_path.clone(),\n #[cfg(feature = \"sqlite\")]\n ConnectionInfo::InMemorySqlite { .. } => \"in-memory\".into(),\n }\n }\n```"}], "func_name": "database_location", "docstring": "A string describing the database location, meant for error messages. It will be the host\nand port on MySQL/Postgres, and the file path on SQLite.", "repo": "prisma/quaint", "path": "src/connector/connection_info.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/connection_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8557abbf934c4921c74b8e5d7925760805eb86f56c3293d66982d3583f9f3dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nParse `Url` to `MysqlUrl`. Returns error for mistyped connection\nparameters.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(url: Url) -> Result {\n let query_params = Self::parse_query_params(&url)?;\n\n Ok(Self { url, query_params })\n }\n```"}], "func_name": "new", "docstring": "Parse `Url` to `MysqlUrl`. Returns error for mistyped connection\nparameters.", "repo": "prisma/quaint", "path": "src/connector/mysql.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/mysql.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "46ffcdee4b9798ced5c1ec39098f73e48aba87d01f17f3a2a5a8fabfdc83c17e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dbname\n\nDocumentation:\nName of the database connected. Defaults to `mysql`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn dbname(&self) -> &str {\n match self.url.path_segments() {\n Some(mut segments) => segments.next().unwrap_or(\"mysql\"),\n None => \"mysql\",\n }\n }\n```"}], "func_name": "dbname", "docstring": "Name of the database connected. Defaults to `mysql`.", "repo": "prisma/quaint", "path": "src/connector/mysql.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/mysql.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d60d09ed58ee964e825844c1efd474d764be6ec42c6c8c3f71aa8706ca672908"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new MySQL connection using `OptsBuilder` from the `mysql` crate.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn new(url: MysqlUrl) -> crate::Result {\n let conn = super::timeout::connect(url.connect_timeout(), my::Conn::new(url.to_opts_builder())).await?;\n\n Ok(Self {\n socket_timeout: url.query_params.socket_timeout,\n conn: Mutex::new(conn),\n statement_cache: Mutex::new(url.cache()),\n url,\n is_healthy: AtomicBool::new(true),\n })\n }\n```"}], "func_name": "new", "docstring": "Create a new MySQL connection using `OptsBuilder` from the `mysql` crate.", "repo": "prisma/quaint", "path": "src/connector/mysql.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/mysql.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "79ccaf72a53e8c02c86a2c7699ed220bf979c9d91bdf57040ee0878e802f258d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_postgres\n\nDocumentation:\nReturns `true` if the postgres flavour is [`Postgres`].\n\n[`Postgres`]: PostgresFlavour::Postgres\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_postgres(&self) -> bool {\n matches!(self, Self::Postgres)\n }\n```"}], "func_name": "is_postgres", "docstring": "Returns `true` if the postgres flavour is [`Postgres`].\n\n[`Postgres`]: PostgresFlavour::Postgres", "repo": "prisma/quaint", "path": "src/connector/postgres.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/postgres.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f82122975468cc2370dd7ece1a1ad7fd20e41fca7bc1e1e4f512c6f137f1a7a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_cockroach\n\nDocumentation:\nReturns `true` if the postgres flavour is [`Cockroach`].\n\n[`Cockroach`]: PostgresFlavour::Cockroach\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_cockroach(&self) -> bool {\n matches!(self, Self::Cockroach)\n }\n```"}], "func_name": "is_cockroach", "docstring": "Returns `true` if the postgres flavour is [`Cockroach`].\n\n[`Cockroach`]: PostgresFlavour::Cockroach", "repo": "prisma/quaint", "path": "src/connector/postgres.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/postgres.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "adc0e2b6e4fae651b49e18603b2685a9804e243eaff01888ed4dd349ae1e7596"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_unknown\n\nDocumentation:\nReturns `true` if the postgres flavour is [`Unknown`].\n\n[`Unknown`]: PostgresFlavour::Unknown\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_unknown(&self) -> bool {\n matches!(self, Self::Unknown)\n }\n```"}], "func_name": "is_unknown", "docstring": "Returns `true` if the postgres flavour is [`Unknown`].\n\n[`Unknown`]: PostgresFlavour::Unknown", "repo": "prisma/quaint", "path": "src/connector/postgres.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/postgres.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4101f5f68bb9fa59b50a1f117e180a520b9731952a8d51b298ab735471e7d007"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: host\n\nDocumentation:\nThe database host. Taken first from the `host` query parameter, then\nfrom the `host` part of the URL. For socket connections, the query\nparameter must be used.\n\nIf none of them are set, defaults to `localhost`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn host(&self) -> &str {\n match (self.query_params.host.as_ref(), self.url.host_str()) {\n (Some(host), _) => host.as_str(),\n (None, Some(\"\")) => \"localhost\",\n (None, None) => \"localhost\",\n (None, Some(host)) => host,\n }\n }\n```"}], "func_name": "host", "docstring": "The database host. Taken first from the `host` query parameter, then\nfrom the `host` part of the URL. For socket connections, the query\nparameter must be used.\n\nIf none of them are set, defaults to `localhost`.", "repo": "prisma/quaint", "path": "src/connector/postgres.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/postgres.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "58d2d8d0410cd7e780d3341b6f6ed081b138bb4b6ca58c18b83e91114de2f4e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new connection to the database.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn new(url: PostgresUrl) -> crate::Result {\n let config = url.to_config();\n\n let mut tls_builder = TlsConnector::builder();\n\n {\n let ssl_params = url.ssl_params();\n let auth = ssl_params.to_owned().into_auth().await?;\n\n if let Some(certificate) = auth.certificate.0 {\n tls_builder.add_root_certificate(certificate);\n }\n\n tls_builder.danger_accept_invalid_certs(auth.ssl_accept_mode == SslAcceptMode::AcceptInvalidCerts);\n\n if let Some(identity) = auth.identity.0 {\n tls_builder.identity(identity);\n }\n }\n\n let tls = MakeTlsConnector::new(tls_builder.build()?);\n let (client, conn) = super::timeout::connect(url.connect_timeout(), config.connect(tls)).await?;\n\n tokio::spawn(conn.map(|r| match r {\n Ok(_) => (),\n Err(e) => {\n tracing::error!(\"Error in PostgreSQL connection: {:?}\", e);\n }\n }));\n\n // On Postgres, we set the SEARCH_PATH and client-encoding through client connection parameters to save a network roundtrip on connection.\n // We can't always do it for CockroachDB because it does not expect quotes for unsafe identifiers (https://github.com/cockroachdb/cockroach/issues/101328), which might change once the issue is fixed.\n // To circumvent that problem, we only set the SEARCH_PATH through client connection parameters for Cockroach when the identifier is safe, so that the quoting does not matter.\n // Finally, to ensure backward compatibility, we keep sending a database query in case the flavour is set to Unknown.\n if let Some(schema) = &url.query_params.schema {\n // PGBouncer does not support the search_path connection parameter.\n // https://www.pgbouncer.org/config.html#ignore_startup_parameters\n if url.query_params.pg_bouncer\n || url.flavour().is_unknown()\n || (url.flavour().is_cockroach() && !is_safe_identifier(schema))\n {\n let session_variables = format!(\n r##\"{set_search_path}\"##,\n set_search_path = SetSearchPath(url.query_params.schema.as_deref())\n );\n\n client.simple_query(session_variables.as_str()).await?;\n }\n }\n\n Ok(Self {\n client: PostgresClient(client),\n socket_timeout: url.query_params.socket_timeout,\n pg_bouncer: url.query_params.pg_bouncer,\n statement_cache: Mutex::new(url.cache()),\n is_healthy: AtomicBool::new(true),\n })\n }\n```"}], "func_name": "new", "docstring": "Create a new connection to the database.", "repo": "prisma/quaint", "path": "src/connector/postgres.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/postgres.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "96977dbd4d4730f9baf796c91b116ebebbc52acdb2b19d80a40a586ff48b5f6b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete\n\nDocumentation:\nExecute a `DELETE` query, returning the number of affected rows.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn delete(&self, q: Delete<'_>) -> crate::Result<()> {\n self.query(q.into()).await?;\n Ok(())\n }\n```"}], "func_name": "delete", "docstring": "Execute a `DELETE` query, returning the number of affected rows.", "repo": "prisma/quaint", "path": "src/connector/queryable.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/queryable.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "065b809b32bb6a1763bc849fd265b08c8e4306f5ff5b5d19b335c58df81d9f0d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance, bound to the given column names and result rows.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(names: Vec, rows: Vec>>) -> Self {\n Self {\n columns: Arc::new(names),\n rows,\n last_insert_id: None,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance, bound to the given column names and result rows.", "repo": "prisma/quaint", "path": "src/connector/result_set.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/result_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "41f7cc5a6c6b5220e284dca982cf617f19301e3b09fae1567e31d5667be9edfa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturns a reference to a row in a given position.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(&self, index: usize) -> Option {\n self.rows.get(index).map(|row| ResultRowRef {\n columns: Arc::clone(&self.columns),\n values: row,\n })\n }\n```"}], "func_name": "get", "docstring": "Returns a reference to a row in a given position.", "repo": "prisma/quaint", "path": "src/connector/result_set.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/result_set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1d952ce9b44d9e4b1bcf250f7d1d4a79c5640378023f643390ccfcdd6b9b5be3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rollback\n\nDocumentation:\nRolls back the changes to the database.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn rollback(&self) -> crate::Result<()> {\n decrement_gauge!(\"prisma_client_queries_active\", 1.0);\n self.inner.raw_cmd(\"ROLLBACK\").await?;\n\n Ok(())\n }\n```"}], "func_name": "rollback", "docstring": "Rolls back the changes to the database.", "repo": "prisma/quaint", "path": "src/connector/transaction.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/transaction.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c4014a7b137d0d647812b358e39355152734659c0a3a77392ad0fa61f9ce4afb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: params_to_types\n\nDocumentation:\nMaps a list of query parameter values to a list of Postgres type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn params_to_types(params: &[Value<'_>]) -> Vec {\n params\n .iter()\n .map(|p| -> PostgresType {\n // While we can infer the underlying type of a null, Prisma can't.\n // Therefore, we let PG infer the underlying type.\n if p.is_null() {\n return PostgresType::UNKNOWN;\n }\n\n match p {\n Value::Int32(_) => PostgresType::INT4,\n Value::Int64(_) => PostgresType::INT8,\n Value::Float(_) => PostgresType::FLOAT4,\n Value::Double(_) => PostgresType::FLOAT8,\n Value::Text(_) => PostgresType::TEXT,\n // Enums are special types, we can't statically infer them, so we let PG infer it\n Value::Enum(_) => PostgresType::UNKNOWN,\n Value::Bytes(_) => PostgresType::BYTEA,\n Value::Boolean(_) => PostgresType::BOOL,\n Value::Char(_) => PostgresType::CHAR,\n #[cfg(feature = \"bigdecimal\")]\n Value::Numeric(_) => PostgresType::NUMERIC,\n #[cfg(feature = \"json\")]\n Value::Json(_) => PostgresType::JSONB,\n Value::Xml(_) => PostgresType::XML,\n #[cfg(feature = \"uuid\")]\n Value::Uuid(_) => PostgresType::UUID,\n #[cfg(feature = \"chrono\")]\n Value::DateTime(_) => PostgresType::TIMESTAMPTZ,\n #[cfg(feature = \"chrono\")]\n Value::Date(_) => PostgresType::TIMESTAMP,\n #[cfg(feature = \"chrono\")]\n Value::Time(_) => PostgresType::TIME,\n Value::Array(ref arr) => {\n let arr = arr.as_ref().unwrap();\n\n // If the array is empty, we can't infer the type so we let PG infer it\n if arr.is_empty() {\n return PostgresType::UNKNOWN;\n }\n\n let first = arr.first().unwrap();\n\n // If the array does not contain the same types of values, we let PG infer the type\n if arr\n .iter()\n .any(|val| std::mem::discriminant(first) != std::mem::discriminant(val))\n {\n return PostgresType::UNKNOWN;\n }\n\n match first {\n Value::Int32(_) => PostgresType::INT4_ARRAY,\n Value::Int64(_) => PostgresType::INT8_ARRAY,\n Value::Float(_) => PostgresType::FLOAT4_ARRAY,\n Value::Double(_) => PostgresType::FLOAT8_ARRAY,\n Value::Text(_) => PostgresType::TEXT_ARRAY,\n // Enums are special types, we can't statically infer them, so we let PG infer it\n Value::Enum(_) => PostgresType::UNKNOWN,\n Value::Bytes(_) => PostgresType::BYTEA_ARRAY,\n Value::Boolean(_) => PostgresType::BOOL_ARRAY,\n Value::Char(_) => PostgresType::CHAR_ARRAY,\n #[cfg(feature = \"bigdecimal\")]\n Value::Numeric(_) => PostgresType::NUMERIC_ARRAY,\n #[cfg(feature = \"json\")]\n Value::Json(_) => PostgresType::JSONB_ARRAY,\n Value::Xml(_) => PostgresType::XML_ARRAY,\n #[cfg(feature = \"uuid\")]\n Value::Uuid(_) => PostgresType::UUID_ARRAY,\n #[cfg(feature = \"chrono\")]\n Value::DateTime(_) => PostgresType::TIMESTAMPTZ_ARRAY,\n #[cfg(feature = \"chrono\")]\n Value::Date(_) => PostgresType::TIMESTAMP_ARRAY,\n #[cfg(feature = \"chrono\")]\n Value::Time(_) => PostgresType::TIME_ARRAY,\n // In the case of nested arrays, we let PG infer the type\n Value::Array(_) => PostgresType::UNKNOWN,\n }\n }\n }\n })\n .collect()\n}\n```"}], "func_name": "params_to_types", "docstring": "Maps a list of query parameter values to a list of Postgres type.", "repo": "prisma/quaint", "path": "src/connector/postgres/conversion.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/postgres/conversion.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6932bd5887bacb067a65f02b23499a6e450f843d5a4abbd496d0ff859120e90f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_ref\n\nDocumentation:\nMake a referring [ResultRowRef](struct.ResultRowRef.html).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_ref(&self) -> ResultRowRef {\n ResultRowRef {\n columns: Arc::clone(&self.columns),\n values: &self.values,\n }\n }\n```"}], "func_name": "as_ref", "docstring": "Make a referring [ResultRowRef](struct.ResultRowRef.html).", "repo": "prisma/quaint", "path": "src/connector/result_set/result_row.rs", "url": "https://github.com/prisma/quaint/blob/master/src/connector/result_set/result_row.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0016ef9dbe80399e87d4d968372ab37c4ab371775ab31e946f714256d1be1b38"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: strip_test_attribute\n\nDocumentation:\nWe do this because Intellij only recognizes functions annotated with #[test]\n*before* macro expansion as tests. This way we can add it manually, and the\ntest macro will strip it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn strip_test_attribute(function: &mut ItemFn) {\n let new_attrs = function\n .attrs\n .drain(..)\n .filter(|attr| attr.path.segments.iter().last().unwrap().ident != \"test\")\n .collect();\n\n function.attrs = new_attrs;\n}\n```"}], "func_name": "strip_test_attribute", "docstring": "We do this because Intellij only recognizes functions annotated with #[test]\n*before* macro expansion as tests. This way we can add it manually, and the\ntest macro will strip it.", "repo": "prisma/quaint", "path": "test-macros/src/lib.rs", "url": "https://github.com/prisma/quaint/blob/master/test-macros/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac0fe810f25c1c7eeb76a8e600416213318db969a3b1b31291a61418db4e6562"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nWraps some `T` into a `GhostCell` with brand `'brand` which associates it to one, and only one, `GhostToken`.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nGhostToken::new(|token| {\nlet cell = GhostCell::new(42);\n\nassert_eq!(42, *cell.borrow(&token));\n});\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn new(value: T) -> Self {\n let _marker = PhantomData;\n let value = UnsafeCell::new(value);\n\n Self { _marker, value }\n }\n```"}], "func_name": "new", "docstring": "Wraps some `T` into a `GhostCell` with brand `'brand` which associates it to one, and only one, `GhostToken`.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nGhostToken::new(|token| {\nlet cell = GhostCell::new(42);\n\nassert_eq!(42, *cell.borrow(&token));\n});\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cell.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cell.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "315f7350f5e16c399271dc5a05d3109312d60b8c5e86a609a457b56b68f52ee1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: borrow\n\nDocumentation:\nImmutably borrows the `GhostCell` with the same-branded token.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\n\nlet value = GhostToken::new(|mut token| {\nlet cell = GhostCell::new(42);\n\nlet vec: Vec<_> = (0..n).map(|_| &cell).collect();\n\nlet one: &i32 = vec[1].borrow(&token);\nlet two: &i32 = vec[2].borrow(&token);\n\n*one + *two\n});\n\nassert_eq!(84, value);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn borrow<'a>(&'a self, _: &'a GhostToken<'brand>) -> &'a T {\n // Safety:\n // - The cell is borrowed immutably by this call, it therefore cannot already be borrowed mutably.\n // - The token is borrowed immutably by this call, it therefore cannot be already borrowed mutably.\n // - `self.value` therefore cannot be already borrowed mutably, as doing so requires calling either:\n // - `borrow_mut`, which would borrow the token mutably.\n // - `get_mut`, which would borrow the cell mutably.\n unsafe { &*self.value.get() }\n }\n```"}], "func_name": "borrow", "docstring": "Immutably borrows the `GhostCell` with the same-branded token.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\n\nlet value = GhostToken::new(|mut token| {\nlet cell = GhostCell::new(42);\n\nlet vec: Vec<_> = (0..n).map(|_| &cell).collect();\n\nlet one: &i32 = vec[1].borrow(&token);\nlet two: &i32 = vec[2].borrow(&token);\n\n*one + *two\n});\n\nassert_eq!(84, value);\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cell.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cell.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "35c5cc1ba68bec14d4e49ba182674e4eb6dd0e4e3b0e262c27bc8ba5ce87e6f9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: borrow_mut\n\nDocumentation:\nMutably borrows the `GhostCell` with the same-branded token.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\n\nlet value = GhostToken::new(|mut token| {\nlet cell = GhostCell::new(42);\n\nlet vec: Vec<_> = (0..n).map(|_| &cell).collect();\n\nlet reference: &mut i32 = vec[n / 2].borrow_mut(&mut token);\n*reference = 33;\n\n*cell.borrow(&token)\n});\n\nassert_eq!(33, value);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn borrow_mut<'a>(&'a self, _: &'a mut GhostToken<'brand>) -> &'a mut T {\n // Safety:\n // - The cell is borrowed immutably by this call, it therefore cannot already be borrowed mutably.\n // - The token is borrowed mutably by this call, it therefore cannot be already borrowed.\n // - `self.value` therefore cannot already be borrowed, as doing so requires calling either:\n // - `borrow` or `borrow_mut`, which would borrow the token.\n // - `get_mut`, which would borrow the cell mutably.\n unsafe { &mut *self.value.get() }\n }\n```"}], "func_name": "borrow_mut", "docstring": "Mutably borrows the `GhostCell` with the same-branded token.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\n\nlet value = GhostToken::new(|mut token| {\nlet cell = GhostCell::new(42);\n\nlet vec: Vec<_> = (0..n).map(|_| &cell).collect();\n\nlet reference: &mut i32 = vec[n / 2].borrow_mut(&mut token);\n*reference = 33;\n\n*cell.borrow(&token)\n});\n\nassert_eq!(33, value);\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cell.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cell.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1d950e9deb254060e509d7897c83677a588e3bfe8457f2beb440e29f78ddcafa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_mut\n\nDocumentation:\nTurns a mutably borrowed `GhostCell` into mutably borrowed data.\n\n`self` is mutably borrowed for the lifetime of the result, ensuring the absence of aliasing.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet value = GhostToken::new(|mut token| {\nlet mut cell = GhostCell::new(42);\n\n*cell.get_mut() = 33;\n\n*cell.borrow(&token)\n});\n\nassert_eq!(33, value);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_mut(&mut self) -> &mut T {\n // Safety:\n // - `self` is mutably borrowed for the duration.\n // - `GhostCell<'_, T>` has the same in-memory representation as `T`.\n unsafe { mem::transmute(self) }\n }\n```"}], "func_name": "get_mut", "docstring": "Turns a mutably borrowed `GhostCell` into mutably borrowed data.\n\n`self` is mutably borrowed for the lifetime of the result, ensuring the absence of aliasing.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet value = GhostToken::new(|mut token| {\nlet mut cell = GhostCell::new(42);\n\n*cell.get_mut() = 33;\n\n*cell.borrow(&token)\n});\n\nassert_eq!(33, value);\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cell.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cell.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c86ca6a93e6f428a2d1328eaafb7b03efe05137185248ec50229fff46bdadf5d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_mut\n\nDocumentation:\nTurns mutably borrowed data into a mutably borrowed `GhostCell`.\n\n`t` is mutably borrowed for the lifetime of the result, ensuring the absence of aliasing.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\nlet mut value = 42;\n\nGhostToken::new(|mut token| {\nlet cell = GhostCell::from_mut(&mut value);\n\nlet vec: Vec<_> = (0..n).map(|_| &cell).collect();\n\n*vec[n / 2].borrow_mut(&mut token) = 33;\n});\n\nassert_eq!(33, value);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_mut(t: &mut T) -> &mut Self {\n // Safety:\n // - `t` is mutably borrowed for the duration.\n // - `GhostCell<'_, T>` has the same in-memory representation as `T`.\n unsafe { mem::transmute(t) }\n }\n```"}], "func_name": "from_mut", "docstring": "Turns mutably borrowed data into a mutably borrowed `GhostCell`.\n\n`t` is mutably borrowed for the lifetime of the result, ensuring the absence of aliasing.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\nlet mut value = 42;\n\nGhostToken::new(|mut token| {\nlet cell = GhostCell::from_mut(&mut value);\n\nlet vec: Vec<_> = (0..n).map(|_| &cell).collect();\n\n*vec[n / 2].borrow_mut(&mut token) = 33;\n});\n\nassert_eq!(33, value);\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cell.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cell.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c4c5239a8fc2e411dec17b92d12d036ebd5de77b845b80628bcf92dde0987a7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: replace\n\nDocumentation:\nReturns the value, replacing it by the supplied one.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\n\nlet value = GhostToken::new(|mut token| {\nlet cell = GhostCell::new(42);\n\nlet vec: Vec<_> = (0..n).map(|_| &cell).collect();\n\nlet previous = vec[n / 2].replace(33, &mut token);\nassert_eq!(42, previous);\n\n*cell.borrow(&token)\n});\n\nassert_eq!(33, value);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn replace(&self, value: T, token: &mut GhostToken<'brand>) -> T {\n mem::replace(self.borrow_mut(token), value)\n }\n```"}], "func_name": "replace", "docstring": "Returns the value, replacing it by the supplied one.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\n\nlet value = GhostToken::new(|mut token| {\nlet cell = GhostCell::new(42);\n\nlet vec: Vec<_> = (0..n).map(|_| &cell).collect();\n\nlet previous = vec[n / 2].replace(33, &mut token);\nassert_eq!(42, previous);\n\n*cell.borrow(&token)\n});\n\nassert_eq!(33, value);\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cell.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cell.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "99e83c32d6dca22daf192925ac605faaca0a6ff5e3f0f978ecb0f7d6180ec5ca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: take\n\nDocumentation:\nReturns the value, replacing it with the default value.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\n\nlet value = GhostToken::new(|mut token| {\nlet cell = GhostCell::new(42);\n\nlet vec: Vec<_> = (0..n).map(|_| &cell).collect();\n\nlet previous = vec[n / 2].take(&mut token);\nassert_eq!(42, previous);\n\n*cell.borrow(&token)\n});\n\nassert_eq!(0, value);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn take(&self, token: &mut GhostToken<'brand>) -> T\n where\n T: Default,\n {\n self.replace(T::default(), token)\n }\n```"}], "func_name": "take", "docstring": "Returns the value, replacing it with the default value.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\n\nlet value = GhostToken::new(|mut token| {\nlet cell = GhostCell::new(42);\n\nlet vec: Vec<_> = (0..n).map(|_| &cell).collect();\n\nlet previous = vec[n / 2].take(&mut token);\nassert_eq!(42, previous);\n\n*cell.borrow(&token)\n});\n\nassert_eq!(0, value);\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cell.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cell.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "afba678396c4fb359c02bfe2011615071d9dbb95611ab6ab5126927d1344b0f8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_slice_of_cells\n\nDocumentation:\nReturns a slice of cells from a cell containing a slice.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\n\nlet value = GhostToken::new(|mut token| {\nlet mut vec: Vec<_> = (0..n).collect();\nlet cell = GhostCell::from_mut(&mut vec[..]);\n\nlet slice = cell.as_slice_of_cells();\n\n*slice[n / 2].borrow_mut(&mut token) = 33;\n\nvec[n / 2]\n});\n\nassert_eq!(33, value);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_slice_of_cells(&self) -> &[GhostCell<'brand, T>] {\n // Safety:\n // - Same lifetime.\n // - `GhostCell<'_, T>` has the same in-memory representation as `T`.\n unsafe { &*(self.as_ptr() as *mut [GhostCell<'brand, T>]) }\n }\n```"}], "func_name": "as_slice_of_cells", "docstring": "Returns a slice of cells from a cell containing a slice.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\n\nlet value = GhostToken::new(|mut token| {\nlet mut vec: Vec<_> = (0..n).collect();\nlet cell = GhostCell::from_mut(&mut vec[..]);\n\nlet slice = cell.as_slice_of_cells();\n\n*slice[n / 2].borrow_mut(&mut token) = 33;\n\nvec[n / 2]\n});\n\nassert_eq!(33, value);\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cell.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cell.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6beecb7cc3f2705cb1fb39f3807856c19097f521b3279801c900052e8f7f17f9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_slice_of_cells\n\nDocumentation:\nReturns a cell containing a slice from slice of cells.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\n\nlet value = GhostToken::new(|mut token| {\nlet mut vec: Vec<_> = (0..n).collect();\nlet cell = GhostCell::from_mut(&mut vec[..]);\nlet all_elements = cell.as_slice_of_cells();\n\nlet quad = GhostCell::from_slice_of_cells(&all_elements[4..][..4]);\nquad.borrow_mut(&mut token).copy_from_slice(&33u32.to_be_bytes());\n\nvec.iter().position(|&v| v == 33)\n});\n\nassert_eq!(Some(7), value);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_slice_of_cells<'slice>(slice: &'slice [GhostCell<'brand, T>]) -> &'slice Self {\n // Safety:\n // - Same lifetime.\n // - `GhostCell<'_, T>` has the same in-memory representation as `T`.\n unsafe { &*(slice as *const _ as *const GhostCell<'brand, [T]>) }\n }\n```"}], "func_name": "from_slice_of_cells", "docstring": "Returns a cell containing a slice from slice of cells.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet n = 12;\n\nlet value = GhostToken::new(|mut token| {\nlet mut vec: Vec<_> = (0..n).collect();\nlet cell = GhostCell::from_mut(&mut vec[..]);\nlet all_elements = cell.as_slice_of_cells();\n\nlet quad = GhostCell::from_slice_of_cells(&all_elements[4..][..4]);\nquad.borrow_mut(&mut token).copy_from_slice(&33u32.to_be_bytes());\n\nvec.iter().position(|&v| v == 33)\n});\n\nassert_eq!(Some(7), value);\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cell.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cell.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e71e0a98c0503740310602eea63c15515c26b4fec8c75596cd4d1c5a691f9313"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_array_of_cells\n\nDocumentation:\nReturns a reference to an array of cells from a cell containing an array.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet value = GhostToken::new(|mut token| {\nlet mut array = [0, 1, 2, 3, 5];\nlet n = array.len();\n\nlet cell = GhostCell::from_mut(&mut array);\n\nlet inner = cell.as_array_of_cells();\n\n*inner[n / 2].borrow_mut(&mut token) = 33;\n\narray[n / 2]\n});\n\nassert_eq!(33, value);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_array_of_cells(&self) -> &[GhostCell<'brand, T>; N] {\n // Safety:\n // - Same lifetime.\n // - `GhostCell<'_, T>` has the same in-memory representation as `T`.\n unsafe { &*(self.as_ptr() as *mut [GhostCell<'brand, T>; N]) }\n }\n```"}], "func_name": "as_array_of_cells", "docstring": "Returns a reference to an array of cells from a cell containing an array.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet value = GhostToken::new(|mut token| {\nlet mut array = [0, 1, 2, 3, 5];\nlet n = array.len();\n\nlet cell = GhostCell::from_mut(&mut array);\n\nlet inner = cell.as_array_of_cells();\n\n*inner[n / 2].borrow_mut(&mut token) = 33;\n\narray[n / 2]\n});\n\nassert_eq!(33, value);\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cell.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cell.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a1c1ad0922593b8686eaee41b2c758190a9ab4db6f6f9c01ea5ba0bad2424d9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_array_of_cells\n\nDocumentation:\nReturns a cell containing an array from an array of cells.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet value = GhostToken::new(|mut token| {\nlet mut array = [0, 1, 2, 3, 5];\nlet n = array.len();\n\nlet cell = GhostCell::from_mut(&mut array);\n\nlet inner = cell.as_array_of_cells();\n\nlet inner = GhostCell::from_array_of_cells(&inner);\n\ninner.borrow_mut(&mut token)[n / 2] = 33;\n\narray[n / 2]\n});\n\nassert_eq!(33, value);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_array_of_cells<'a>(array: &'a [GhostCell<'brand, T>; N]) -> &'a Self {\n // Safety:\n // - Same lifetime.\n // - `GhostCell<'_, T>` has the same in-memory representation as `T`.\n unsafe { &*(array as *const [GhostCell<'brand, T>; N] as *const Self) }\n }\n```"}], "func_name": "from_array_of_cells", "docstring": "Returns a cell containing an array from an array of cells.\n\n# Example\n\n```rust\nuse ghost_cell::{GhostToken, GhostCell};\n\nlet value = GhostToken::new(|mut token| {\nlet mut array = [0, 1, 2, 3, 5];\nlet n = array.len();\n\nlet cell = GhostCell::from_mut(&mut array);\n\nlet inner = cell.as_array_of_cells();\n\nlet inner = GhostCell::from_array_of_cells(&inner);\n\ninner.borrow_mut(&mut token)[n / 2] = 33;\n\narray[n / 2]\n});\n\nassert_eq!(33, value);\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cell.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cell.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "179d3286ea9ff392a83ed59171faeac161fcdfd3149dd5c1affec79d8001388c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance of the cursor.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(token: &'a mut GhostToken<'brand>, cell: Option<&'a GhostCell<'brand, T>>) -> Self {\n let token = NonNull::from(token);\n\n Self { token, cell }\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance of the cursor.", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cursor.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cursor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "05e07b4ae3d765a8d1f5a0cdf04c400cf15a6ec5aa310aea17746e62dbcb6e9b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_inner\n\nDocumentation:\nReturns a mutable reference to the current element, if any.\n\n# Safety\n\nThe token is still mutably borrowed for as long as the return value lives.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_inner(self) -> Option<&'a mut T> {\n // Safety:\n // - `self` is not borrowed, therefore the token is not borrowed.\n // - The lifetime of the result ensures that the token remains mutably borrowed for as long as the result\n // exists.\n let token = unsafe { as_mut(self.token) };\n\n self.cell.map(move |cell| cell.borrow_mut(token))\n }\n```"}], "func_name": "into_inner", "docstring": "Returns a mutable reference to the current element, if any.\n\n# Safety\n\nThe token is still mutably borrowed for as long as the return value lives.", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cursor.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cursor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3c93032aad6b09fc1fa9b5bec29e9c14c1fc05889204f1dba7b8cd9234461974"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_parts\n\nDocumentation:\nReturns the token and currently pointed to cell.\n\n# Safety\n\nThe token is still mutably borrowed for as long as the return value lives.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_parts(self) -> (&'a GhostToken<'brand>, Option<&'a GhostCell<'brand, T>>) {\n // Why cannot `into_parts` returns a mutable reference to `GhostToken`?\n //\n // This is a tempting option, as it would match the constructor (`new`) perfectly. It is also unsound,\n // unfortunately, as demonstrated in #25.\n //\n // The current reference pointed to by the cursor may be owned (transitively) by another `GhostCell`.\n // Returning a mutable reference to the `GhostToken` allows mutating this other `GhostCell` in a way that may\n // destroy (and free), the `GhostCell` this returned reference refers to, thereby allowing a use-after-free.\n //\n // Therefore, this function needs to choose between returning a mutable reference to the token or returning\n // a reference to the `GhostCell`; it cannot do both at once, not safely.\n\n // Safety:\n // - `self` is not borrowed, therefore the token is not borrowed.\n // - The lifetime of the result ensures that the token and cell remain borrowed for as long as the result\n // exists.\n (unsafe { as_ref(self.token) }, self.cell)\n }\n```"}], "func_name": "into_parts", "docstring": "Returns the token and currently pointed to cell.\n\n# Safety\n\nThe token is still mutably borrowed for as long as the return value lives.", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cursor.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cursor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e04d34f37530b1241a4d50ed17bfcc186cd51a23d0967a540fa4a8bc7f3d3d7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: token\n\nDocumentation:\nReturns a reference to the token.\n\nThis borrows `self` immutably for the duration, preventing any materialization of a mutable token.\n\n# Note\n\nThere is no equivalent `token_mut` to avoid jeopardizing the anchoring path of the current reference within the\ncursor.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn token(&self) -> &GhostToken<'brand> {\n // Safety:\n // - Borrows self, immutably, restricting uses of the cursor and token to immutable borrows.\n unsafe { as_ref(self.token) }\n }\n```"}], "func_name": "token", "docstring": "Returns a reference to the token.\n\nThis borrows `self` immutably for the duration, preventing any materialization of a mutable token.\n\n# Note\n\nThere is no equivalent `token_mut` to avoid jeopardizing the anchoring path of the current reference within the\ncursor.", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cursor.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cursor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b943cdde2315b4bf3eaba11e43e0d7f93fa8c592b3c3ac7940fd04bed32a412"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: borrow\n\nDocumentation:\nReturns a reference to the inner value of the current cell.\n\n# Example\n\n```\nuse ghost_cell::{GhostCell, GhostCursor, GhostToken};\n\nGhostToken::new(|mut token| {\nlet cell = GhostCell::new(42);\n\nlet cursor = GhostCursor::new(&mut token, Some(&cell));\n\nassert_eq!(Some(&42), cursor.borrow());\n});\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn borrow(&self) -> Option<&T> {\n // Safety:\n // - Borrows `self`, therefore ensuring that no mutable borrow of the token exists.\n // - Restricts the lifetime of `token` to that of `self`.\n let token = unsafe { as_ref(self.token) };\n\n self.cell.map(|cell| cell.borrow(token))\n }\n```"}], "func_name": "borrow", "docstring": "Returns a reference to the inner value of the current cell.\n\n# Example\n\n```\nuse ghost_cell::{GhostCell, GhostCursor, GhostToken};\n\nGhostToken::new(|mut token| {\nlet cell = GhostCell::new(42);\n\nlet cursor = GhostCursor::new(&mut token, Some(&cell));\n\nassert_eq!(Some(&42), cursor.borrow());\n});\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cursor.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cursor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d2e65f42c0ac3c53fd5e6de2cc57b6e5ceeb8c432360e0bec12464041a59a7e8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: borrow_mut\n\nDocumentation:\nReturns a mutable reference to the inner value of the current cell.\n\n# Example\n\n```\nuse ghost_cell::{GhostCell, GhostCursor, GhostToken};\n\nGhostToken::new(|mut token| {\nlet cell = GhostCell::new(42);\n\nlet mut cursor = GhostCursor::new(&mut token, Some(&cell));\n\nif let Some(r) = cursor.borrow_mut() {\n*r = 33;\n}\n\nassert_eq!(Some(&33), cursor.borrow());\n});\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn borrow_mut(&mut self) -> Option<&mut T> {\n // Safety:\n // - Borrows `self` mutably, therefore ensuring that no other borrow of the token exists.\n // - Restricts the lifetime of `token` to that of `self.`\n let token = unsafe { as_mut(self.token) };\n\n self.cell.map(move |cell| cell.borrow_mut(token))\n }\n```"}], "func_name": "borrow_mut", "docstring": "Returns a mutable reference to the inner value of the current cell.\n\n# Example\n\n```\nuse ghost_cell::{GhostCell, GhostCursor, GhostToken};\n\nGhostToken::new(|mut token| {\nlet cell = GhostCell::new(42);\n\nlet mut cursor = GhostCursor::new(&mut token, Some(&cell));\n\nif let Some(r) = cursor.borrow_mut() {\n*r = 33;\n}\n\nassert_eq!(Some(&33), cursor.borrow());\n});\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cursor.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cursor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ff92eb86bb8542158bd52ad6eeb50ae09a2d978da8b6e5a9539979cb5e773db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: move_into\n\nDocumentation:\nAttempts to move from the current cell to another cell, derived from it.\n\nReturns an error if either:\n- There is no current cell.\n- `fun` returns no cell.\n\nIn case of an error, the current cursor is returned.\n\n# Example\n\n```\nuse ghost_cell::{GhostCell, GhostCursor, GhostToken};\n\nstruct Leaf<'brand>(GhostCell<'brand, String>);\n\nGhostToken::new(|mut token| {\nlet leaf = Leaf(GhostCell::new(\"Terminal\".to_string()));\nlet inner = GhostCell::new(leaf);\n\nlet cursor = GhostCursor::new(&mut token, Some(&inner));\n\nlet mut cursor = cursor.move_into(|leaf| Some(&leaf.0))\n.or(Err(()))\n.expect(\"inner.0 points to leaf\");\n\nif let Some(s) = cursor.borrow_mut() {\nlet previous = std::mem::replace(s, \"Station\".to_string());\nassert_eq!(\"Terminal\", previous);\n}\n});\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn move_into(mut self, fun: F) -> Result, Self>\n where\n F: FnOnce(&T) -> Option<&GhostCell<'brand, U>>,\n {\n let result = self.move_into_impl(fun);\n\n result.or(Err(self))\n }\n```"}], "func_name": "move_into", "docstring": "Attempts to move from the current cell to another cell, derived from it.\n\nReturns an error if either:\n- There is no current cell.\n- `fun` returns no cell.\n\nIn case of an error, the current cursor is returned.\n\n# Example\n\n```\nuse ghost_cell::{GhostCell, GhostCursor, GhostToken};\n\nstruct Leaf<'brand>(GhostCell<'brand, String>);\n\nGhostToken::new(|mut token| {\nlet leaf = Leaf(GhostCell::new(\"Terminal\".to_string()));\nlet inner = GhostCell::new(leaf);\n\nlet cursor = GhostCursor::new(&mut token, Some(&inner));\n\nlet mut cursor = cursor.move_into(|leaf| Some(&leaf.0))\n.or(Err(()))\n.expect(\"inner.0 points to leaf\");\n\nif let Some(s) = cursor.borrow_mut() {\nlet previous = std::mem::replace(s, \"Station\".to_string());\nassert_eq!(\"Terminal\", previous);\n}\n});\n```", "repo": "matthieu-m/ghost-cell", "path": "src/ghost_cursor.rs", "url": "https://github.com/matthieu-m/ghost-cell/blob/master/src/ghost_cursor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "172f6c119c528084fdd85dd77bc769e7178d48322ae466122161e7d2ec99658e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: main\n\nDocumentation:\nOutput:\n\n```plain\nEntry [key = 2] [value = First] is released.\nEntry [key = 1] [value = Second] is released.\nEntry [key = 3] [value = Third] is released.\nEntry [key = 3] [value = Forth] is released.\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn main() {\n let cache: Cache = CacheBuilder::new(2)\n .with_event_listener(Arc::new(EchoEventListener))\n .with_eviction_config(FifoConfig::default())\n .with_shards(1)\n .build();\n\n cache.insert(1, \"Second\".to_string());\n cache.insert_with_properties(2, \"First\".to_string(), CacheProperties::default().with_ephemeral(true));\n cache.insert(3, \"Third\".to_string());\n cache.insert(3, \"Forth\".to_string());\n}\n```"}], "func_name": "main", "docstring": "Output:\n\n```plain\nEntry [key = 2] [value = First] is released.\nEntry [key = 1] [value = Second] is released.\nEntry [key = 3] [value = Third] is released.\nEntry [key = 3] [value = Forth] is released.\n```", "repo": "foyer-rs/foyer", "path": "examples/event_listener.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/examples/event_listener.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "83c5b6d2776742a5360c75101b655eaef21bc19128511b6039680fe18f5f000b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_name\n\nDocumentation:\nSet the name of the foyer hybrid cache instance.\n\nfoyer will use the name as the prefix of the metric names.\n\nDefault: `foyer`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_name(mut self, name: impl Into>) -> Self {\n self.name = name.into();\n self\n }\n```"}], "func_name": "with_name", "docstring": "Set the name of the foyer hybrid cache instance.\n\nfoyer will use the name as the prefix of the metric names.\n\nDefault: `foyer`.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "047c49d12f0e2c853339551303c956e9f161811f59d23ee66f4a606879e82ead"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_policy\n\nDocumentation:\nSet the policy of the hybrid cache.\n\nDefault: [`HybridCachePolicy::default()`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_policy(mut self, policy: HybridCachePolicy) -> Self {\n self.options.policy = policy;\n self\n }\n```"}], "func_name": "with_policy", "docstring": "Set the policy of the hybrid cache.\n\nDefault: [`HybridCachePolicy::default()`].", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b9615622ddaa82f971308e931ab7949970fe2829eb0117eb92680ca19c0486ef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_event_listener\n\nDocumentation:\nSet event listener.\n\nDefault: No event listener installed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_event_listener(mut self, event_listener: Arc>) -> Self {\n self.event_listener = Some(event_listener);\n self\n }\n```"}], "func_name": "with_event_listener", "docstring": "Set event listener.\n\nDefault: No event listener installed.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5ddf3cbbc9a33843bfc1fe042a8ab51c02aa467872123c0762ffe6d46755b8eb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_flush_on_close\n\nDocumentation:\nSet whether flush all in-memory cached entries to disk cache on close.\n\nBased on the disk cache performance and the io throttle configuration, this may take some extra time on close.\n\nDefault: `true`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_flush_on_close(mut self, flush_on_close: bool) -> Self {\n self.options.flush_on_close = flush_on_close;\n self\n }\n```"}], "func_name": "with_flush_on_close", "docstring": "Set whether flush all in-memory cached entries to disk cache on close.\n\nBased on the disk cache performance and the io throttle configuration, this may take some extra time on close.\n\nDefault: `true`.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fcf904f9bee78e3007b6059eca00441c4503e3743ac870430a4bb3255527c6a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: memory\n\nDocumentation:\nContinue to modify the in-memory cache configurations.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn memory(self, capacity: usize) -> HybridCacheBuilderPhaseMemory\n where\n K: StorageKey,\n V: StorageValue,\n {\n let metrics = Arc::new(Metrics::new(self.name.clone(), &self.registry));\n let mut builder = CacheBuilder::new(capacity)\n .with_name(self.name.clone())\n .with_metrics(metrics.clone());\n if let Some(event_listener) = self.event_listener {\n builder = builder.with_event_listener(event_listener);\n }\n HybridCacheBuilderPhaseMemory {\n name: self.name,\n options: self.options,\n metrics,\n builder,\n }\n }\n```"}], "func_name": "memory", "docstring": "Continue to modify the in-memory cache configurations.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d56df45a05d2a4eb4bdbf9bf5f27dc7dda6532250f2261b91e75f1bdb46972b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_shards\n\nDocumentation:\nSet in-memory cache sharding count. Entries will be distributed to different shards based on their hash.\nOperations on different shard can be parallelized.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_shards(self, shards: usize) -> Self {\n let builder = self.builder.with_shards(shards);\n HybridCacheBuilderPhaseMemory {\n name: self.name,\n options: self.options,\n metrics: self.metrics,\n builder,\n }\n }\n```"}], "func_name": "with_shards", "docstring": "Set in-memory cache sharding count. Entries will be distributed to different shards based on their hash.\nOperations on different shard can be parallelized.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "929069b6211aa65b722de2e074ee93703301966e7399c650dce65b8c32723378"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_eviction_config\n\nDocumentation:\nSet in-memory cache eviction algorithm.\n\nThe default value is a general-used w-TinyLFU algorithm.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_eviction_config(self, eviction_config: impl Into) -> Self {\n let builder = self.builder.with_eviction_config(eviction_config.into());\n HybridCacheBuilderPhaseMemory {\n name: self.name,\n options: self.options,\n metrics: self.metrics,\n builder,\n }\n }\n```"}], "func_name": "with_eviction_config", "docstring": "Set in-memory cache eviction algorithm.\n\nThe default value is a general-used w-TinyLFU algorithm.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a417a9df937dea879e2994a6a56ebd5099af6a7ee35e9f896769536844eff60"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_hash_builder\n\nDocumentation:\nSet in-memory cache hash builder.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_hash_builder(self, hash_builder: OS) -> HybridCacheBuilderPhaseMemory\n where\n OS: HashBuilder + Debug,\n {\n let builder = self.builder.with_hash_builder(hash_builder);\n HybridCacheBuilderPhaseMemory {\n name: self.name,\n options: self.options,\n metrics: self.metrics,\n builder,\n }\n }\n```"}], "func_name": "with_hash_builder", "docstring": "Set in-memory cache hash builder.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "458ddc6e60d6c960ab6fe190a1b758e059e62681df699f14216263538a9dbacc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: storage\n\nDocumentation:\nContinue to modify the disk cache configurations.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn storage(self, engine: Engine) -> HybridCacheBuilderPhaseStorage {\n let memory = self.builder.build();\n HybridCacheBuilderPhaseStorage {\n name: self.name.clone(),\n options: self.options,\n metrics: self.metrics.clone(),\n memory: memory.clone(),\n builder: StoreBuilder::new(self.name, memory, self.metrics, engine),\n }\n }\n```"}], "func_name": "storage", "docstring": "Continue to modify the disk cache configurations.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fee0fcb7443aacee22f4579d72c69f11ba9d6ce0f9adb8ee91660cb717e6ca71"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_device_options\n\nDocumentation:\nSet device options for the disk cache store.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_device_options(self, device_options: impl Into) -> Self {\n let builder = self.builder.with_device_options(device_options);\n Self {\n name: self.name,\n options: self.options,\n metrics: self.metrics,\n memory: self.memory,\n builder,\n }\n }\n```"}], "func_name": "with_device_options", "docstring": "Set device options for the disk cache store.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b4571271ff4ed6815bdceba8c6c9de45099da37f363305e2cf3dcfa0b72f76e8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_flush\n\nDocumentation:\nEnable/disable `sync` after writes.\n\nDefault: `false`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_flush(self, flush: bool) -> Self {\n let builder = self.builder.with_flush(flush);\n Self {\n name: self.name,\n options: self.options,\n metrics: self.metrics,\n memory: self.memory,\n builder,\n }\n }\n```"}], "func_name": "with_flush", "docstring": "Enable/disable `sync` after writes.\n\nDefault: `false`.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef1d3ef516bc1194399aab1232f84137dd71cae1b874e23059a973b0f51b10da"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_recover_mode\n\nDocumentation:\nSet the recover mode for the disk cache store.\n\nSee more in [`RecoverMode`].\n\nDefault: [`RecoverMode::Quiet`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_recover_mode(self, recover_mode: RecoverMode) -> Self {\n let builder = self.builder.with_recover_mode(recover_mode);\n Self {\n name: self.name,\n options: self.options,\n metrics: self.metrics,\n memory: self.memory,\n builder,\n }\n }\n```"}], "func_name": "with_recover_mode", "docstring": "Set the recover mode for the disk cache store.\n\nSee more in [`RecoverMode`].\n\nDefault: [`RecoverMode::Quiet`].", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "129b31150440afce8ec811a7239c09f12022f59c2367d9d273092bbb887467c7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_compression\n\nDocumentation:\nSet the compression algorithm of the disk cache store.\n\nDefault: [`Compression::None`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_compression(self, compression: Compression) -> Self {\n let builder = self.builder.with_compression(compression);\n Self {\n name: self.name,\n options: self.options,\n metrics: self.metrics,\n memory: self.memory,\n builder,\n }\n }\n```"}], "func_name": "with_compression", "docstring": "Set the compression algorithm of the disk cache store.\n\nDefault: [`Compression::None`].", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7db78125829316f9bb5b6852ca734b33b0d87dabc54be7f348ca3624cf0e2506"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_runtime_options\n\nDocumentation:\nConfigure the dedicated runtime for the disk cache store.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_runtime_options(self, runtime_options: RuntimeOptions) -> Self {\n let builder = self.builder.with_runtime_options(runtime_options);\n Self {\n name: self.name,\n options: self.options,\n metrics: self.metrics,\n memory: self.memory,\n builder,\n }\n }\n```"}], "func_name": "with_runtime_options", "docstring": "Configure the dedicated runtime for the disk cache store.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d0d5bcee1e1191172f249eb72ae627d9ad6324b15bc30024b59fd5383cbdad34"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nBuild and open the hybrid cache with the given configurations.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn build(self) -> anyhow::Result> {\n let builder = self.builder;\n\n let piped = !builder.is_noop() && self.options.policy == HybridCachePolicy::WriteOnEviction;\n\n let memory = self.memory;\n let storage = builder.build().await?;\n\n if piped {\n let pipe = HybridCachePipe::new(storage.clone());\n memory.set_pipe(Box::new(pipe));\n }\n\n Ok(HybridCache::new(self.options, memory, storage, self.metrics))\n }\n```"}], "func_name": "build", "docstring": "Build and open the hybrid cache with the given configurations.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/builder.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb08c186a8005245a7ea746ded796ffc71ecbce364482a42cbefbb43185429f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_ephemeral\n\nDocumentation:\nSet the entry to be ephemeral.\n\nAn ephemeral entry will be evicted immediately after all its holders drop it,\nno matter if the capacity is reached.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_ephemeral(mut self, ephemeral: bool) -> Self {\n self.ephemeral = ephemeral;\n self\n }\n```"}], "func_name": "with_ephemeral", "docstring": "Set the entry to be ephemeral.\n\nAn ephemeral entry will be evicted immediately after all its holders drop it,\nno matter if the capacity is reached.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c3d3e8755a5d5d1be14bee2bc0f9045da98a5874df2368eb5e6e4b3a91eed4fc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nInsert cache entry to the hybrid cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert(&self, key: K, value: V) -> HybridCacheEntry {\n root_span!(self, span, \"foyer::hybrid::cache::insert\");\n\n #[cfg(feature = \"tracing\")]\n let _guard = span.set_local_parent();\n\n let now = Instant::now();\n\n let entry = self.memory.insert(key, value);\n if self.policy == HybridCachePolicy::WriteOnInsertion {\n self.storage.enqueue(entry.piece(), false);\n }\n\n self.metrics.hybrid_insert.increase(1);\n self.metrics.hybrid_insert_duration.record(now.elapsed().as_secs_f64());\n\n try_cancel!(self, span, record_hybrid_insert_threshold);\n\n entry\n }\n```"}], "func_name": "insert", "docstring": "Insert cache entry to the hybrid cache.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "47806bf067aaef978e460223c402ed1fc32876c888d0b59316d8f2c4ad132852"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert_with_properties\n\nDocumentation:\nInsert cache entry to the hybrid cache with properties.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert_with_properties(\n &self,\n key: K,\n value: V,\n properties: HybridCacheProperties,\n ) -> HybridCacheEntry {\n root_span!(self, span, \"foyer::hybrid::cache::insert\");\n\n #[cfg(feature = \"tracing\")]\n let _guard = span.set_local_parent();\n\n let now = Instant::now();\n\n let ephemeral = matches! { properties.location(), Location::OnDisk };\n let entry = self\n .memory\n .insert_with_properties(key, value, properties.with_ephemeral(ephemeral));\n if self.policy == HybridCachePolicy::WriteOnInsertion && entry.properties().location() != Location::InMem {\n self.storage.enqueue(entry.piece(), false);\n }\n\n self.metrics.hybrid_insert.increase(1);\n self.metrics.hybrid_insert_duration.record(now.elapsed().as_secs_f64());\n\n try_cancel!(self, span, record_hybrid_insert_threshold);\n\n entry\n }\n```"}], "func_name": "insert_with_properties", "docstring": "Insert cache entry to the hybrid cache with properties.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d4e47da31af051d2264189c05bf6b3b5bb2b652e3ea85c09c036a85c761cebde"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nGet cached entry with the given key from the hybrid cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get(&self, key: &Q) -> anyhow::Result>>\n where\n Q: Hash + Equivalent + Send + Sync + 'static + Clone,\n {\n root_span!(self, span, \"foyer::hybrid::cache::get\");\n\n let now = Instant::now();\n\n let record_hit = || {\n self.metrics.hybrid_hit.increase(1);\n self.metrics.hybrid_hit_duration.record(now.elapsed().as_secs_f64());\n };\n let record_miss = || {\n self.metrics.hybrid_miss.increase(1);\n self.metrics.hybrid_miss_duration.record(now.elapsed().as_secs_f64());\n };\n let record_throttled = || {\n self.metrics.hybrid_throttled.increase(1);\n self.metrics\n .hybrid_throttled_duration\n .record(now.elapsed().as_secs_f64());\n };\n\n #[cfg(feature = \"tracing\")]\n let guard = span.set_local_parent();\n if let Some(entry) = self.memory.get(key) {\n record_hit();\n try_cancel!(self, span, record_hybrid_get_threshold);\n return Ok(Some(entry));\n }\n #[cfg(feature = \"tracing\")]\n drop(guard);\n\n #[cfg(feature = \"tracing\")]\n let load = self\n .storage\n .load(key)\n .in_span(Span::enter_with_parent(\"foyer::hybrid::cache::get::poll\", &span));\n #[cfg(not(feature = \"tracing\"))]\n let load = self.storage.load(key);\n\n let entry = match load.await? {\n Load::Entry { key, value, populated } => {\n record_hit();\n Some(self.memory.insert_with_properties(\n key,\n value,\n HybridCacheProperties::default().with_source(Source::Populated(populated)),\n ))\n }\n Load::Throttled => {\n record_throttled();\n None\n }\n Load::Miss => {\n record_miss();\n None\n }\n };\n\n try_cancel!(self, span, record_hybrid_get_threshold);\n\n Ok(entry)\n }\n```"}], "func_name": "get", "docstring": "Get cached entry with the given key from the hybrid cache.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "010e8319346d195301e9ba16ab64ecc17f0395227dcae617cac0ea090fde2396"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: obtain\n\nDocumentation:\nGet cached entry with the given key from the hybrid cache.\n\nDifferent from `get`, `obtain` deduplicates the disk cache queries.\n\n`obtain` is always supposed to be used instead of `get` if the overhead of getting the ownership of the given\nkey is acceptable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn obtain(&self, key: K) -> anyhow::Result>>\n where\n K: Clone,\n {\n root_span!(self, span, \"foyer::hybrid::cache::obtain\");\n\n let now = Instant::now();\n\n #[cfg(feature = \"tracing\")]\n let guard = span.set_local_parent();\n\n let fetch = self.memory.fetch_inner(\n key.clone(),\n HybridCacheProperties::default(),\n || {\n let store = self.storage.clone();\n async move {\n match store.load(&key).await.map_err(anyhow::Error::from) {\n Ok(Load::Entry {\n key: _,\n value,\n populated,\n }) => Diversion {\n target: Ok(value),\n store: Some(FetchContext {\n throttled: false,\n source: Source::Populated(populated),\n }),\n },\n Ok(Load::Throttled) => Err(ObtainFetchError::Throttled).into(),\n Ok(Load::Miss) => Err(ObtainFetchError::NotExist).into(),\n Err(e) => Err(ObtainFetchError::Err(e)).into(),\n }\n }\n },\n &tokio::runtime::Handle::current().into(),\n );\n #[cfg(feature = \"tracing\")]\n drop(guard);\n\n let res = fetch.await;\n\n match res {\n Ok(entry) => {\n self.metrics.hybrid_hit.increase(1);\n self.metrics.hybrid_hit_duration.record(now.elapsed().as_secs_f64());\n try_cancel!(self, span, record_hybrid_obtain_threshold);\n Ok(Some(entry))\n }\n Err(ObtainFetchError::Throttled) => {\n self.metrics.hybrid_throttled.increase(1);\n self.metrics\n .hybrid_throttled_duration\n .record(now.elapsed().as_secs_f64());\n try_cancel!(self, span, record_hybrid_obtain_threshold);\n Ok(None)\n }\n Err(ObtainFetchError::NotExist) => {\n self.metrics.hybrid_miss.increase(1);\n self.metrics.hybrid_miss_duration.record(now.elapsed().as_secs_f64());\n try_cancel!(self, span, record_hybrid_obtain_threshold);\n Ok(None)\n }\n Err(ObtainFetchError::RecvError(_)) => {\n try_cancel!(self, span, record_hybrid_obtain_threshold);\n Ok(None)\n }\n Err(ObtainFetchError::Err(e)) => {\n try_cancel!(self, span, record_hybrid_obtain_threshold);\n Err(e)\n }\n }\n }\n```"}], "func_name": "obtain", "docstring": "Get cached entry with the given key from the hybrid cache.\n\nDifferent from `get`, `obtain` deduplicates the disk cache queries.\n\n`obtain` is always supposed to be used instead of `get` if the overhead of getting the ownership of the given\nkey is acceptable.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fee2db5296bee6c1b2798f42031189c3b319fbae9950c40a5b898160caa097fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove\n\nDocumentation:\nRemove a cached entry with the given key from the hybrid cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn remove(&self, key: &Q)\n where\n Q: Hash + Equivalent + ?Sized + Send + Sync + 'static,\n {\n root_span!(self, span, \"foyer::hybrid::cache::remove\");\n\n #[cfg(feature = \"tracing\")]\n let _guard = span.set_local_parent();\n\n let now = Instant::now();\n\n self.memory.remove(key);\n self.storage.delete(key);\n\n self.metrics.hybrid_remove.increase(1);\n self.metrics.hybrid_remove_duration.record(now.elapsed().as_secs_f64());\n\n try_cancel!(self, span, record_hybrid_remove_threshold);\n }\n```"}], "func_name": "remove", "docstring": "Remove a cached entry with the given key from the hybrid cache.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8a51d8b75c6e116452309a98e5ba725dce2e1c7b13c46d2ff27e746d20582ca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: contains\n\nDocumentation:\nCheck if the hybrid cache contains a cached entry with the given key.\n\n`contains` may return a false-positive result if there is a hash collision with the given key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn contains(&self, key: &Q) -> bool\n where\n Q: Hash + Equivalent + ?Sized,\n {\n self.memory.contains(key) || self.storage.may_contains(key)\n }\n```"}], "func_name": "contains", "docstring": "Check if the hybrid cache contains a cached entry with the given key.\n\n`contains` may return a false-positive result if there is a hash collision with the given key.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ae151a10c5ed98dfbf07fbf8d901d0448f719b17d943a57fe0aeecda6fbb80e3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: close\n\nDocumentation:\nGracefully close the hybrid cache.\n\n`close` will wait for the ongoing flush and reclaim tasks to finish.\n\nBased on the `flush_on_close` option, `close` will flush all in-memory cached entries to the disk cache.\n\nFor more details, please refer to [`super::builder::HybridCacheBuilder::with_flush_on_close()`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn close(&self) -> anyhow::Result<()> {\n let now = Instant::now();\n if self.flush_on_close {\n let bytes = self.memory.usage();\n tracing::info!(bytes, \"[hybrid]: flush all in-memory cached entries to disk on close\");\n self.memory.flush().await;\n }\n self.storage.close().await?;\n let elapsed = now.elapsed();\n tracing::info!(\"[hybrid]: close consumes {elapsed:?}\",);\n Ok(())\n }\n```"}], "func_name": "close", "docstring": "Gracefully close the hybrid cache.\n\n`close` will wait for the ongoing flush and reclaim tasks to finish.\n\nBased on the `flush_on_close` option, `close` will flush all in-memory cached entries to the disk cache.\n\nFor more details, please refer to [`super::builder::HybridCacheBuilder::with_flush_on_close()`].", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea99926c64eb07dbd5e794d0b1eec12895ce3d9829fec8ff6ab6e67222291c60"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fetch\n\nDocumentation:\nFetch and insert a cache entry with the given key and method if there is a cache miss.\n\nIf the dedicated runtime of the foyer storage engine is enabled, `fetch` will spawn task with the dedicated\nruntime. Otherwise, the user's runtime will be used.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fetch(&self, key: K, fetch: F) -> HybridFetch\n where\n F: FnOnce() -> FU,\n FU: Future> + Send + 'static,\n {\n self.fetch_inner(key, HybridCacheProperties::default(), fetch)\n }\n```"}], "func_name": "fetch", "docstring": "Fetch and insert a cache entry with the given key and method if there is a cache miss.\n\nIf the dedicated runtime of the foyer storage engine is enabled, `fetch` will spawn task with the dedicated\nruntime. Otherwise, the user's runtime will be used.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "911e82f167c50223bf492e9540793d59d199afc701dd28d33de21b3d61c01344"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fetch_with_properties\n\nDocumentation:\nFetch and insert a cache entry with the given key, properties, and method if there is a cache miss.\n\nIf the dedicated runtime of the foyer storage engine is enabled, `fetch` will spawn task with the dedicated\nruntime. Otherwise, the user's runtime will be used.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fetch_with_properties(\n &self,\n key: K,\n properties: HybridCacheProperties,\n fetch: F,\n ) -> HybridFetch\n where\n F: FnOnce() -> FU,\n FU: Future> + Send + 'static,\n {\n self.fetch_inner(key, properties, fetch)\n }\n```"}], "func_name": "fetch_with_properties", "docstring": "Fetch and insert a cache entry with the given key, properties, and method if there is a cache miss.\n\nIf the dedicated runtime of the foyer storage engine is enabled, `fetch` will spawn task with the dedicated\nruntime. Otherwise, the user's runtime will be used.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "61c507fa6784e79753329ce877418999d95c1f25cf0554c61fe8e8aab201c03b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nInsert the entry to the hybrid cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert(self, value: V) -> HybridCacheEntry {\n self.hybrid.insert(self.key, value)\n }\n```"}], "func_name": "insert", "docstring": "Insert the entry to the hybrid cache.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/writer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/writer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "39e97e558ddd15e871536949a24cdd3776515c1a133449908528705e916bc554"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert_with_properties\n\nDocumentation:\nInsert the entry with properties to the hybrid cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert_with_properties(self, value: V, properties: HybridCacheProperties) -> HybridCacheEntry {\n self.hybrid.insert_with_properties(self.key, value, properties)\n }\n```"}], "func_name": "insert_with_properties", "docstring": "Insert the entry with properties to the hybrid cache.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/writer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/writer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9dc90467178264ecf1cdc5ec5d0d0098cd69341e6d1fa1942c8dfd3c7bcc0ab9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nInsert the entry to the disk cache only.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert(self, value: V) -> Option> {\n self.insert_inner(value, HybridCacheProperties::default())\n }\n```"}], "func_name": "insert", "docstring": "Insert the entry to the disk cache only.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/writer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/writer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "726c236adc007fce000559a87cdf67de9ac6f49fbae6818d772b0a8bafe62bc3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert_with_properties\n\nDocumentation:\nInsert the entry with properties to the disk cache only.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert_with_properties(\n self,\n value: V,\n properties: HybridCacheProperties,\n ) -> Option> {\n self.insert_inner(value, properties)\n }\n```"}], "func_name": "insert_with_properties", "docstring": "Insert the entry with properties to the disk cache only.", "repo": "foyer-rs/foyer", "path": "foyer/src/hybrid/writer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer/src/hybrid/writer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d0dd745fac11b62aa7438b58b06d1c8e8c0b6d4975e84f96b3e73c72199f83d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: asyncify_with_runtime\n\nDocumentation:\nConvert the block call to async call with given runtime.\n\nmadsim compatible mode.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn asyncify_with_runtime(_: &SingletonHandle, f: F) -> T\nwhere\n F: FnOnce() -> T + Send + 'static,\n T: Send + 'static,\n{\n f()\n}\n```"}], "func_name": "asyncify_with_runtime", "docstring": "Convert the block call to async call with given runtime.\n\nmadsim compatible mode.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/asyncify.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/asyncify.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6284c4afec1f92f775c1a22d4b661bfd7fc37b768e0085484e1036c8816f1f52"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCountdown `counter` times.\n\n# Safety\n\nPanics if `counter` exceeds [`isize::MAX`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(counter: usize) -> Self {\n Self {\n finish: AtomicBool::new(false),\n counter: AtomicIsize::new(isize::try_from(counter).expect(\"`counter` must NOT exceed `isize::MAX`.\")),\n }\n }\n```"}], "func_name": "new", "docstring": "Countdown `counter` times.\n\n# Safety\n\nPanics if `counter` exceeds [`isize::MAX`].", "repo": "foyer-rs/foyer", "path": "foyer-common/src/countdown.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/countdown.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ab70811cd37d3485cd310c7a7f72936bc949ef02de93fe10ff418b828189b71"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: countdown\n\nDocumentation:\nReturns `false` for the first `counter` times, then always returns `true`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn countdown(&self) -> bool {\n if self.finish.load(Ordering::Relaxed) {\n return true;\n }\n self.counter.fetch_sub(1, Ordering::Relaxed) <= 0\n }\n```"}], "func_name": "countdown", "docstring": "Returns `false` for the first `counter` times, then always returns `true`.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/countdown.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/countdown.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f8007568819790aaee9e7f910fa4332d2d79ba32d21cc419e06613f29bba0a35"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new metric with the given name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(name: impl Into>, registry: &BoxedRegistry) -> Self {\n let name = name.into();\n\n /* in-memory cache metrics */\n\n let foyer_memory_op_total = registry.register_counter_vec(\n \"foyer_memory_op_total\".into(),\n \"foyer in-memory cache operations\".into(),\n &[\"name\", \"op\"],\n );\n let foyer_memory_usage = registry.register_gauge_vec(\n \"foyer_memory_usage\".into(),\n \"foyer in-memory cache usage\".into(),\n &[\"name\"],\n );\n\n let memory_insert = foyer_memory_op_total.counter(&[name.clone(), \"insert\".into()]);\n let memory_replace = foyer_memory_op_total.counter(&[name.clone(), \"replace\".into()]);\n let memory_hit = foyer_memory_op_total.counter(&[name.clone(), \"hit\".into()]);\n let memory_miss = foyer_memory_op_total.counter(&[name.clone(), \"miss\".into()]);\n let memory_remove = foyer_memory_op_total.counter(&[name.clone(), \"remove\".into()]);\n let memory_evict = foyer_memory_op_total.counter(&[name.clone(), \"evict\".into()]);\n let memory_reinsert = foyer_memory_op_total.counter(&[name.clone(), \"reinsert\".into()]);\n let memory_release = foyer_memory_op_total.counter(&[name.clone(), \"release\".into()]);\n let memory_queue = foyer_memory_op_total.counter(&[name.clone(), \"queue\".into()]);\n let memory_fetch = foyer_memory_op_total.counter(&[name.clone(), \"fetch\".into()]);\n\n let memory_usage = foyer_memory_usage.gauge(&[name.clone()]);\n\n /* disk cache metrics */\n\n let foyer_storage_op_total = registry.register_counter_vec(\n \"foyer_storage_op_total\".into(),\n \"foyer disk cache operations\".into(),\n &[\"name\", \"op\"],\n );\n let foyer_storage_op_duration = registry.register_histogram_vec_with_buckets(\n \"foyer_storage_op_duration\".into(),\n \"foyer disk cache op durations\".into(),\n &[\"name\", \"op\"],\n // 1us ~ 4s\n Buckets::exponential(0.000_001, 2.0, 23),\n );\n\n let foyer_storage_inner_op_total = registry.register_counter_vec(\n \"foyer_storage_inner_op_total\".into(),\n \"foyer disk cache inner operations\".into(),\n &[\"name\", \"op\"],\n );\n let foyer_storage_inner_op_duration = registry.register_histogram_vec_with_buckets(\n \"foyer_storage_inner_op_duration\".into(),\n \"foyer disk cache inner op durations\".into(),\n &[\"name\", \"op\"],\n // 1us ~ 16s\n Buckets::exponential(0.000_001, 2.0, 25),\n );\n\n let foyer_storage_disk_io_total = registry.register_counter_vec(\n \"foyer_storage_disk_io_total\".into(),\n \"foyer disk cache disk operations\".into(),\n &[\"name\", \"op\"],\n );\n let foyer_storage_disk_io_bytes = registry.register_counter_vec(\n \"foyer_storage_disk_io_bytes\".into(),\n \"foyer disk cache disk io bytes\".into(),\n &[\"name\", \"op\"],\n );\n let foyer_storage_disk_io_duration = registry.register_histogram_vec_with_buckets(\n \"foyer_storage_disk_io_duration\".into(),\n \"foyer disk cache disk io duration\".into(),\n &[\"name\", \"op\"],\n // 1us ~ 4s\n Buckets::exponential(0.000_001, 2.0, 23),\n );\n\n let foyer_storage_region = registry.register_gauge_vec(\n \"foyer_storage_region\".into(),\n \"foyer disk cache regions\".into(),\n &[\"name\", \"type\"],\n );\n let foyer_storage_region_size_bytes = registry.register_gauge_vec(\n \"foyer_storage_region_size_bytes\".into(),\n \"foyer disk cache region sizes\".into(),\n &[\"name\"],\n );\n\n let foyer_storage_entry_serde_duration = registry.register_histogram_vec_with_buckets(\n \"foyer_storage_entry_serde_duration\".into(),\n \"foyer disk cache entry serde durations\".into(),\n &[\"name\", \"op\"],\n // 10ns ~ 40ms\n Buckets::exponential(0.000_000_01, 2.0, 23),\n );\n\n let foyer_storage_lodc_op_total = registry.register_counter_vec(\n \"foyer_storage_lodc_op_total\".into(),\n \"foyer large object disk cache operations\".into(),\n &[\"name\", \"op\"],\n );\n\n let foyer_storage_lodc_buffer_efficiency = registry.register_histogram_vec_with_buckets(\n \"foyer_storage_lodc_buffer_efficiency\".into(),\n \"foyer large object disk cache buffer efficiency\".into(),\n &[\"name\"],\n // 0% ~ 100%\n Buckets::linear(0.1, 0.1, 10),\n );\n\n let foyer_storage_lodc_recover_duration = registry.register_histogram_vec_with_buckets(\n \"foyer_storage_lodc_recover_duration\".into(),\n \"foyer large object disk cache recover duration\".into(),\n &[\"name\"],\n // 1ms ~ 1000s\n Buckets::exponential(0.001, 2.0, 21),\n );\n\n let storage_enqueue = foyer_storage_op_total.counter(&[name.clone(), \"enqueue\".into()]);\n let storage_hit = foyer_storage_op_total.counter(&[name.clone(), \"hit\".into()]);\n let storage_miss = foyer_storage_op_total.counter(&[name.clone(), \"miss\".into()]);\n let storage_delete = foyer_storage_op_total.counter(&[name.clone(), \"delete\".into()]);\n let storage_error = foyer_storage_op_total.counter(&[name.clone(), \"error\".into()]);\n\n let storage_enqueue_duration = foyer_storage_op_duration.histogram(&[name.clone(), \"enqueue\".into()]);\n let storage_hit_duration = foyer_storage_op_duration.histogram(&[name.clone(), \"hit\".into()]);\n let storage_miss_duration = foyer_storage_op_duration.histogram(&[name.clone(), \"miss\".into()]);\n let storage_delete_duration = foyer_storage_op_duration.histogram(&[name.clone(), \"delete\".into()]);\n\n let storage_queue_rotate = foyer_storage_inner_op_total.counter(&[name.clone(), \"queue_rotate\".into()]);\n let storage_queue_buffer_overflow =\n foyer_storage_inner_op_total.counter(&[name.clone(), \"buffer_overflow\".into()]);\n let storage_queue_channel_overflow =\n foyer_storage_inner_op_total.counter(&[name.clone(), \"channel_overflow\".into()]);\n\n let storage_queue_rotate_duration =\n foyer_storage_inner_op_duration.histogram(&[name.clone(), \"queue_rotate\".into()]);\n\n let storage_disk_write = foyer_storage_disk_io_total.counter(&[name.clone(), \"write\".into()]);\n let storage_disk_read = foyer_storage_disk_io_total.counter(&[name.clone(), \"read\".into()]);\n let storage_disk_flush = foyer_storage_disk_io_total.counter(&[name.clone(), \"flush\".into()]);\n\n let storage_disk_write_bytes = foyer_storage_disk_io_bytes.counter(&[name.clone(), \"write\".into()]);\n let storage_disk_read_bytes = foyer_storage_disk_io_bytes.counter(&[name.clone(), \"read\".into()]);\n\n let storage_disk_write_duration = foyer_storage_disk_io_duration.histogram(&[name.clone(), \"write\".into()]);\n let storage_disk_read_duration = foyer_storage_disk_io_duration.histogram(&[name.clone(), \"read\".into()]);\n let storage_disk_flush_duration = foyer_storage_disk_io_duration.histogram(&[name.clone(), \"flush\".into()]);\n\n let storage_region_total = foyer_storage_region.gauge(&[name.clone(), \"total\".into()]);\n let storage_region_clean = foyer_storage_region.gauge(&[name.clone(), \"clean\".into()]);\n let storage_region_evictable = foyer_storage_region.gauge(&[name.clone(), \"evictable\".into()]);\n\n let storage_region_size_bytes = foyer_storage_region_size_bytes.gauge(&[name.clone()]);\n\n let storage_entry_serialize_duration =\n foyer_storage_entry_serde_duration.histogram(&[name.clone(), \"serialize\".into()]);\n let storage_entry_deserialize_duration =\n foyer_storage_entry_serde_duration.histogram(&[name.clone(), \"deserialize\".into()]);\n\n let storage_lodc_indexer_conflict =\n foyer_storage_lodc_op_total.counter(&[name.clone(), \"indexer_conflict\".into()]);\n let storage_lodc_enqueue_skip = foyer_storage_lodc_op_total.counter(&[name.clone(), \"enqueue_skip\".into()]);\n let storage_lodc_buffer_efficiency = foyer_storage_lodc_buffer_efficiency.histogram(&[name.clone()]);\n let storage_lodc_recover_duration = foyer_storage_lodc_recover_duration.histogram(&[name.clone()]);\n\n /* hybrid cache metrics */\n\n let foyer_hybrid_op_total = registry.register_counter_vec(\n \"foyer_hybrid_op_total\".into(),\n \"foyer hybrid cache operations\".into(),\n &[\"name\", \"op\"],\n );\n let foyer_hybrid_op_duration = registry.register_histogram_vec(\n \"foyer_hybrid_op_duration\".into(),\n \"foyer hybrid cache operation durations\".into(),\n &[\"name\", \"op\"],\n );\n\n let hybrid_insert = foyer_hybrid_op_total.counter(&[name.clone(), \"insert\".into()]);\n let hybrid_hit = foyer_hybrid_op_total.counter(&[name.clone(), \"hit\".into()]);\n let hybrid_miss = foyer_hybrid_op_total.counter(&[name.clone(), \"miss\".into()]);\n let hybrid_throttled = foyer_hybrid_op_total.counter(&[name.clone(), \"throttled\".into()]);\n let hybrid_remove = foyer_hybrid_op_total.counter(&[name.clone(), \"remove\".into()]);\n\n let hybrid_insert_duration = foyer_hybrid_op_duration.histogram(&[name.clone(), \"insert\".into()]);\n let hybrid_hit_duration = foyer_hybrid_op_duration.histogram(&[name.clone(), \"hit\".into()]);\n let hybrid_miss_duration = foyer_hybrid_op_duration.histogram(&[name.clone(), \"miss\".into()]);\n let hybrid_throttled_duration = foyer_hybrid_op_duration.histogram(&[name.clone(), \"throttled\".into()]);\n let hybrid_remove_duration = foyer_hybrid_op_duration.histogram(&[name.clone(), \"remove\".into()]);\n let hybrid_fetch_duration = foyer_hybrid_op_duration.histogram(&[name.clone(), \"fetch\".into()]);\n\n Self {\n memory_insert,\n memory_replace,\n memory_hit,\n memory_miss,\n memory_remove,\n memory_evict,\n memory_reinsert,\n memory_release,\n memory_queue,\n memory_fetch,\n memory_usage,\n\n storage_enqueue,\n storage_hit,\n storage_miss,\n storage_delete,\n storage_error,\n storage_enqueue_duration,\n storage_hit_duration,\n storage_miss_duration,\n storage_delete_duration,\n storage_queue_rotate,\n storage_queue_rotate_duration,\n storage_queue_buffer_overflow,\n storage_queue_channel_overflow,\n storage_disk_write,\n storage_disk_read,\n storage_disk_flush,\n storage_disk_write_bytes,\n storage_disk_read_bytes,\n storage_disk_write_duration,\n storage_disk_read_duration,\n storage_disk_flush_duration,\n storage_region_total,\n storage_region_clean,\n storage_region_evictable,\n storage_region_size_bytes,\n storage_entry_serialize_duration,\n storage_entry_deserialize_duration,\n storage_lodc_indexer_conflict,\n storage_lodc_enqueue_skip,\n storage_lodc_buffer_efficiency,\n storage_lodc_recover_duration,\n\n hybrid_insert,\n hybrid_hit,\n hybrid_miss,\n hybrid_throttled,\n hybrid_throttled_duration,\n hybrid_remove,\n hybrid_insert_duration,\n hybrid_hit_duration,\n hybrid_miss_duration,\n hybrid_remove_duration,\n hybrid_fetch_duration,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new metric with the given name.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/metrics.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/metrics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "582e661b2400ab97ec791781535723a0b15b171368ea0a011f5283fbe371f17e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: probe\n\nDocumentation:\nCheck if there is still some quota left.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn probe(&self) -> bool {\n let mut inner = self.inner.lock();\n\n let now = Instant::now();\n let refill = now.duration_since(inner.last).as_secs_f64() * self.rate;\n inner.last = now;\n inner.quota = f64::min(inner.quota + refill, self.rate);\n\n inner.quota > 0.0\n }\n```"}], "func_name": "probe", "docstring": "Check if there is still some quota left.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/rated_ticket.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/rated_ticket.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "84e0463c5aee84f225a421cacc4754a16fe5648eb3e23fafa13a7b2f815f2389"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn\n\nDocumentation:\nSpawns a future onto the Tokio runtime.\n\nThis spawns the given future onto the runtime's executor, usually a\nthread pool. The thread pool is then responsible for polling the future\nuntil it completes.\n\nThe provided future will start running in the background immediately\nwhen `spawn` is called, even if you don't await the returned\n`JoinHandle`.\n\nSee [module level][mod] documentation for more details.\n\n[mod]: index.html\n\n# Examples\n\n```\nuse tokio::runtime::Runtime;\n\n# fn dox() {\n// Create the runtime\nlet rt = Runtime::new().unwrap();\n// Get a handle from this runtime\nlet handle = rt.handle();\n\n// Spawn a future onto the runtime using the handle\nhandle.spawn(async {\nprintln!(\"now running on a worker thread\");\n});\n# }\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn spawn(&self, future: F) -> JoinHandle\n where\n F: Future + Send + 'static,\n F::Output: Send + 'static,\n {\n self.0.spawn(future)\n }\n```"}], "func_name": "spawn", "docstring": "Spawns a future onto the Tokio runtime.\n\nThis spawns the given future onto the runtime's executor, usually a\nthread pool. The thread pool is then responsible for polling the future\nuntil it completes.\n\nThe provided future will start running in the background immediately\nwhen `spawn` is called, even if you don't await the returned\n`JoinHandle`.\n\nSee [module level][mod] documentation for more details.\n\n[mod]: index.html\n\n# Examples\n\n```\nuse tokio::runtime::Runtime;\n\n# fn dox() {\n// Create the runtime\nlet rt = Runtime::new().unwrap();\n// Get a handle from this runtime\nlet handle = rt.handle();\n\n// Spawn a future onto the runtime using the handle\nhandle.spawn(async {\nprintln!(\"now running on a worker thread\");\n});\n# }\n```", "repo": "foyer-rs/foyer", "path": "foyer-common/src/runtime.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/runtime.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a138e84896e989626837637c9a32e11d71a248b5e1af38f893a03146a7f02a5a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn_blocking\n\nDocumentation:\nRuns the provided function on an executor dedicated to blocking\noperations.\n\n# Examples\n\n```\nuse tokio::runtime::Runtime;\n\n# fn dox() {\n// Create the runtime\nlet rt = Runtime::new().unwrap();\n// Get a handle from this runtime\nlet handle = rt.handle();\n\n// Spawn a blocking function onto the runtime using the handle\nhandle.spawn_blocking(|| {\nprintln!(\"now running on a worker thread\");\n});\n# }\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn spawn_blocking(&self, func: F) -> JoinHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n self.0.spawn_blocking(func)\n }\n```"}], "func_name": "spawn_blocking", "docstring": "Runs the provided function on an executor dedicated to blocking\noperations.\n\n# Examples\n\n```\nuse tokio::runtime::Runtime;\n\n# fn dox() {\n// Create the runtime\nlet rt = Runtime::new().unwrap();\n// Get a handle from this runtime\nlet handle = rt.handle();\n\n// Spawn a blocking function onto the runtime using the handle\nhandle.spawn_blocking(|| {\nprintln!(\"now running on a worker thread\");\n});\n# }", "repo": "foyer-rs/foyer", "path": "foyer-common/src/runtime.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/runtime.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "15ecd66a6742bae6aba2717c7daab8dbf9a8dd02c4277b5eab621249c0a07722"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_record_hybrid_insert_threshold\n\nDocumentation:\nSet the threshold for recording the hybrid cache `insert` and `insert_with_context` operation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_record_hybrid_insert_threshold(mut self, threshold: Duration) -> Self {\n self.record_hybrid_insert_threshold = Some(threshold);\n self\n }\n```"}], "func_name": "with_record_hybrid_insert_threshold", "docstring": "Set the threshold for recording the hybrid cache `insert` and `insert_with_context` operation.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/tracing.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/tracing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad9a8bd5d58b533d5098d1fb0d6ec5b3b3b35cd3bbf5909d7079df10817c17bf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_record_hybrid_get_threshold\n\nDocumentation:\nSet the threshold for recording the hybrid cache `get` operation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_record_hybrid_get_threshold(mut self, threshold: Duration) -> Self {\n self.record_hybrid_get_threshold = Some(threshold);\n self\n }\n```"}], "func_name": "with_record_hybrid_get_threshold", "docstring": "Set the threshold for recording the hybrid cache `get` operation.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/tracing.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/tracing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "72293c89b4869bbf47579c625384086f37a4505cccf74f83680fb55079d98bfe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_record_hybrid_obtain_threshold\n\nDocumentation:\nSet the threshold for recording the hybrid cache `obtain` operation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_record_hybrid_obtain_threshold(mut self, threshold: Duration) -> Self {\n self.record_hybrid_obtain_threshold = Some(threshold);\n self\n }\n```"}], "func_name": "with_record_hybrid_obtain_threshold", "docstring": "Set the threshold for recording the hybrid cache `obtain` operation.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/tracing.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/tracing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48a13a5b9f7ae447e160935e74a35a4f8f2d793f5d7dfdcf0f924e8dbf05c72b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_record_hybrid_remove_threshold\n\nDocumentation:\nSet the threshold for recording the hybrid cache `remove` operation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_record_hybrid_remove_threshold(mut self, threshold: Duration) -> Self {\n self.record_hybrid_remove_threshold = Some(threshold);\n self\n }\n```"}], "func_name": "with_record_hybrid_remove_threshold", "docstring": "Set the threshold for recording the hybrid cache `remove` operation.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/tracing.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/tracing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a94b8279f37a24927749384fe957709c2bb71992971c3cae9852ecb875d663c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_record_hybrid_fetch_threshold\n\nDocumentation:\nSet the threshold for recording the hybrid cache `fetch` operation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_record_hybrid_fetch_threshold(mut self, threshold: Duration) -> Self {\n self.record_hybrid_fetch_threshold = Some(threshold);\n self\n }\n```"}], "func_name": "with_record_hybrid_fetch_threshold", "docstring": "Set the threshold for recording the hybrid cache `fetch` operation.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/tracing.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/tracing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "306bdff1b06bb775ac5d77abd24a4814c7018b61df3b861a150bcd261d2691eb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a traced future with the given root span.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(inner: F, root: Span) -> Self\n where\n F: Future,\n {\n Self {\n inner,\n root: Some(root),\n threshold: None,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a traced future with the given root span.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/tracing.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/tracing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ca815b14466f9ea3f5bbfa9d3c8c6feacfbcc9a4f3c4464ee845c52358c2842"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_threshold\n\nDocumentation:\nSet record threshold for the root span.\n\nIf the duration of the root span is lower than the threshold, the root span will not be recorded.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_threshold(mut self, threshold: Duration) -> Self {\n self.threshold = Some(threshold);\n self\n }\n```"}], "func_name": "with_threshold", "docstring": "Set record threshold for the root span.\n\nIf the duration of the root span is lower than the threshold, the root span will not be recorded.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/tracing.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/tracing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3fd2fa1a79b834fe1ec903600fcd9cb9e1a6da9f44dbec582854ffb4603d5b5f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start\n\nDocumentation:\nGet the start bound of the range.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn start(&self) -> Option {\n match self.start_bound() {\n Bound::Included(v) => Some(*v),\n Bound::Excluded(v) => Some(*v + ZeroOne::one()),\n Bound::Unbounded => None,\n }\n }\n```"}], "func_name": "start", "docstring": "Get the start bound of the range.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/utils/range.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/utils/range.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f2d100eee84f35fd8d35166806fed635c51372a173967759188af3969a2abbdf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: end\n\nDocumentation:\nGet the end bound of the range.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn end(&self) -> Option {\n match self.end_bound() {\n Bound::Included(v) => Some(*v + ZeroOne::one()),\n Bound::Excluded(v) => Some(*v),\n Bound::Unbounded => None,\n }\n }\n```"}], "func_name": "end", "docstring": "Get the end bound of the range.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/utils/range.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/utils/range.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c1f3b70c7b81191bd251bad760e4ac31184b4a2b862dc0158fdc4d596835f00"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bounds\n\nDocumentation:\nGet the new range with the given range bounds.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn bounds(&self, range: Range) -> Range {\n let start = self.start_with_bound(range.start);\n let end = self.end_with_bound(range.end);\n start..end\n }\n```"}], "func_name": "bounds", "docstring": "Get the new range with the given range bounds.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/utils/range.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/utils/range.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c306a3cbd5670f348bc575c677560fdff07d7a66af95444980e4d64fee845472"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_empty\n\nDocumentation:\nCheck if the range is empty.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_empty(&self) -> bool {\n match self.size() {\n Some(len) => len == ZeroOne::zero(),\n None => false,\n }\n }\n```"}], "func_name": "is_empty", "docstring": "Check if the range is empty.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/utils/range.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/utils/range.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d1dd4506af55c5964a6e3db5ffe80d21b09894b8de41c04ec6c339d067e91beb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_full\n\nDocumentation:\nCheck is the range is a full range.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_full(&self) -> bool {\n self.start_bound() == Bound::Unbounded && self.end_bound() == Bound::Unbounded\n }\n```"}], "func_name": "is_full", "docstring": "Check is the range is a full range.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/utils/range.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/utils/range.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00f97c7d239439bb5ff97dbc71ae6a7b992874cbc660c6cd3e06464469adad11"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: map\n\nDocumentation:\nMap the range with the given method.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn map(&self, f: F) -> (Bound, Bound)\n where\n F: Fn(&T) -> R,\n {\n (self.start_bound().map(&f), self.end_bound().map(&f))\n }\n```"}], "func_name": "map", "docstring": "Map the range with the given method.", "repo": "foyer-rs/foyer", "path": "foyer-common/src/utils/range.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-common/src/utils/range.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a428c5860198e678e240f03042b70e9e5e266a418eb84a990032d1bd1251e449"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: hash\n\nDocumentation:\nKey hash of the cached entry.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn hash(&self) -> u64 {\n match self {\n CacheEntry::Fifo(entry) => entry.hash(),\n CacheEntry::Lru(entry) => entry.hash(),\n CacheEntry::Lfu(entry) => entry.hash(),\n CacheEntry::S3Fifo(entry) => entry.hash(),\n }\n }\n```"}], "func_name": "hash", "docstring": "Key hash of the cached entry.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0329011dd210bd768287af232bc6e35868f921b9d79c7e90b98b12b37a96a703"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: refs\n\nDocumentation:\nExternal reference count of the cached entry.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn refs(&self) -> usize {\n match self {\n CacheEntry::Fifo(entry) => entry.refs(),\n CacheEntry::Lru(entry) => entry.refs(),\n CacheEntry::Lfu(entry) => entry.refs(),\n CacheEntry::S3Fifo(entry) => entry.refs(),\n }\n }\n```"}], "func_name": "refs", "docstring": "External reference count of the cached entry.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b18539f678039563d2eddc2149396806dad29a447005860d0044ca496f43df6c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_outdated\n\nDocumentation:\nIf the cached entry is updated and outdated.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_outdated(&self) -> bool {\n match self {\n CacheEntry::Fifo(entry) => entry.is_outdated(),\n CacheEntry::Lru(entry) => entry.is_outdated(),\n CacheEntry::Lfu(entry) => entry.is_outdated(),\n CacheEntry::S3Fifo(entry) => entry.is_outdated(),\n }\n }\n```"}], "func_name": "is_outdated", "docstring": "If the cached entry is updated and outdated.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0207d7c03b1f06750846ae854f564df303d30043d345fb2c487183dac63c19d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: piece\n\nDocumentation:\nGet the piece of the entry record.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn piece(&self) -> Piece {\n match self {\n CacheEntry::Fifo(entry) => entry.piece(),\n CacheEntry::Lru(entry) => entry.piece(),\n CacheEntry::Lfu(entry) => entry.piece(),\n CacheEntry::S3Fifo(entry) => entry.piece(),\n }\n }\n```"}], "func_name": "piece", "docstring": "Get the piece of the entry record.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "596604c527acad0963b3180d82ba0cfb03bef69f03d88b20fbdab8a9271d8719"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new in-memory cache builder.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(capacity: usize) -> Self {\n Self {\n name: \"foyer\".into(),\n\n capacity,\n shards: 8,\n eviction_config: LruConfig::default().into(),\n\n hash_builder: Default::default(),\n weighter: Arc::new(|_, _| 1),\n event_listener: None,\n\n registry: Box::new(NoopMetricsRegistry),\n metrics: None,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new in-memory cache builder.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e3357acf6885dbbe90a51a4c91c74fb3935c126a334de4396925ef34bee52f71"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nBuild in-memory cache with the given configuration.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build

(self) -> Cache\n where\n P: Properties,\n {\n if self.capacity < self.shards {\n tracing::warn!(\n \"The in-memory cache capacity({}) < shards({}).\",\n self.capacity,\n self.shards\n );\n }\n\n let metrics = self\n .metrics\n .unwrap_or_else(|| Arc::new(Metrics::new(self.name, &self.registry)));\n\n match self.eviction_config {\n EvictionConfig::Fifo(eviction_config) => Cache::Fifo(Arc::new(RawCache::new(RawCacheConfig {\n capacity: self.capacity,\n shards: self.shards,\n eviction_config,\n hash_builder: self.hash_builder,\n weighter: self.weighter,\n event_listener: self.event_listener,\n metrics,\n }))),\n EvictionConfig::S3Fifo(eviction_config) => Cache::S3Fifo(Arc::new(RawCache::new(RawCacheConfig {\n capacity: self.capacity,\n shards: self.shards,\n eviction_config,\n hash_builder: self.hash_builder,\n weighter: self.weighter,\n event_listener: self.event_listener,\n metrics,\n }))),\n EvictionConfig::Lru(eviction_config) => Cache::Lru(Arc::new(RawCache::new(RawCacheConfig {\n capacity: self.capacity,\n shards: self.shards,\n eviction_config,\n hash_builder: self.hash_builder,\n weighter: self.weighter,\n event_listener: self.event_listener,\n metrics,\n }))),\n EvictionConfig::Lfu(eviction_config) => Cache::Lfu(Arc::new(RawCache::new(RawCacheConfig {\n capacity: self.capacity,\n shards: self.shards,\n eviction_config,\n hash_builder: self.hash_builder,\n weighter: self.weighter,\n event_listener: self.event_listener,\n metrics,\n }))),\n }\n }\n```"}], "func_name": "build", "docstring": "Build in-memory cache with the given configuration.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "49f4fb4e3b4e56390f513aed107cb469ed91733d6013828b00c412cfacd5fbc1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: capacity\n\nDocumentation:\nGet the capacity of the in-memory cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn capacity(&self) -> usize {\n match self {\n Cache::Fifo(cache) => cache.capacity(),\n Cache::S3Fifo(cache) => cache.capacity(),\n Cache::Lru(cache) => cache.capacity(),\n Cache::Lfu(cache) => cache.capacity(),\n }\n }\n```"}], "func_name": "capacity", "docstring": "Get the capacity of the in-memory cache.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c05a60aaf595017f9713050262e764ab6d787088f1731eeba8286cc3e1f7a0d6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: usage\n\nDocumentation:\nGet the usage of the in-memory cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn usage(&self) -> usize {\n match self {\n Cache::Fifo(cache) => cache.usage(),\n Cache::S3Fifo(cache) => cache.usage(),\n Cache::Lru(cache) => cache.usage(),\n Cache::Lfu(cache) => cache.usage(),\n }\n }\n```"}], "func_name": "usage", "docstring": "Get the usage of the in-memory cache.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fb6040f8f89680cddb08d4343dc2309fca0b95a2122b54036af07f54b7cc297f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: hash\n\nDocumentation:\nHash the given key with the hash builder of the cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn hash(&self, key: &Q) -> u64\n where\n Q: Hash + ?Sized,\n {\n self.hash_builder().hash_one(key)\n }\n```"}], "func_name": "hash", "docstring": "Hash the given key with the hash builder of the cache.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aac4b5bba35d88a0bdf02f7a81384acab01a6adfd50653d7fdfd196974b3b0f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: hash_builder\n\nDocumentation:\nGet the hash builder of the in-memory cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn hash_builder(&self) -> &Arc {\n match self {\n Cache::Fifo(cache) => cache.hash_builder(),\n Cache::S3Fifo(cache) => cache.hash_builder(),\n Cache::Lru(cache) => cache.hash_builder(),\n Cache::Lfu(cache) => cache.hash_builder(),\n }\n }\n```"}], "func_name": "hash_builder", "docstring": "Get the hash builder of the in-memory cache.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e252c1b331342e49ad801240a311b0568727aee66cbe16e5ad546f9f666cda2b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shards\n\nDocumentation:\nGet the shards of the in-memory cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn shards(&self) -> usize {\n match self {\n Cache::Fifo(cache) => cache.shards(),\n Cache::S3Fifo(cache) => cache.shards(),\n Cache::Lru(cache) => cache.shards(),\n Cache::Lfu(cache) => cache.shards(),\n }\n }\n```"}], "func_name": "shards", "docstring": "Get the shards of the in-memory cache.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd249007dd1b232ccbde6f96b380c04588fc6f9411ead6db9941eec029f610f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: evict_all\n\nDocumentation:\nEvict all entries from the in-memory cache.\n\nInstead of [`Cache::clear`], [`Cache::evict_all`] will send the evicted pipe to the pipe.\nIt is useful when the cache is used as a hybrid cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn evict_all(&self) {\n match self {\n Cache::Fifo(cache) => cache.evict_all(),\n Cache::S3Fifo(cache) => cache.evict_all(),\n Cache::Lru(cache) => cache.evict_all(),\n Cache::Lfu(cache) => cache.evict_all(),\n }\n }\n```"}], "func_name": "evict_all", "docstring": "Evict all entries from the in-memory cache.\n\nInstead of [`Cache::clear`], [`Cache::evict_all`] will send the evicted pipe to the pipe.\nIt is useful when the cache is used as a hybrid cache.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/cache.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3815441476bd40616176b97ea194673965d181c856793445d07b3a1624c0a34a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a record piece from an record wrapped by [`Arc`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(record: Arc>) -> Self\n where\n E: Eviction,\n {\n let raw = Arc::into_raw(record);\n let record = raw as *const ();\n let key = unsafe { (*raw).key() } as *const _;\n let value = unsafe { (*raw).value() } as *const _;\n let hash = unsafe { (*raw).hash() };\n let properties = unsafe { (*raw).properties() } as *const _;\n let drop_fn = |ptr| unsafe {\n let _ = Arc::from_raw(ptr as *const Record);\n };\n Self {\n record,\n key,\n value,\n hash,\n properties,\n drop_fn,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a record piece from an record wrapped by [`Arc`].", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/pipe.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/pipe.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3c0a7dd3f4597a0a1dcb25649d3549ed85aeb7d1e7c3ef3226c48ec176afdeea"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: key\n\nDocumentation:\nGet the key of the record.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn key(&self) -> &K {\n unsafe { &*self.key }\n }\n```"}], "func_name": "key", "docstring": "Get the key of the record.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/pipe.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/pipe.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bca3d6c09ab3f1394468cdbf03c8bce02a5eb71c0ae5dab3d159b743e783f89c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: value\n\nDocumentation:\nGet the value of the record.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn value(&self) -> &V {\n unsafe { &*self.value }\n }\n```"}], "func_name": "value", "docstring": "Get the value of the record.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/pipe.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/pipe.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f99b30038059dbcc879332a71e44cce99c0a7726bfd7f84ac84b1e430610aefe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: properties\n\nDocumentation:\nGet the properties of the record.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn properties(&self) -> &P {\n unsafe { &*self.properties }\n }\n```"}], "func_name": "properties", "docstring": "Get the properties of the record.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/pipe.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/pipe.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ccad309f8a9c37aa32cfa498503f9c22936a5d4ff3dffa563f447ceac13b63e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: evict\n\nDocumentation:\nEvict entries to fit the target usage.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn evict(&mut self, target: usize, garbages: &mut Vec<(Event, Arc>)>) {\n // Evict overflow records.\n while self.usage > target {\n let evicted = match self.eviction.pop() {\n Some(evicted) => evicted,\n None => break,\n };\n self.metrics.memory_evict.increase(1);\n\n let e = self.indexer.remove(evicted.hash(), evicted.key()).unwrap();\n assert_eq!(Arc::as_ptr(&evicted), Arc::as_ptr(&e));\n\n strict_assert!(!evicted.as_ref().is_in_indexer());\n strict_assert!(!evicted.as_ref().is_in_eviction());\n\n self.usage -= evicted.weight();\n\n garbages.push((Event::Evict, evicted));\n }\n }\n```"}], "func_name": "evict", "docstring": "Evict entries to fit the target usage.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/raw.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/raw.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a1ce9559561e46b874a5181d3f12eaeba9d6da64d0c791b481a6866de12e7769"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_in_eviction\n\nDocumentation:\nSet in eviction flag with relaxed memory order.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_in_eviction(&self, val: bool) {\n self.set_flags(Flags::IN_EVICTION, val, Ordering::Release);\n }\n```"}], "func_name": "set_in_eviction", "docstring": "Set in eviction flag with relaxed memory order.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/record.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/record.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e368a1a5f900edaf3b6b2efb00b0030d96813f64357fd255f7b7e8662aba1bcc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_in_eviction\n\nDocumentation:\nGet in eviction flag with relaxed memory order.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_in_eviction(&self) -> bool {\n self.get_flags(Flags::IN_EVICTION, Ordering::Acquire)\n }\n```"}], "func_name": "is_in_eviction", "docstring": "Get in eviction flag with relaxed memory order.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/record.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/record.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f17faf69a67b4bcad985e9adf32ae11d3d1d4c157883a6b82ab0379324a41d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_in_indexer\n\nDocumentation:\nSet in indexer flag with relaxed memory order.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_in_indexer(&self, val: bool) {\n self.set_flags(Flags::IN_INDEXER, val, Ordering::Release);\n }\n```"}], "func_name": "set_in_indexer", "docstring": "Set in indexer flag with relaxed memory order.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/record.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/record.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b1ff58e0c0171e354e83a6d249f45f02b5596a95a5f10508a8a7a944b1d6e86"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_in_indexer\n\nDocumentation:\nGet in indexer flag with relaxed memory order.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_in_indexer(&self) -> bool {\n self.get_flags(Flags::IN_INDEXER, Ordering::Acquire)\n }\n```"}], "func_name": "is_in_indexer", "docstring": "Get in indexer flag with relaxed memory order.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/record.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/record.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a9911d39980fb2b7233560cdec7cc13e4071fc410cdb208c6664de1d38c7b69"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_ephemeral\n\nDocumentation:\nSet ephemeral flag with relaxed memory order.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_ephemeral(&self, val: bool) {\n self.set_flags(Flags::EPHEMERAL, val, Ordering::Release);\n }\n```"}], "func_name": "set_ephemeral", "docstring": "Set ephemeral flag with relaxed memory order.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/record.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/record.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "def7aeb24a3ab4806702350e42a71337f09b9891b1cb72428362f113fdb40bfa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_ephemeral\n\nDocumentation:\nGet ephemeral flag with relaxed memory order.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_ephemeral(&self) -> bool {\n self.get_flags(Flags::EPHEMERAL, Ordering::Acquire)\n }\n```"}], "func_name": "is_ephemeral", "docstring": "Get ephemeral flag with relaxed memory order.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/record.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/record.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf992254c5743967b5e46ece1c440f2dd18b44727a544c10e0cea3e650aea654"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: inc_refs\n\nDocumentation:\nIncrease the atomic reference count.\n\nThis function returns the new reference count after the op.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn inc_refs(&self, val: usize) -> usize {\n let old = self.refs.fetch_add(val, Ordering::SeqCst);\n tracing::trace!(\n \"[record]: inc record (hash: {}) refs: {} => {}\",\n self.hash(),\n old,\n old + val\n );\n old + val\n }\n```"}], "func_name": "inc_refs", "docstring": "Increase the atomic reference count.\n\nThis function returns the new reference count after the op.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/record.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/record.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "accc837bc0398765ea6a588a2ba500113e95a5230a41ef204ae10696c41880ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dec_refs\n\nDocumentation:\nDecrease the atomic reference count.\n\nThis function returns the new reference count after the op.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn dec_refs(&self, val: usize) -> usize {\n let old = self.refs.fetch_sub(val, Ordering::SeqCst);\n tracing::trace!(\n \"[record]: dec record (hash: {}) refs: {} => {}\",\n self.hash(),\n old,\n old - val\n );\n old - val\n }\n```"}], "func_name": "dec_refs", "docstring": "Decrease the atomic reference count.\n\nThis function returns the new reference count after the op.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/record.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/record.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1cb5e84f2f3a289b9c5fd4aca43f25e306c8003c54f62cb3a929b34df338e712"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push\n\nDocumentation:\nPush a new record to `window`.\n\nOverflow record from `window` to `probation` if needed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn push(&mut self, record: Arc>) {\n let state = unsafe { &mut *record.state().get() };\n\n strict_assert!(!state.link.is_linked());\n strict_assert!(!record.is_in_eviction());\n strict_assert_eq!(state.queue, Queue::None);\n\n record.set_in_eviction(true);\n state.queue = Queue::Window;\n self.increase_queue_weight(Queue::Window, record.weight());\n self.update_frequencies(record.hash());\n self.window.push_back(record);\n\n // If `window` weight exceeds the capacity, overflow entry from `window` to `probation`.\n while self.window_weight > self.window_weight_capacity {\n strict_assert!(!self.window.is_empty());\n let r = self.window.pop_front().unwrap();\n let s = unsafe { &mut *r.state().get() };\n self.decrease_queue_weight(Queue::Window, r.weight());\n s.queue = Queue::Probation;\n self.increase_queue_weight(Queue::Probation, r.weight());\n self.probation.push_back(r);\n }\n }\n```"}], "func_name": "push", "docstring": "Push a new record to `window`.\n\nOverflow record from `window` to `probation` if needed.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/eviction/lfu.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/eviction/lfu.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e48701ab27e97acd78cb67933cc0ac992e917f35f230c749fdaf8b68cd2a673"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clear\n\nDocumentation:\nRemove all records from the cache eviction algorithm instance.\n\nThe cache eviction algorithm instance MUST remove the records and set its `IN_EVICTION` flag to false.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn clear(&mut self) {\n while self.pop().is_some() {}\n }\n```"}], "func_name": "clear", "docstring": "Remove all records from the cache eviction algorithm instance.\n\nThe cache eviction algorithm instance MUST remove the records and set its `IN_EVICTION` flag to false.", "repo": "foyer-rs/foyer", "path": "foyer-memory/src/eviction/mod.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-memory/src/eviction/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e77e341b640c0a6c9df712b5d90e9d88c97b75b6c01291cb3ea2cf7bd5272854"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_u8\n\nDocumentation:\nGet the u8 that represent the compression algorithm.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_u8(&self) -> u8 {\n match self {\n Self::None => 0,\n Self::Zstd => 1,\n Self::Lz4 => 2,\n }\n }\n```"}], "func_name": "to_u8", "docstring": "Get the u8 that represent the compression algorithm.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/compress.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/compress.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d989ec6fcacbb63057dd185322f1fda2e08626e38d4525cae8b9751d23de5448"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new runtime with runtimes if given.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n read_runtime: Option>,\n write_runtime: Option>,\n user_runtime_handle: Handle,\n ) -> Self {\n let read_runtime_handle = read_runtime\n .as_ref()\n .map(|rt| rt.handle().clone())\n .unwrap_or(user_runtime_handle.clone());\n let write_runtime_handle = write_runtime\n .as_ref()\n .map(|rt| rt.handle().clone())\n .unwrap_or(user_runtime_handle.clone());\n Self {\n inner: Arc::new(RuntimeInner {\n _read_runtime: read_runtime,\n _write_runtime: write_runtime,\n read_runtime_handle: read_runtime_handle.into(),\n write_runtime_handle: write_runtime_handle.into(),\n user_runtime_handle: user_runtime_handle.into(),\n }),\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new runtime with runtimes if given.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/runtime.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/runtime.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b5501c492cdf311d12f1dfa09be4d8e87da048e48b48f1ea205eafab7d9b355"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: current\n\nDocumentation:\nCreate a new runtime with current runtime env only.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn current() -> Self {\n Self {\n inner: Arc::new(RuntimeInner {\n _read_runtime: None,\n _write_runtime: None,\n read_runtime_handle: Handle::current().into(),\n write_runtime_handle: Handle::current().into(),\n user_runtime_handle: Handle::current().into(),\n }),\n }\n }\n```"}], "func_name": "current", "docstring": "Create a new runtime with current runtime env only.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/runtime.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/runtime.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6050a405d2f0e6b482e05c1f971e800bbe606a760d205fdfc51947e7dd309e31"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: record_disk_write\n\nDocumentation:\nRecord the write IO and update the statistics.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn record_disk_write(&self, bytes: usize) {\n self.disk_write_bytes.fetch_add(bytes, Ordering::Relaxed);\n self.disk_write_ios\n .fetch_add(self.iops_counter.count(bytes), Ordering::Relaxed);\n }\n```"}], "func_name": "record_disk_write", "docstring": "Record the write IO and update the statistics.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/statistics.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/statistics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27e027c7e4922558c1ce41ac96ddae785f41b572d3ac2df392442606eecaa4b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: record_disk_read\n\nDocumentation:\nRecord the read IO and update the statistics.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn record_disk_read(&self, bytes: usize) {\n self.disk_read_bytes.fetch_add(bytes, Ordering::Relaxed);\n self.disk_read_ios\n .fetch_add(self.iops_counter.count(bytes), Ordering::Relaxed);\n }\n```"}], "func_name": "record_disk_read", "docstring": "Record the read IO and update the statistics.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/statistics.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/statistics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5fe05ac63d3b0a7a10c46dfcdad0622c24864f4afbf9f6320fac939e69250539"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: entry\n\nDocumentation:\nReturn `Some` with the entry if load success, otherwise return `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn entry(self) -> Option<(K, V, Populated)> {\n match self {\n Load::Entry { key, value, populated } => Some((key, value, populated)),\n _ => None,\n }\n }\n```"}], "func_name": "entry", "docstring": "Return `Some` with the entry if load success, otherwise return `None`.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b012d91de1231c0fca6c162a26e880274232a8fc785bd16a8c4bd2e2e6a2e84d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: kv\n\nDocumentation:\nReturn `Some` with the entry if load success, otherwise return `None`.\n\nOnly key and value will be returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn kv(self) -> Option<(K, V)> {\n match self {\n Load::Entry { key, value, .. } => Some((key, value)),\n _ => None,\n }\n }\n```"}], "func_name": "kv", "docstring": "Return `Some` with the entry if load success, otherwise return `None`.\n\nOnly key and value will be returned.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7a65b7d35323ce0d4d323a9ee6b6333f8fb3e1875378057d6ca95c71963e2543"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_entry\n\nDocumentation:\nCheck if the load result is a cache entry.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_entry(&self) -> bool {\n matches!(self, Load::Entry { .. })\n }\n```"}], "func_name": "is_entry", "docstring": "Check if the load result is a cache entry.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c85559c84efdbef5fd4ae79a00a9be7dbcb4fa0b6f94f9c10ee59d531bc2d2f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_miss\n\nDocumentation:\nCheck if the load result is a cache miss.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_miss(&self) -> bool {\n matches!(self, Load::Miss)\n }\n```"}], "func_name": "is_miss", "docstring": "Check if the load result is a cache miss.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "28db589a57d1e6f4765a8d599905d7b903427c3ad4a280d20dd2c9126cf860e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_throttled\n\nDocumentation:\nCheck if the load result is miss caused by io throttled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_throttled(&self) -> bool {\n matches!(self, Load::Throttled)\n }\n```"}], "func_name": "is_throttled", "docstring": "Check if the load result is miss caused by io throttled.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a906c9a989d1c601f081b82ed9ca80c8d1fbbafcee3a60b76ff3f7a1aff71071"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pick\n\nDocumentation:\nReturn if the given key can be picked by the admission picker.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pick(&self, hash: u64) -> Pick {\n self.inner.admission_picker.pick(&self.inner.statistics, hash)\n }\n```"}], "func_name": "pick", "docstring": "Return if the given key can be picked by the admission picker.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ccf85475ecf62771f4c9ef6ee5e77654a1620e01d09c0e98f6072c4403ee115c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: enqueue\n\nDocumentation:\nPush a in-memory cache piece to the disk cache write queue.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn enqueue(&self, piece: Piece, force: bool) {\n tracing::trace!(hash = piece.hash(), \"[store]: enqueue piece\");\n let now = Instant::now();\n\n if force || self.pick(piece.hash()).admitted() {\n let estimated_size = EntrySerializer::estimated_size(piece.key(), piece.value());\n self.inner.engine.enqueue(piece, estimated_size);\n }\n\n self.inner.metrics.storage_enqueue.increase(1);\n self.inner\n .metrics\n .storage_enqueue_duration\n .record(now.elapsed().as_secs_f64());\n }\n```"}], "func_name": "enqueue", "docstring": "Push a in-memory cache piece to the disk cache write queue.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fed16c53e4b26cb6be3872423a459d2bdb47d64f87f657841084cf379e44ab1d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load\n\nDocumentation:\nLoad a cache entry from the disk cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn load(&self, key: &Q) -> Result>\n where\n Q: Hash + Equivalent + ?Sized + Send + Sync + 'static,\n {\n let hash = self.inner.hasher.hash_one(key);\n\n #[cfg(feature = \"test_utils\")]\n if self.inner.load_throttle_switch.is_throttled() {\n return Ok(Load::Throttled);\n }\n\n if let Some(throttler) = self.inner.load_throttler.as_ref() {\n match throttler.pick(&self.inner.statistics, hash) {\n Pick::Admit => {}\n Pick::Reject => unreachable!(),\n Pick::Throttled(_) => {\n if self.inner.engine.may_contains(hash) {\n return Ok(Load::Throttled);\n } else {\n return Ok(Load::Miss);\n }\n }\n }\n }\n\n let future = self.inner.engine.load(hash);\n match self.inner.runtime.read().spawn(future).await.unwrap() {\n Ok(Load::Entry {\n key: k,\n value: v,\n populated: p,\n }) if key.equivalent(&k) => Ok(Load::Entry {\n key: k,\n value: v,\n populated: p,\n }),\n Ok(Load::Entry { .. }) | Ok(Load::Miss) => Ok(Load::Miss),\n Ok(Load::Throttled) => Ok(Load::Throttled),\n Err(e) => Err(e),\n }\n }\n```"}], "func_name": "load", "docstring": "Load a cache entry from the disk cache.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e5784cd4c0ce037a98f884e5a3ad9954d8e0420f6132576a469dd995b7d9ba7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete\n\nDocumentation:\nDelete the cache entry with the given key from the disk cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn delete<'a, Q>(&'a self, key: &'a Q)\n where\n Q: Hash + Equivalent + ?Sized,\n {\n let hash = self.inner.hasher.hash_one(key);\n self.inner.engine.delete(hash)\n }\n```"}], "func_name": "delete", "docstring": "Delete the cache entry with the given key from the disk cache.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b4532efff4a819f0d40bbbf8b3fd41da3403467e07aaa9d3c6782693f72730e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: may_contains\n\nDocumentation:\nCheck if the disk cache contains a cached entry with the given key.\n\n`contains` may return a false-positive result if there is a hash collision with the given key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn may_contains(&self, key: &Q) -> bool\n where\n Q: Hash + Equivalent + ?Sized,\n {\n let hash = self.inner.hasher.hash_one(key);\n self.inner.engine.may_contains(hash)\n }\n```"}], "func_name": "may_contains", "docstring": "Check if the disk cache contains a cached entry with the given key.\n\n`contains` may return a false-positive result if there is a hash collision with the given key.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "491a855a774af6bb9f31a76d0425fb5b9baa00c0aaee8d0cb812feb71b1567ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: entry_estimated_size\n\nDocumentation:\nReturn the estimated serialized size of the entry.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn entry_estimated_size(&self, key: &K, value: &V) -> usize {\n EntrySerializer::estimated_size(key, value)\n }\n```"}], "func_name": "entry_estimated_size", "docstring": "Return the estimated serialized size of the entry.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4984a3ddc2bb0aab687faba6df83b9dd46b7f383f18b2b1debc044895e33347b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mixed\n\nDocumentation:\nMixed large and small object disk cache storage engine with default configurations.\n\nThe ratio of the small object disk cache is set to `0.1`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn mixed() -> Self {\n Self::Mixed {\n ratio: 0.1,\n large: LargeEngineOptions::default(),\n small: SmallEngineOptions::default(),\n }\n }\n```"}], "func_name": "mixed", "docstring": "Mixed large and small object disk cache storage engine with default configurations.\n\nThe ratio of the small object disk cache is set to `0.1`.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "88ec222f504c93a382948b6968fdbbaad49c23b91cb6d0b0acf126e810a6df73"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nSetup disk cache store for the given in-memory cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n name: impl Into>,\n memory: Cache,\n metrics: Arc,\n engine: Engine,\n ) -> Self {\n if matches!(engine, Engine::Mixed{ ratio, .. } if !(0.0..=1.0).contains(&ratio)) {\n panic!(\"mixed engine small object disk cache ratio must be a f64 in range [0.0, 1.0]\");\n }\n\n Self {\n name: name.into(),\n memory,\n metrics,\n\n device_options: DeviceOptions::None,\n engine,\n runtime_config: RuntimeOptions::Disabled,\n\n admission_picker: Arc::::default(),\n compression: Compression::None,\n recover_mode: RecoverMode::Quiet,\n flush: false,\n }\n }\n```"}], "func_name": "new", "docstring": "Setup disk cache store for the given in-memory cache.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "05150d5c38fcbb425fd147b7c34f6880719deef5378a267341503d1364f1f2eb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nBuild the disk cache store with the given configuration.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn build(self) -> Result> {\n let memory = self.memory.clone();\n let metrics = self.metrics.clone();\n let mut admission_picker = self.admission_picker.clone();\n\n let compression = self.compression;\n\n let build_runtime = |config: &TokioRuntimeOptions, suffix: &str| {\n let mut builder = tokio::runtime::Builder::new_multi_thread();\n #[cfg(madsim)]\n let _ = config;\n #[cfg(not(madsim))]\n if config.worker_threads != 0 {\n builder.worker_threads(config.worker_threads);\n }\n #[cfg(not(madsim))]\n if config.max_blocking_threads != 0 {\n builder.max_blocking_threads(config.max_blocking_threads);\n }\n builder.thread_name(format!(\"{}-{}\", &self.name, suffix));\n let runtime = builder.enable_all().build().map_err(anyhow::Error::from)?;\n let runtime = BackgroundShutdownRuntime::from(runtime);\n Ok::<_, Error>(Arc::new(runtime))\n };\n\n let user_runtime_handle = Handle::current();\n let (read_runtime, write_runtime) = match self.runtime_config {\n RuntimeOptions::Disabled => {\n tracing::warn!(\"[store]: Dedicated runtime is disabled\");\n (None, None)\n }\n RuntimeOptions::Unified(runtime_config) => {\n let runtime = build_runtime(&runtime_config, \"unified\")?;\n (Some(runtime.clone()), Some(runtime.clone()))\n }\n RuntimeOptions::Separated {\n read_runtime_options: read_runtime_config,\n write_runtime_options: write_runtime_config,\n } => {\n let read_runtime = build_runtime(&read_runtime_config, \"read\")?;\n let write_runtime = build_runtime(&write_runtime_config, \"write\")?;\n (Some(read_runtime), Some(write_runtime))\n }\n };\n let runtime = Runtime::new(read_runtime, write_runtime, user_runtime_handle);\n\n let engine = {\n let metrics = metrics.clone();\n let runtime = runtime.clone();\n // Use the user runtime to open engine.\n tokio::spawn(async move {\n match self.device_options {\n DeviceOptions::None => {\n tracing::warn!(\n \"[store builder]: No device config set. Use `NoneStore` which always returns `None` for queries.\"\n );\n EngineEnum::open(EngineConfig::Noop).await\n }\n DeviceOptions::DeviceConfig(options) => {\n let device = match Monitored::open(MonitoredConfig {\n config: options,\n metrics: metrics.clone(),\n }, runtime.clone())\n .await {\n Ok(device) => device,\n Err(e) =>return Err(e),\n };\n match self.engine {\n Engine::Large(large) => {\n let regions = 0..device.regions() as RegionId;\n EngineEnum::open(EngineConfig::Large(GenericLargeStorageConfig {\n device,\n regions,\n compression: self.compression,\n flush: self.flush,\n indexer_shards: large.indexer_shards,\n recover_mode: self.recover_mode,\n recover_concurrency: large.recover_concurrency,\n flushers: large.flushers,\n reclaimers: large.reclaimers,\n clean_region_threshold: large.clean_region_threshold.unwrap_or(large.reclaimers),\n eviction_pickers: large.eviction_pickers,\n reinsertion_picker: large.reinsertion_picker,\n tombstone_log_config: large.tombstone_log_config,\n buffer_pool_size: large.buffer_pool_size,\n blob_index_size: large.blob_index_size,\n submit_queue_size_threshold: large.submit_queue_size_threshold.unwrap_or(large.buffer_pool_size * 2),\n runtime,\n marker: PhantomData,\n }))\n .await\n }\n Engine::Small(small) => {\n let regions = 0..device.regions() as RegionId;\n EngineEnum::open(EngineConfig::Small(GenericSmallStorageConfig {\n set_size: small.set_size,\n set_cache_capacity: small.set_cache_capacity,\n set_cache_shards: small.set_cache_shards,\n device,\n regions,\n flush: self.flush,\n flushers: small.flushers,\n buffer_pool_size: small.buffer_pool_size,\n runtime,\n marker: PhantomData,\n }))\n .await\n }\n Engine::Mixed{ratio, large, small} => {\n let small_region_count = std::cmp::max((device.regions() as f64 * ratio) as usize,1);\n let small_regions = 0..small_region_count as RegionId;\n let large_regions = small_region_count as RegionId..device.regions() as RegionId;\n EngineEnum::open(EngineConfig::Mixed(EitherConfig {\n selector: SizeSelector::new(Engine::OBJECT_SIZE_THRESHOLD),\n left: GenericSmallStorageConfig {\n set_size: small.set_size,\n set_cache_capacity: small.set_cache_capacity,\n set_cache_shards: small.set_cache_shards,\n device: device.clone(),\n regions: small_regions,\n flush: self.flush,\n flushers: small.flushers,\n buffer_pool_size: small.buffer_pool_size,\n runtime: runtime.clone(),\n marker: PhantomData,\n },\n right: GenericLargeStorageConfig {\n device,\n regions: large_regions,\n compression: self.compression,\n flush: self.flush,\n indexer_shards: large.indexer_shards,\n recover_mode: self.recover_mode,\n recover_concurrency: large.recover_concurrency,\n flushers: large.flushers,\n reclaimers: large.reclaimers,\n clean_region_threshold: large.clean_region_threshold.unwrap_or(large.reclaimers),\n eviction_pickers: large.eviction_pickers,\n reinsertion_picker: large.reinsertion_picker,\n tombstone_log_config: large.tombstone_log_config,\n buffer_pool_size: large.buffer_pool_size,\n blob_index_size: large.blob_index_size,\n submit_queue_size_threshold: large.submit_queue_size_threshold.unwrap_or(large.buffer_pool_size * 2),\n runtime,\n marker: PhantomData,\n },\n load_order: Engine::MIXED_LOAD_ORDER,\n }))\n .await\n }\n }\n }\n }\n }).await.unwrap()?\n };\n\n let statistics = engine.statistics().clone();\n\n let throttle = engine.throttle();\n if throttle.write_throughput.is_some() || throttle.write_iops.is_some() {\n tracing::debug!(?throttle, \"[store builder]: Device is throttled.\");\n admission_picker = Arc::new(\n ChainedAdmissionPickerBuilder::default()\n .chain(Arc::new(IoThrottlerPicker::new(\n IoThrottlerTarget::Write,\n throttle.write_throughput,\n throttle.write_iops,\n )))\n .chain(admission_picker)\n .build(),\n );\n }\n let load_throttler = (throttle.read_throughput.is_some() || throttle.read_iops.is_some()).then_some(\n IoThrottlerPicker::new(IoThrottlerTarget::Read, throttle.read_throughput, throttle.read_iops),\n );\n\n let hasher = memory.hash_builder().clone();\n let inner = StoreInner {\n hasher,\n engine,\n admission_picker,\n load_throttler,\n compression,\n runtime,\n statistics,\n metrics,\n\n #[cfg(feature = \"test_utils\")]\n load_throttle_switch: LoadThrottleSwitch::default(),\n };\n let inner = Arc::new(inner);\n let store = Store { inner };\n\n Ok(store)\n }\n```"}], "func_name": "build", "docstring": "Build the disk cache store with the given configuration.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8bbf0a30bf17e781ddda6ac8c45116971c4a939c2ecaa3fedf0a7808e3567f1f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_noop\n\nDocumentation:\nReturn true the builder is based on a noop device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_noop(&self) -> bool {\n matches! {self.device_options, DeviceOptions::None}\n }\n```"}], "func_name": "is_noop", "docstring": "Return true the builder is based on a noop device.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d4f71a0fffc790223d16564f7771b3126a3e47a1c3f933b13d0463db36381aae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate large object disk cache engine default options.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new() -> Self {\n Self {\n indexer_shards: 64,\n recover_concurrency: 8,\n flushers: 1,\n reclaimers: 1,\n buffer_pool_size: 16 * 1024 * 1024, // 16 MiB\n blob_index_size: 4 * 1024, // 4 KiB\n submit_queue_size_threshold: None,\n clean_region_threshold: None,\n eviction_pickers: vec![Box::new(InvalidRatioPicker::new(0.8)), Box::::default()],\n reinsertion_picker: Arc::::default(),\n tombstone_log_config: None,\n }\n }\n```"}], "func_name": "new", "docstring": "Create large object disk cache engine default options.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "129ee94370d74d228766d49cbc170ef209c9b9924048e511235d986c8d5e1caf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_indexer_shards\n\nDocumentation:\nSet the shard num of the indexer. Each shard has its own lock.\n\nDefault: `64`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_indexer_shards(mut self, indexer_shards: usize) -> Self {\n self.indexer_shards = indexer_shards;\n self\n }\n```"}], "func_name": "with_indexer_shards", "docstring": "Set the shard num of the indexer. Each shard has its own lock.\n\nDefault: `64`.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e57a21316672fbb1c99157f144226898fb66d69d5677d90f79d8fab9894ea4b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_recover_concurrency\n\nDocumentation:\nSet the recover concurrency for the disk cache store.\n\nDefault: `8`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_recover_concurrency(mut self, recover_concurrency: usize) -> Self {\n self.recover_concurrency = recover_concurrency;\n self\n }\n```"}], "func_name": "with_recover_concurrency", "docstring": "Set the recover concurrency for the disk cache store.\n\nDefault: `8`.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "949ac99bf8bdeaaf4b9012558dc5762927dca837a35bdf1b2d836eb15c77707e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_buffer_pool_size\n\nDocumentation:\nSet the total flush buffer pool size.\n\nEach flusher shares a volume at `threshold / flushers`.\n\nIf the buffer of the flush queue exceeds the threshold, the further entries will be ignored.\n\nDefault: 16 MiB.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_buffer_pool_size(mut self, buffer_pool_size: usize) -> Self {\n self.buffer_pool_size = buffer_pool_size;\n self\n }\n```"}], "func_name": "with_buffer_pool_size", "docstring": "Set the total flush buffer pool size.\n\nEach flusher shares a volume at `threshold / flushers`.\n\nIf the buffer of the flush queue exceeds the threshold, the further entries will be ignored.\n\nDefault: 16 MiB.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "03f07b1e592623ea159164e9b2848335cb8a212a9c4bd0292a770aac1b91b989"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_blob_index_size\n\nDocumentation:\nSet the blob index size for each blob.\n\nA larger blob index size can hold more blob entries, but it will also increase the io size of each blob part\nwrite.\n\nNOTE: The size will be aligned up to a multiplier of 4K.\n\nDefault: 4 KiB\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_blob_index_size(mut self, blob_index_size: usize) -> Self {\n let blob_index_size = bits::align_up(PAGE, blob_index_size);\n self.blob_index_size = blob_index_size;\n self\n }\n```"}], "func_name": "with_blob_index_size", "docstring": "Set the blob index size for each blob.\n\nA larger blob index size can hold more blob entries, but it will also increase the io size of each blob part\nwrite.\n\nNOTE: The size will be aligned up to a multiplier of 4K.\n\nDefault: 4 KiB", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a437f34be65b49729958065e395c1bd13ae6e67841debd713bcf172701b0ea1a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_clean_region_threshold\n\nDocumentation:\nSet the clean region threshold for the disk cache store.\n\nThe reclaimers only work when the clean region count is equal to or lower than the clean region threshold.\n\nDefault: the same value as the `reclaimers`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_clean_region_threshold(mut self, clean_region_threshold: usize) -> Self {\n self.clean_region_threshold = Some(clean_region_threshold);\n self\n }\n```"}], "func_name": "with_clean_region_threshold", "docstring": "Set the clean region threshold for the disk cache store.\n\nThe reclaimers only work when the clean region count is equal to or lower than the clean region threshold.\n\nDefault: the same value as the `reclaimers`.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5fa8289b1e4cddd7d45c5b50fe702d934296e3ab62d81afa7ed8d74bf3576bbb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_eviction_pickers\n\nDocumentation:\nSet the eviction pickers for th disk cache store.\n\nThe eviction picker is used to pick the region to reclaim.\n\nThe eviction pickers are applied in order. If the previous eviction picker doesn't pick any region, the next one\nwill be applied.\n\nIf no eviction picker picks a region, a region will be picked randomly.\n\nDefault: [ invalid ratio picker { threshold = 0.8 }, fifo picker ]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_eviction_pickers(mut self, eviction_pickers: Vec>) -> Self {\n self.eviction_pickers = eviction_pickers;\n self\n }\n```"}], "func_name": "with_eviction_pickers", "docstring": "Set the eviction pickers for th disk cache store.\n\nThe eviction picker is used to pick the region to reclaim.\n\nThe eviction pickers are applied in order. If the previous eviction picker doesn't pick any region, the next one\nwill be applied.\n\nIf no eviction picker picks a region, a region will be picked randomly.\n\nDefault: [ invalid ratio picker { threshold = 0.8 }, fifo picker ]", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "095389f89f257ac7f41fc21d061191b83cf11a4623ee9b64684b940c04b1bd60"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_reinsertion_picker\n\nDocumentation:\nSet the reinsertion pickers for th disk cache store.\n\nThe reinsertion picker is used to pick the entries that can be reinsertion into the disk cache store while\nreclaiming.\n\nNote: Only extremely important entries should be picked. If too many entries are picked, both insertion and\nreinsertion will be stuck.\n\nDefault: [`RejectAllPicker`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_reinsertion_picker(mut self, reinsertion_picker: Arc) -> Self {\n self.reinsertion_picker = reinsertion_picker;\n self\n }\n```"}], "func_name": "with_reinsertion_picker", "docstring": "Set the reinsertion pickers for th disk cache store.\n\nThe reinsertion picker is used to pick the entries that can be reinsertion into the disk cache store while\nreclaiming.\n\nNote: Only extremely important entries should be picked. If too many entries are picked, both insertion and\nreinsertion will be stuck.\n\nDefault: [`RejectAllPicker`].", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "01e47eda3e12ec396b5d431c01dbaa48565ecbf8285846878420b7d6693313a1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_tombstone_log_config\n\nDocumentation:\nEnable the tombstone log with the given config.\n\nFor updatable cache, either the tombstone log or [`RecoverMode::None`] must be enabled to prevent from the\nphantom entries after reopen.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_tombstone_log_config(mut self, tombstone_log_config: TombstoneLogConfig) -> Self {\n self.tombstone_log_config = Some(tombstone_log_config);\n self\n }\n```"}], "func_name": "with_tombstone_log_config", "docstring": "Enable the tombstone log with the given config.\n\nFor updatable cache, either the tombstone log or [`RecoverMode::None`] must be enabled to prevent from the\nphantom entries after reopen.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2e060f5933a0274be4c2e40ea02cbaebc232c11f9566c04e979ad49f35060196"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate small object disk cache engine default options.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new() -> Self {\n Self {\n set_size: 16 * 1024, // 16 KiB\n set_cache_capacity: 64, // 64 sets\n set_cache_shards: 4,\n flushers: 1,\n buffer_pool_size: 4 * 1024 * 1024, // 4 MiB\n }\n }\n```"}], "func_name": "new", "docstring": "Create small object disk cache engine default options.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c53814d75a59404d786d451434f24c1e0d336038e0117b02bf6e9ea49681cad8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_set_size\n\nDocumentation:\nSet the set size of the set-associated cache.\n\nThe set size will be 4K aligned.\n\nDefault: 16 KiB\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_set_size(mut self, set_size: usize) -> Self {\n bits::assert_aligned(PAGE, set_size);\n self.set_size = set_size;\n self\n }\n```"}], "func_name": "with_set_size", "docstring": "Set the set size of the set-associated cache.\n\nThe set size will be 4K aligned.\n\nDefault: 16 KiB", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dbbe12ef553dc127808024c2111270522981c0e127aeba45c330295df6c6c0bb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_set_cache_capacity\n\nDocumentation:\nSet the capacity of the set cache.\n\nCount by set amount.\n\nDefault: 64\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_set_cache_capacity(mut self, set_cache_capacity: usize) -> Self {\n self.set_cache_capacity = set_cache_capacity;\n self\n }\n```"}], "func_name": "with_set_cache_capacity", "docstring": "Set the capacity of the set cache.\n\nCount by set amount.\n\nDefault: 64", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "448d5727895200d809fdfb906a33588250f9c2c56d72c857c405140035fcb349"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_set_cache_shards\n\nDocumentation:\nSet the shards of the set cache.\n\nDefault: 4\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_set_cache_shards(mut self, set_cache_shards: usize) -> Self {\n self.set_cache_shards = set_cache_shards;\n self\n }\n```"}], "func_name": "with_set_cache_shards", "docstring": "Set the shards of the set cache.\n\nDefault: 4", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/store.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c50c21a745517b94f4b3a7f370fa632d55762e09f33f94adc226e2638b737aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remains\n\nDocumentation:\nGet the hash set of the remaining hash at the moment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn remains(&self) -> HashSet {\n let records = self.dump();\n let mut res = HashSet::default();\n for record in records {\n match record {\n Record::Admit(key) => {\n res.insert(key);\n }\n Record::Evict(key) => {\n res.remove(&key);\n }\n }\n }\n res\n }\n```"}], "func_name": "remains", "docstring": "Get the hash set of the remaining hash at the moment.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/test_utils.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51010b2f3c1f66fe3cc4ae4c0e697f26fd5fc752629165d21e976a574b298b23"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nUse the given file path as the direct file device path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(path: impl AsRef) -> Self {\n Self {\n path: path.as_ref().into(),\n capacity: None,\n region_size: None,\n throttle: Throttle::default(),\n }\n }\n```"}], "func_name": "new", "docstring": "Use the given file path as the direct file device path.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/direct_file.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/direct_file.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "72aada1a3788713f342db1d870d59e65b3e0681df675cd2674c3fdd002613ee3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_capacity\n\nDocumentation:\nSet the capacity of the direct file device.\n\nThe given capacity may be modified on build for alignment.\n\nThe direct file device uses 80% of the current free disk space by default.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = Some(capacity);\n self\n }\n```"}], "func_name": "with_capacity", "docstring": "Set the capacity of the direct file device.\n\nThe given capacity may be modified on build for alignment.\n\nThe direct file device uses 80% of the current free disk space by default.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/direct_file.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/direct_file.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "12693acade48da56efd541f2c80beb50ce4d65dbc1cdf40deecde6dfdedc555b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_region_size\n\nDocumentation:\nSet the file size of the direct file device.\n\nThe given file size may be modified on build for alignment.\n\nThe serialized entry size (with extra metadata) must be equal to or smaller than the file size.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_region_size(mut self, region_size: usize) -> Self {\n self.region_size = Some(region_size);\n self\n }\n```"}], "func_name": "with_region_size", "docstring": "Set the file size of the direct file device.\n\nThe given file size may be modified on build for alignment.\n\nThe serialized entry size (with extra metadata) must be equal to or smaller than the file size.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/direct_file.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/direct_file.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b7b1a1b9c09beaa79a89dc42ec84e7d59b9475ab0fad12def66b5cf98a4911b8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_throttle\n\nDocumentation:\nSet the throttle of the direct file device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_throttle(mut self, throttle: Throttle) -> Self {\n self.throttle = throttle;\n self\n }\n```"}], "func_name": "with_throttle", "docstring": "Set the throttle of the direct file device.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/direct_file.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/direct_file.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e58ae9ec823f1a7b59e723f96b960ebdd5e7e544034338b7dd4799405d96b2a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nUse the given `dir` as the direct fs device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(dir: impl AsRef) -> Self {\n Self {\n dir: dir.as_ref().into(),\n capacity: None,\n file_size: None,\n throttle: Throttle::default(),\n }\n }\n```"}], "func_name": "new", "docstring": "Use the given `dir` as the direct fs device.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/direct_fs.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/direct_fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "12ef6abc136f0a9ff6dc1e6c6af70b3a982c50491209d72dd1c33f21f2bff9ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_file_size\n\nDocumentation:\nSet the file size of the direct fs device.\n\nThe given file size may be modified on build for alignment.\n\nThe serialized entry size (with extra metadata) must be equal to or smaller than the file size.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_file_size(mut self, file_size: usize) -> Self {\n self.file_size = Some(file_size);\n self\n }\n```"}], "func_name": "with_file_size", "docstring": "Set the file size of the direct fs device.\n\nThe given file size may be modified on build for alignment.\n\nThe serialized entry size (with extra metadata) must be equal to or smaller than the file size.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/direct_fs.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/direct_fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d03ff4fdcfec7f61960c8e0b95acce8a653d31a80f0241e80a164b3201a103b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: per_io_size\n\nDocumentation:\nCreate a new iops counter that count 1 iops for every io size in bytes among ios.\n\nNOTE: `io_size` must NOT be zero.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn per_io_size(io_size: usize) -> Self {\n Self::PerIoSize(NonZeroUsize::new(io_size).expect(\"io size must be non-zero\"))\n }\n```"}], "func_name": "per_io_size", "docstring": "Create a new iops counter that count 1 iops for every io size in bytes among ios.\n\nNOTE: `io_size` must NOT be zero.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/mod.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "76d8d64b004697cb0f32701fd313dcdb41ee461542bcd52723fec0b0f9edff9a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: count\n\nDocumentation:\nCount io(s) by io size in bytes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn count(&self, bytes: usize) -> usize {\n match self {\n IopsCounter::PerIo => 1,\n IopsCounter::PerIoSize(size) => bytes / *size + if bytes % *size != 0 { 1 } else { 0 },\n }\n }\n```"}], "func_name": "count", "docstring": "Count io(s) by io size in bytes.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/mod.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca9f9bb1467200d5718b2ff4af7cd9d5070000a25e934ddf1f5bf8e54c95d1bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_write_iops\n\nDocumentation:\nSet the maximum write iops for the device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_write_iops(mut self, iops: usize) -> Self {\n self.write_iops = NonZeroUsize::new(iops);\n self\n }\n```"}], "func_name": "with_write_iops", "docstring": "Set the maximum write iops for the device.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/mod.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fd910a06d5b1376e45f9e5f1cbdb8bb25cb2d0556bfb37f80d5e5ec07aeab41c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_read_iops\n\nDocumentation:\nSet the maximum read iops for the device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_read_iops(mut self, iops: usize) -> Self {\n self.read_iops = NonZeroUsize::new(iops);\n self\n }\n```"}], "func_name": "with_read_iops", "docstring": "Set the maximum read iops for the device.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/mod.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8f25d3e5759818bcd3668080921d26791dd8cba318e4dcb13a223d9ea27fdf50"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_write_throughput\n\nDocumentation:\nSet the maximum write throughput for the device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_write_throughput(mut self, throughput: usize) -> Self {\n self.write_throughput = NonZeroUsize::new(throughput);\n self\n }\n```"}], "func_name": "with_write_throughput", "docstring": "Set the maximum write throughput for the device.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/mod.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0001f093a2a165061fb4dff914a2d6978a8545d151436c2cd29db162cf3fb452"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_read_throughput\n\nDocumentation:\nSet the maximum read throughput for the device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_read_throughput(mut self, throughput: usize) -> Self {\n self.read_throughput = NonZeroUsize::new(throughput);\n self\n }\n```"}], "func_name": "with_read_throughput", "docstring": "Set the maximum read throughput for the device.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/mod.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aa29bfd336674c0179e5552331ade20183be1f681d59a8fd4421011e11123d77"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_iops_counter\n\nDocumentation:\nSet the iops counter for the device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_iops_counter(mut self, counter: IopsCounter) -> Self {\n self.iops_counter = counter;\n self\n }\n```"}], "func_name": "with_iops_counter", "docstring": "Set the iops counter for the device.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/mod.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9fa86b72b0b475731d613547ce5c6690e45c0ab3ba5e853d392b4cb8751eb0cd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: regions\n\nDocumentation:\nGet the region count of the device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn regions(&self) -> usize {\n self.capacity() / self.region_size()\n }\n```"}], "func_name": "regions", "docstring": "Get the region count of the device.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/device/mod.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/device/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "543de0b5de851bcedb597f6abc353d8fa548fce4a43c94adf2b18918da5c8f90"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nAllocate an 4K-aligned [`IoBuffer`] with at least `capacity` bytes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(capacity: usize) -> Self {\n let capacity = bits::align_up(PAGE, capacity);\n let layout = unsafe { Layout::from_size_align_unchecked(capacity, PAGE) };\n let mut nonnull = match Global.allocate(layout) {\n Ok(nonnull) => nonnull,\n Err(_) => handle_alloc_error(layout),\n };\n let slice = unsafe { nonnull.as_mut() };\n let ptr = slice.as_mut_ptr();\n let cap = slice.len();\n Self { ptr, cap }\n }\n```"}], "func_name": "new", "docstring": "Allocate an 4K-aligned [`IoBuffer`] with at least `capacity` bytes.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/io/buffer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/io/buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0b051ed2d18ce8f550c3d17a8cd7c8468436cba8b5a93680f4bb09b357328c0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_raw_parts\n\nDocumentation:\nConsume [`IoBuffer`] and get the raw pointer and the capacity.\n\n# Safety\n\n[`IoBuffer::from_raw_parts`] must be called later. Otherwise the buffer memory will leak.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_raw_parts(self) -> (*mut u8, usize) {\n let res = (self.ptr, self.cap);\n std::mem::forget(self);\n res\n }\n```"}], "func_name": "into_raw_parts", "docstring": "Consume [`IoBuffer`] and get the raw pointer and the capacity.\n\n# Safety\n\n[`IoBuffer::from_raw_parts`] must be called later. Otherwise the buffer memory will leak.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/io/buffer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/io/buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0322718359d8d868be0aec8a02627d68aef495cf274fdb5a8893720fb74e5656"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_raw_parts\n\nDocumentation:\nConstruct [`IoBuffer`] with the raw pointer and the capacity.\n\n# Safety\n\nThe `ptr` and `cap` must be returned by [`IoBuffer::into_raw_parts`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub unsafe fn from_raw_parts(ptr: *mut u8, cap: usize) -> Self {\n Self { ptr, cap }\n }\n```"}], "func_name": "from_raw_parts", "docstring": "Construct [`IoBuffer`] with the raw pointer and the capacity.\n\n# Safety\n\nThe `ptr` and `cap` must be returned by [`IoBuffer::into_raw_parts`].", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/io/buffer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/io/buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fd3e441adef6423dd6b400316386119107bc288fdc4309e927e1528ef9d70cc7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: slice_mut\n\nDocumentation:\nSlice the [`OwnedIoSlice`] with relative range.\n\n# Safety\n\nThe range start and end must be 4K-aligned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn slice_mut(&mut self, range: impl RangeBounds + std::fmt::Debug) {\n let s = match range.start_bound() {\n std::ops::Bound::Included(i) => self.start + *i,\n std::ops::Bound::Excluded(_) => unreachable!(),\n std::ops::Bound::Unbounded => self.start,\n };\n\n let e = match range.end_bound() {\n std::ops::Bound::Included(i) => self.start + *i + 1,\n std::ops::Bound::Excluded(i) => self.start + *i,\n std::ops::Bound::Unbounded => self.end,\n };\n\n if s > e {\n panic!(\"slice index starts at {s} but ends at {e}\");\n }\n\n bits::assert_aligned(PAGE, s);\n bits::assert_aligned(PAGE, e);\n\n self.start = s;\n self.end = e;\n }\n```"}], "func_name": "slice_mut", "docstring": "Slice the [`OwnedIoSlice`] with relative range.\n\n# Safety\n\nThe range start and end must be 4K-aligned.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/io/buffer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/io/buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "91248c0c8a0e02ec64fc09868078b5a8af3c3d30d4b012b20a2ec9843bd71007"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: absolute_slice_mut\n\nDocumentation:\nSlice the [`OwnedIoSlice`] with absolute range.\n\n# Safety\n\nThe range start and end must be 4K-aligned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn absolute_slice_mut(&mut self, range: impl RangeBounds) {\n let s = match range.start_bound() {\n std::ops::Bound::Included(i) => *i,\n std::ops::Bound::Excluded(_) => unreachable!(),\n std::ops::Bound::Unbounded => 0,\n };\n\n let e = match range.end_bound() {\n std::ops::Bound::Included(i) => *i + 1,\n std::ops::Bound::Excluded(i) => *i,\n std::ops::Bound::Unbounded => self.buffer.len(),\n };\n\n if s > e {\n panic!(\"slice index starts at {s} but ends at {e}\");\n }\n\n bits::assert_aligned(PAGE, s);\n bits::assert_aligned(PAGE, e);\n\n self.start = s;\n self.end = e;\n }\n```"}], "func_name": "absolute_slice_mut", "docstring": "Slice the [`OwnedIoSlice`] with absolute range.\n\n# Safety\n\nThe range start and end must be 4K-aligned.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/io/buffer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/io/buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8e1b2b4820ebf6232c537c605565b5184abb0e707ce7222def6b6cd76300cd17"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: slice\n\nDocumentation:\nSlice the [`SharedIoSlice`] with relative range.\n\n# Safety\n\nThe range start and end must be 4K-aligned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn slice(&self, range: impl RangeBounds) -> Self {\n let s = match range.start_bound() {\n std::ops::Bound::Included(i) => self.start + *i,\n std::ops::Bound::Excluded(_) => unreachable!(),\n std::ops::Bound::Unbounded => self.start,\n };\n\n let e = match range.end_bound() {\n std::ops::Bound::Included(i) => self.start + *i + 1,\n std::ops::Bound::Excluded(i) => self.start + *i,\n std::ops::Bound::Unbounded => self.end,\n };\n\n if s > e {\n panic!(\"slice index starts at {s} but ends at {e}\");\n }\n\n bits::assert_aligned(PAGE, s);\n bits::assert_aligned(PAGE, e);\n\n Self {\n buffer: self.buffer.clone(),\n start: s,\n end: e,\n }\n }\n```"}], "func_name": "slice", "docstring": "Slice the [`SharedIoSlice`] with relative range.\n\n# Safety\n\nThe range start and end must be 4K-aligned.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/io/buffer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/io/buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "766d33b6a3e011757255556e3481029f30c1953b6b204bc2a4bfde2a2f46375f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: absolute_slice\n\nDocumentation:\nSlice the [`SharedIoSlice`] with absolute range.\n\n# Safety\n\nThe range start and end must be 4K-aligned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn absolute_slice(&self, range: impl RangeBounds) -> Self {\n let s = match range.start_bound() {\n std::ops::Bound::Included(i) => *i,\n std::ops::Bound::Excluded(_) => unreachable!(),\n std::ops::Bound::Unbounded => 0,\n };\n\n let e = match range.end_bound() {\n std::ops::Bound::Included(i) => *i + 1,\n std::ops::Bound::Excluded(i) => *i,\n std::ops::Bound::Unbounded => self.buffer.len(),\n };\n\n if s > e {\n panic!(\"slice index starts at {s} but ends at {e}\");\n }\n\n bits::assert_aligned(PAGE, s);\n bits::assert_aligned(PAGE, e);\n\n Self {\n buffer: self.buffer.clone(),\n start: s,\n end: e,\n }\n }\n```"}], "func_name": "absolute_slice", "docstring": "Slice the [`SharedIoSlice`] with absolute range.\n\n# Safety\n\nThe range start and end must be 4K-aligned.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/io/buffer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/io/buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d079fb7aa13d4838a5761b997323b5b2ce52cfa0f69533290b6256503f99f19e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: slice\n\nDocumentation:\nSlice the [`OwnedIoSlice`] with relative range.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn slice(self, range: impl RangeBounds) -> Self {\n let s = match range.start_bound() {\n std::ops::Bound::Included(i) => self.start + *i,\n std::ops::Bound::Excluded(_) => unreachable!(),\n std::ops::Bound::Unbounded => self.start,\n };\n\n let e = match range.end_bound() {\n std::ops::Bound::Included(i) => self.start + *i + 1,\n std::ops::Bound::Excluded(i) => self.start + *i,\n std::ops::Bound::Unbounded => self.end,\n };\n\n if s > e {\n panic!(\"slice index starts at {s} but ends at {e}\");\n }\n\n Self {\n buffer: self.buffer,\n start: s,\n end: e,\n }\n }\n```"}], "func_name": "slice", "docstring": "Slice the [`OwnedIoSlice`] with relative range.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/io/buffer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/io/buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1cabc3d7e812abe791ebcd0c7d932eb557517fee7e034031432a0d3e7deb8e34"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: absolute_slice\n\nDocumentation:\nSlice the [`OwnedIoSlice`] with absolute range.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn absolute_slice(self, range: impl RangeBounds) -> Self {\n let s = match range.start_bound() {\n std::ops::Bound::Included(i) => *i,\n std::ops::Bound::Excluded(_) => unreachable!(),\n std::ops::Bound::Unbounded => 0,\n };\n\n let e = match range.end_bound() {\n std::ops::Bound::Included(i) => *i + 1,\n std::ops::Bound::Excluded(i) => *i,\n std::ops::Bound::Unbounded => self.buffer.len(),\n };\n\n if s > e {\n panic!(\"slice index starts at {s} but ends at {e}\");\n }\n\n Self {\n buffer: self.buffer,\n start: s,\n end: e,\n }\n }\n```"}], "func_name": "absolute_slice", "docstring": "Slice the [`OwnedIoSlice`] with absolute range.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/io/buffer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/io/buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ddab63f4f3b9fb79ff2694202f2f0cf5a5852fb9e8e56b44690ad53c40c898a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write\n\nDocumentation:\n# Panics\n\nPanics if the buffer is already full.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write(&mut self, index: &BlobEntryIndex) {\n assert!(!self.is_full());\n let start = BlobIndex::INDEX_OFFSET + self.count * BlobEntryIndex::serialized_len();\n let end = start + BlobEntryIndex::serialized_len();\n index.write(&mut self.io_buffer[start..end]);\n self.count += 1;\n }\n```"}], "func_name": "write", "docstring": "# Panics\n\nPanics if the buffer is already full.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/large/buffer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/large/buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "08abcecce6c3705f39313ddccedc8cac88c340c6ded1c33f12182859555b42a3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_slice\n\nDocumentation:\nSerialize an serialized kv entry slice into the dest.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn push_slice(&mut self, slice: &[u8], hash: u64, sequence: Sequence) -> bool {\n tracing::trace!(hash, \"[blob writer]: push slice\");\n\n let offset = self.written;\n let buf = &mut self.io_buffer[offset..];\n\n let len = slice.len();\n let aligned = bits::align_up(PAGE, slice.len());\n\n if aligned > self.max_entry_size || aligned > buf.len() {\n return false;\n }\n\n buf[..slice.len()].copy_from_slice(slice);\n\n let info = BufferEntryInfo {\n hash,\n sequence,\n offset,\n len,\n };\n self.entry_infos.push(info);\n self.written += aligned;\n\n tracing::trace!(hash, \"[blob writer]: push slice finish\");\n\n true\n }\n```"}], "func_name": "push_slice", "docstring": "Serialize an serialized kv entry slice into the dest.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/large/buffer.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/large/buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5321317207f6d3e91b50458e3a45641fc9f83b181c667276741bb7a10934b108"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: store_for_test\n\nDocumentation:\n4 files, fifo eviction, 16 KiB region, 64 KiB capacity.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn store_for_test(dir: impl AsRef) -> GenericLargeStorage, TestProperties> {\n store_for_test_with_reinsertion_picker(dir, Arc::::default()).await\n }\n```"}], "func_name": "store_for_test", "docstring": "4 files, fifo eviction, 16 KiB region, 64 KiB capacity.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/large/generic.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/large/generic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c98d7b30c5085aec4c8a509d4fa692dd5907f40ffbfddace0027e0694321bfe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new builder for the tombstone log config on the given path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(path: impl AsRef) -> Self {\n Self {\n path: path.as_ref().into(),\n flush: true,\n iops_counter: IopsCounter::per_io(),\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new builder for the tombstone log config on the given path.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/large/tombstone.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/large/tombstone.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1973f4b5dcf43ecbf4e1e5c2a9a256ab6f97a16fcf26ed9661f5ee8ef96ab93f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_flush\n\nDocumentation:\nSet whether to enable flush.\n\nIf enabled, `sync` will be called after writes to make sure the data is safely persisted on the device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_flush(mut self, flush: bool) -> Self {\n self.flush = flush;\n self\n }\n```"}], "func_name": "with_flush", "docstring": "Set whether to enable flush.\n\nIf enabled, `sync` will be called after writes to make sure the data is safely persisted on the device.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/large/tombstone.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/large/tombstone.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4186a3d11a058fa35c55324d6da24fdaede5c11520d01fc3e830ed6c724c5443"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_iops_counter\n\nDocumentation:\nSet iops counter for the tombstone log device monitor.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_iops_counter(mut self, iops_counter: IopsCounter) -> Self {\n self.iops_counter = iops_counter;\n self\n }\n```"}], "func_name": "with_iops_counter", "docstring": "Set iops counter for the tombstone log device monitor.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/large/tombstone.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/large/tombstone.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "049704bca87346242449b730f4a7b56b6a3ef2757bdea1dc62b3e4fce3f5c9aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nBuild the tombstone log config with the given args.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> TombstoneLogConfig {\n TombstoneLogConfig {\n path: self.path,\n flush: self.flush,\n iops_counter: self.iops_counter,\n }\n }\n```"}], "func_name": "build", "docstring": "Build the tombstone log config with the given args.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/large/tombstone.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/large/tombstone.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "68405a9da5e8cd5f858eb90cedbd8ea80080171d2453439a97f8b5b3d28a33a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open\n\nDocumentation:\nOpen the tombstone log with given a dedicated device.\n\nThe tombstone log will\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn open(\n config: &TombstoneLogConfig,\n cache_device: D,\n tombstones: &mut Vec,\n metrics: Arc,\n runtime: Runtime,\n ) -> Result\n where\n D: Dev,\n {\n let align = cache_device.align();\n\n // For large entry disk cache, the minimum entry size is the alignment.\n //\n // So, the tombstone log needs at most `cache device capacity / align` slots.\n //\n // For the alignment is 4K and the slot size is 16B, tombstone log requires 1/256 of the cache device size.\n let capacity = bits::align_up(align, (cache_device.capacity() / align) * Tombstone::serialized_len());\n\n let device = Monitored::open(\n MonitoredConfig {\n config: DirectFileDeviceOptions::new(&config.path)\n .with_region_size(align)\n .with_capacity(capacity)\n .into(),\n metrics: metrics.clone(),\n },\n runtime,\n )\n .await?;\n\n let tasks = bits::align_up(Self::RECOVER_IO_SIZE, capacity) / Self::RECOVER_IO_SIZE;\n tracing::trace!(\"[tombstone log]: recover task count: {tasks}\");\n let res = try_join_all((0..tasks).map(|i| {\n let offset = i * Self::RECOVER_IO_SIZE;\n let len = std::cmp::min(offset + Self::RECOVER_IO_SIZE, capacity) - offset;\n let device = device.clone();\n async move {\n let buf = IoBuffer::new(len);\n let (buffer, res) = device.pread(buf, offset as _).await;\n res?;\n\n let mut seq = 0;\n let mut addr = 0;\n let mut hash = 0;\n let mut tombstones = vec![];\n\n // TODO(MrCroxx): use `array_chunks` after `#![feature(array_chunks)]` is stable.\n for (slot, buf) in buffer.array_chunks_ext::<{ Tombstone::serialized_len() }>().enumerate() {\n let tombstone = Tombstone::read(&buf[..]);\n if tombstone.sequence > seq {\n seq = tombstone.sequence;\n addr = offset + slot * Tombstone::serialized_len();\n hash = tombstone.hash\n }\n tombstones.push(tombstone);\n }\n\n Ok::<_, Error>((tombstones, seq, addr, hash))\n }\n }))\n .await?;\n let offset = res\n .iter()\n .reduce(|a, b| if a.1 > b.1 { a } else { b })\n .inspect(|(_, seq, addr, hash)| {\n tracing::trace!(\n \"[tombstone log]: found latest tombstone at {addr} with sequence = {seq}, hash = {hash}\"\n )\n })\n .map(|(_, _, addr, _)| *addr)\n .unwrap() as u64;\n\n res.into_iter().for_each(|mut r| tombstones.append(&mut r.0));\n let offset = (offset + Tombstone::serialized_len() as u64) % capacity as u64;\n\n let region = bits::align_down(align as RegionId, offset as RegionId) / align as RegionId;\n let buffer = PageBuffer::open(device, region, 0, config.flush).await?;\n\n Ok(Self {\n inner: Arc::new(Mutex::new(TombstoneLogInner { offset, buffer })),\n })\n }\n```"}], "func_name": "open", "docstring": "Open the tombstone log with given a dedicated device.\n\nThe tombstone log will", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/large/tombstone.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/large/tombstone.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "37a9a914dc05e9c564d705e81cfc4f18ee8b7cbfa4d4f84362c368ff2c53a1dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rejected\n\nDocumentation:\nReturn `true` if the pick result is `Reject`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn rejected(&self) -> bool {\n matches! {self, Self::Reject}\n }\n```"}], "func_name": "rejected", "docstring": "Return `true` if the pick result is `Reject`.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/picker/mod.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/picker/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b52c19c1e0b741c3983a07bf10c5c56bba11d79b5c42824309a0daf0077cab13"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new [`FifoPicker`] with the given `probation_ratio` (0.0 ~ 1.0).\n\nThe `probation_ratio` is the ratio of regions that will be marked as probation.\nThe regions that are marked as probation will be evicted first.\n\nThe default value is 0.1.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(probation_ratio: f64) -> Self {\n assert!(\n (0.0..=1.0).contains(&probation_ratio),\n \"probation ratio {} must be in [0.0, 1.0]\",\n probation_ratio\n );\n Self {\n queue: VecDeque::new(),\n regions: 0,\n probations: 0,\n probation_ratio,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new [`FifoPicker`] with the given `probation_ratio` (0.0 ~ 1.0).\n\nThe `probation_ratio` is the ratio of regions that will be marked as probation.\nThe regions that are marked as probation will be evicted first.\n\nThe default value is 0.1.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/picker/utils.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/picker/utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "631f41bca5d69e705182579e65fd54095fb490d21298305529364007182bca31"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate [`InvalidRatioPicker`] with the given `threshold` (0.0 ~ 1.0).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(threshold: f64) -> Self {\n let ratio = threshold.clamp(0.0, 1.0);\n Self {\n threshold: ratio,\n region_size: 0,\n }\n }\n```"}], "func_name": "new", "docstring": "Create [`InvalidRatioPicker`] with the given `threshold` (0.0 ~ 1.0).", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/picker/utils.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/picker/utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "946f441fbe94536bc58a72a3094a48418e432aab2b76b2e3cabeb1c56fdf459f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait\n\nDocumentation:\nRegister a waiter to be notified after the batch is finished.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn wait(&mut self, tx: oneshot::Sender<()>) {\n tracing::trace!(\"[sodc batch]: register waiter\");\n if self.init.is_none() {\n self.init = Some(Instant::now());\n }\n self.waiters.push(tx);\n }\n```"}], "func_name": "wait", "docstring": "Register a waiter to be notified after the batch is finished.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/small/batch.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/small/batch.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "447220a1614d40c4b7272eae021cadd40216754f63c0e37a327ff530ebed744c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load\n\nDocumentation:\nLoad the set storage from buffer.\n\nIf `after` is set and the set storage is before the timestamp, load an empty set storage.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load(buffer: IoBuffer, watermark: u128, metrics: Arc) -> Self {\n assert!(buffer.len() >= Self::SET_HEADER_SIZE);\n\n let checksum = (&buffer[0..4]).get_u32();\n let timestamp = (&buffer[4..20]).get_u128();\n let len = (&buffer[20..24]).get_u32() as usize;\n let bloom_filter = BloomFilterU64::read(&buffer[24..56]);\n\n let mut this = Self {\n checksum,\n len,\n capacity: buffer.len() - Self::SET_HEADER_SIZE,\n size: buffer.len(),\n timestamp,\n bloom_filter,\n buffer,\n metrics,\n };\n\n this.verify(watermark);\n\n this\n }\n```"}], "func_name": "load", "docstring": "Load the set storage from buffer.\n\nIf `after` is set and the set storage is before the timestamp, load an empty set storage.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/small/set.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/small/set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8020385f5a2954f370394dd187cd00d56790c3a92c82e566101e686e156ce048"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reserve\n\nDocumentation:\nfrom:\n\n```plain\n0 wipe len capacity\n|_________|ooooooooooooo|___________|\n```\n\nto:\n\n```plain\n0 new len = len - wipe capacity\n|ooooooooooooo|_____________________|\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reserve(&mut self, required: usize) {\n let remains = self.capacity - self.len;\n if remains >= required {\n return;\n }\n\n let mut wipe = 0;\n for entry in self.iter() {\n wipe += entry.len();\n if remains + wipe >= required {\n break;\n }\n }\n self.buffer.copy_within(\n Self::SET_HEADER_SIZE + wipe..Self::SET_HEADER_SIZE + self.len,\n Self::SET_HEADER_SIZE,\n );\n self.len -= wipe;\n assert!(self.capacity - self.len >= required);\n let mut bloom_filter = BloomFilterU64::default();\n for entry in self.iter() {\n bloom_filter.insert(entry.hash);\n }\n self.bloom_filter = bloom_filter;\n }\n```"}], "func_name": "reserve", "docstring": "from:\n\n```plain\n0 wipe len capacity\n|_________|ooooooooooooo|___________|\n```\n\nto:\n\n```plain\n0 new len = len - wipe capacity\n|ooooooooooooo|_____________________|\n```", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/small/set.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/small/set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b4b6099c74a91f89202571626f60ef24c93cecefa25813c7a3648b3c8b9f6a7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: len\n\nDocumentation:\nLength of the entry with header, key and value included.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn len(&self) -> usize {\n debug_assert_eq!(\n self.buf.len(),\n EntryHeader::ENTRY_HEADER_SIZE + self.key_len + self.value_len\n );\n self.buf.len()\n }\n```"}], "func_name": "len", "docstring": "Length of the entry with header, key and value included.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/small/set.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/small/set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a7be0a612a0bdf709e65a462c2d309e7409d464c5624c0000a5dea8025e61961"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a [`SetPicker`] with a total size count.\n\nThe `sets` should be the count of all sets.\n\nNote:\n\nThe 0th set will be used as the meta set.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(sets: usize) -> Self {\n Self { sets }\n }\n```"}], "func_name": "new", "docstring": "Create a [`SetPicker`] with a total size count.\n\nThe `sets` should be the count of all sets.\n\nNote:\n\nThe 0th set will be used as the meta set.", "repo": "foyer-rs/foyer", "path": "foyer-storage/src/small/set_manager.rs", "url": "https://github.com/foyer-rs/foyer/blob/master/foyer-storage/src/small/set_manager.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b1445ad11b58e93cd7cca996796ff445bd7e40e023d2c15b8fda71474ad9d7e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: setup_empty_table\n\nDocumentation:\nCreates the table and assures it is empty. Columns are named a,b,c, etc.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn setup_empty_table(\n conn: &Connection<'_>,\n table_name: &str,\n column_types: &[&str],\n) -> std::result::Result<(), OdbcError> {\n let drop_table = &format!(\"DROP TABLE IF EXISTS {}\", table_name);\n\n let column_names = &[\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\"];\n let cols = column_types\n .iter()\n .zip(column_names)\n .map(|(ty, name)| format!(\"{} {}\", name, ty))\n .collect::>()\n .join(\", \");\n\n let create_table = format!(\n \"CREATE TABLE {} (id int IDENTITY(1,1),{});\",\n table_name, cols\n );\n conn.execute(drop_table, ())?;\n conn.execute(&create_table, ())?;\n Ok(())\n}\n```"}], "func_name": "setup_empty_table", "docstring": "Creates the table and assures it is empty. Columns are named a,b,c, etc.", "repo": "jorgecarleitao/arrow2", "path": "arrow-odbc-integration-testing/src/lib.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/arrow-odbc-integration-testing/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7136292fa155087aaae1de82a7874285036678ba72e948ec4176baf7f8d3753d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: import\n\nDocumentation:\n# Safety\n`ArrowArray` and `ArrowSchema` must be valid\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn import(array: ffi::ArrowArray, schema: &ffi::ArrowSchema) -> Result> {\n let field = ffi::import_field_from_c(schema)?;\n ffi::import_array_from_c(array, field.data_type)\n}\n```"}], "func_name": "import", "docstring": "# Safety\n`ArrowArray` and `ArrowSchema` must be valid", "repo": "jorgecarleitao/arrow2", "path": "examples/ffi.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/examples/ffi.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0a73e067a0f3a22efb28ff4e5264172ec0ac20f144ca668f5c7ff655bc374011"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read\n\nDocumentation:\nReads chunks from a query done against an ODBC connection\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read(connection: &api::Connection<'_>, query: &str) -> Result>>> {\n let mut a = connection.prepare(query)?;\n let fields = read::infer_schema(&a)?;\n\n let max_batch_size = 100;\n let buffer = read::buffer_from_metadata(&a, max_batch_size)?;\n\n let cursor = a.execute(())?.unwrap();\n let mut cursor = cursor.bind_buffer(buffer)?;\n\n let mut chunks = vec![];\n while let Some(batch) = cursor.fetch()? {\n let arrays = (0..batch.num_cols())\n .zip(fields.iter())\n .map(|(index, field)| {\n let column_view = batch.column(index);\n read::deserialize(column_view, field.data_type.clone())\n })\n .collect::>();\n chunks.push(Chunk::new(arrays));\n }\n\n Ok(chunks)\n}\n```"}], "func_name": "read", "docstring": "Reads chunks from a query done against an ODBC connection", "repo": "jorgecarleitao/arrow2", "path": "examples/io_odbc.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/examples/io_odbc.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c19d7e6aa5bfb261d14b5ad905765c43450c412ca0ecaacc4815d6aa57858e7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_batch\n\nDocumentation:\nRandom access way: read a single record batch from the file. This can be used e.g. for random access.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_batch(path: &str) -> Result<(Schema, Chunk>)> {\n let mut file = File::open(path)?;\n\n // read the files' metadata. At this point, we can distribute the read whatever we like.\n let metadata = read::read_file_metadata(&mut file)?;\n\n let schema = metadata.schema.clone();\n\n // advanced way: read the dictionary\n let dictionaries = read::read_file_dictionaries(&mut file, &metadata, &mut Default::default())?;\n\n // and the chunk\n let chunk_index = 0;\n\n let chunk = read::read_batch(\n &mut file,\n &dictionaries,\n &metadata,\n None,\n None,\n chunk_index,\n &mut Default::default(),\n &mut Default::default(),\n )?;\n\n Ok((schema, chunk))\n}\n```"}], "func_name": "read_batch", "docstring": "Random access way: read a single record batch from the file. This can be used e.g. for random access.", "repo": "jorgecarleitao/arrow2", "path": "examples/ipc_file_read.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/examples/ipc_file_read.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2247afab0b704a8f00a748700bf0e44759410ca2f9f382267deb27fe8d20459d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: deserialize_parallel\n\nDocumentation:\nAdvances each iterator in parallel\n# Panic\nIf the iterators are empty\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn deserialize_parallel(iters: &mut [ArrayIter<'static>]) -> Result>> {\n // CPU-bounded\n let arrays = iters\n .par_iter_mut()\n .map(|iter| iter.next().transpose())\n .collect::>>()?;\n\n Chunk::try_new(arrays.into_iter().map(|x| x.unwrap()).collect())\n}\n```"}], "func_name": "deserialize_parallel", "docstring": "Advances each iterator in parallel\n# Panic\nIf the iterators are empty", "repo": "jorgecarleitao/arrow2", "path": "examples/parquet_read_parallel/src/main.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/examples/parquet_read_parallel/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a7837593648e20a41a40b50fb84cdb5bb3c86528ca7f886de2e64fb50a64378e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_check_utf8\n\nDocumentation:\n# Error\n* any offset is larger or equal to `values_len`.\n* any slice of `values` between two consecutive pairs from `offsets` is invalid `utf8`, or\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn try_check_utf8>(\n offsets: &C,\n values: &[u8],\n) -> Result<()> {\n if offsets.as_slice().len() == 1 {\n return Ok(());\n }\n\n try_check_offsets_bounds(offsets, values.len())?;\n\n if values.is_ascii() {\n Ok(())\n } else {\n simdutf8::basic::from_utf8(values)?;\n\n // offsets can be == values.len()\n // find first offset from the end that is smaller\n // Example:\n // values.len() = 10\n // offsets = [0, 5, 10, 10]\n let offsets = offsets.as_slice();\n let last = offsets\n .iter()\n .enumerate()\n .skip(1)\n .rev()\n .find_map(|(i, offset)| (offset.to_usize() < values.len()).then(|| i));\n\n let last = if let Some(last) = last {\n // following the example: last = 1 (offset = 5)\n last\n } else {\n // given `l = values.len()`, this branch is hit iff either:\n // * `offsets = [0, l, l, ...]`, which was covered by `from_utf8(values)` above\n // * `offsets = [0]`, which never happens because offsets.as_slice().len() == 1 is short-circuited above\n return Ok(());\n };\n\n // trucate to relevant offsets. Note: `=last` because last was computed skipping the first item\n // following the example: starts = [0, 5]\n let starts = unsafe { offsets.get_unchecked(..=last) };\n\n let mut any_invalid = false;\n for start in starts {\n let start = start.to_usize();\n\n // Safety: `try_check_offsets_bounds` just checked for bounds\n let b = *unsafe { values.get_unchecked(start) };\n\n // A valid code-point iff it does not start with 0b10xxxxxx\n // Bit-magic taken from `std::str::is_char_boundary`\n if (b as i8) < -0x40 {\n any_invalid = true\n }\n }\n if any_invalid {\n return Err(Error::oos(\"Non-valid char boundary detected\"));\n }\n Ok(())\n }\n}\n```"}], "func_name": "try_check_utf8", "docstring": "# Error\n* any offset is larger or equal to `values_len`.\n* any slice of `values` between two consecutive pairs from `offsets` is invalid `utf8`, or", "repo": "jorgecarleitao/arrow2", "path": "src/array/specification.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/array/specification.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "72f0ed56a0078292abd14f488ee425a6152dbf14a33060d9c43c7f9653a2a8a1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set\n\nDocumentation:\nSets position `index` to `value`.\nNote that if it is the first time a null appears in this array,\nthis initializes the validity bitmap (`O(N)`).\n# Panic\nPanics iff index is larger than `self.len()`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set(&mut self, index: usize, value: Option) {\n self.values.set(index, value.unwrap_or_default());\n\n if value.is_none() && self.validity.is_none() {\n // When the validity is None, all elements so far are valid. When one of the elements is set fo null,\n // the validity must be initialized.\n self.validity = Some(MutableBitmap::from_trusted_len_iter(\n std::iter::repeat(true).take(self.len()),\n ));\n }\n if let Some(x) = self.validity.as_mut() {\n x.set(index, value.is_some())\n }\n }\n```"}], "func_name": "set", "docstring": "Sets position `index` to `value`.\nNote that if it is the first time a null appears in this array,\nthis initializes the validity bitmap (`O(N)`).\n# Panic\nPanics iff index is larger than `self.len()`.", "repo": "jorgecarleitao/arrow2", "path": "src/array/boolean/mutable.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/array/boolean/mutable.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f2279f34969f683a1a3553ead57b4abb8feb5714094589a57c93a66432bc0fab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_push_valid\n\nDocumentation:\nTry to insert a value and return its index (it may or may not get inserted).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_push_valid(\n &mut self,\n value: V,\n mut push: impl FnMut(&mut M, V) -> Result<()>,\n ) -> Result\n where\n M: Indexable,\n V: AsIndexed,\n M::Type: Eq + Hash,\n {\n let hash = ahash_hash(value.as_indexed());\n Ok(\n match self.map.raw_entry_mut().from_hash(hash, |item| {\n // safety: we've already checked (the inverse) when we pushed it, so it should be ok?\n let index = unsafe { item.key.as_usize() };\n // safety: invariant of the struct, it's always in bounds since we maintain it\n let stored_value = unsafe { self.values.value_unchecked_at(index) };\n stored_value.borrow() == value.as_indexed()\n }) {\n RawEntryMut::Occupied(entry) => entry.key().key,\n RawEntryMut::Vacant(entry) => {\n let index = self.values.len();\n let key = K::try_from(index).map_err(|_| Error::Overflow)?;\n entry.insert_hashed_nocheck(hash, Hashed { hash, key }, ()); // NB: don't use .insert() here!\n push(&mut self.values, value)?;\n debug_assert_eq!(self.values.len(), index + 1);\n key\n }\n },\n )\n }\n```"}], "func_name": "try_push_valid", "docstring": "Try to insert a value and return its index (it may or may not get inserted).", "repo": "jorgecarleitao/arrow2", "path": "src/array/dictionary/value_map.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/array/dictionary/value_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa6c5fa5b059a878ae0d6276d84bc3c95aac20732f4776ce280e395042c88b42"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_new\n\nDocumentation:\nCreates a new [`FixedSizeBinaryArray`].\n\n# Errors\nThis function returns an error iff:\n* The `data_type`'s physical type is not [`crate::datatypes::PhysicalType::FixedSizeBinary`]\n* The length of `values` is not a multiple of `size` in `data_type`\n* the validity's length is not equal to `values.len() / size`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_new(\n data_type: DataType,\n values: Buffer,\n validity: Option,\n ) -> Result {\n let size = Self::maybe_get_size(&data_type)?;\n\n if values.len() % size != 0 {\n return Err(Error::oos(format!(\n \"values (of len {}) must be a multiple of size ({}) in FixedSizeBinaryArray.\",\n values.len(),\n size\n )));\n }\n let len = values.len() / size;\n\n if validity\n .as_ref()\n .map_or(false, |validity| validity.len() != len)\n {\n return Err(Error::oos(\n \"validity mask length must be equal to the number of values divided by size\",\n ));\n }\n\n Ok(Self {\n size,\n data_type,\n values,\n validity,\n })\n }\n```"}], "func_name": "try_new", "docstring": "Creates a new [`FixedSizeBinaryArray`].\n\n# Errors\nThis function returns an error iff:\n* The `data_type`'s physical type is not [`crate::datatypes::PhysicalType::FixedSizeBinary`]\n* The length of `values` is not a multiple of `size` in `data_type`\n* the validity's length is not equal to `values.len() / size`.", "repo": "jorgecarleitao/arrow2", "path": "src/array/fixed_size_binary/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/array/fixed_size_binary/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e4ae5617b270535b58a1a4d9bc2678e7be22c6bca93cce05cf5c37d1a2e8e601"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_get_child\n\nDocumentation:\nReturns a the inner [`Field`]\n# Errors\nPanics iff the logical type is not consistent with this struct.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_get_child(data_type: &DataType) -> Result<&Field, Error> {\n if O::IS_LARGE {\n match data_type.to_logical_type() {\n DataType::LargeList(child) => Ok(child.as_ref()),\n _ => Err(Error::oos(\"ListArray expects DataType::LargeList\")),\n }\n } else {\n match data_type.to_logical_type() {\n DataType::List(child) => Ok(child.as_ref()),\n _ => Err(Error::oos(\"ListArray expects DataType::List\")),\n }\n }\n }\n```"}], "func_name": "try_get_child", "docstring": "Returns a the inner [`Field`]\n# Errors\nPanics iff the logical type is not consistent with this struct.", "repo": "jorgecarleitao/arrow2", "path": "src/array/list/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/array/list/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "437bf426760f01c7043a9c09e0ad82af449966e92bd592ed9a43fba419116063"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_new\n\nDocumentation:\nReturns a new [`MapArray`].\n# Errors\nThis function errors iff:\n* The last offset is not equal to the field' length\n* The `data_type`'s physical type is not [`crate::datatypes::PhysicalType::Map`]\n* The fields' `data_type` is not equal to the inner field of `data_type`\n* The validity is not `None` and its length is different from `offsets.len() - 1`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_new(\n data_type: DataType,\n offsets: OffsetsBuffer,\n field: Box,\n validity: Option,\n ) -> Result {\n try_check_offsets_bounds(&offsets, field.len())?;\n\n let inner_field = Self::try_get_field(&data_type)?;\n if let DataType::Struct(inner) = inner_field.data_type() {\n if inner.len() != 2 {\n return Err(Error::InvalidArgumentError(\n \"MapArray's inner `Struct` must have 2 fields (keys and maps)\".to_string(),\n ));\n }\n } else {\n return Err(Error::InvalidArgumentError(\n \"MapArray expects `DataType::Struct` as its inner logical type\".to_string(),\n ));\n }\n if field.data_type() != inner_field.data_type() {\n return Err(Error::InvalidArgumentError(\n \"MapArray expects `field.data_type` to match its inner DataType\".to_string(),\n ));\n }\n\n if validity\n .as_ref()\n .map_or(false, |validity| validity.len() != offsets.len_proxy())\n {\n return Err(Error::oos(\n \"validity mask length must match the number of values\",\n ));\n }\n\n Ok(Self {\n data_type,\n field,\n offsets,\n validity,\n })\n }\n```"}], "func_name": "try_new", "docstring": "Returns a new [`MapArray`].\n# Errors\nThis function errors iff:\n* The last offset is not equal to the field' length\n* The `data_type`'s physical type is not [`crate::datatypes::PhysicalType::Map`]\n* The fields' `data_type` is not equal to the inner field of `data_type`\n* The validity is not `None` and its length is different from `offsets.len() - 1`.", "repo": "jorgecarleitao/arrow2", "path": "src/array/map/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/array/map/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "870f8c1172d104a253e4695a9a617b6ab9511e2b4adbf39ca696980f160871b5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_unchecked\n\nDocumentation:\nSets position `index` to `value`.\nNote that if it is the first time a null appears in this array,\nthis initializes the validity bitmap (`O(N)`).\n# Safety\nCaller must ensure `index < self.len()`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub unsafe fn set_unchecked(&mut self, index: usize, value: Option) {\n *self.values.get_unchecked_mut(index) = value.unwrap_or_default();\n\n if value.is_none() && self.validity.is_none() {\n // When the validity is None, all elements so far are valid. When one of the elements is set fo null,\n // the validity must be initialized.\n let mut validity = MutableBitmap::new();\n validity.extend_constant(self.len(), true);\n self.validity = Some(validity);\n }\n if let Some(x) = self.validity.as_mut() {\n x.set_unchecked(index, value.is_some())\n }\n }\n```"}], "func_name": "set_unchecked", "docstring": "Sets position `index` to `value`.\nNote that if it is the first time a null appears in this array,\nthis initializes the validity bitmap (`O(N)`).\n# Safety\nCaller must ensure `index < self.len()`", "repo": "jorgecarleitao/arrow2", "path": "src/array/primitive/mutable.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/array/primitive/mutable.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2fc9f3c21ec625a7cc30bc30c2f677695c05bf23971ab04931fd11ddc9201a09"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_with_validity\n\nDocumentation:\nReturns a new [`ZipValidity`] and drops the `validity` if all values\nare valid.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_with_validity(values: I, validity: Option<&'a Bitmap>) -> Self {\n // only if the validity has nulls we take the optional branch.\n match validity.and_then(|validity| (validity.unset_bits() > 0).then(|| validity.iter())) {\n Some(validity) => Self::Optional(ZipValidityIter::new(values, validity)),\n _ => Self::Required(values),\n }\n }\n```"}], "func_name": "new_with_validity", "docstring": "Returns a new [`ZipValidity`] and drops the `validity` if all values\nare valid.", "repo": "jorgecarleitao/arrow2", "path": "src/bitmap/utils/zip_validity.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/bitmap/utils/zip_validity.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8a788840eeca289e3f618a3bcf73477228422fdef29b182e84b754588d2fe083"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unwrap_required\n\nDocumentation:\nUnwrap into an iterator that has no null values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unwrap_required(self) -> I {\n match self {\n ZipValidity::Required(i) => i,\n _ => panic!(\"Could not 'unwrap_required'. 'ZipValidity' iterator has nulls.\"),\n }\n }\n```"}], "func_name": "unwrap_required", "docstring": "Unwrap into an iterator that has no null values.", "repo": "jorgecarleitao/arrow2", "path": "src/bitmap/utils/zip_validity.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/bitmap/utils/zip_validity.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c3bc023b098131e60d93c4dac127d0e7322cd27aed41d9faede8ba883a320f18"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unwrap_optional\n\nDocumentation:\nUnwrap into an iterator that has null values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unwrap_optional(self) -> ZipValidityIter {\n match self {\n ZipValidity::Optional(i) => i,\n _ => panic!(\"Could not 'unwrap_optional'. 'ZipValidity' iterator has no nulls.\"),\n }\n }\n```"}], "func_name": "unwrap_optional", "docstring": "Unwrap into an iterator that has null values.", "repo": "jorgecarleitao/arrow2", "path": "src/bitmap/utils/zip_validity.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/bitmap/utils/zip_validity.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e996d55d6b10b61332fa5e2b82f738c5a61cdfbe897505b26f7252c21e5fa74f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_bytes\n\nDocumentation:\nAuxiliary method to create a new Buffer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn from_bytes(bytes: Bytes) -> Self {\n let length = bytes.len();\n Buffer {\n data: Arc::new(bytes),\n offset: 0,\n length,\n }\n }\n```"}], "func_name": "from_bytes", "docstring": "Auxiliary method to create a new Buffer", "repo": "jorgecarleitao/arrow2", "path": "src/buffer/immutable.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/buffer/immutable.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f7311ebb96b6cb0c34e428b7f1e45941b6f92d2f4aae67bc12b65858c8c396ed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unary_checked\n\nDocumentation:\nVersion of unary that creates a mutable bitmap that is used to keep track\nof checked operations. The resulting bitmap is compared with the array\nbitmap to create the final validity array.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unary_checked(\n array: &PrimitiveArray,\n op: F,\n data_type: DataType,\n) -> PrimitiveArray\nwhere\n I: NativeType,\n O: NativeType,\n F: Fn(I) -> Option,\n{\n let mut mut_bitmap = MutableBitmap::with_capacity(array.len());\n\n let values = array\n .values()\n .iter()\n .map(|v| match op(*v) {\n Some(val) => {\n mut_bitmap.push(true);\n val\n }\n None => {\n mut_bitmap.push(false);\n O::default()\n }\n })\n .collect::>()\n .into();\n\n // The validity has to be checked against the bitmap created during the\n // creation of the values with the iterator. If an error was found during\n // the iteration, then the validity is changed to None to mark the value\n // as Null\n let bitmap: Bitmap = mut_bitmap.into();\n let validity = combine_validities(array.validity(), Some(&bitmap));\n\n PrimitiveArray::::new(data_type, values, validity)\n}\n```"}], "func_name": "unary_checked", "docstring": "Version of unary that creates a mutable bitmap that is used to keep track\nof checked operations. The resulting bitmap is compared with the array\nbitmap to create the final validity array.", "repo": "jorgecarleitao/arrow2", "path": "src/compute/arity.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/arity.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f644d27bf3c65880004ce33c01188e6760dd88ff2a60d534ea5c48e96456e86"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: binary_checked\n\nDocumentation:\nVersion of binary that creates a mutable bitmap that is used to keep track\nof checked operations. The resulting bitmap is compared with the array\nbitmap to create the final validity array.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn binary_checked(\n lhs: &PrimitiveArray,\n rhs: &PrimitiveArray,\n data_type: DataType,\n op: F,\n) -> PrimitiveArray\nwhere\n T: NativeType,\n D: NativeType,\n F: Fn(T, D) -> Option,\n{\n check_same_len(lhs, rhs).unwrap();\n\n let mut mut_bitmap = MutableBitmap::with_capacity(lhs.len());\n\n let values = lhs\n .values()\n .iter()\n .zip(rhs.values().iter())\n .map(|(l, r)| match op(*l, *r) {\n Some(val) => {\n mut_bitmap.push(true);\n val\n }\n None => {\n mut_bitmap.push(false);\n T::default()\n }\n })\n .collect::>()\n .into();\n\n let bitmap: Bitmap = mut_bitmap.into();\n let validity = combine_validities(lhs.validity(), rhs.validity());\n\n // The validity has to be checked against the bitmap created during the\n // creation of the values with the iterator. If an error was found during\n // the iteration, then the validity is changed to None to mark the value\n // as Null\n let validity = combine_validities(validity.as_ref(), Some(&bitmap));\n\n PrimitiveArray::::new(data_type, values, validity)\n}\n```"}], "func_name": "binary_checked", "docstring": "Version of binary that creates a mutable bitmap that is used to keep track\nof checked operations. The resulting bitmap is compared with the array\nbitmap to create the final validity array.", "repo": "jorgecarleitao/arrow2", "path": "src/compute/arity.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/arity.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fd53aa8d06866d77582503616ea65c968367c3362c0d00a7983bd9522d29c92f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: binary_boolean_kernel\n\nDocumentation:\nHelper function to implement binary kernels\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn binary_boolean_kernel(\n lhs: &BooleanArray,\n rhs: &BooleanArray,\n op: F,\n) -> BooleanArray\nwhere\n F: Fn(&Bitmap, &Bitmap) -> Bitmap,\n{\n assert_lengths(lhs, rhs);\n let validity = combine_validities(lhs.validity(), rhs.validity());\n\n let left_buffer = lhs.values();\n let right_buffer = rhs.values();\n\n let values = op(left_buffer, right_buffer);\n\n BooleanArray::new(DataType::Boolean, values, validity)\n}\n```"}], "func_name": "binary_boolean_kernel", "docstring": "Helper function to implement binary kernels", "repo": "jorgecarleitao/arrow2", "path": "src/compute/boolean.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/boolean.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c490c5ec7610a0d7d8e27e0ab97a6a307ae15cd5b11aad7f9191f24e73f87648"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lexicographical_partition_ranges\n\nDocumentation:\nGiven a list of already sorted columns, find partition ranges that would partition\nlexicographically equal values across columns.\n\nHere LexicographicalComparator is used in conjunction with binary\nsearch so the columns *MUST* be pre-sorted already.\n\nThe returned vec would be of size k where k is cardinality of the sorted values; Consecutive\nvalues will be connected: (a, b) and (b, c), where start = 0 and end = n for the first and last\nrange.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn lexicographical_partition_ranges(\n columns: &[SortColumn],\n) -> Result>> {\n LexicographicalPartitionIterator::try_new(columns)\n}\n```"}], "func_name": "lexicographical_partition_ranges", "docstring": "Given a list of already sorted columns, find partition ranges that would partition\nlexicographically equal values across columns.\n\nHere LexicographicalComparator is used in conjunction with binary\nsearch so the columns *MUST* be pre-sorted already.\n\nThe returned vec would be of size k where k is cardinality of the sorted values; Consecutive\nvalues will be connected: (a, b) and (b, c), where start = 0 and end = n for the first and last\nrange.", "repo": "jorgecarleitao/arrow2", "path": "src/compute/partition.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/partition.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "adc2e58552b6a8595ce2e362bca351b7b5572e47570e39594724db3816e4f056"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: substring\n\nDocumentation:\nReturns an ArrayRef with a substring starting from `start` and with optional length `length` of each of the elements in `array`.\n`start` can be negative, in which case the start counts from the end of the string.\nthis function errors when the passed array is not a \\[Large\\]String array.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn substring(array: &dyn Array, start: i64, length: &Option) -> Result> {\n match array.data_type() {\n DataType::Binary => Ok(Box::new(binary_substring(\n array\n .as_any()\n .downcast_ref::>()\n .expect(\"A binary is expected\"),\n start as i32,\n &length.map(|e| e as i32),\n ))),\n DataType::LargeBinary => Ok(Box::new(binary_substring(\n array\n .as_any()\n .downcast_ref::>()\n .expect(\"A large binary is expected\"),\n start,\n &length.map(|e| e as i64),\n ))),\n DataType::LargeUtf8 => Ok(Box::new(utf8_substring(\n array\n .as_any()\n .downcast_ref::>()\n .expect(\"A large string is expected\"),\n start,\n &length.map(|e| e as i64),\n ))),\n DataType::Utf8 => Ok(Box::new(utf8_substring(\n array\n .as_any()\n .downcast_ref::>()\n .expect(\"A string is expected\"),\n start as i32,\n &length.map(|e| e as i32),\n ))),\n _ => Err(Error::InvalidArgumentError(format!(\n \"substring does not support type {:?}\",\n array.data_type()\n ))),\n }\n}\n```"}], "func_name": "substring", "docstring": "Returns an ArrayRef with a substring starting from `start` and with optional length `length` of each of the elements in `array`.\n`start` can be negative, in which case the start counts from the end of the string.\nthis function errors when the passed array is not a \\[Large\\]String array.", "repo": "jorgecarleitao/arrow2", "path": "src/compute/substring.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/substring.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "077c4ae8bd08202192769f42dcae2c82adad088fda387014ea5829b34b08613c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: min_primitive\n\nDocumentation:\nReturns the minimum value in the array, according to the natural order.\nFor floating point arrays any NaN values are considered to be greater than any other non-null value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn min_primitive(array: &PrimitiveArray) -> Option\nwhere\n T: NativeType + Simd,\n T::Simd: SimdOrd,\n{\n let null_count = array.null_count();\n\n // Includes case array.len() == 0\n if null_count == array.len() {\n return None;\n }\n let values = array.values();\n\n Some(if let Some(validity) = array.validity() {\n null_min_primitive(values, validity)\n } else {\n nonnull_min_primitive(values)\n })\n}\n```"}], "func_name": "min_primitive", "docstring": "Returns the minimum value in the array, according to the natural order.\nFor floating point arrays any NaN values are considered to be greater than any other non-null value", "repo": "jorgecarleitao/arrow2", "path": "src/compute/aggregate/min_max.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/aggregate/min_max.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0b5e401c8b67e3b599e4df14809d4f9dbbaf2283dfbb8a2c0d2a1d6ef5c09b5e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: max_primitive\n\nDocumentation:\nReturns the maximum value in the array, according to the natural order.\nFor floating point arrays any NaN values are considered to be greater than any other non-null value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn max_primitive(array: &PrimitiveArray) -> Option\nwhere\n T: NativeType + Simd,\n T::Simd: SimdOrd,\n{\n let null_count = array.null_count();\n\n // Includes case array.len() == 0\n if null_count == array.len() {\n return None;\n }\n let values = array.values();\n\n Some(if let Some(validity) = array.validity() {\n null_max_primitive(values, validity)\n } else {\n nonnull_max_primitive(values)\n })\n}\n```"}], "func_name": "max_primitive", "docstring": "Returns the maximum value in the array, according to the natural order.\nFor floating point arrays any NaN values are considered to be greater than any other non-null value", "repo": "jorgecarleitao/arrow2", "path": "src/compute/aggregate/min_max.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/aggregate/min_max.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e191c7d5282b303bc163b3d51b1d581338e17648738a123df5cad0af20b70ce"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: max_binary\n\nDocumentation:\nReturns the maximum value in the binary array, according to the natural order.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn max_binary(array: &BinaryArray) -> Option<&[u8]> {\n min_max_binary_utf8!(array, |a, b| a < b)\n}\n```"}], "func_name": "max_binary", "docstring": "Returns the maximum value in the binary array, according to the natural order.", "repo": "jorgecarleitao/arrow2", "path": "src/compute/aggregate/min_max.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/aggregate/min_max.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f3510d2e2d42f51a6b2c2e2022b6bb7420ba814d7663f791ca66baae61740a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: min_binary\n\nDocumentation:\nReturns the minimum value in the binary array, according to the natural order.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn min_binary(array: &BinaryArray) -> Option<&[u8]> {\n min_max_binary_utf8!(array, |a, b| a > b)\n}\n```"}], "func_name": "min_binary", "docstring": "Returns the minimum value in the binary array, according to the natural order.", "repo": "jorgecarleitao/arrow2", "path": "src/compute/aggregate/min_max.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/aggregate/min_max.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c1dea4ea1675c1633ffcbdb68344554f84d148d6891b6c55c8156fcb234d8b51"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: max_string\n\nDocumentation:\nReturns the maximum value in the string array, according to the natural order.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn max_string(array: &Utf8Array) -> Option<&str> {\n min_max_binary_utf8!(array, |a, b| a < b)\n}\n```"}], "func_name": "max_string", "docstring": "Returns the maximum value in the string array, according to the natural order.", "repo": "jorgecarleitao/arrow2", "path": "src/compute/aggregate/min_max.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/aggregate/min_max.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "99bbe36ee3addc4eb053def7b6c0bf62996fe7bf0c96a3fb71ce832f016df47f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: min_string\n\nDocumentation:\nReturns the minimum value in the string array, according to the natural order.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn min_string(array: &Utf8Array) -> Option<&str> {\n min_max_binary_utf8!(array, |a, b| a > b)\n}\n```"}], "func_name": "min_string", "docstring": "Returns the minimum value in the string array, according to the natural order.", "repo": "jorgecarleitao/arrow2", "path": "src/compute/aggregate/min_max.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/aggregate/min_max.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a0f7f71c6673e467c99b1d47b3e277262a07fcc0c6768c06fe63273a8e63d00c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_interval\n\nDocumentation:\nAdds an interval to a [`DataType::Timestamp`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_interval(\n timestamp: &PrimitiveArray,\n interval: &PrimitiveArray,\n) -> Result> {\n match timestamp.data_type().to_logical_type() {\n DataType::Timestamp(time_unit, Some(timezone_str)) => {\n let time_unit = *time_unit;\n let timezone = temporal_conversions::parse_offset(timezone_str);\n match timezone {\n Ok(timezone) => Ok(binary(\n timestamp,\n interval,\n timestamp.data_type().clone(),\n |timestamp, interval| {\n temporal_conversions::add_interval(\n timestamp, time_unit, interval, &timezone,\n )\n },\n )),\n #[cfg(feature = \"chrono-tz\")]\n Err(_) => {\n let timezone = temporal_conversions::parse_offset_tz(timezone_str)?;\n Ok(binary(\n timestamp,\n interval,\n timestamp.data_type().clone(),\n |timestamp, interval| {\n temporal_conversions::add_interval(\n timestamp, time_unit, interval, &timezone,\n )\n },\n ))\n }\n #[cfg(not(feature = \"chrono-tz\"))]\n _ => Err(Error::InvalidArgumentError(format!(\n \"timezone \\\"{}\\\" cannot be parsed (feature chrono-tz is not active)\",\n timezone_str\n ))),\n }\n }\n DataType::Timestamp(time_unit, None) => {\n let time_unit = *time_unit;\n Ok(binary(\n timestamp,\n interval,\n timestamp.data_type().clone(),\n |timestamp, interval| {\n temporal_conversions::add_naive_interval(timestamp, time_unit, interval)\n },\n ))\n }\n _ => Err(Error::InvalidArgumentError(\n \"Adding an interval is only supported for `DataType::Timestamp`\".to_string(),\n )),\n }\n}\n```"}], "func_name": "add_interval", "docstring": "Adds an interval to a [`DataType::Timestamp`].", "repo": "jorgecarleitao/arrow2", "path": "src/compute/arithmetics/time.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/arithmetics/time.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5e1c4eba3271411c20bed0d0af8af2fc7b57bf9aa52882b61597c8530371aae9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: boolean_to_utf8\n\nDocumentation:\nCasts the [`BooleanArray`] to a [`Utf8Array`], casting trues to `\"1\"` and falses to `\"0\"`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn boolean_to_utf8(from: &BooleanArray) -> Utf8Array {\n let iter = from.values().iter().map(|x| if x { \"1\" } else { \"0\" });\n Utf8Array::from_trusted_len_values_iter(iter)\n}\n```"}], "func_name": "boolean_to_utf8", "docstring": "Casts the [`BooleanArray`] to a [`Utf8Array`], casting trues to `\"1\"` and falses to `\"0\"`", "repo": "jorgecarleitao/arrow2", "path": "src/compute/cast/boolean_to.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/cast/boolean_to.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5aafe04bc3db7ad8da598570a892317e862427f04cb674019ed2271be56673b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: boolean_to_binary\n\nDocumentation:\nCasts the [`BooleanArray`] to a [`BinaryArray`], casting trues to `\"1\"` and falses to `\"0\"`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn boolean_to_binary(from: &BooleanArray) -> BinaryArray {\n let iter = from.values().iter().map(|x| if x { b\"1\" } else { b\"0\" });\n BinaryArray::from_trusted_len_values_iter(iter)\n}\n```"}], "func_name": "boolean_to_binary", "docstring": "Casts the [`BooleanArray`] to a [`BinaryArray`], casting trues to `\"1\"` and falses to `\"0\"`", "repo": "jorgecarleitao/arrow2", "path": "src/compute/cast/boolean_to.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/cast/boolean_to.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "873d067b08a0687b77a19db50b154ccc3dc5336b439e8145291700c944506358"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_numeric\n\nDocumentation:\nReturns true if this type is numeric: (UInt*, Unit*, or Float*).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_numeric(t: &DataType) -> bool {\n use DataType::*;\n matches!(\n t,\n UInt8 | UInt16 | UInt32 | UInt64 | Int8 | Int16 | Int32 | Int64 | Float32 | Float64\n )\n}\n```"}], "func_name": "is_numeric", "docstring": "Returns true if this type is numeric: (UInt*, Unit*, or Float*).", "repo": "jorgecarleitao/arrow2", "path": "src/compute/cast/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/cast/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ddcaec2a40e4b121382fc330fbec502893a8ad1e1ec13fdf9472a90980fc875"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: can_cast_types\n\nDocumentation:\nReturn true if a value of type `from_type` can be cast into a\nvalue of `to_type`. Note that such as cast may be lossy.\n\nIf this function returns true to stay consistent with the `cast` kernel below.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn can_cast_types(from_type: &DataType, to_type: &DataType) -> bool {\n use self::DataType::*;\n if from_type == to_type {\n return true;\n }\n\n match (from_type, to_type) {\n (Null, _) | (_, Null) => true,\n (Struct(_), _) => false,\n (_, Struct(_)) => false,\n (FixedSizeList(list_from, _), List(list_to)) => {\n can_cast_types(&list_from.data_type, &list_to.data_type)\n }\n (FixedSizeList(list_from, _), LargeList(list_to)) => {\n can_cast_types(&list_from.data_type, &list_to.data_type)\n }\n (List(list_from), FixedSizeList(list_to, _)) => {\n can_cast_types(&list_from.data_type, &list_to.data_type)\n }\n (LargeList(list_from), FixedSizeList(list_to, _)) => {\n can_cast_types(&list_from.data_type, &list_to.data_type)\n }\n (List(list_from), List(list_to)) => {\n can_cast_types(&list_from.data_type, &list_to.data_type)\n }\n (LargeList(list_from), LargeList(list_to)) => {\n can_cast_types(&list_from.data_type, &list_to.data_type)\n }\n (List(list_from), LargeList(list_to)) if list_from == list_to => true,\n (LargeList(list_from), List(list_to)) if list_from == list_to => true,\n (_, List(list_to)) => can_cast_types(from_type, &list_to.data_type),\n (_, LargeList(list_to)) if from_type != &LargeBinary => {\n can_cast_types(from_type, &list_to.data_type)\n }\n (Dictionary(_, from_value_type, _), Dictionary(_, to_value_type, _)) => {\n can_cast_types(from_value_type, to_value_type)\n }\n (Dictionary(_, value_type, _), _) => can_cast_types(value_type, to_type),\n (_, Dictionary(_, value_type, _)) => can_cast_types(from_type, value_type),\n\n (_, Boolean) => is_numeric(from_type),\n (Boolean, _) => {\n is_numeric(to_type)\n || to_type == &Utf8\n || to_type == &LargeUtf8\n || to_type == &Binary\n || to_type == &LargeBinary\n }\n\n (Utf8, to_type) => {\n is_numeric(to_type)\n || matches!(\n to_type,\n LargeUtf8 | Binary | Date32 | Date64 | Timestamp(TimeUnit::Nanosecond, _)\n )\n }\n (LargeUtf8, to_type) => {\n is_numeric(to_type)\n || matches!(\n to_type,\n Utf8 | LargeBinary | Date32 | Date64 | Timestamp(TimeUnit::Nanosecond, _)\n )\n }\n\n (Binary, to_type) => {\n is_numeric(to_type) || matches!(to_type, LargeBinary | Utf8 | LargeUtf8)\n }\n (LargeBinary, to_type) => {\n is_numeric(to_type)\n || match to_type {\n Binary | LargeUtf8 => true,\n LargeList(field) => matches!(field.data_type, UInt8),\n _ => false,\n }\n }\n (FixedSizeBinary(_), to_type) => matches!(to_type, Binary | LargeBinary),\n (Timestamp(_, _), Utf8) => true,\n (Timestamp(_, _), LargeUtf8) => true,\n (_, Utf8) => is_numeric(from_type) || from_type == &Binary,\n (_, LargeUtf8) => is_numeric(from_type) || from_type == &LargeBinary,\n\n (_, Binary) => is_numeric(from_type),\n (_, LargeBinary) => is_numeric(from_type),\n\n // start numeric casts\n (UInt8, UInt16) => true,\n (UInt8, UInt32) => true,\n (UInt8, UInt64) => true,\n (UInt8, Int8) => true,\n (UInt8, Int16) => true,\n (UInt8, Int32) => true,\n (UInt8, Int64) => true,\n (UInt8, Float32) => true,\n (UInt8, Float64) => true,\n (UInt8, Decimal(_, _)) => true,\n\n (UInt16, UInt8) => true,\n (UInt16, UInt32) => true,\n (UInt16, UInt64) => true,\n (UInt16, Int8) => true,\n (UInt16, Int16) => true,\n (UInt16, Int32) => true,\n (UInt16, Int64) => true,\n (UInt16, Float32) => true,\n (UInt16, Float64) => true,\n (UInt16, Decimal(_, _)) => true,\n\n (UInt32, UInt8) => true,\n (UInt32, UInt16) => true,\n (UInt32, UInt64) => true,\n (UInt32, Int8) => true,\n (UInt32, Int16) => true,\n (UInt32, Int32) => true,\n (UInt32, Int64) => true,\n (UInt32, Float32) => true,\n (UInt32, Float64) => true,\n (UInt32, Decimal(_, _)) => true,\n\n (UInt64, UInt8) => true,\n (UInt64, UInt16) => true,\n (UInt64, UInt32) => true,\n (UInt64, Int8) => true,\n (UInt64, Int16) => true,\n (UInt64, Int32) => true,\n (UInt64, Int64) => true,\n (UInt64, Float32) => true,\n (UInt64, Float64) => true,\n (UInt64, Decimal(_, _)) => true,\n\n (Int8, UInt8) => true,\n (Int8, UInt16) => true,\n (Int8, UInt32) => true,\n (Int8, UInt64) => true,\n (Int8, Int16) => true,\n (Int8, Int32) => true,\n (Int8, Int64) => true,\n (Int8, Float32) => true,\n (Int8, Float64) => true,\n (Int8, Decimal(_, _)) => true,\n\n (Int16, UInt8) => true,\n (Int16, UInt16) => true,\n (Int16, UInt32) => true,\n (Int16, UInt64) => true,\n (Int16, Int8) => true,\n (Int16, Int32) => true,\n (Int16, Int64) => true,\n (Int16, Float32) => true,\n (Int16, Float64) => true,\n (Int16, Decimal(_, _)) => true,\n\n (Int32, UInt8) => true,\n (Int32, UInt16) => true,\n (Int32, UInt32) => true,\n (Int32, UInt64) => true,\n (Int32, Int8) => true,\n (Int32, Int16) => true,\n (Int32, Int64) => true,\n (Int32, Float32) => true,\n (Int32, Float64) => true,\n (Int32, Decimal(_, _)) => true,\n\n (Int64, UInt8) => true,\n (Int64, UInt16) => true,\n (Int64, UInt32) => true,\n (Int64, UInt64) => true,\n (Int64, Int8) => true,\n (Int64, Int16) => true,\n (Int64, Int32) => true,\n (Int64, Float32) => true,\n (Int64, Float64) => true,\n (Int64, Decimal(_, _)) => true,\n\n (Float16, Float32) => true,\n\n (Float32, UInt8) => true,\n (Float32, UInt16) => true,\n (Float32, UInt32) => true,\n (Float32, UInt64) => true,\n (Float32, Int8) => true,\n (Float32, Int16) => true,\n (Float32, Int32) => true,\n (Float32, Int64) => true,\n (Float32, Float64) => true,\n (Float32, Decimal(_, _)) => true,\n\n (Float64, UInt8) => true,\n (Float64, UInt16) => true,\n (Float64, UInt32) => true,\n (Float64, UInt64) => true,\n (Float64, Int8) => true,\n (Float64, Int16) => true,\n (Float64, Int32) => true,\n (Float64, Int64) => true,\n (Float64, Float32) => true,\n (Float64, Decimal(_, _)) => true,\n\n (\n Decimal(_, _),\n UInt8\n | UInt16\n | UInt32\n | UInt64\n | Int8\n | Int16\n | Int32\n | Int64\n | Float32\n | Float64\n | Decimal(_, _),\n ) => true,\n // end numeric casts\n\n // temporal casts\n (Int32, Date32) => true,\n (Int32, Time32(_)) => true,\n (Date32, Int32) => true,\n (Date32, Int64) => true,\n (Time32(_), Int32) => true,\n (Int64, Date64) => true,\n (Int64, Time64(_)) => true,\n (Date64, Int32) => true,\n (Date64, Int64) => true,\n (Time64(_), Int64) => true,\n (Date32, Date64) => true,\n (Date64, Date32) => true,\n (Time32(TimeUnit::Second), Time32(TimeUnit::Millisecond)) => true,\n (Time32(TimeUnit::Millisecond), Time32(TimeUnit::Second)) => true,\n (Time32(_), Time64(_)) => true,\n (Time64(TimeUnit::Microsecond), Time64(TimeUnit::Nanosecond)) => true,\n (Time64(TimeUnit::Nanosecond), Time64(TimeUnit::Microsecond)) => true,\n (Time64(_), Time32(to_unit)) => {\n matches!(to_unit, TimeUnit::Second | TimeUnit::Millisecond)\n }\n (Timestamp(_, _), Int64) => true,\n (Int64, Timestamp(_, _)) => true,\n (Timestamp(_, _), Timestamp(_, _)) => true,\n (Timestamp(_, _), Date32) => true,\n (Timestamp(_, _), Date64) => true,\n (Int64, Duration(_)) => true,\n (Duration(_), Int64) => true,\n (Interval(_), Interval(IntervalUnit::MonthDayNano)) => true,\n (_, _) => false,\n }\n}\n```"}], "func_name": "can_cast_types", "docstring": "Return true if a value of type `from_type` can be cast into a\nvalue of `to_type`. Note that such as cast may be lossy.\n\nIf this function returns true to stay consistent with the `cast` kernel below.", "repo": "jorgecarleitao/arrow2", "path": "src/compute/cast/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/cast/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "edf011d1e3d05d3a8ed10081be6f7b5c3a431744bd28e327f396011beaef041a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cast_to_dictionary\n\nDocumentation:\nAttempts to encode an array into an `ArrayDictionary` with index\ntype K and value (dictionary) type value_type\n\nK is the key type\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn cast_to_dictionary(\n array: &dyn Array,\n dict_value_type: &DataType,\n options: CastOptions,\n) -> Result> {\n let array = cast(array, dict_value_type, options)?;\n let array = array.as_ref();\n match *dict_value_type {\n DataType::Int8 => primitive_to_dictionary_dyn::(array),\n DataType::Int16 => primitive_to_dictionary_dyn::(array),\n DataType::Int32 => primitive_to_dictionary_dyn::(array),\n DataType::Int64 => primitive_to_dictionary_dyn::(array),\n DataType::UInt8 => primitive_to_dictionary_dyn::(array),\n DataType::UInt16 => primitive_to_dictionary_dyn::(array),\n DataType::UInt32 => primitive_to_dictionary_dyn::(array),\n DataType::UInt64 => primitive_to_dictionary_dyn::(array),\n DataType::Utf8 => utf8_to_dictionary_dyn::(array),\n DataType::LargeUtf8 => utf8_to_dictionary_dyn::(array),\n DataType::Binary => binary_to_dictionary_dyn::(array),\n DataType::LargeBinary => binary_to_dictionary_dyn::(array),\n _ => Err(Error::NotYetImplemented(format!(\n \"Unsupported output type for dictionary packing: {dict_value_type:?}\"\n ))),\n }\n}\n```"}], "func_name": "cast_to_dictionary", "docstring": "Attempts to encode an array into an `ArrayDictionary` with index\ntype K and value (dictionary) type value_type\n\nK is the key type", "repo": "jorgecarleitao/arrow2", "path": "src/compute/cast/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/cast/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "05ac07cb86eda7a5d9bbadbd95e2e9fd7f06ae70f3f1deb16e9df36dfb013c26"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: time_unit_multiple\n\nDocumentation:\nGet the time unit as a multiple of a second\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nconst fn time_unit_multiple(unit: TimeUnit) -> i64 {\n match unit {\n TimeUnit::Second => 1,\n TimeUnit::Millisecond => MILLISECONDS,\n TimeUnit::Microsecond => MICROSECONDS,\n TimeUnit::Nanosecond => NANOSECONDS,\n }\n}\n```"}], "func_name": "time_unit_multiple", "docstring": "Get the time unit as a multiple of a second", "repo": "jorgecarleitao/arrow2", "path": "src/compute/cast/primitive_to.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/cast/primitive_to.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8be1effad280a5c86d19aba81fc7ab7c23779ed47841674da9f2543d15e555b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cmp_array\n\nDocumentation:\nCompare two `Array`s based on the ordering defined in [ord](crate::array::ord).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn cmp_array(a: &dyn Array, b: &dyn Array) -> Ordering {\n let cmp_op = ord::build_compare(a, b).unwrap();\n let length = a.len().min(b.len());\n\n for i in 0..length {\n let result = cmp_op(i, i);\n if result != Ordering::Equal {\n return result;\n }\n }\n a.len().cmp(&b.len())\n}\n```"}], "func_name": "cmp_array", "docstring": "Compare two `Array`s based on the ordering defined in [ord](crate::array::ord).", "repo": "jorgecarleitao/arrow2", "path": "src/compute/sort/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/sort/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51be4092756a87d7312108e08777c11901070215c083b7eaf655dc2dcfdcdd73"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encoded_len\n\nDocumentation:\nReturns the total encoded length (including null byte) for a value of type `T::Native`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn encoded_len(_col: &PrimitiveArray) -> usize\nwhere\n T: NativeType + FixedLengthEncoding,\n{\n T::ENCODED_LEN\n}\n```"}], "func_name": "encoded_len", "docstring": "Returns the total encoded length (including null byte) for a value of type `T::Native`", "repo": "jorgecarleitao/arrow2", "path": "src/compute/sort/row/fixed.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/sort/row/fixed.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c914c89ca528c0109572ceca43a417c3774b49aa88c0eb4f0ecdc957a10de53"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode\n\nDocumentation:\nFixed width types are encoded as\n\n- 1 byte `0` if null or `1` if valid\n- bytes of [`FixedLengthEncoding`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn encode>>(\n out: &mut Rows,\n i: I,\n opts: SortOptions,\n) {\n for (offset, maybe_val) in out.offsets.iter_mut().skip(1).zip(i) {\n let end_offset = *offset + T::ENCODED_LEN;\n if let Some(val) = maybe_val {\n let to_write = &mut out.buffer[*offset..end_offset];\n to_write[0] = 1;\n let mut encoded = val.encode();\n if opts.descending {\n // Flip bits to reverse order\n encoded.as_mut().iter_mut().for_each(|v| *v = !*v)\n }\n to_write[1..].copy_from_slice(encoded.as_ref())\n } else {\n out.buffer[*offset] = null_sentinel(opts);\n }\n *offset = end_offset;\n }\n}\n```"}], "func_name": "encode", "docstring": "Fixed width types are encoded as\n\n- 1 byte `0` if null or `1` if valid\n- bytes of [`FixedLengthEncoding`]", "repo": "jorgecarleitao/arrow2", "path": "src/compute/sort/row/fixed.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/sort/row/fixed.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e9ff68e3c8ec25b0db2f8ff3a52b8c3c001e62289ac761ffaf86ac6a8e1d81db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode\n\nDocumentation:\nVariable length values are encoded as\n\n- single `0_u8` if null\n- single `1_u8` if empty array\n- `2_u8` if not empty, followed by one or more blocks\n\nwhere a block is encoded as\n\n- [`BLOCK_SIZE`] bytes of string data, padded with 0s\n- `0xFF_u8` if this is not the last block for this string\n- otherwise the length of the block as a `u8`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn encode<'a, I: Iterator>>(out: &mut Rows, i: I, opts: SortOptions) {\n for (offset, maybe_val) in out.offsets.iter_mut().skip(1).zip(i) {\n match maybe_val {\n Some(val) if val.is_empty() => {\n out.buffer[*offset] = match opts.descending {\n true => !EMPTY_SENTINEL,\n false => EMPTY_SENTINEL,\n };\n *offset += 1;\n }\n Some(val) => {\n let block_count = div_ceil(val.len(), BLOCK_SIZE);\n let end_offset = *offset + 1 + block_count * (BLOCK_SIZE + 1);\n let to_write = &mut out.buffer[*offset..end_offset];\n\n // Write `2_u8` to demarcate as non-empty, non-null string\n to_write[0] = NON_EMPTY_SENTINEL;\n\n let mut chunks = val.chunks_exact(BLOCK_SIZE);\n for (input, output) in chunks\n .by_ref()\n .zip(to_write[1..].chunks_exact_mut(BLOCK_SIZE + 1))\n {\n let input: &[u8; BLOCK_SIZE] = input.try_into().unwrap();\n let out_block: &mut [u8; BLOCK_SIZE] =\n (&mut output[..BLOCK_SIZE]).try_into().unwrap();\n\n *out_block = *input;\n\n // Indicate that there are further blocks to follow\n output[BLOCK_SIZE] = BLOCK_CONTINUATION;\n }\n\n let remainder = chunks.remainder();\n if !remainder.is_empty() {\n let start_offset = 1 + (block_count - 1) * (BLOCK_SIZE + 1);\n to_write[start_offset..start_offset + remainder.len()]\n .copy_from_slice(remainder);\n *to_write.last_mut().unwrap() = remainder.len() as u8;\n } else {\n // We must overwrite the continuation marker written by the loop above\n *to_write.last_mut().unwrap() = BLOCK_SIZE as u8;\n }\n\n *offset = end_offset;\n\n if opts.descending {\n // Invert bits\n to_write.iter_mut().for_each(|v| *v = !*v)\n }\n }\n None => {\n out.buffer[*offset] = null_sentinel(opts);\n *offset += 1;\n }\n }\n }\n}\n```"}], "func_name": "encode", "docstring": "Variable length values are encoded as\n\n- single `0_u8` if null\n- single `1_u8` if empty array\n- `2_u8` if not empty, followed by one or more blocks\n\nwhere a block is encoded as\n\n- [`BLOCK_SIZE`] bytes of string data, padded with 0s\n- `0xFF_u8` if this is not the last block for this string\n- otherwise the length of the block as a `u8`", "repo": "jorgecarleitao/arrow2", "path": "src/compute/sort/row/variable.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/sort/row/variable.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "229efe8277a7cc1d3b99feda0d431d368f4d4964a439d487c5afe61ad32f89bc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: take\n\nDocumentation:\n`take` implementation for dictionary arrays\n\napplies `take` to the keys of the dictionary array and returns a new dictionary array\nwith the same dictionary values and reordered keys\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn take(values: &DictionaryArray, indices: &PrimitiveArray) -> DictionaryArray\nwhere\n K: DictionaryKey,\n I: Index,\n{\n let keys = take_primitive::(values.keys(), indices);\n // safety - this operation takes a subset of keys and thus preserves the dictionary's invariant\n unsafe {\n DictionaryArray::::try_new_unchecked(\n values.data_type().clone(),\n keys,\n values.values().clone(),\n )\n .unwrap()\n }\n}\n```"}], "func_name": "take", "docstring": "`take` implementation for dictionary arrays\n\napplies `take` to the keys of the dictionary array and returns a new dictionary array\nwith the same dictionary values and reordered keys", "repo": "jorgecarleitao/arrow2", "path": "src/compute/take/dict.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/compute/take/dict.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a43bd320a6505a07eec23bc82e41aed92fe611164e1ba1a23d4e4b434e63c0a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: null_count\n\nDocumentation:\nthe null count of the array\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn null_count(&self) -> usize {\n self.null_count as usize\n }\n```"}], "func_name": "null_count", "docstring": "the null count of the array", "repo": "jorgecarleitao/arrow2", "path": "src/ffi/array.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/ffi/array.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "573fc50cfad01caad477fd3f8d15565c97b6fd68647eebac476a75ae1d417bcd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_buffer\n\nDocumentation:\nreturns the buffer `i` of `array` interpreted as a [`Buffer`].\n# Safety\nThis function is safe iff:\n* the buffers up to position `index` are valid for the declared length\n* the buffers' pointers are not mutably shared for the lifetime of `owner`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn create_buffer(\n array: &ArrowArray,\n data_type: &DataType,\n owner: InternalArrowArray,\n index: usize,\n) -> Result> {\n let len = buffer_len(array, data_type, index)?;\n\n if len == 0 {\n return Ok(Buffer::new());\n }\n\n let offset = buffer_offset(array, data_type, index);\n let ptr: *mut T = get_buffer_ptr(array, data_type, index)?;\n\n // We have to check alignment.\n // This is the zero-copy path.\n if ptr.align_offset(std::mem::align_of::()) == 0 {\n let bytes = Bytes::from_foreign(ptr, len, BytesAllocator::InternalArrowArray(owner));\n Ok(Buffer::from_bytes(bytes).sliced(offset, len - offset))\n }\n // This is the path where alignment isn't correct.\n // We copy the data to a new vec\n else {\n let buf = std::slice::from_raw_parts(ptr, len - offset).to_vec();\n Ok(Buffer::from(buf))\n }\n}\n```"}], "func_name": "create_buffer", "docstring": "returns the buffer `i` of `array` interpreted as a [`Buffer`].\n# Safety\nThis function is safe iff:\n* the buffers up to position `index` are valid for the declared length\n* the buffers' pointers are not mutably shared for the lifetime of `owner`", "repo": "jorgecarleitao/arrow2", "path": "src/ffi/array.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/ffi/array.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "20757479725d89ca4d28043933429cd1447df703d38417be81cef91517963cee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bitmap\n\nDocumentation:\nCreates a (non-null) [`BooleanArray`] from a slice of bits.\nThis does not have memcopy and is the fastest way to create a [`BooleanArray`].\n\nThis can be useful if you want to apply arrow kernels on slices without incurring\na memcopy cost.\n\nThe `offset` indicates where the first bit starts in the first byte.\n\n# Safety\n\nUsing this function is not unsafe, but the returned BooleanArrays's lifetime is bound to the lifetime\nof the slice. The returned [`BooleanArray`] _must not_ outlive the passed slice.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub unsafe fn bitmap(data: &[u8], offset: usize, length: usize) -> Result {\n if offset >= 8 {\n return Err(Error::InvalidArgumentError(\"offset should be < 8\".into()));\n };\n if length > data.len() * 8 - offset {\n return Err(Error::InvalidArgumentError(\"given length is oob\".into()));\n }\n let null_count = 0;\n let validity = None;\n\n let ptr = data.as_ptr() as *const u8;\n let data = Arc::new(data);\n\n // safety: the underlying assumption of this function: the array will not be used\n // beyond the\n let array = create_array(\n data,\n length,\n null_count,\n [validity, Some(ptr)].into_iter(),\n [].into_iter(),\n None,\n Some(offset),\n );\n let array = InternalArrowArray::new(array, DataType::Boolean);\n\n // safety: we just created a valid array\n Ok(unsafe { BooleanArray::try_from_ffi(array) }.unwrap())\n}\n```"}], "func_name": "bitmap", "docstring": "Creates a (non-null) [`BooleanArray`] from a slice of bits.\nThis does not have memcopy and is the fastest way to create a [`BooleanArray`].\n\nThis can be useful if you want to apply arrow kernels on slices without incurring\na memcopy cost.\n\nThe `offset` indicates where the first bit starts in the first byte.\n\n# Safety\n\nUsing this function is not unsafe, but the returned BooleanArrays's lifetime is bound to the lifetime\nof the slice. The returned [`BooleanArray`] _must not_ outlive the passed slice.", "repo": "jorgecarleitao/arrow2", "path": "src/ffi/mmap.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/ffi/mmap.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac80363ef3d66dadda2e0e57c736ad4c47893d967124d67cc984c5db4ce8e8fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: infer\n\nDocumentation:\nInfers [`DataType`] from `bytes`\n# Implementation\n* case insensitive \"true\" or \"false\" are mapped to [`DataType::Boolean`]\n* parsable to integer is mapped to [`DataType::Int64`]\n* parsable to float is mapped to [`DataType::Float64`]\n* parsable to date is mapped to [`DataType::Date32`]\n* parsable to time is mapped to [`DataType::Time32(TimeUnit::Millisecond)`]\n* parsable to naive datetime is mapped to [`DataType::Timestamp(TimeUnit::Millisecond, None)`]\n* parsable to time-aware datetime is mapped to [`DataType::Timestamp`] of milliseconds and parsed offset.\n* other utf8 is mapped to [`DataType::Utf8`]\n* invalid utf8 is mapped to [`DataType::Binary`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn infer(bytes: &[u8]) -> DataType {\n if is_boolean(bytes) {\n DataType::Boolean\n } else if is_integer(bytes) {\n DataType::Int64\n } else if is_float(bytes) {\n DataType::Float64\n } else if let Ok(string) = simdutf8::basic::from_utf8(bytes) {\n if is_date(string) {\n DataType::Date32\n } else if is_time(string) {\n DataType::Time32(TimeUnit::Millisecond)\n } else if is_naive_datetime(string) {\n DataType::Timestamp(TimeUnit::Millisecond, None)\n } else if let Some(offset) = is_datetime(string) {\n DataType::Timestamp(TimeUnit::Millisecond, Some(offset))\n } else {\n DataType::Utf8\n }\n } else {\n // invalid utf8\n DataType::Binary\n }\n}\n```"}], "func_name": "infer", "docstring": "Infers [`DataType`] from `bytes`\n# Implementation\n* case insensitive \"true\" or \"false\" are mapped to [`DataType::Boolean`]\n* parsable to integer is mapped to [`DataType::Int64`]\n* parsable to float is mapped to [`DataType::Float64`]\n* parsable to date is mapped to [`DataType::Date32`]\n* parsable to time is mapped to [`DataType::Time32(TimeUnit::Millisecond)`]\n* parsable to naive datetime is mapped to [`DataType::Timestamp(TimeUnit::Millisecond, None)`]\n* parsable to time-aware datetime is mapped to [`DataType::Timestamp`] of milliseconds and parsed offset.\n* other utf8 is mapped to [`DataType::Utf8`]\n* invalid utf8 is mapped to [`DataType::Binary`]", "repo": "jorgecarleitao/arrow2", "path": "src/io/csv/utils.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/csv/utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ed90c8ee8a91d7955fcfcb89b70a61ef10dad206a2897d2a4c9c95d0540b47a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: infer_schema\n\nDocumentation:\nInfers the [`Field`]s of a CSV file by reading through the first n records up to `max_rows`.\nAlso returns the number of rows used to infer.\nSeeks back to the begining of the file _after_ the header\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn infer_schema DataType>(\n reader: &mut Reader,\n max_rows: Option,\n has_header: bool,\n infer: &F,\n) -> Result<(Vec, usize)> {\n // get or create header names\n // when has_header is false, creates default column names with column_ prefix\n let headers: Vec = if has_header {\n reader.headers()?.iter().map(|s| s.to_string()).collect()\n } else {\n let first_record_count = &reader.headers()?.len();\n (0..*first_record_count)\n .map(|i| format!(\"column_{}\", i + 1))\n .collect()\n };\n\n // save the csv reader position after reading headers\n let position = reader.position().clone();\n\n let header_length = headers.len();\n // keep track of inferred field types\n let mut column_types: Vec> = vec![AHashSet::new(); header_length];\n\n let mut records_count = 0;\n\n let mut record = ByteRecord::new();\n let max_records = max_rows.unwrap_or(usize::MAX);\n while records_count < max_records {\n if !reader.read_byte_record(&mut record)? {\n break;\n }\n records_count += 1;\n\n for (i, column) in column_types.iter_mut().enumerate() {\n if let Some(string) = record.get(i) {\n if !string.is_empty() {\n column.insert(infer(string));\n }\n }\n }\n }\n\n let fields = merge_schema(&headers, &mut column_types);\n\n // return the reader seek back to the start\n reader.seek(position)?;\n\n Ok((fields, records_count))\n}\n```"}], "func_name": "infer_schema", "docstring": "Infers the [`Field`]s of a CSV file by reading through the first n records up to `max_rows`.\nAlso returns the number of rows used to infer.\nSeeks back to the begining of the file _after_ the header", "repo": "jorgecarleitao/arrow2", "path": "src/io/csv/read/infer_schema.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/csv/read/infer_schema.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e1e70e7b76cc96ec20e0e801eb08daa6857b9ff1c7dbf121c683891090e2cd9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: infer_schema\n\nDocumentation:\nInfers the [`Field`]s of a CSV file by reading through the first n records up to `max_rows`.\nSeeks back to the begining of the file _after_ the header\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn infer_schema(\n reader: &mut AsyncReader,\n max_rows: Option,\n has_header: bool,\n infer: &F,\n) -> Result<(Vec, usize)>\nwhere\n R: AsyncRead + AsyncSeek + Unpin + Send + Sync,\n F: Fn(&[u8]) -> DataType,\n{\n // get or create header names\n // when has_header is false, creates default column names with column_ prefix\n let headers: Vec = if has_header {\n reader\n .headers()\n .await?\n .iter()\n .map(|s| s.to_string())\n .collect()\n } else {\n let first_record_count = &reader.headers().await?.len();\n (0..*first_record_count)\n .map(|i| format!(\"column_{}\", i + 1))\n .collect()\n };\n\n // save the csv reader position after reading headers\n let position = reader.position().clone();\n\n let header_length = headers.len();\n // keep track of inferred field types\n let mut column_types: Vec> = vec![AHashSet::new(); header_length];\n\n let mut records_count = 0;\n\n let mut record = ByteRecord::new();\n let max_records = max_rows.unwrap_or(usize::MAX);\n while records_count < max_records {\n if !reader.read_byte_record(&mut record).await? {\n break;\n }\n records_count += 1;\n\n for (i, column) in column_types.iter_mut().enumerate() {\n if let Some(string) = record.get(i) {\n column.insert(infer(string));\n }\n }\n }\n\n let fields = merge_schema(&headers, &mut column_types);\n\n // return the reader seek back to the start\n reader.seek(position).await?;\n\n Ok((fields, records_count))\n}\n```"}], "func_name": "infer_schema", "docstring": "Infers the [`Field`]s of a CSV file by reading through the first n records up to `max_rows`.\nSeeks back to the begining of the file _after_ the header", "repo": "jorgecarleitao/arrow2", "path": "src/io/csv/read_async/infer_schema.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/csv/read_async/infer_schema.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "594d392feeaeb6252f37284b0f63720d02d8172d859c85623e8ee955ea57e66c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_rows\n\nDocumentation:\nAsynchronosly read `len` rows from `reader` into `row`, skiping the first `skip`.\nThis operation has minimal CPU work and is thus the fastest way to read through a CSV\nwithout deserializing the contents to Arrow.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn read_rows(\n reader: &mut AsyncReader,\n skip: usize,\n rows: &mut [ByteRecord],\n) -> Result\nwhere\n R: AsyncRead + Unpin + Send + Sync,\n{\n // skip first `start` rows.\n let mut row = ByteRecord::new();\n for _ in 0..skip {\n let res = reader.read_byte_record(&mut row).await;\n if !res.unwrap_or(false) {\n break;\n }\n }\n\n let mut row_number = 0;\n for row in rows.iter_mut() {\n let has_more = reader\n .read_byte_record(row)\n .await\n .map_err(|e| Error::External(format!(\" at line {}\", skip + row_number), Box::new(e)))?;\n if !has_more {\n break;\n }\n row_number += 1;\n }\n Ok(row_number)\n}\n```"}], "func_name": "read_rows", "docstring": "Asynchronosly read `len` rows from `reader` into `row`, skiping the first `skip`.\nThis operation has minimal CPU work and is thus the fastest way to read through a CSV\nwithout deserializing the contents to Arrow.", "repo": "jorgecarleitao/arrow2", "path": "src/io/csv/read_async/reader.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/csv/read_async/reader.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c50d686c4c1c5b9798c7cb1a813d9e19801d6154f700ab2a90d912799c04283"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_from_file\n\nDocumentation:\nCreates a new [`FileWriter`] from an existing file, seeking to the last message\nand appending new messages afterwards. Users call `finish` to write the footer (with both)\nthe existing and appended messages on it.\n# Error\nThis function errors iff:\n* the file's endianess is not the native endianess (not yet supported)\n* the file is not a valid Arrow IPC file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_from_file(\n mut writer: R,\n metadata: FileMetadata,\n options: WriteOptions,\n ) -> Result> {\n if metadata.ipc_schema.is_little_endian != is_native_little_endian() {\n return Err(Error::nyi(\n \"Appending to a file of a non-native endianess is still not supported\",\n ));\n }\n\n let dictionaries =\n read::read_file_dictionaries(&mut writer, &metadata, &mut Default::default())?;\n\n let last_block = metadata.blocks.last().ok_or_else(|| {\n Error::oos(\"An Arrow IPC file must have at least 1 message (the schema message)\")\n })?;\n let offset: u64 = last_block\n .offset\n .try_into()\n .map_err(|_| Error::oos(\"The block's offset must be a positive number\"))?;\n let meta_data_length: u64 = last_block\n .meta_data_length\n .try_into()\n .map_err(|_| Error::oos(\"The block's meta length must be a positive number\"))?;\n let body_length: u64 = last_block\n .body_length\n .try_into()\n .map_err(|_| Error::oos(\"The block's body length must be a positive number\"))?;\n let offset: u64 = offset + meta_data_length + body_length;\n\n writer.seek(SeekFrom::Start(offset))?;\n\n Ok(FileWriter {\n writer,\n options,\n schema: metadata.schema,\n ipc_fields: metadata.ipc_schema.fields,\n block_offsets: offset as usize,\n dictionary_blocks: metadata.dictionaries.unwrap_or_default(),\n record_blocks: metadata.blocks,\n state: State::Started, // file already exists, so we are ready\n dictionary_tracker: DictionaryTracker {\n dictionaries,\n cannot_replace: true,\n },\n encoded_message: Default::default(),\n })\n }\n```"}], "func_name": "try_from_file", "docstring": "Creates a new [`FileWriter`] from an existing file, seeking to the last message\nand appending new messages afterwards. Users call `finish` to write the footer (with both)\nthe existing and appended messages on it.\n# Error\nThis function errors iff:\n* the file's endianess is not the native endianess (not yet supported)\n* the file is not a valid Arrow IPC file", "repo": "jorgecarleitao/arrow2", "path": "src/io/ipc/append/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/ipc/append/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d4a606cd8a06c363e3471888b50f7c7f50d2922de230c6c9e6ee5320cb729e23"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_data_type\n\nDocumentation:\nGet the Arrow data type from the flatbuffer Field table\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_data_type(\n field: arrow_format::ipc::FieldRef,\n extension: Extension,\n may_be_dictionary: bool,\n) -> Result<(DataType, IpcField)> {\n if let Some(dictionary) = field.dictionary()? {\n if may_be_dictionary {\n let int = dictionary\n .index_type()?\n .ok_or_else(|| Error::oos(\"indexType is mandatory in Dictionary.\"))?;\n let index_type = deserialize_integer(int)?;\n let (inner, mut ipc_field) = get_data_type(field, extension, false)?;\n ipc_field.dictionary_id = Some(dictionary.id()?);\n return Ok((\n DataType::Dictionary(index_type, Box::new(inner), dictionary.is_ordered()?),\n ipc_field,\n ));\n }\n }\n\n if let Some(extension) = extension {\n let (name, metadata) = extension;\n let (data_type, fields) = get_data_type(field, None, false)?;\n return Ok((\n DataType::Extension(name, Box::new(data_type), metadata),\n fields,\n ));\n }\n\n let type_ = field\n .type_()?\n .ok_or_else(|| Error::oos(\"IPC: field type is mandatory\"))?;\n\n use arrow_format::ipc::TypeRef::*;\n Ok(match type_ {\n Null(_) => (DataType::Null, IpcField::default()),\n Bool(_) => (DataType::Boolean, IpcField::default()),\n Int(int) => {\n let data_type = deserialize_integer(int)?.into();\n (data_type, IpcField::default())\n }\n Binary(_) => (DataType::Binary, IpcField::default()),\n LargeBinary(_) => (DataType::LargeBinary, IpcField::default()),\n Utf8(_) => (DataType::Utf8, IpcField::default()),\n LargeUtf8(_) => (DataType::LargeUtf8, IpcField::default()),\n FixedSizeBinary(fixed) => (\n DataType::FixedSizeBinary(\n fixed\n .byte_width()?\n .try_into()\n .map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?,\n ),\n IpcField::default(),\n ),\n FloatingPoint(float) => {\n let data_type = match float.precision()? {\n arrow_format::ipc::Precision::Half => DataType::Float16,\n arrow_format::ipc::Precision::Single => DataType::Float32,\n arrow_format::ipc::Precision::Double => DataType::Float64,\n };\n (data_type, IpcField::default())\n }\n Date(date) => {\n let data_type = match date.unit()? {\n arrow_format::ipc::DateUnit::Day => DataType::Date32,\n arrow_format::ipc::DateUnit::Millisecond => DataType::Date64,\n };\n (data_type, IpcField::default())\n }\n Time(time) => deserialize_time(time)?,\n Timestamp(timestamp) => deserialize_timestamp(timestamp)?,\n Interval(interval) => {\n let data_type = match interval.unit()? {\n arrow_format::ipc::IntervalUnit::YearMonth => {\n DataType::Interval(IntervalUnit::YearMonth)\n }\n arrow_format::ipc::IntervalUnit::DayTime => {\n DataType::Interval(IntervalUnit::DayTime)\n }\n arrow_format::ipc::IntervalUnit::MonthDayNano => {\n DataType::Interval(IntervalUnit::MonthDayNano)\n }\n };\n (data_type, IpcField::default())\n }\n Duration(duration) => {\n let time_unit = deserialize_timeunit(duration.unit()?)?;\n (DataType::Duration(time_unit), IpcField::default())\n }\n Decimal(decimal) => {\n let bit_width: usize = decimal\n .bit_width()?\n .try_into()\n .map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?;\n let precision: usize = decimal\n .precision()?\n .try_into()\n .map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?;\n let scale: usize = decimal\n .scale()?\n .try_into()\n .map_err(|_| Error::from(OutOfSpecKind::NegativeFooterLength))?;\n\n let data_type = match bit_width {\n 128 => DataType::Decimal(precision, scale),\n 256 => DataType::Decimal256(precision, scale),\n _ => return Err(Error::from(OutOfSpecKind::NegativeFooterLength)),\n };\n\n (data_type, IpcField::default())\n }\n List(_) => deserialize_list(field)?,\n LargeList(_) => deserialize_large_list(field)?,\n FixedSizeList(list) => deserialize_fixed_size_list(list, field)?,\n Struct(_) => deserialize_struct(field)?,\n Union(union_) => deserialize_union(union_, field)?,\n Map(map) => deserialize_map(map, field)?,\n })\n}\n```"}], "func_name": "get_data_type", "docstring": "Get the Arrow data type from the flatbuffer Field table", "repo": "jorgecarleitao/arrow2", "path": "src/io/ipc/read/schema.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/ipc/read/schema.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "571104d5ef3c7d0822021573d0b9949506fbc3dc679c23cf975e801e6ab717a3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nTry to create a new stream reader\n\nThe first message in the stream is the schema, the reader will fail if it does not\nencounter a schema.\nTo check if the reader is done, use `is_finished(self)`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(reader: R, metadata: StreamMetadata, projection: Option>) -> Self {\n let projection = projection.map(|projection| {\n let (p, h, fields) = prepare_projection(&metadata.schema.fields, projection);\n let schema = Schema {\n fields,\n metadata: metadata.schema.metadata.clone(),\n };\n (p, h, schema)\n });\n\n Self {\n reader,\n metadata,\n dictionaries: Default::default(),\n finished: false,\n data_buffer: Default::default(),\n message_buffer: Default::default(),\n projection,\n scratch: Default::default(),\n }\n }\n```"}], "func_name": "new", "docstring": "Try to create a new stream reader\n\nThe first message in the stream is the schema, the reader will fail if it does not\nencounter a schema.\nTo check if the reader is done, use `is_finished(self)`", "repo": "jorgecarleitao/arrow2", "path": "src/io/ipc/read/stream.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/ipc/read/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6c14786c98fcea6c6b8f844fcf8ac2499c2c10c875fa65266f858f0f763af135"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nKeep track of the dictionary with the given ID and values. Behavior:\n\n* If this ID has been written already and has the same data, return `Ok(false)` to indicate\nthat the dictionary was not actually inserted (because it's already been seen).\n* If this ID has been written already but with different data, and this tracker is\nconfigured to return an error, return an error.\n* If the tracker has not been configured to error on replacement or this dictionary\nhas never been seen before, return `Ok(true)` to indicate that the dictionary was just\ninserted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert(&mut self, dict_id: i64, array: &dyn Array) -> Result {\n let values = match array.data_type() {\n DataType::Dictionary(key_type, _, _) => {\n match_integer_type!(key_type, |$T| {\n let array = array\n .as_any()\n .downcast_ref::>()\n .unwrap();\n array.values()\n })\n }\n _ => unreachable!(),\n };\n\n // If a dictionary with this id was already emitted, check if it was the same.\n if let Some(last) = self.dictionaries.get(&dict_id) {\n if last.as_ref() == values.as_ref() {\n // Same dictionary values => no need to emit it again\n return Ok(false);\n } else if self.cannot_replace {\n return Err(Error::InvalidArgumentError(\n \"Dictionary replacement detected when writing IPC file format. \\\n Arrow IPC files only support a single dictionary for a given field \\\n across all batches.\"\n .to_string(),\n ));\n }\n };\n\n self.dictionaries.insert(dict_id, values.clone());\n Ok(true)\n }\n```"}], "func_name": "insert", "docstring": "Keep track of the dictionary with the given ID and values. Behavior:\n\n* If this ID has been written already and has the same data, return `Ok(false)` to indicate\nthat the dictionary was not actually inserted (because it's already been seen).\n* If this ID has been written already but with different data, and this tracker is\nconfigured to return an error, return an error.\n* If the tracker has not been configured to error on replacement or this dictionary\nhas never been seen before, return `Ok(true)` to indicate that the dictionary was just\ninserted.", "repo": "jorgecarleitao/arrow2", "path": "src/io/ipc/write/common.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/ipc/write/common.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b4f072d402bfc03c96fae971598fdad11c6c166cc35f978550973fcaa5a6d405"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_message\n\nDocumentation:\nWrite a message's IPC data and buffers, returning metadata and buffer data lengths written\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn write_message(\n mut writer: W,\n encoded: EncodedData,\n) -> Result<(usize, usize)> {\n let arrow_data_len = encoded.arrow_data.len();\n\n let a = 64 - 1;\n let buffer = encoded.ipc_message;\n let flatbuf_size = buffer.len();\n let prefix_size = 8; // the message length\n let aligned_size = (flatbuf_size + prefix_size + a) & !a;\n let padding_bytes = aligned_size - flatbuf_size - prefix_size;\n\n write_continuation(&mut writer, (aligned_size - prefix_size) as i32).await?;\n\n // write the flatbuf\n if flatbuf_size > 0 {\n writer.write_all(&buffer).await?;\n }\n // write padding\n writer.write_all(&vec![0; padding_bytes]).await?;\n\n // write arrow data\n let body_len = if arrow_data_len > 0 {\n write_body_buffers(writer, &encoded.arrow_data).await?\n } else {\n 0\n };\n\n Ok((aligned_size, body_len))\n}\n```"}], "func_name": "write_message", "docstring": "Write a message's IPC data and buffers, returning metadata and buffer data lengths written", "repo": "jorgecarleitao/arrow2", "path": "src/io/ipc/write/common_async.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/ipc/write/common_async.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b9e9a09a7aabc293e1f04be9a6bc812983858fb2b790b361340a60715e9ca5f8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_continuation\n\nDocumentation:\nWrite a record batch to the writer, writing the message size before the message\nif the record batch is being written to a stream\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn write_continuation(\n mut writer: W,\n total_len: i32,\n) -> Result {\n writer.write_all(&CONTINUATION_MARKER).await?;\n writer.write_all(&total_len.to_le_bytes()[..]).await?;\n Ok(8)\n}\n```"}], "func_name": "write_continuation", "docstring": "Write a record batch to the writer, writing the message size before the message\nif the record batch is being written to a stream", "repo": "jorgecarleitao/arrow2", "path": "src/io/ipc/write/common_async.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/ipc/write/common_async.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e55b404da0c0be0c78ef1f6452634ca5305f22b8a8426e457ddd2f9a91a24e4a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: serialize_field\n\nDocumentation:\nCreate an IPC Field from an Arrow Field\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn serialize_field(field: &Field, ipc_field: &IpcField) -> arrow_format::ipc::Field {\n // custom metadata.\n let mut kv_vec = vec![];\n if let DataType::Extension(name, _, metadata) = field.data_type() {\n write_extension(name, metadata, &mut kv_vec);\n }\n\n let type_ = serialize_type(field.data_type());\n let children = serialize_children(field.data_type(), ipc_field);\n\n let dictionary = if let DataType::Dictionary(index_type, inner, is_ordered) = field.data_type()\n {\n if let DataType::Extension(name, _, metadata) = inner.as_ref() {\n write_extension(name, metadata, &mut kv_vec);\n }\n Some(serialize_dictionary(\n index_type,\n ipc_field\n .dictionary_id\n .expect(\"All Dictionary types have `dict_id`\"),\n *is_ordered,\n ))\n } else {\n None\n };\n\n write_metadata(&field.metadata, &mut kv_vec);\n\n let custom_metadata = if !kv_vec.is_empty() {\n Some(kv_vec)\n } else {\n None\n };\n\n arrow_format::ipc::Field {\n name: Some(field.name.clone()),\n nullable: field.is_nullable,\n type_: Some(type_),\n dictionary: dictionary.map(Box::new),\n children: Some(children),\n custom_metadata,\n }\n}\n```"}], "func_name": "serialize_field", "docstring": "Create an IPC Field from an Arrow Field", "repo": "jorgecarleitao/arrow2", "path": "src/io/ipc/write/schema.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/ipc/write/schema.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "809ad7f2f49e64686039f32a0f9ae66debcd4310ce707d0ce052f86dda8f3449"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start\n\nDocumentation:\nStarts the stream by writing a Schema message to it.\nUse `ipc_fields` to declare dictionary ids in the schema, for dictionary-reuse\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start(&mut self, schema: &Schema, ipc_fields: Option>) -> Result<()> {\n self.ipc_fields = Some(if let Some(ipc_fields) = ipc_fields {\n ipc_fields\n } else {\n default_ipc_fields(&schema.fields)\n });\n\n let encoded_message = EncodedData {\n ipc_message: schema_to_bytes(schema, self.ipc_fields.as_ref().unwrap()),\n arrow_data: vec![],\n };\n write_message(&mut self.writer, &encoded_message)?;\n Ok(())\n }\n```"}], "func_name": "start", "docstring": "Starts the stream by writing a Schema message to it.\nUse `ipc_fields` to declare dictionary ids in the schema, for dictionary-reuse", "repo": "jorgecarleitao/arrow2", "path": "src/io/ipc/write/stream.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/ipc/write/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27a68ef4d39d3c46ff287812b0aa7870f1a185ca4dab2c9249fa530e149b227d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish\n\nDocumentation:\nWrite continuation bytes, and mark the stream as done\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn finish(&mut self) -> Result<()> {\n write_continuation(&mut self.writer, 0)?;\n\n self.finished = true;\n\n Ok(())\n }\n```"}], "func_name": "finish", "docstring": "Write continuation bytes, and mark the stream as done", "repo": "jorgecarleitao/arrow2", "path": "src/io/ipc/write/stream.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/ipc/write/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "373557ae0e02303569296d2ca7dd3ce05bb0889c789e8caff2e4ebed1ad050cd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish\n\nDocumentation:\nWrite footer and closing tag, then mark the writer as done\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn finish(&mut self) -> Result<()> {\n if self.state != State::Started {\n return Err(Error::oos(\n \"The IPC file must be started before it can be finished. Call `start` before `finish`\",\n ));\n }\n\n // write EOS\n write_continuation(&mut self.writer, 0)?;\n\n let schema = schema::serialize_schema(&self.schema, &self.ipc_fields);\n\n let root = arrow_format::ipc::Footer {\n version: arrow_format::ipc::MetadataVersion::V5,\n schema: Some(Box::new(schema)),\n dictionaries: Some(std::mem::take(&mut self.dictionary_blocks)),\n record_batches: Some(std::mem::take(&mut self.record_blocks)),\n custom_metadata: None,\n };\n let mut builder = Builder::new();\n let footer_data = builder.finish(&root, None);\n self.writer.write_all(footer_data)?;\n self.writer\n .write_all(&(footer_data.len() as i32).to_le_bytes())?;\n self.writer.write_all(&ARROW_MAGIC_V2)?;\n self.writer.flush()?;\n self.state = State::Finished;\n\n Ok(())\n }\n```"}], "func_name": "finish", "docstring": "Write footer and closing tag, then mark the writer as done", "repo": "jorgecarleitao/arrow2", "path": "src/io/ipc/write/writer.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/ipc/write/writer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a722e8a8a356e01e0bbe6649cf6452702b50173617cc931928fec6eaab588071"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: coerce_data_type\n\nDocumentation:\nCoerce an heterogeneous set of [`DataType`] into a single one. Rules:\n* The empty set is coerced to `Null`\n* `Int64` and `Float64` are `Float64`\n* Lists and scalars are coerced to a list of a compatible scalar\n* Structs contain the union of all fields\n* All other types are coerced to `Utf8`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn coerce_data_type>(datatypes: &[A]) -> DataType {\n use DataType::*;\n\n if datatypes.is_empty() {\n return DataType::Null;\n }\n\n let are_all_equal = datatypes.windows(2).all(|w| w[0].borrow() == w[1].borrow());\n\n if are_all_equal {\n return datatypes[0].borrow().clone();\n }\n\n let are_all_structs = datatypes.iter().all(|x| matches!(x.borrow(), Struct(_)));\n\n if are_all_structs {\n // all are structs => union of all fields (that may have equal names)\n let fields = datatypes.iter().fold(vec![], |mut acc, dt| {\n if let Struct(new_fields) = dt.borrow() {\n acc.extend(new_fields);\n };\n acc\n });\n // group fields by unique\n let fields = fields.iter().fold(\n HashMap::<&String, HashSet<&DataType>>::new(),\n |mut acc, field| {\n match acc.entry(&field.name) {\n indexmap::map::Entry::Occupied(mut v) => {\n v.get_mut().insert(&field.data_type);\n }\n indexmap::map::Entry::Vacant(v) => {\n let mut a = HashSet::new();\n a.insert(&field.data_type);\n v.insert(a);\n }\n }\n acc\n },\n );\n // and finally, coerce each of the fields within the same name\n let fields = fields\n .into_iter()\n .map(|(name, dts)| {\n let dts = dts.into_iter().collect::>();\n Field::new(name, coerce_data_type(&dts), true)\n })\n .collect();\n return Struct(fields);\n } else if datatypes.len() > 2 {\n return Utf8;\n }\n let (lhs, rhs) = (datatypes[0].borrow(), datatypes[1].borrow());\n\n return match (lhs, rhs) {\n (lhs, rhs) if lhs == rhs => lhs.clone(),\n (List(lhs), List(rhs)) => {\n let inner = coerce_data_type(&[lhs.data_type(), rhs.data_type()]);\n List(Box::new(Field::new(ITEM_NAME, inner, true)))\n }\n (scalar, List(list)) => {\n let inner = coerce_data_type(&[scalar, list.data_type()]);\n List(Box::new(Field::new(ITEM_NAME, inner, true)))\n }\n (List(list), scalar) => {\n let inner = coerce_data_type(&[scalar, list.data_type()]);\n List(Box::new(Field::new(ITEM_NAME, inner, true)))\n }\n (Float64, Int64) => Float64,\n (Int64, Float64) => Float64,\n (Int64, Boolean) => Int64,\n (Boolean, Int64) => Int64,\n (_, _) => Utf8,\n };\n}\n```"}], "func_name": "coerce_data_type", "docstring": "Coerce an heterogeneous set of [`DataType`] into a single one. Rules:\n* The empty set is coerced to `Null`\n* `Int64` and `Float64` are `Float64`\n* Lists and scalars are coerced to a list of a compatible scalar\n* Structs contain the union of all fields\n* All other types are coerced to `Utf8`", "repo": "jorgecarleitao/arrow2", "path": "src/io/json/read/infer_schema.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/json/read/infer_schema.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8531391064a445be3704a0e7f762154b2ff51d6b3ddd36d7185a20aa7341b571"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write\n\nDocumentation:\nWrites valid JSON from an iterator of (assumed JSON-encoded) bytes to `writer`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write(writer: &mut W, mut blocks: I) -> Result<(), Error>\nwhere\n W: std::io::Write,\n I: FallibleStreamingIterator,\n{\n writer.write_all(&[b'['])?;\n let mut is_first_row = true;\n while let Some(block) = blocks.next()? {\n if !is_first_row {\n writer.write_all(&[b','])?;\n }\n is_first_row = false;\n writer.write_all(block)?;\n }\n writer.write_all(&[b']'])?;\n Ok(())\n}\n```"}], "func_name": "write", "docstring": "Writes valid JSON from an iterator of (assumed JSON-encoded) bytes to `writer`", "repo": "jorgecarleitao/arrow2", "path": "src/io/json/write/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/json/write/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c297405f4ae5aeb185474a188379f4ce50b74cae4afffa61a39d2a0fceb37df4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: serialize\n\nDocumentation:\nSerializes `array` to a valid JSON to `buffer`\n# Implementation\nThis operation is CPU-bounded\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn serialize(array: &dyn Array, buffer: &mut Vec) {\n let mut serializer = new_serializer(array, 0, usize::MAX);\n\n (0..array.len()).for_each(|i| {\n if i != 0 {\n buffer.push(b',');\n }\n buffer.extend_from_slice(serializer.next().unwrap());\n });\n}\n```"}], "func_name": "serialize", "docstring": "Serializes `array` to a valid JSON to `buffer`\n# Implementation\nThis operation is CPU-bounded", "repo": "jorgecarleitao/arrow2", "path": "src/io/json/write/serialize.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/json/write/serialize.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ff287fb181ba5c87eb1fc61d12e3014a864f9eaa53c4d05da9ee795f9d670d3c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_metadata\n\nDocumentation:\nParse a `metadata` definition from a JSON representation.\nThe JSON can either be an Object or an Array of Objects.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_metadata(json: &Value) -> Result {\n match json {\n Value::Array(_) => {\n let values: Vec = serde_json::from_value(json.clone())?;\n Ok(values\n .into_iter()\n .map(|key_value| (key_value.key, key_value.value))\n .collect())\n }\n Value::Object(md) => md\n .iter()\n .map(|(k, v)| {\n if let Value::String(v) = v {\n Ok((k.to_string(), v.to_string()))\n } else {\n Err(Error::OutOfSpec(\n \"metadata `value` field must be a string\".to_string(),\n ))\n }\n })\n .collect::>(),\n _ => Err(Error::OutOfSpec(\n \"`metadata` field must be an object\".to_string(),\n )),\n }\n}\n```"}], "func_name": "from_metadata", "docstring": "Parse a `metadata` definition from a JSON representation.\nThe JSON can either be an Object or an Array of Objects.", "repo": "jorgecarleitao/arrow2", "path": "src/io/json_integration/read/schema.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/json_integration/read/schema.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0c3eba2c5568753a6756c63a8474de5b3668d8bd655934fda2b259889d8ac13"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_deserializer\n\nDocumentation:\nConverts a vector of columns associated with the parquet field whose name is [`Field`]\nto an iterator of [`Array`], [`ArrayIter`] of chunk size `chunk_size`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_deserializer<'a>(\n columns: Vec<(&ColumnChunkMetaData, Vec)>,\n field: Field,\n num_rows: usize,\n chunk_size: Option,\n pages: Option>>,\n) -> Result> {\n let chunk_size = chunk_size.map(|c| c.min(num_rows));\n\n let (columns, types) = if let Some(pages) = pages {\n let (columns, types): (Vec<_>, Vec<_>) = columns\n .into_iter()\n .zip(pages.into_iter())\n .map(|((column_meta, chunk), mut pages)| {\n // de-offset the start, since we read in chunks (and offset is from start of file)\n let mut meta: PageMetaData = column_meta.into();\n pages\n .iter_mut()\n .for_each(|page| page.start -= meta.column_start);\n meta.column_start = 0;\n let pages = IndexedPageReader::new_with_page_meta(\n std::io::Cursor::new(chunk),\n meta,\n pages,\n vec![],\n vec![],\n );\n let pages = Box::new(pages) as Pages;\n (\n BasicDecompressor::new(pages, vec![]),\n &column_meta.descriptor().descriptor.primitive_type,\n )\n })\n .unzip();\n\n (columns, types)\n } else {\n let (columns, types): (Vec<_>, Vec<_>) = columns\n .into_iter()\n .map(|(column_meta, chunk)| {\n let len = chunk.len();\n let pages = PageReader::new(\n std::io::Cursor::new(chunk),\n column_meta,\n std::sync::Arc::new(|_, _| true),\n vec![],\n len * 2 + 1024,\n );\n let pages = Box::new(pages) as Pages;\n (\n BasicDecompressor::new(pages, vec![]),\n &column_meta.descriptor().descriptor.primitive_type,\n )\n })\n .unzip();\n\n (columns, types)\n };\n\n column_iter_to_arrays(columns, types, field, chunk_size, num_rows)\n}\n```"}], "func_name": "to_deserializer", "docstring": "Converts a vector of columns associated with the parquet field whose name is [`Field`]\nto an iterator of [`Array`], [`ArrayIter`] of chunk size `chunk_size`.", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/row_group.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/row_group.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f73098078f4bddcea6f74dcd5cf1f12197eaf1a801db945c120b9ca3d9b406fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_columns_many\n\nDocumentation:\nReturns a vector of iterators of [`Array`] ([`ArrayIter`]) corresponding to the top\nlevel parquet fields whose name matches `fields`'s names.\n\n# Implementation\nThis operation is IO-bounded `O(C)` where C is the number of columns in the row group -\nit reads all the columns to memory from the row group associated to the requested fields.\n\nThis operation is single-threaded. For readers with stronger invariants\n(e.g. implement [`Clone`]) you can use [`read_columns`] to read multiple columns at once\nand convert them to [`ArrayIter`] via [`to_deserializer`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_columns_many<'a, R: Read + Seek>(\n reader: &mut R,\n row_group: &RowGroupMetaData,\n fields: Vec,\n chunk_size: Option,\n limit: Option,\n pages: Option>>>,\n) -> Result>> {\n let num_rows = row_group.num_rows();\n let num_rows = limit.map(|limit| limit.min(num_rows)).unwrap_or(num_rows);\n\n // reads all the necessary columns for all fields from the row group\n // This operation is IO-bounded `O(C)` where C is the number of columns in the row group\n let field_columns = fields\n .iter()\n .map(|field| read_columns(reader, row_group.columns(), &field.name))\n .collect::>>()?;\n\n if let Some(pages) = pages {\n field_columns\n .into_iter()\n .zip(fields)\n .zip(pages)\n .map(|((columns, field), pages)| {\n to_deserializer(columns, field, num_rows, chunk_size, Some(pages))\n })\n .collect()\n } else {\n field_columns\n .into_iter()\n .zip(fields.into_iter())\n .map(|(columns, field)| to_deserializer(columns, field, num_rows, chunk_size, None))\n .collect()\n }\n}\n```"}], "func_name": "read_columns_many", "docstring": "Returns a vector of iterators of [`Array`] ([`ArrayIter`]) corresponding to the top\nlevel parquet fields whose name matches `fields`'s names.\n\n# Implementation\nThis operation is IO-bounded `O(C)` where C is the number of columns in the row group -\nit reads all the columns to memory from the row group associated to the requested fields.\n\nThis operation is single-threaded. For readers with stronger invariants\n(e.g. implement [`Clone`]) you can use [`read_columns`] to read multiple columns at once\nand convert them to [`ArrayIter`] via [`to_deserializer`].", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/row_group.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/row_group.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "944d318cba20da0ab7936dd97fbbcb0c7f30eb43ec07f7f801e3a8308a90186b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: column_iter_to_arrays\n\nDocumentation:\nAn iterator adapter that maps multiple iterators of [`Pages`] into an iterator of [`Array`]s.\n\nFor a non-nested datatypes such as [`DataType::Int32`], this function requires a single element in `columns` and `types`.\nFor nested types, `columns` must be composed by all parquet columns with associated types `types`.\n\nThe arrays are guaranteed to be at most of size `chunk_size` and data type `field.data_type`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn column_iter_to_arrays<'a, I: 'a>(\n columns: Vec,\n types: Vec<&PrimitiveType>,\n field: Field,\n chunk_size: Option,\n num_rows: usize,\n) -> Result>\nwhere\n I: Pages,\n{\n Ok(Box::new(\n columns_to_iter_recursive(columns, types, field, vec![], num_rows, chunk_size)?\n .map(|x| x.map(|x| x.1)),\n ))\n}\n```"}], "func_name": "column_iter_to_arrays", "docstring": "An iterator adapter that maps multiple iterators of [`Pages`] into an iterator of [`Array`]s.\n\nFor a non-nested datatypes such as [`DataType::Int32`], this function requires a single element in `columns` and `types`.\nFor nested types, `columns` must be composed by all parquet columns with associated types `types`.\n\nThe arrays are guaranteed to be at most of size `chunk_size` and data type `field.data_type`.", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/deserialize/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/deserialize/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b86efeee1794df0e006dfabeee8264b5889ca0cb580343e542296f0774323a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: nested_column_iter_to_arrays\n\nDocumentation:\nBasically the same as `column_iter_to_arrays`, with the addition of the `init` parameter\nto read the inner columns of the nested type directly, instead of reading the entire nested type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn nested_column_iter_to_arrays<'a, I: 'a>(\n columns: Vec,\n types: Vec<&PrimitiveType>,\n field: Field,\n init: Vec,\n chunk_size: Option,\n num_rows: usize,\n) -> Result>\nwhere\n I: Pages,\n{\n Ok(Box::new(\n nested::columns_to_iter_recursive(columns, types, field, init, num_rows, chunk_size)?\n .map(|x| x.map(|x| x.1)),\n ))\n}\n```"}], "func_name": "nested_column_iter_to_arrays", "docstring": "Basically the same as `column_iter_to_arrays`, with the addition of the `init` parameter\nto read the inner columns of the nested type directly, instead of reading the entire nested type.", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/deserialize/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/deserialize/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "55fb800ffbb2775846bb6cf8f05c219d279fb11c4937ddade4f006dce4dbb241"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extend\n\nDocumentation:\nExtends `items` by consuming `page`, first trying to complete the last `item`\nand extending it if more are needed\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn extend<'a, D: NestedDecoder<'a>>(\n page: &'a DataPage,\n init: &[InitNested],\n items: &mut VecDeque<(NestedState, D::DecodedState)>,\n dict: Option<&'a D::Dictionary>,\n remaining: &mut usize,\n decoder: &D,\n chunk_size: Option,\n) -> Result<()> {\n let mut values_page = decoder.build_state(page, dict)?;\n let mut page = NestedPage::try_new(page)?;\n\n let capacity = chunk_size.unwrap_or(0);\n // chunk_size = None, remaining = 44 => chunk_size = 44\n let chunk_size = chunk_size.unwrap_or(usize::MAX);\n\n let (mut nested, mut decoded) = if let Some((nested, decoded)) = items.pop_back() {\n (nested, decoded)\n } else {\n // there is no state => initialize it\n (init_nested(init, capacity), decoder.with_capacity(0))\n };\n let existing = nested.len();\n\n let additional = (chunk_size - existing).min(*remaining);\n\n // extend the current state\n extend_offsets2(\n &mut page,\n &mut values_page,\n &mut nested.nested,\n &mut decoded,\n decoder,\n additional,\n )?;\n *remaining -= nested.len() - existing;\n items.push_back((nested, decoded));\n\n while page.len() > 0 && *remaining > 0 {\n let additional = chunk_size.min(*remaining);\n\n let mut nested = init_nested(init, additional);\n let mut decoded = decoder.with_capacity(0);\n extend_offsets2(\n &mut page,\n &mut values_page,\n &mut nested.nested,\n &mut decoded,\n decoder,\n additional,\n )?;\n *remaining -= nested.len();\n items.push_back((nested, decoded));\n }\n Ok(())\n}\n```"}], "func_name": "extend", "docstring": "Extends `items` by consuming `page`, first trying to complete the last `item`\nand extending it if more are needed", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/deserialize/nested_utils.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/deserialize/nested_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f7eba3bf3013681f056643718867695966f411d0546820b0b95be03bd097b86b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: page_iter_to_arrays\n\nDocumentation:\nAn iterator adapter that maps an iterator of Pages into an iterator of Arrays\nof [`DataType`] `data_type` and length `chunk_size`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn page_iter_to_arrays<'a, I: Pages + 'a>(\n pages: I,\n type_: &PrimitiveType,\n data_type: DataType,\n chunk_size: Option,\n num_rows: usize,\n) -> Result> {\n use DataType::*;\n\n let physical_type = &type_.physical_type;\n let logical_type = &type_.logical_type;\n\n Ok(match (physical_type, data_type.to_logical_type()) {\n (_, Null) => null::iter_to_arrays(pages, data_type, chunk_size, num_rows),\n (PhysicalType::Boolean, Boolean) => {\n dyn_iter(boolean::Iter::new(pages, data_type, chunk_size, num_rows))\n }\n (PhysicalType::Int32, UInt8) => dyn_iter(iden(primitive::IntegerIter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: i32| x as u8,\n ))),\n (PhysicalType::Int32, UInt16) => dyn_iter(iden(primitive::IntegerIter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: i32| x as u16,\n ))),\n (PhysicalType::Int32, UInt32) => dyn_iter(iden(primitive::IntegerIter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: i32| x as u32,\n ))),\n (PhysicalType::Int64, UInt32) => dyn_iter(iden(primitive::IntegerIter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: i64| x as u32,\n ))),\n (PhysicalType::Int32, Int8) => dyn_iter(iden(primitive::IntegerIter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: i32| x as i8,\n ))),\n (PhysicalType::Int32, Int16) => dyn_iter(iden(primitive::IntegerIter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: i32| x as i16,\n ))),\n (PhysicalType::Int32, Int32 | Date32 | Time32(_)) => dyn_iter(iden(\n primitive::IntegerIter::new(pages, data_type, num_rows, chunk_size, |x: i32| x),\n )),\n (PhysicalType::Int64 | PhysicalType::Int96, Timestamp(time_unit, _)) => {\n let time_unit = *time_unit;\n return timestamp(\n pages,\n physical_type,\n logical_type,\n data_type,\n num_rows,\n chunk_size,\n time_unit,\n );\n }\n (PhysicalType::FixedLenByteArray(_), FixedSizeBinary(_)) => dyn_iter(\n fixed_size_binary::Iter::new(pages, data_type, num_rows, chunk_size),\n ),\n (PhysicalType::FixedLenByteArray(12), Interval(IntervalUnit::YearMonth)) => {\n let n = 12;\n let pages = fixed_size_binary::Iter::new(\n pages,\n DataType::FixedSizeBinary(n),\n num_rows,\n chunk_size,\n );\n\n let pages = pages.map(move |maybe_array| {\n let array = maybe_array?;\n let values = array\n .values()\n .chunks_exact(n)\n .map(|value: &[u8]| i32::from_le_bytes(value[..4].try_into().unwrap()))\n .collect::>();\n let validity = array.validity().cloned();\n\n PrimitiveArray::::try_new(data_type.clone(), values.into(), validity)\n });\n\n let arrays = pages.map(|x| x.map(|x| x.boxed()));\n\n Box::new(arrays) as _\n }\n (PhysicalType::FixedLenByteArray(12), Interval(IntervalUnit::DayTime)) => {\n let n = 12;\n let pages = fixed_size_binary::Iter::new(\n pages,\n DataType::FixedSizeBinary(n),\n num_rows,\n chunk_size,\n );\n\n let pages = pages.map(move |maybe_array| {\n let array = maybe_array?;\n let values = array\n .values()\n .chunks_exact(n)\n .map(super::super::convert_days_ms)\n .collect::>();\n let validity = array.validity().cloned();\n\n PrimitiveArray::::try_new(data_type.clone(), values.into(), validity)\n });\n\n let arrays = pages.map(|x| x.map(|x| x.boxed()));\n\n Box::new(arrays) as _\n }\n (PhysicalType::Int32, Decimal(_, _)) => dyn_iter(iden(primitive::IntegerIter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: i32| x as i128,\n ))),\n (PhysicalType::Int64, Decimal(_, _)) => dyn_iter(iden(primitive::IntegerIter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: i64| x as i128,\n ))),\n (PhysicalType::FixedLenByteArray(n), Decimal(_, _)) if *n > 16 => {\n return Err(Error::NotYetImplemented(format!(\n \"Can't decode Decimal128 type from Fixed Size Byte Array of len {n:?}\"\n )))\n }\n (PhysicalType::FixedLenByteArray(n), Decimal(_, _)) => {\n let n = *n;\n\n let pages = fixed_size_binary::Iter::new(\n pages,\n DataType::FixedSizeBinary(n),\n num_rows,\n chunk_size,\n );\n\n let pages = pages.map(move |maybe_array| {\n let array = maybe_array?;\n let values = array\n .values()\n .chunks_exact(n)\n .map(|value: &[u8]| super::super::convert_i128(value, n))\n .collect::>();\n let validity = array.validity().cloned();\n\n PrimitiveArray::::try_new(data_type.clone(), values.into(), validity)\n });\n\n let arrays = pages.map(|x| x.map(|x| x.boxed()));\n\n Box::new(arrays) as _\n }\n (PhysicalType::Int32, Decimal256(_, _)) => dyn_iter(iden(primitive::IntegerIter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: i32| i256(I256::new(x as i128)),\n ))),\n (PhysicalType::Int64, Decimal256(_, _)) => dyn_iter(iden(primitive::IntegerIter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: i64| i256(I256::new(x as i128)),\n ))),\n (PhysicalType::FixedLenByteArray(n), Decimal256(_, _)) if *n <= 16 => {\n let n = *n;\n\n let pages = fixed_size_binary::Iter::new(\n pages,\n DataType::FixedSizeBinary(n),\n num_rows,\n chunk_size,\n );\n\n let pages = pages.map(move |maybe_array| {\n let array = maybe_array?;\n let values = array\n .values()\n .chunks_exact(n)\n .map(|value: &[u8]| i256(I256::new(super::super::convert_i128(value, n))))\n .collect::>();\n let validity = array.validity().cloned();\n\n PrimitiveArray::::try_new(data_type.clone(), values.into(), validity)\n });\n\n let arrays = pages.map(|x| x.map(|x| x.boxed()));\n\n Box::new(arrays) as _\n }\n (PhysicalType::FixedLenByteArray(n), Decimal256(_, _)) if *n <= 32 => {\n let n = *n;\n\n let pages = fixed_size_binary::Iter::new(\n pages,\n DataType::FixedSizeBinary(n),\n num_rows,\n chunk_size,\n );\n\n let pages = pages.map(move |maybe_array| {\n let array = maybe_array?;\n let values = array\n .values()\n .chunks_exact(n)\n .map(super::super::convert_i256)\n .collect::>();\n let validity = array.validity().cloned();\n\n PrimitiveArray::::try_new(data_type.clone(), values.into(), validity)\n });\n\n let arrays = pages.map(|x| x.map(|x| x.boxed()));\n\n Box::new(arrays) as _\n }\n (PhysicalType::FixedLenByteArray(n), Decimal256(_, _)) if *n > 32 => {\n return Err(Error::NotYetImplemented(format!(\n \"Can't decode Decimal256 type from Fixed Size Byte Array of len {n:?}\"\n )))\n }\n (PhysicalType::Int32, Date64) => dyn_iter(iden(primitive::IntegerIter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: i32| x as i64 * 86400000,\n ))),\n (PhysicalType::Int64, Date64) => dyn_iter(iden(primitive::IntegerIter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: i64| x,\n ))),\n (PhysicalType::Int64, Int64 | Time64(_) | Duration(_)) => dyn_iter(iden(\n primitive::IntegerIter::new(pages, data_type, num_rows, chunk_size, |x: i64| x),\n )),\n (PhysicalType::Int64, UInt64) => dyn_iter(iden(primitive::IntegerIter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: i64| x as u64,\n ))),\n (PhysicalType::Float, Float32) => dyn_iter(iden(primitive::Iter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: f32| x,\n ))),\n (PhysicalType::Double, Float64) => dyn_iter(iden(primitive::Iter::new(\n pages,\n data_type,\n num_rows,\n chunk_size,\n |x: f64| x,\n ))),\n\n (PhysicalType::ByteArray, Utf8 | Binary) => Box::new(binary::Iter::::new(\n pages, data_type, chunk_size, num_rows,\n )),\n (PhysicalType::ByteArray, LargeBinary | LargeUtf8) => Box::new(\n binary::Iter::::new(pages, data_type, chunk_size, num_rows),\n ),\n\n (_, Dictionary(key_type, _, _)) => {\n return match_integer_type!(key_type, |$K| {\n dict_read::<$K, _>(pages, physical_type, logical_type, data_type, num_rows, chunk_size)\n })\n }\n (from, to) => {\n return Err(Error::NotYetImplemented(format!(\n \"Reading parquet type {from:?} to {to:?} still not implemented\"\n )))\n }\n })\n}\n```"}], "func_name": "page_iter_to_arrays", "docstring": "An iterator adapter that maps an iterator of Pages into an iterator of Arrays\nof [`DataType`] `data_type` and length `chunk_size`.", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/deserialize/simple.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/deserialize/simple.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b3c36f4fffdaeedfa050e5778922cfced6861a8b09d96b7c981ae2e90c7facc8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parquet_to_arrow_schema\n\nDocumentation:\nConverts [`ParquetType`]s to a [`Field`], ignoring parquet fields that do not contain\nany physical column.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parquet_to_arrow_schema(fields: &[ParquetType]) -> Vec {\n parquet_to_arrow_schema_with_options(fields, &None)\n}\n```"}], "func_name": "parquet_to_arrow_schema", "docstring": "Converts [`ParquetType`]s to a [`Field`], ignoring parquet fields that do not contain\nany physical column.", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/schema/convert.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/schema/convert.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b63d17578da90c1e9ce326e723d7938c704c0ca25782705f84028a368649f42"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parquet_to_arrow_schema_with_options\n\nDocumentation:\nLike [`parquet_to_arrow_schema`] but with configurable options which affect the behavior of schema inference\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parquet_to_arrow_schema_with_options(\n fields: &[ParquetType],\n options: &Option,\n) -> Vec {\n fields\n .iter()\n .filter_map(|f| to_field(f, options.as_ref().unwrap_or(&Default::default())))\n .collect::>()\n}\n```"}], "func_name": "parquet_to_arrow_schema_with_options", "docstring": "Like [`parquet_to_arrow_schema`] but with configurable options which affect the behavior of schema inference", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/schema/convert.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/schema/convert.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "317c7946fa1818b82fb21296538afb6940b212368eebdb36e649c5a0c5a4e126"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_primitive_type_inner\n\nDocumentation:\nMaps a [`PhysicalType`] with optional metadata to a [`DataType`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn to_primitive_type_inner(\n primitive_type: &PrimitiveType,\n options: &SchemaInferenceOptions,\n) -> DataType {\n match primitive_type.physical_type {\n PhysicalType::Boolean => DataType::Boolean,\n PhysicalType::Int32 => {\n from_int32(primitive_type.logical_type, primitive_type.converted_type)\n }\n PhysicalType::Int64 => {\n from_int64(primitive_type.logical_type, primitive_type.converted_type)\n }\n PhysicalType::Int96 => DataType::Timestamp(options.int96_coerce_to_timeunit, None),\n PhysicalType::Float => DataType::Float32,\n PhysicalType::Double => DataType::Float64,\n PhysicalType::ByteArray => {\n from_byte_array(&primitive_type.logical_type, &primitive_type.converted_type)\n }\n PhysicalType::FixedLenByteArray(length) => from_fixed_len_byte_array(\n length,\n primitive_type.logical_type,\n primitive_type.converted_type,\n ),\n }\n}\n```"}], "func_name": "to_primitive_type_inner", "docstring": "Maps a [`PhysicalType`] with optional metadata to a [`DataType`]", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/schema/convert.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/schema/convert.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac9b5369922aff20eb343ccf4f3895b007af1a5aaf5da90ed53387078e434f2a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_group_type\n\nDocumentation:\nEntry point for converting parquet group type.\n\nThis function takes care of logical type and repetition.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn to_group_type(\n field_info: &FieldInfo,\n logical_type: &Option,\n converted_type: &Option,\n fields: &[ParquetType],\n parent_name: &str,\n options: &SchemaInferenceOptions,\n) -> Option {\n debug_assert!(!fields.is_empty());\n if field_info.repetition == Repetition::Repeated {\n Some(DataType::List(Box::new(Field::new(\n &field_info.name,\n to_struct(fields, options)?,\n is_nullable(field_info),\n ))))\n } else {\n non_repeated_group(logical_type, converted_type, fields, parent_name, options)\n }\n}\n```"}], "func_name": "to_group_type", "docstring": "Entry point for converting parquet group type.\n\nThis function takes care of logical type and repetition.", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/schema/convert.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/schema/convert.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c11798e97cc4e85a23ae25a4e57ad3084b69367dac5516deabbbdac8227e07d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_nullable\n\nDocumentation:\nChecks whether this schema is nullable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn is_nullable(field_info: &FieldInfo) -> bool {\n match field_info.repetition {\n Repetition::Optional => true,\n Repetition::Repeated => false,\n Repetition::Required => false,\n }\n}\n```"}], "func_name": "is_nullable", "docstring": "Checks whether this schema is nullable.", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/schema/convert.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/schema/convert.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2497d8c3c8f39c3bb2e70815590d0b3ec271f8095accfbbde7007ba3e6eaf966"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_arrow_schema_from_metadata\n\nDocumentation:\nTry to convert Arrow schema metadata into a schema\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_arrow_schema_from_metadata(encoded_meta: &str) -> Result {\n let decoded = general_purpose::STANDARD.decode(encoded_meta);\n match decoded {\n Ok(bytes) => {\n let slice = if bytes[0..4] == [255u8; 4] {\n &bytes[8..]\n } else {\n bytes.as_slice()\n };\n deserialize_schema(slice).map(|x| x.0)\n }\n Err(err) => {\n // The C++ implementation returns an error if the schema can't be parsed.\n Err(Error::InvalidArgumentError(format!(\n \"Unable to decode the encoded schema stored in {ARROW_SCHEMA_META_KEY}, {err:?}\"\n )))\n }\n }\n}\n```"}], "func_name": "get_arrow_schema_from_metadata", "docstring": "Try to convert Arrow schema metadata into a schema", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/schema/metadata.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/schema/metadata.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d52926e85f1dcf29bc5483b62c75671eb8f80dcf4958b6ff371845cbf8211005"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: infer_schema\n\nDocumentation:\nInfers a [`Schema`] from parquet's [`FileMetaData`]. This first looks for the metadata key\n`\"ARROW:schema\"`; if it does not exist, it converts the parquet types declared in the\nfile's parquet schema to Arrow's equivalent.\n# Error\nThis function errors iff the key `\"ARROW:schema\"` exists but is not correctly encoded,\nindicating that that the file's arrow metadata was incorrectly written.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn infer_schema(file_metadata: &FileMetaData) -> Result {\n infer_schema_with_options(file_metadata, &None)\n}\n```"}], "func_name": "infer_schema", "docstring": "Infers a [`Schema`] from parquet's [`FileMetaData`]. This first looks for the metadata key\n`\"ARROW:schema\"`; if it does not exist, it converts the parquet types declared in the\nfile's parquet schema to Arrow's equivalent.\n# Error\nThis function errors iff the key `\"ARROW:schema\"` exists but is not correctly encoded,\nindicating that that the file's arrow metadata was incorrectly written.", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/schema/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/schema/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "10449fe8e941dff7955856dd4cca5b95460cdfb2c854de0d66ce564d1d0de88f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: infer_schema_with_options\n\nDocumentation:\nLike [`infer_schema`] but with configurable options which affects the behavior of inference\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn infer_schema_with_options(\n file_metadata: &FileMetaData,\n options: &Option,\n) -> Result {\n let mut metadata = parse_key_value_metadata(file_metadata.key_value_metadata());\n\n let schema = read_schema_from_metadata(&mut metadata)?;\n Ok(schema.unwrap_or_else(|| {\n let fields = parquet_to_arrow_schema_with_options(file_metadata.schema().fields(), options);\n Schema { fields, metadata }\n }))\n}\n```"}], "func_name": "infer_schema_with_options", "docstring": "Like [`infer_schema`] but with configurable options which affects the behavior of inference", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/read/schema/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/read/schema/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "41ca965566cc2a5b1c529cb0cecef539b4197d1ef77a126f2dfb7bef45220d6c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: array_to_columns\n\nDocumentation:\nReturns a vector of iterators of [`Page`], one per leaf column in the array\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn array_to_columns + Send + Sync>(\n array: A,\n type_: ParquetType,\n options: WriteOptions,\n encoding: &[Encoding],\n) -> Result>>> {\n let array = array.as_ref();\n let nested = to_nested(array, &type_)?;\n\n let types = to_parquet_leaves(type_);\n\n let values = to_leaves(array);\n\n assert_eq!(encoding.len(), types.len());\n\n values\n .iter()\n .zip(nested.into_iter())\n .zip(types.into_iter())\n .zip(encoding.iter())\n .map(|(((values, nested), type_), encoding)| {\n array_to_pages(*values, type_, &nested, options, *encoding)\n })\n .collect()\n}\n```"}], "func_name": "array_to_columns", "docstring": "Returns a vector of iterators of [`Page`], one per leaf column in the array", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/write/pages.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/write/pages.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a324b9696645551fd65f253e34ed8a8f43a29ded72367ad12f0fdc940bd48a5b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: row_group_iter\n\nDocumentation:\nMaps a [`Chunk`] and parquet-specific options to an [`RowGroupIter`] used to\nwrite to parquet\n# Panics\nIff\n* `encodings.len() != fields.len()` or\n* `encodings.len() != chunk.arrays().len()`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn row_group_iter + 'static + Send + Sync>(\n chunk: Chunk,\n encodings: Vec>,\n fields: Vec,\n options: WriteOptions,\n) -> RowGroupIter<'static, Error> {\n assert_eq!(encodings.len(), fields.len());\n assert_eq!(encodings.len(), chunk.arrays().len());\n DynIter::new(\n chunk\n .into_arrays()\n .into_iter()\n .zip(fields.into_iter())\n .zip(encodings.into_iter())\n .flat_map(move |((array, type_), encoding)| {\n let encoded_columns = array_to_columns(array, type_, options, &encoding).unwrap();\n encoded_columns\n .into_iter()\n .map(|encoded_pages| {\n let pages = encoded_pages;\n\n let pages = DynIter::new(\n pages\n .into_iter()\n .map(|x| x.map_err(|e| ParquetError::OutOfSpec(e.to_string()))),\n );\n\n let compressed_pages = Compressor::new(pages, options.compression, vec![])\n .map_err(Error::from);\n Ok(DynStreamingIterator::new(compressed_pages))\n })\n .collect::>()\n }),\n )\n}\n```"}], "func_name": "row_group_iter", "docstring": "Maps a [`Chunk`] and parquet-specific options to an [`RowGroupIter`] used to\nwrite to parquet\n# Panics\nIff\n* `encodings.len() != fields.len()` or\n* `encodings.len() != chunk.arrays().len()`", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/write/row_group.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/write/row_group.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "605026d73d9e145cf23794c18833ee8a5d89a2ce712d6e691373f2ef5f49d583"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: num_values\n\nDocumentation:\nreturn number values of the nested\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn num_values(nested: &[Nested]) -> usize {\n let pr = match nested.last().unwrap() {\n Nested::Primitive(_, _, len) => *len,\n _ => todo!(),\n };\n\n iter(nested)\n .into_iter()\n .enumerate()\n .map(|(_, lengths)| {\n lengths\n .map(|length| if length == 0 { 1 } else { 0 })\n .sum::()\n })\n .sum::()\n + pr\n}\n```"}], "func_name": "num_values", "docstring": "return number values of the nested", "repo": "jorgecarleitao/arrow2", "path": "src/io/parquet/write/nested/rep.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/io/parquet/write/nested/rep.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8e5854447f928eb012e5410613b766621942b676cf06ce7941228babde51195b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_primitive_array\n\nDocumentation:\nCreates an random (but fixed-seeded) array of a given size and null density\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_primitive_array(size: usize, null_density: f32) -> PrimitiveArray\nwhere\n T: NativeType,\n Standard: Distribution,\n{\n let mut rng = seedable_rng();\n\n (0..size)\n .map(|_| {\n if rng.gen::() < null_density {\n None\n } else {\n Some(rng.gen())\n }\n })\n .collect::>()\n}\n```"}], "func_name": "create_primitive_array", "docstring": "Creates an random (but fixed-seeded) array of a given size and null density", "repo": "jorgecarleitao/arrow2", "path": "src/util/bench_util.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/src/util/bench_util.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b5ef57ff5e8552f9cb582e0923035d1264bbe135d4c415c532614060e38b1dd3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_fixed_size_list_array\n\nDocumentation:\nCreate a fixed size list of 2 value lengths\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn create_fixed_size_list_array, T: AsRef<[Option]>>(\n data: T,\n) -> FixedSizeListArray {\n let data = data.as_ref().iter().map(|x| {\n Some(match x {\n Some(x) => x.as_ref().iter().map(|x| Some(*x)).collect::>(),\n None => std::iter::repeat(None).take(3).collect::>(),\n })\n });\n\n let mut list = MutableFixedSizeListArray::new(MutablePrimitiveArray::::new(), 3);\n list.try_extend(data).unwrap();\n list.into()\n}\n```"}], "func_name": "create_fixed_size_list_array", "docstring": "Create a fixed size list of 2 value lengths", "repo": "jorgecarleitao/arrow2", "path": "tests/it/array/equal/fixed_size_list.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/tests/it/array/equal/fixed_size_list.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be5813a46135937f659a7582ca8551ebb0dcf1a2792afffca6dde7cb0d7e91c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bitmap_strategy\n\nDocumentation:\nReturns a strategy of an arbitrary sliced [`Bitmap`] of size up to 1000\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn bitmap_strategy() -> impl Strategy {\n prop::collection::vec(any::(), 1..1000)\n .prop_flat_map(|vec| {\n let len = vec.len();\n (Just(vec), 0..len)\n })\n .prop_flat_map(|(vec, index)| {\n let len = vec.len();\n (Just(vec), Just(index), 0..len - index)\n })\n .prop_flat_map(|(vec, index, len)| {\n let bitmap = Bitmap::from(&vec);\n let bitmap = bitmap.sliced(index, len);\n Just(bitmap)\n })\n}\n```"}], "func_name": "bitmap_strategy", "docstring": "Returns a strategy of an arbitrary sliced [`Bitmap`] of size up to 1000", "repo": "jorgecarleitao/arrow2", "path": "tests/it/bitmap/mod.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/tests/it/bitmap/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2103b9199f898a3c0a1e5fd49acdc2d5adfb13b6c10e96896a72864df2a6643a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pages\n\nDocumentation:\nReturns 2 sets of pages with different the same number of rows distributed un-evenly\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn pages(arrays: &[&dyn Array], encoding: Encoding) -> Result<(Vec, Vec, Schema)> {\n // create pages with different number of rows\n let array11 = PrimitiveArray::::from_slice([1, 2, 3, 4]);\n let array12 = PrimitiveArray::::from_slice([5]);\n let array13 = PrimitiveArray::::from_slice([6]);\n\n let schema = Schema::from(vec![\n Field::new(\"a1\", DataType::Int64, false),\n Field::new(\n \"a2\",\n arrays[0].data_type().clone(),\n arrays.iter().map(|x| x.null_count()).sum::() != 0usize,\n ),\n ]);\n\n let parquet_schema = to_parquet_schema(&schema)?;\n\n let options = WriteOptions {\n write_statistics: true,\n compression: CompressionOptions::Uncompressed,\n version: Version::V1,\n data_pagesize_limit: None,\n };\n\n let pages1 = [array11, array12, array13]\n .into_iter()\n .map(|array| {\n array_to_page(\n &array,\n parquet_schema.columns()[0]\n .descriptor\n .primitive_type\n .clone(),\n &[Nested::Primitive(None, true, array.len())],\n options,\n Encoding::Plain,\n )\n })\n .collect::>>()?;\n\n let pages2 = arrays\n .iter()\n .flat_map(|array| {\n array_to_pages(\n *array,\n parquet_schema.columns()[1]\n .descriptor\n .primitive_type\n .clone(),\n &[Nested::Primitive(None, true, array.len())],\n options,\n encoding,\n )\n .unwrap()\n .collect::>>()\n .unwrap()\n })\n .collect::>();\n\n Ok((pages1, pages2, schema))\n}\n```"}], "func_name": "pages", "docstring": "Returns 2 sets of pages with different the same number of rows distributed un-evenly", "repo": "jorgecarleitao/arrow2", "path": "tests/it/io/parquet/read_indexes.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/tests/it/io/parquet/read_indexes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "066d7d47c524b8490daad3ff86fc993fb7424dbf741695bf92b155938f2b5e69"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_with_indexes\n\nDocumentation:\nTests reading pages while skipping indexes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_with_indexes(\n (pages1, pages2, schema): (Vec, Vec, Schema),\n expected: Box,\n) -> Result<()> {\n let options = WriteOptions {\n write_statistics: true,\n compression: CompressionOptions::Uncompressed,\n version: Version::V1,\n data_pagesize_limit: None,\n };\n\n let to_compressed = |pages: Vec| {\n let encoded_pages = DynIter::new(pages.into_iter().map(Ok));\n let compressed_pages =\n Compressor::new(encoded_pages, options.compression, vec![]).map_err(Error::from);\n Result::Ok(DynStreamingIterator::new(compressed_pages))\n };\n\n let row_group = DynIter::new(vec![to_compressed(pages1), to_compressed(pages2)].into_iter());\n\n let writer = vec![];\n let mut writer = FileWriter::try_new(writer, schema, options)?;\n\n writer.write(row_group)?;\n writer.end(None)?;\n let data = writer.into_inner();\n\n let mut reader = Cursor::new(data);\n\n let metadata = read_metadata(&mut reader)?;\n\n let schema = infer_schema(&metadata)?;\n\n // row group-based filtering can be done here\n let row_groups = metadata.row_groups;\n\n // one per row group\n let pages = row_groups\n .iter()\n .map(|row_group| {\n assert!(indexes::has_indexes(row_group));\n\n indexes::read_filtered_pages(&mut reader, row_group, &schema.fields, |_, intervals| {\n let first_field = &intervals[0];\n let first_field_column = &first_field[0];\n assert_eq!(first_field_column.len(), 3);\n let selection = [false, true, false];\n\n first_field_column\n .iter()\n .zip(selection)\n .filter_map(|(i, is_selected)| is_selected.then(|| *i))\n .collect()\n })\n })\n .collect::>>()?;\n\n // apply projection pushdown\n let schema = schema.filter(|index, _| index == 1);\n let pages = pages\n .into_iter()\n .map(|pages| {\n pages\n .into_iter()\n .enumerate()\n .filter(|(index, _)| *index == 1)\n .map(|(_, pages)| pages)\n .collect::>()\n })\n .collect::>();\n\n let expected = Chunk::new(vec![expected]);\n\n let chunks = FileReader::new(\n reader,\n row_groups,\n schema,\n Some(1024 * 8 * 8),\n None,\n Some(pages),\n );\n\n let arrays = chunks.collect::>>()?;\n\n assert_eq!(arrays, vec![expected]);\n Ok(())\n}\n```"}], "func_name": "read_with_indexes", "docstring": "Tests reading pages while skipping indexes", "repo": "jorgecarleitao/arrow2", "path": "tests/it/io/parquet/read_indexes.rs", "url": "https://github.com/jorgecarleitao/arrow2/blob/master/tests/it/io/parquet/read_indexes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "af610e319af9d329a97b724e2324b60071698f9afef3082cf650dbe08d31c1c0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_leeway\n\nDocumentation:\nConstructs a new [`Deduper`] that will skip duplicated entries after\nsome record has been received for the consecutive times specified by\n`leeway`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_leeway(leeway: NonZeroUsize) -> Self {\n Self {\n deduper: Mutex::new(Deduper::with_leeway(leeway)),\n }\n }\n```"}], "func_name": "with_leeway", "docstring": "Constructs a new [`Deduper`] that will skip duplicated entries after\nsome record has been received for the consecutive times specified by\n`leeway`.", "repo": "emabee/flexi_logger", "path": "examples/dedup.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/examples/dedup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "007f9cfc842021fcfe8fafc33078163158d27997b6e2f3956709ae8ab1d19fe9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dedup\n\nDocumentation:\nReturns wether a record should be skipped or allowed.\n\nSee [`DedupAction`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn dedup(&mut self, record: &Record) -> DedupAction {\n let new_line = record.line();\n let new_file = record.file();\n let new_msg = record.args().to_string();\n if new_line == self.last_record.line\n && new_file == self.last_record.file.as_deref()\n && new_msg == self.last_record.msg\n {\n // Update dups count\n if let Some(updated_dups) = self.duplicates.checked_add(1) {\n self.duplicates = updated_dups;\n } else {\n let skipped = self.duplicates - self.leeway();\n self.duplicates = 0;\n return DedupAction::AllowAfterSkipped(skipped);\n }\n\n match self.duplicates.cmp(&self.leeway()) {\n Ordering::Less => DedupAction::Allow,\n Ordering::Equal => DedupAction::AllowLastOfLeeway(self.leeway()),\n Ordering::Greater => DedupAction::Skip,\n }\n } else {\n // Update last record\n self.last_record.file = new_file.map(ToOwned::to_owned);\n self.last_record.line = new_line;\n self.last_record.msg = new_msg;\n\n let dups = self.duplicates;\n self.duplicates = 0;\n\n match dups {\n n if n > self.leeway() => DedupAction::AllowAfterSkipped(n - self.leeway()),\n _ => DedupAction::Allow,\n }\n }\n }\n```"}], "func_name": "dedup", "docstring": "Returns wether a record should be skipped or allowed.\n\nSee [`DedupAction`].", "repo": "emabee/flexi_logger", "path": "examples/dedup.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/examples/dedup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3b7029a4601407a1c7e37d4ca44a65cf452888c25506ec4f4408e4322a966e2c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: format\n\nDocumentation:\nProduces a preformatted object suitable for printing.\n\n# Panics\n\nPanics if `fmt` has an inappropriate value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn format<'b>(&'a mut self, fmt: &'b str) -> DelayedFormat> {\n if use_utc() {\n self.now_utc_owned().format(fmt)\n } else {\n self.now().format(fmt)\n }\n }\n```"}], "func_name": "format", "docstring": "Produces a preformatted object suitable for printing.\n\n# Panics\n\nPanics if `fmt` has an inappropriate value.", "repo": "emabee/flexi_logger", "path": "src/deferred_now.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/deferred_now.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "21eaaa1a0ccc2305ee3311741a30ab1ade59cbdf671cbd233bbf5d9070ab9b5a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: format_rfc3339\n\nDocumentation:\nPrints itself in a format compliant with RFC 3339.\n\nExample: 2021-04-29T13:14:15.678+01:00\n\nWe do not use the Z variant of RFC 3339, because it is often misinterpreted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn format_rfc3339(&mut self) -> String {\n if use_utc() {\n self.now_utc_owned()\n .to_rfc3339_opts(SecondsFormat::Millis, false)\n } else {\n self.now().to_rfc3339_opts(SecondsFormat::Millis, false)\n }\n }\n```"}], "func_name": "format_rfc3339", "docstring": "Prints itself in a format compliant with RFC 3339.\n\nExample: 2021-04-29T13:14:15.678+01:00\n\nWe do not use the Z variant of RFC 3339, because it is often misinterpreted.", "repo": "emabee/flexi_logger", "path": "src/deferred_now.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/deferred_now.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e208719252a874b9c84b0080e59ab0a14153d772aaec9ce7ca6db3337e46ee55"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: force_utc\n\nDocumentation:\nEnforce the use of UTC rather than local time.\n\nBy default, `flexi_logger` uses or tries to use local time.\nBy calling early in your program either `Logger::use_utc()` or directly this method,\nyou can override this to always use UTC.\n\n# Panics\n\nPanics if called too late, i.e., if [`DeferredNow::now`] was already called before on\nany instance of `DeferredNow`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn force_utc() {\n let mut cfg_force_utc = cfg_force_utc().lock().unwrap();\n match *cfg_force_utc {\n Some(false) => {\n panic!(\"offset is already initialized not to enforce UTC\");\n }\n Some(true) => {\n // is already set, nothing to do\n }\n None => *cfg_force_utc = Some(true),\n }\n }\n```"}], "func_name": "force_utc", "docstring": "Enforce the use of UTC rather than local time.\n\nBy default, `flexi_logger` uses or tries to use local time.\nBy calling early in your program either `Logger::use_utc()` or directly this method,\nyou can override this to always use UTC.\n\n# Panics\n\nPanics if called too late, i.e., if [`DeferredNow::now`] was already called before on\nany instance of `DeferredNow`.", "repo": "emabee/flexi_logger", "path": "src/deferred_now.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/deferred_now.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9f7dc0dad2274e02a2763fd271f18494530a417be86caec217eb304253ec7266"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_format\n\nDocumentation:\nA logline-formatter that produces log lines like
\n```INFO [my_prog::some_submodule] Task successfully read from conf.json```.\n\nIf the kv-feature is used, the log lines look like\n```INFO [my_prog::some_submodule] {a=17, b=\"foo\"} Task successfully read from conf.json```\n\n# Errors\n\nSee `std::write`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn default_format(\n w: &mut dyn std::io::Write,\n _now: &mut DeferredNow,\n record: &Record,\n) -> Result<(), std::io::Error> {\n write!(\n w,\n \"{} [{}] \",\n record.level(),\n record.module_path().unwrap_or(\"\"),\n )?;\n\n #[cfg(feature = \"kv\")]\n write_key_value_pairs(w, record)?;\n\n write!(w, \"{}\", record.args())\n}\n```"}], "func_name": "default_format", "docstring": "A logline-formatter that produces log lines like
\n```INFO [my_prog::some_submodule] Task successfully read from conf.json```.\n\nIf the kv-feature is used, the log lines look like\n```INFO [my_prog::some_submodule] {a=17, b=\"foo\"} Task successfully read from conf.json```\n\n# Errors\n\nSee `std::write`", "repo": "emabee/flexi_logger", "path": "src/formats.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/formats.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8b7ed2b5044382aa490d8e5e356089e4444ab26b2e78fa110bb5fa6255baa36e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: opt_format\n\nDocumentation:\nA logline-formatter that produces log lines with timestamp and file location, like\n
\n```[2016-01-13 15:25:01.640870 +01:00] INFO [src/foo/bar:26] Task successfully read from conf.json```\n
\n\n# Errors\n\nSee `std::write`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn opt_format(\n w: &mut dyn std::io::Write,\n now: &mut DeferredNow,\n record: &Record,\n) -> Result<(), std::io::Error> {\n write!(\n w,\n \"[{}] {} [{}:{}] \",\n now.format(TS_DASHES_BLANK_COLONS_DOT_BLANK),\n record.level(),\n record.file().unwrap_or(\"\"),\n record.line().unwrap_or(0),\n )?;\n\n #[cfg(feature = \"kv\")]\n write_key_value_pairs(w, record)?;\n\n write!(w, \"{}\", &record.args())\n}\n```"}], "func_name": "opt_format", "docstring": "A logline-formatter that produces log lines with timestamp and file location, like\n
\n```[2016-01-13 15:25:01.640870 +01:00] INFO [src/foo/bar:26] Task successfully read from conf.json```\n
\n\n# Errors\n\nSee `std::write`", "repo": "emabee/flexi_logger", "path": "src/formats.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/formats.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1030a44e04d9f1869b860e122bc55df128e07946fe3ec198ef72017104088ad0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: detailed_format\n\nDocumentation:\nA logline-formatter that produces log lines like
\n```[2016-01-13 15:25:01.640870 +01:00] INFO [foo::bar] src/foo/bar.rs:26: Task successfully read from conf.json```\n\nI.e. with timestamp, module path and file location.\n\n# Errors\n\nSee `std::write`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn detailed_format(\n w: &mut dyn std::io::Write,\n now: &mut DeferredNow,\n record: &Record,\n) -> Result<(), std::io::Error> {\n write!(\n w,\n \"[{}] {} [{}] {}:{}: \",\n now.format(TS_DASHES_BLANK_COLONS_DOT_BLANK),\n record.level(),\n record.module_path().unwrap_or(\"\"),\n record.file().unwrap_or(\"\"),\n record.line().unwrap_or(0),\n )?;\n\n #[cfg(feature = \"kv\")]\n write_key_value_pairs(w, record)?;\n\n write!(w, \"{}\", &record.args())\n}\n```"}], "func_name": "detailed_format", "docstring": "A logline-formatter that produces log lines like
\n```[2016-01-13 15:25:01.640870 +01:00] INFO [foo::bar] src/foo/bar.rs:26: Task successfully read from conf.json```\n\nI.e. with timestamp, module path and file location.\n\n# Errors\n\nSee `std::write`", "repo": "emabee/flexi_logger", "path": "src/formats.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/formats.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c4bf90f91fe9b908e1d4936d9a0973beac214e66c45050ab0ffa7ca57ce3da9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_thread\n\nDocumentation:\nA logline-formatter that produces log lines like
\n```[2016-01-13 15:25:01.640870 +01:00] T[taskreader] INFO [src/foo/bar:26] Task successfully read from conf.json```\n\nI.e. with timestamp, thread name and file location.\n\n# Errors\n\nSee `std::write`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_thread(\n w: &mut dyn std::io::Write,\n now: &mut DeferredNow,\n record: &Record,\n) -> Result<(), std::io::Error> {\n write!(\n w,\n \"[{}] T[{}] {} [{}:{}] \",\n now.format(TS_DASHES_BLANK_COLONS_DOT_BLANK),\n thread::current().name().unwrap_or(\"\"),\n record.level(),\n record.file().unwrap_or(\"\"),\n record.line().unwrap_or(0),\n )?;\n\n #[cfg(feature = \"kv\")]\n write_key_value_pairs(w, record)?;\n\n write!(w, \"{}\", &record.args())\n}\n```"}], "func_name": "with_thread", "docstring": "A logline-formatter that produces log lines like
\n```[2016-01-13 15:25:01.640870 +01:00] T[taskreader] INFO [src/foo/bar:26] Task successfully read from conf.json```\n\nI.e. with timestamp, thread name and file location.\n\n# Errors\n\nSee `std::write`", "repo": "emabee/flexi_logger", "path": "src/formats.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/formats.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63af78e0c352601b74b91f2036c3ac7a250e73a84ce38a7b10e10b0d07ff406a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init\n\nDocumentation:\nShortest form to get started.\n\n`flexi_logger::init();`.\n\nEquivalent to\n```rust\n# use flexi_logger::{Logger,LogSpecification};\nLogger::try_with_env_or_str(\"info\")\n.unwrap_or_else(|_e| Logger::with(LogSpecification::info()))\n.log_to_stderr()\n.start()\n.ok();\n```\nthat means,\n\n- you configure the log specification via the environment variable `RUST_LOG`,\nor use the default log specification (`'info'`)\n- logs are directly written to `stderr`, without any buffering, so implicitly dropping the\n`LogHandle` (which is returned from `Logger::start()`) is ok.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn init() {\n Logger::try_with_env_or_str(\"info\")\n .unwrap_or_else(|_e| Logger::with(LogSpecification::info()))\n .log_to_stderr()\n .start()\n .ok();\n}\n```"}], "func_name": "init", "docstring": "Shortest form to get started.\n\n`flexi_logger::init();`.\n\nEquivalent to\n```rust\n# use flexi_logger::{Logger,LogSpecification};\nLogger::try_with_env_or_str(\"info\")\n.unwrap_or_else(|_e| Logger::with(LogSpecification::info()))\n.log_to_stderr()\n.start()\n.ok();\n```\nthat means,\n\n- you configure the log specification via the environment variable `RUST_LOG`,\nor use the default log specification (`'info'`)\n- logs are directly written to `stderr`, without any buffering, so implicitly dropping the\n`LogHandle` (which is returned from `Logger::start()`) is ok.", "repo": "emabee/flexi_logger", "path": "src/lib.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "33c1efd24724c46bb89a81917d4eacfd0789971a9973d89346492eb70b1d1735"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_with_str\n\nDocumentation:\nCreates a Logger that reads the [`LogSpecification`] from a `String` or `&str`.\nSee [`LogSpecification`] for the syntax.\n\n# Errors\n\n`FlexiLoggerError::Parse` if the String uses an erroneous syntax.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_with_str>(s: S) -> Result {\n Ok(Self::from_spec_and_errs(LogSpecification::parse(\n s.as_ref(),\n )?))\n }\n```"}], "func_name": "try_with_str", "docstring": "Creates a Logger that reads the [`LogSpecification`] from a `String` or `&str`.\nSee [`LogSpecification`] for the syntax.\n\n# Errors\n\n`FlexiLoggerError::Parse` if the String uses an erroneous syntax.", "repo": "emabee/flexi_logger", "path": "src/logger.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0625c7b0327934b2759b7cb790dda213e7bde4f7e3ba900ce40ca553556ed57e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_new_spec\n\nDocumentation:\nTries to replace the active `LogSpecification` with the result from parsing the given String.\n\n# Errors\n\n[`FlexiLoggerError::Parse`] if the input is malformed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_new_spec(&self, spec: &str) -> Result<(), FlexiLoggerError> {\n self.set_new_spec(LogSpecification::parse(spec)?);\n Ok(())\n }\n```"}], "func_name": "parse_new_spec", "docstring": "Tries to replace the active `LogSpecification` with the result from parsing the given String.\n\n# Errors\n\n[`FlexiLoggerError::Parse`] if the input is malformed.", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8061812c6bf1584e8ed2d36495b09a3ec4dbca76e1b7f32d1dc399b8ed3b4939"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_and_push_temp_spec\n\nDocumentation:\nTries to replace the active `LogSpecification` with the result from parsing the given String\nand pushes the previous one to a Stack.\n\n# Errors\n\n[`FlexiLoggerError::Parse`] if the input is malformed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_and_push_temp_spec>(\n &mut self,\n new_spec: S,\n ) -> Result<(), FlexiLoggerError> {\n self.writers_handle.spec_stack.push(\n self.writers_handle\n .spec\n .read()\n .map_err(|_| FlexiLoggerError::Poison)?\n .clone(),\n );\n self.set_new_spec(LogSpecification::parse(new_spec)?);\n Ok(())\n }\n```"}], "func_name": "parse_and_push_temp_spec", "docstring": "Tries to replace the active `LogSpecification` with the result from parsing the given String\nand pushes the previous one to a Stack.\n\n# Errors\n\n[`FlexiLoggerError::Parse`] if the input is malformed.", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "284771fefd3c8d9dbed1b5e91ef881f9605613b7648c382f794e730d8622d85c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pop_temp_spec\n\nDocumentation:\nReverts to the previous `LogSpecification`, if any.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pop_temp_spec(&mut self) {\n if let Some(previous_spec) = self.writers_handle.spec_stack.pop() {\n self.set_new_spec(previous_spec);\n }\n }\n```"}], "func_name": "pop_temp_spec", "docstring": "Reverts to the previous `LogSpecification`, if any.", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "115304ff6a33a4da4fac42dd4b87a011c40e9b1b2f5e7fd2a53a6f197bbffe0f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_flw\n\nDocumentation:\nReplaces parts of the configuration of the file log writer.\n\nNote that neither the write mode nor the format function can be reset and\nthat the provided `FileLogWriterBuilder` must have the same values for these as the\ncurrently used `FileLogWriter`.\n\n# Example\n\nSee [`code_examples`](code_examples/index.html#reconfigure-the-file-log-writer).\n\n# Errors\n\n`FlexiLoggerError::NoFileLogger` if no file log writer is configured.\n\n`FlexiLoggerError::Reset` if a reset was tried with a different write mode.\n\n`FlexiLoggerError::Io` if the specified path doesn't work.\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reset_flw(&self, flwb: &FileLogWriterBuilder) -> Result<(), FlexiLoggerError> {\n if let PrimaryWriter::Multi(ref mw) = &*self.writers_handle.primary_writer {\n mw.reset_file_log_writer(flwb)\n } else {\n Err(FlexiLoggerError::NoFileLogger)\n }\n }\n```"}], "func_name": "reset_flw", "docstring": "Replaces parts of the configuration of the file log writer.\n\nNote that neither the write mode nor the format function can be reset and\nthat the provided `FileLogWriterBuilder` must have the same values for these as the\ncurrently used `FileLogWriter`.\n\n# Example\n\nSee [`code_examples`](code_examples/index.html#reconfigure-the-file-log-writer).\n\n# Errors\n\n`FlexiLoggerError::NoFileLogger` if no file log writer is configured.\n\n`FlexiLoggerError::Reset` if a reset was tried with a different write mode.\n\n`FlexiLoggerError::Io` if the specified path doesn't work.\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "359f630fa870b47803d20dae4b4f36b0fd42061f5f1fe1ed77a08d22024caa37"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: flw_config\n\nDocumentation:\nReturns the current configuration of the file log writer.\n\n# Errors\n\n`FlexiLoggerError::NoFileLogger` if no file log writer is configured.\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn flw_config(&self) -> Result {\n if let PrimaryWriter::Multi(ref mw) = &*self.writers_handle.primary_writer {\n mw.flw_config()\n } else {\n Err(FlexiLoggerError::NoFileLogger)\n }\n }\n```"}], "func_name": "flw_config", "docstring": "Returns the current configuration of the file log writer.\n\n# Errors\n\n`FlexiLoggerError::NoFileLogger` if no file log writer is configured.\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "43d9eccfa62c8d79187f8173bfc73acb9ec9fc8f3ee70657b936563c8a683ff1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: current_max_level\n\nDocumentation:\nGet the current maximimum log level.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn current_max_level(&self) -> Result {\n let read_guard = self\n .writers_handle\n .spec\n .read()\n .map_err(|_| FlexiLoggerError::Poison)?;\n Ok(read_guard.max_level())\n }\n```"}], "func_name": "current_max_level", "docstring": "Get the current maximimum log level.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18350ff499229ae224f2582be98e25dd92a88559053a94b18c182f460d3fbd83"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: current_log_spec\n\nDocumentation:\nGet a copy of the current log spec.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn current_log_spec(&self) -> Result {\n Ok(self\n .writers_handle\n .spec\n .read()\n .map_err(|_| FlexiLoggerError::Poison)?\n .clone())\n }\n```"}], "func_name": "current_log_spec", "docstring": "Get a copy of the current log spec.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "190741a35e2d31bb379e100c0083bed496b70c8dadec032155c04fe604d49eb3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reopen_output\n\nDocumentation:\nMakes the logger re-open the current log file.\n\nIf the log is written to a file, `flexi_logger` expects that nobody else modifies the file,\nand offers capabilities to rotate, compress, and clean up log files.\n\nHowever, if you use tools like linux' `logrotate`\nto rename or delete the current output file, you need to inform `flexi_logger` about\nsuch actions by calling this method. Otherwise `flexi_logger` will not stop\nwriting to the renamed or even deleted file!\n\nIn more complex configurations, i.e. when more than one output stream is written to,\nall of them will be attempted to be re-opened; only the first error will be reported.\n\n# Example\n\n`logrotate` e.g. can be configured to send a `SIGHUP` signal to your program. You need to\nhandle `SIGHUP` in your program explicitly,\ne.g. using a crate like [`ctrlc`](https://docs.rs/ctrlc/latest/ctrlc/),\nand call this function from the registered signal handler.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.\n\nOther variants of `FlexiLoggerError`, depending on the used writers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reopen_output(&self) -> Result<(), FlexiLoggerError> {\n let mut result = if let PrimaryWriter::Multi(ref mw) = &*self.writers_handle.primary_writer\n {\n mw.reopen_output()\n } else {\n Ok(())\n };\n\n for blw in self.writers_handle.other_writers.values() {\n let result2 = blw.reopen_output();\n if result.is_ok() && result2.is_err() {\n result = result2;\n }\n }\n\n result\n }\n```"}], "func_name": "reopen_output", "docstring": "Makes the logger re-open the current log file.\n\nIf the log is written to a file, `flexi_logger` expects that nobody else modifies the file,\nand offers capabilities to rotate, compress, and clean up log files.\n\nHowever, if you use tools like linux' `logrotate`\nto rename or delete the current output file, you need to inform `flexi_logger` about\nsuch actions by calling this method. Otherwise `flexi_logger` will not stop\nwriting to the renamed or even deleted file!\n\nIn more complex configurations, i.e. when more than one output stream is written to,\nall of them will be attempted to be re-opened; only the first error will be reported.\n\n# Example\n\n`logrotate` e.g. can be configured to send a `SIGHUP` signal to your program. You need to\nhandle `SIGHUP` in your program explicitly,\ne.g. using a crate like [`ctrlc`](https://docs.rs/ctrlc/latest/ctrlc/),\nand call this function from the registered signal handler.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.\n\nOther variants of `FlexiLoggerError`, depending on the used writers.", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a74b814096f0a7bdfba6c2b7a3adbb5b145b3727635c81774131a8fbc18b7e8e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: trigger_rotation\n\nDocumentation:\nTrigger an extra log file rotation.\n\nDoes nothing if rotation is not configured.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.\n\nIO errors.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn trigger_rotation(&self) -> Result<(), FlexiLoggerError> {\n let mut result = if let PrimaryWriter::Multi(ref mw) = &*self.writers_handle.primary_writer\n {\n mw.trigger_rotation()\n } else {\n Ok(())\n };\n\n for blw in self.writers_handle.other_writers.values() {\n let result2 = blw.rotate();\n if result.is_ok() && result2.is_err() {\n result = result2;\n }\n }\n result\n }\n```"}], "func_name": "trigger_rotation", "docstring": "Trigger an extra log file rotation.\n\nDoes nothing if rotation is not configured.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.\n\nIO errors.", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f692b4f3504242c16af277c1ae06841a4f2075c447b26edb965f8781e140b08a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shutdown\n\nDocumentation:\nShutdown all participating writers.\n\nThis method is supposed to be called at the very end of your program, if\n\n- you use some [`Cleanup`](crate::Cleanup) strategy with compression:\nthen you want to ensure that a termination of your program\ndoes not interrput the cleanup-thread when it is compressing a log file,\nwhich could leave unexpected files in the filesystem\n- you use your own writer(s), and they need to clean up resources\n\nSee also [`writers::LogWriter::shutdown`](crate::writers::LogWriter::shutdown).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn shutdown(&self) {\n self.writers_handle.primary_writer.shutdown();\n for writer in self.writers_handle.other_writers.values() {\n writer.shutdown();\n }\n }\n```"}], "func_name": "shutdown", "docstring": "Shutdown all participating writers.\n\nThis method is supposed to be called at the very end of your program, if\n\n- you use some [`Cleanup`](crate::Cleanup) strategy with compression:\nthen you want to ensure that a termination of your program\ndoes not interrput the cleanup-thread when it is compressing a log file,\nwhich could leave unexpected files in the filesystem\n- you use your own writer(s), and they need to clean up resources\n\nSee also [`writers::LogWriter::shutdown`](crate::writers::LogWriter::shutdown).", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9f0ac4f41bca76745a3911c642bc45be3fd72ed5e22cba723493e11aa2ae88d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: existing_log_files\n\nDocumentation:\nReturns the list of existing log files according to the current `FileSpec`.\n\nDepending on the given selector, the list may include the CURRENT log file\nand the compressed files, if they exist.\nThe list is empty if the logger is not configured for writing to files.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn existing_log_files(\n &self,\n selector: &LogfileSelector,\n ) -> Result, FlexiLoggerError> {\n let mut log_files = self\n .writers_handle\n .primary_writer\n .existing_log_files(selector)?;\n log_files.sort();\n Ok(log_files)\n }\n```"}], "func_name": "existing_log_files", "docstring": "Returns the list of existing log files according to the current `FileSpec`.\n\nDepending on the given selector, the list may include the CURRENT log file\nand the compressed files, if they exist.\nThe list is empty if the logger is not configured for writing to files.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "58f00791f74686b5854ca6c96461aee806b5154e3eea2b76a75a3060971722e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: adapt_duplication_to_stderr\n\nDocumentation:\nAllows re-configuring duplication to stderr.\n\n# Errors\n\n`FlexiLoggerError::NoDuplication`\nif `FlexiLogger` was initialized without duplication support\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn adapt_duplication_to_stderr(&mut self, dup: Duplicate) -> Result<(), FlexiLoggerError> {\n if let PrimaryWriter::Multi(ref mw) = &*self.writers_handle.primary_writer {\n mw.adapt_duplication_to_stderr(dup);\n Ok(())\n } else {\n Err(FlexiLoggerError::NoFileLogger)\n }\n }\n```"}], "func_name": "adapt_duplication_to_stderr", "docstring": "Allows re-configuring duplication to stderr.\n\n# Errors\n\n`FlexiLoggerError::NoDuplication`\nif `FlexiLogger` was initialized without duplication support", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "595d349c4e9d9cb9ede744ec619cac7b6a5796dedc313a66b29d5c9b550fe647"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: adapt_duplication_to_stdout\n\nDocumentation:\nAllows re-configuring duplication to stdout.\n\n# Errors\n\n`FlexiLoggerError::NoDuplication`\nif `FlexiLogger` was initialized without duplication support\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn adapt_duplication_to_stdout(&mut self, dup: Duplicate) -> Result<(), FlexiLoggerError> {\n if let PrimaryWriter::Multi(ref mw) = &*self.writers_handle.primary_writer {\n mw.adapt_duplication_to_stdout(dup);\n Ok(())\n } else {\n Err(FlexiLoggerError::NoFileLogger)\n }\n }\n```"}], "func_name": "adapt_duplication_to_stdout", "docstring": "Allows re-configuring duplication to stdout.\n\n# Errors\n\n`FlexiLoggerError::NoDuplication`\nif `FlexiLogger` was initialized without duplication support", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "239dd4386a7fa28af038c754f487c53308fb353e09b57e08efb8b6eef95698cd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default\n\nDocumentation:\nSelects plain log files without the `rCURRENT` file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn default() -> Self {\n Self {\n with_plain_files: true,\n with_r_current: false,\n with_compressed_files: false,\n with_configured_current: None,\n }\n }\n```"}], "func_name": "default", "docstring": "Selects plain log files without the `rCURRENT` file.", "repo": "emabee/flexi_logger", "path": "src/logger_handle.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/logger_handle.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ecb546a6d63b064987bd523059701382abca570ba273966299133e845b341f97"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: setup_tracing\n\nDocumentation:\nSet up tracing to write into the specified `FileLogWriter`,\nand to use the (optionally) specified specfile.\n\nNot that the `FileLogWriter`'s formatting are bypassed and not be used,\ninstead the `tracing` formatting will be used, which can be configured via `config: FormatConfig`.\n\nThe returned handles must be kept alive and should be dropped at the very end of the program.\n\n### Example\n\nUse [`FileLogWriter`]([crate::FileLogWriter) as trace writer,\nwith support for dynamically adapting trace levels while your program is running.\n\n```rust\n# #[cfg(feature = \"specfile_without_notification\")]\n# {\nuse std::{error::Error, path::PathBuf};\nuse flexi_logger::{\ntrc::FormatConfig,\nwriters::FileLogWriter,\nAge, Cleanup, Criterion, FileSpec, LogSpecification, Naming, WriteMode,\n};\n\n# fn main() -> Result<(), Box> {\n\n// Drop the keep-alive-handles only in the shutdown of your program\nlet _keep_alive_handles = flexi_logger::trc::setup_tracing(\nLogSpecification::info(),\nSome(&PathBuf::from(\"trcspecfile.toml\")),\nFileLogWriter::builder(FileSpec::default())\n.rotate(\nCriterion::Age(Age::Day),\nNaming::Timestamps,\nCleanup::KeepLogFiles(7),\n)\n.write_mode(WriteMode::Async),\n&FormatConfig::default()\n.with_file(true),\n)?;\n\ntracing::debug!(\"now we start doing what we really wanted to do...\");\n# Ok(())}}\n```\n\n\n# Panics\n\n# Errors\n\nVarious variants of `FlexiLoggerError` can occur.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn setup_tracing(\n initial_logspec: LogSpecification,\n o_specfile: Option<&PathBuf>,\n flwb: FileLogWriterBuilder,\n config: &FormatConfig,\n) -> Result<(FileLogWriterHandle, SpecFileNotifier), FlexiLoggerError> {\n let (file_writer, fw_handle) = flwb.try_build_with_handle()?;\n\n // Set up subscriber that makes use of the file writer, with some hardcoded initial log spec.\n // Ugly code duplication here, due to \"sophisticated\" use of types in `tracing-subscriber`\n if config.with_time {\n let subscriber_builder = FmtSubscriber::builder()\n .with_writer(move || file_writer.clone())\n .with_ansi(config.with_ansi)\n .with_env_filter(EnvFilter::from_default_env())\n .with_file(config.with_file)\n .with_filter_reloading()\n .with_level(config.with_level)\n .with_line_number(config.with_line_number)\n .with_target(config.with_target)\n .with_thread_ids(config.with_thread_ids)\n .with_thread_names(config.with_thread_names)\n .with_thread_ids(config.with_thread_ids)\n .with_thread_names(config.with_thread_names)\n .with_env_filter(LogSpecAsFilter(initial_logspec.clone()))\n .with_filter_reloading();\n // Set up specfile watching\n let spec_file_notifier = SpecFileNotifier {\n _watcher: match o_specfile {\n Some(specfile) => {\n let reload_handle = Box::new(subscriber_builder.reload_handle());\n subscribe_to_specfile(\n specfile,\n Box::new(move |logspec| {\n { reload_handle.reload(LogSpecAsFilter(logspec)) }.unwrap(/* OK */);\n }),\n initial_logspec,\n )?\n }\n None => None,\n },\n };\n\n // Get ready to trace\n tracing::subscriber::set_global_default(subscriber_builder.finish())?;\n\n Ok((fw_handle, spec_file_notifier))\n } else {\n let subscriber_builder = FmtSubscriber::builder()\n .without_time()\n .with_writer(move || file_writer.clone())\n .with_ansi(config.with_ansi)\n .with_env_filter(EnvFilter::from_default_env())\n .with_file(config.with_file)\n .with_filter_reloading()\n .with_level(config.with_level)\n .with_line_number(config.with_line_number)\n .with_target(config.with_target)\n .with_thread_ids(config.with_thread_ids)\n .with_thread_names(config.with_thread_names)\n .with_thread_ids(config.with_thread_ids)\n .with_thread_names(config.with_thread_names)\n .with_env_filter(LogSpecAsFilter(initial_logspec.clone()))\n .with_filter_reloading();\n // Set up specfile watching\n let spec_file_notifier = SpecFileNotifier {\n _watcher: match o_specfile {\n Some(specfile) => {\n let reload_handle = Box::new(subscriber_builder.reload_handle());\n subscribe_to_specfile(\n specfile,\n Box::new(move |logspec| {\n { reload_handle.reload(LogSpecAsFilter(logspec)) }.unwrap(/* OK */);\n }),\n initial_logspec,\n )?\n }\n None => None,\n },\n };\n\n // Get ready to trace\n tracing::subscriber::set_global_default(subscriber_builder.finish())?;\n Ok((fw_handle, spec_file_notifier))\n }\n}\n```"}], "func_name": "setup_tracing", "docstring": "Set up tracing to write into the specified `FileLogWriter`,\nand to use the (optionally) specified specfile.\n\nNot that the `FileLogWriter`'s formatting are bypassed and not be used,\ninstead the `tracing` formatting will be used, which can be configured via `config: FormatConfig`.\n\nThe returned handles must be kept alive and should be dropped at the very end of the program.\n\n### Example\n\nUse [`FileLogWriter`]([crate::FileLogWriter) as trace writer,\nwith support for dynamically adapting trace levels while your program is running.\n\n```rust\n# #[cfg(feature = \"specfile_without_notification\")]\n# {\nuse std::{error::Error, path::PathBuf};\nuse flexi_logger::{\ntrc::FormatConfig,\nwriters::FileLogWriter,\nAge, Cleanup, Criterion, FileSpec, LogSpecification, Naming, WriteMode,\n};\n\n# fn main() -> Result<(), Box> {\n\n// Drop the keep-alive-handles only in the shutdown of your program\nlet _keep_alive_handles = flexi_logger::trc::setup_tracing(\nLogSpecification::info(),\nSome(&PathBuf::from(\"trcspecfile.toml\")),\nFileLogWriter::builder(FileSpec::default())\n.rotate(\nCriterion::Age(Age::Day),\nNaming::Timestamps,\nCleanup::KeepLogFiles(7),\n)\n.write_mode(WriteMode::Async),\n&FormatConfig::default()\n.with_file(true),\n)?;\n\ntracing::debug!(\"now we start doing what we really wanted to do...\");\n# Ok(())}}\n```\n\n\n# Panics\n\n# Errors\n\nVarious variants of `FlexiLoggerError` can occur.", "repo": "emabee/flexi_logger", "path": "src/trc.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/trc.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f6532df7d854c54e3f407efdc8ee8e2d35371a64b9fdeb555aff97b8a6218c98"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default\n\nDocumentation:\nDescribes a file in the current folder,\nusing, as its filestem, the program name followed by the current timestamp,\nand the suffix \".log\".\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn default() -> Self {\n FileSpec {\n directory: PathBuf::from(\".\"),\n basename: Self::default_basename(),\n o_discriminant: None,\n timestamp_cfg: TimestampCfg::Default,\n o_suffix: Some(String::from(\"log\")),\n use_utc: false,\n }\n }\n```"}], "func_name": "default", "docstring": "Describes a file in the current folder,\nusing, as its filestem, the program name followed by the current timestamp,\nand the suffix \".log\".", "repo": "emabee/flexi_logger", "path": "src/parameters/file_spec.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/parameters/file_spec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b00874405d01ac6a78d18ebdf3468a14b6ae5de9e08c117038c5eca9c5dc723f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_from\n\nDocumentation:\nThe provided path should describe a log file.\nIf it exists, it must be a file, not a folder.\nIf necessary, parent folders will be created.\n\n```rust\n# use flexi_logger::FileSpec;\nassert_eq!(\nFileSpec::default()\n.directory(\"/a/b/c\")\n.basename(\"foo\")\n.suppress_timestamp()\n.suffix(\"bar\"),\nFileSpec::try_from(\"/a/b/c/foo.bar\").unwrap()\n);\n```\n# Errors\n\n[`FlexiLoggerError::OutputBadFile`] if the given path exists and is a folder.\n\n# Panics\n\nPanics if the basename of the given path has no filename\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_from>(p: P) -> Result {\n let p: PathBuf = p.into();\n if p.is_dir() {\n Err(FlexiLoggerError::OutputBadFile)\n } else {\n Ok(FileSpec {\n directory: p.parent().unwrap(/*cannot fail*/).to_path_buf(),\n basename: p.file_stem().unwrap(/*ok*/).to_string_lossy().to_string(),\n o_discriminant: None,\n o_suffix: p.extension().map(|s| s.to_string_lossy().to_string()),\n timestamp_cfg: TimestampCfg::No,\n use_utc: false,\n })\n }\n }\n```"}], "func_name": "try_from", "docstring": "The provided path should describe a log file.\nIf it exists, it must be a file, not a folder.\nIf necessary, parent folders will be created.\n\n```rust\n# use flexi_logger::FileSpec;\nassert_eq!(\nFileSpec::default()\n.directory(\"/a/b/c\")\n.basename(\"foo\")\n.suppress_timestamp()\n.suffix(\"bar\"),\nFileSpec::try_from(\"/a/b/c/foo.bar\").unwrap()\n);\n```\n# Errors\n\n[`FlexiLoggerError::OutputBadFile`] if the given path exists and is a folder.\n\n# Panics\n\nPanics if the basename of the given path has no filename", "repo": "emabee/flexi_logger", "path": "src/parameters/file_spec.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/parameters/file_spec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "66bd081be106f5059e0d9f2f7950cf441996b73b838cdf411a46355e4d19516d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: max_log_level\n\nDocumentation:\nProvides the maximum log level that is to be written.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn max_log_level(&self) -> log::LevelFilter {\n *self\n .o_file_writer\n .as_ref()\n .map(|w| w.max_log_level())\n .iter()\n .chain(\n self.o_other_writer\n .as_ref()\n .map(|w| w.max_log_level())\n .iter(),\n )\n .max()\n .unwrap(/*ok*/)\n }\n```"}], "func_name": "max_log_level", "docstring": "Provides the maximum log level that is to be written.", "repo": "emabee/flexi_logger", "path": "src/primary_writer/multi_writer.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/primary_writer/multi_writer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d54099b6d25f63b4f80750ee3b3c6d784ad12db317ae70b1a89bef98aae91658"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_snapshot\n\nDocumentation:\nUpdates a snapshot with the current buffer content.\n\nDoes nothing if the snapshot is up-to-date.\n\nReturns whether the snapshot was updated.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn update_snapshot(&self, snapshot: &mut Snapshot) -> Result {\n let state = self.lock_state()?;\n if snapshot.last_update == state.last_update {\n Ok(false)\n } else {\n snapshot.text.clear();\n for bufline in &state.buffer {\n snapshot.text.push_str(bufline);\n snapshot.text.push('\\n');\n }\n snapshot.last_update = state.last_update;\n Ok(true)\n }\n }\n```"}], "func_name": "update_snapshot", "docstring": "Updates a snapshot with the current buffer content.\n\nDoes nothing if the snapshot is up-to-date.\n\nReturns whether the snapshot was updated.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.", "repo": "emabee/flexi_logger", "path": "src/writers/buffer_writer.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/writers/buffer_writer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "47021212148d70160fe6c3d53e40bbfa99bb3fbc883489c285400691f15a41a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: existing_log_files\n\nDocumentation:\nReturns the list of existing log files according to the current `FileSpec`.\n\nThe list includes the current log file and the compressed files, if they exist.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn existing_log_files(\n &self,\n selector: &LogfileSelector,\n ) -> Result, FlexiLoggerError> {\n self.state_handle.existing_log_files(selector)\n }\n```"}], "func_name": "existing_log_files", "docstring": "Returns the list of existing log files according to the current `FileSpec`.\n\nThe list includes the current log file and the compressed files, if they exist.\n\n# Errors\n\n`FlexiLoggerError::Poison` if some mutex is poisoned.", "repo": "emabee/flexi_logger", "path": "src/writers/file_log_writer.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/writers/file_log_writer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c35c1407a6fc2254594475a10c5ed1de1baa134068964ccb8ee93fb66da086d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: format\n\nDocumentation:\nSets the format function.\n\nDefaults to [`default_format`](crate::default_format),\nbut can be changed with a call to\n[`Logger::format_for_writer`](crate::Logger::format_for_writer).\n\nThe default implementation is a no-op.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn format(&mut self, format: FormatFunction) {\n _ = format;\n }\n```"}], "func_name": "format", "docstring": "Sets the format function.\n\nDefaults to [`default_format`](crate::default_format),\nbut can be changed with a call to\n[`Logger::format_for_writer`](crate::Logger::format_for_writer).\n\nThe default implementation is a no-op.", "repo": "emabee/flexi_logger", "path": "src/writers/log_writer.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/writers/log_writer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "85d6a905639b6476d3e57a05425071369fb3428b15f4e3bb8c1da7a25dc72cf0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_build\n\nDocumentation:\nProduces the `FileLogWriter`.\n\n# Errors\n\n`FlexiLoggerError::Io` if the specified path doesn't work.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_build(self) -> Result {\n Ok(FileLogWriter::new(\n self.try_build_state()?,\n self.max_log_level,\n self.format,\n ))\n }\n```"}], "func_name": "try_build", "docstring": "Produces the `FileLogWriter`.\n\n# Errors\n\n`FlexiLoggerError::Io` if the specified path doesn't work.", "repo": "emabee/flexi_logger", "path": "src/writers/file_log_writer/builder.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/writers/file_log_writer/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b62e3e13070ef33720ff0a766c16706e3611563cbe3a5dbfd9f786c907f4688a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_build_with_handle\n\nDocumentation:\nProduces the `FileLogWriter` and a handle that is connected with it.\n\nThis allows handing out the `FileLogWriter` instance to methods that consume it, and still\nbe able to influence it via the handle.\n\n# Errors\n\n`FlexiLoggerError::Io` if the specified path doesn't work.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_build_with_handle(\n self,\n ) -> Result<(ArcFileLogWriter, FileLogWriterHandle), FlexiLoggerError> {\n Ok(ArcFileLogWriter::new_with_handle(FileLogWriter::new(\n self.try_build_state()?,\n self.max_log_level,\n self.format,\n )))\n }\n```"}], "func_name": "try_build_with_handle", "docstring": "Produces the `FileLogWriter` and a handle that is connected with it.\n\nThis allows handing out the `FileLogWriter` instance to methods that consume it, and still\nbe able to influence it via the handle.\n\n# Errors\n\n`FlexiLoggerError::Io` if the specified path doesn't work.", "repo": "emabee/flexi_logger", "path": "src/writers/file_log_writer/builder.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/writers/file_log_writer/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3411ccdc6eea58b6c1beadd33743add4d04eae595f678833afa66b3b52ed8ae1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nReturns a boxed instance of `SysLogWriter`.\n\n# Errors\n\n`std::io::Error` if the program's argument list is empty so that the process\nidentifier for the syslog cannot be determined\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> IoResult> {\n Ok(Box::new(SyslogWriter::new(\n std::process::id(),\n self.custom_process_name\n .or(std::env::args().next())\n .ok_or_else(|| {\n IoError::other(\n \"Can't provide a process name as no env args are present and \\\n no custom process name is set\"\n .to_owned(),\n )\n })?,\n self.syslog_line_header,\n self.syslog_facility,\n self.determine_severity,\n self.syslog_connection,\n self.max_log_level,\n self.format,\n )?))\n }\n```"}], "func_name": "build", "docstring": "Returns a boxed instance of `SysLogWriter`.\n\n# Errors\n\n`std::io::Error` if the program's argument list is empty so that the process\nidentifier for the syslog cannot be determined", "repo": "emabee/flexi_logger", "path": "src/writers/syslog/builder.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/writers/syslog/builder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8a42dd20e8d07d2695bf5b3d88845dc92869606d5a503795f5db263310fd6ad5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: syslog_default_format\n\nDocumentation:\nDefault way of writing the message to the syslog.\n\nJust uses the `Display` implementation of `record.args()`.\n\n# Errors\n\n`std:io::Error` from writing to the given output stram.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn syslog_default_format(\n w: &mut dyn std::io::Write,\n _now: &mut DeferredNow,\n record: &Record,\n) -> Result<(), std::io::Error> {\n write!(w, \"{}\", record.args())\n}\n```"}], "func_name": "syslog_default_format", "docstring": "Default way of writing the message to the syslog.\n\nJust uses the `Display` implementation of `record.args()`.\n\n# Errors\n\n`std:io::Error` from writing to the given output stram.", "repo": "emabee/flexi_logger", "path": "src/writers/syslog/formats.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/writers/syslog/formats.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea193db24509fe440e8bc75cfd997a030dd3e0e837ce32f47f2911449e2e6359"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: syslog_format_with_thread\n\nDocumentation:\nSimilar to `syslog_default_format`, but inserts the thread name in the beginning of the message,\nencapsulated in square brackets.\n\n# Errors\n\n`std:io::Error` from writing to the given output stram.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn syslog_format_with_thread(\n w: &mut dyn std::io::Write,\n _now: &mut DeferredNow,\n record: &Record,\n) -> Result<(), std::io::Error> {\n write!(\n w,\n \"[{}] {}\",\n std::thread::current().name().unwrap_or(\"\"),\n record.args()\n )\n}\n```"}], "func_name": "syslog_format_with_thread", "docstring": "Similar to `syslog_default_format`, but inserts the thread name in the beginning of the message,\nencapsulated in square brackets.\n\n# Errors\n\n`std:io::Error` from writing to the given output stram.", "repo": "emabee/flexi_logger", "path": "src/writers/syslog/formats.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/writers/syslog/formats.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b3de209d68c5f5007feaec0048d9a48e184a970d21c4e74b193aab287220a42b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_tcp\n\nDocumentation:\nReturns a `Syslog` that sends the log lines via TCP to the specified address.\n\n# Errors\n\n`std::io::Error` if opening the stream fails.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_tcp(server: T) -> IoResult {\n Ok(SyslogConnection(Connection::Tcp(TcpStream::connect(\n server,\n )?)))\n }\n```"}], "func_name": "try_tcp", "docstring": "Returns a `Syslog` that sends the log lines via TCP to the specified address.\n\n# Errors\n\n`std::io::Error` if opening the stream fails.", "repo": "emabee/flexi_logger", "path": "src/writers/syslog/syslog_connection.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/writers/syslog/syslog_connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3d704178b3359d37f5a726365e0c102730b0c0006d10e88217ecebe356dac3f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_udp\n\nDocumentation:\nReturns a `Syslog` that sends the log via the fragile UDP protocol from local\nto server.\n\n# Errors\n\n`std::io::Error` if opening the stream fails.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_udp(local: T, server: T) -> IoResult {\n let socket = UdpSocket::bind(local)?;\n socket.connect(server)?;\n Ok(SyslogConnection(Connection::Udp(socket)))\n }\n```"}], "func_name": "try_udp", "docstring": "Returns a `Syslog` that sends the log via the fragile UDP protocol from local\nto server.\n\n# Errors\n\n`std::io::Error` if opening the stream fails.", "repo": "emabee/flexi_logger", "path": "src/writers/syslog/syslog_connection.rs", "url": "https://github.com/emabee/flexi_logger/blob/master/src/writers/syslog/syslog_connection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "16d01edb1726f18e0bfafa0eb604eac297c86de04ab33f0e66a2712fb409aa10"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_local_user_id\n\nDocumentation:\nParses user ID as our local user\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn parse_local_user_id(services: &Services, user_id: &str) -> Result {\n\tlet user_id = parse_user_id(services, user_id)?;\n\n\tif !services.globals.user_is_local(&user_id) {\n\t\treturn Err!(\"User {user_id:?} does not belong to our server.\");\n\t}\n\n\tOk(user_id)\n}\n```"}], "func_name": "parse_local_user_id", "docstring": "Parses user ID as our local user", "repo": "girlbossceo/conduwuit", "path": "src/admin/utils.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/admin/utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "98668c85112ce62cccab669ba387365b80d758668651fe732786b94dc5602e5a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_active_local_user_id\n\nDocumentation:\nParses user ID that is an active (not guest or deactivated) local user\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn parse_active_local_user_id(\n\tservices: &Services,\n\tuser_id: &str,\n) -> Result {\n\tlet user_id = parse_local_user_id(services, user_id)?;\n\n\tif !services.users.exists(&user_id).await {\n\t\treturn Err!(\"User {user_id:?} does not exist on this server.\");\n\t}\n\n\tif services.users.is_deactivated(&user_id).await? {\n\t\treturn Err!(\"User {user_id:?} is deactivated.\");\n\t}\n\n\tOk(user_id)\n}\n```"}], "func_name": "parse_active_local_user_id", "docstring": "Parses user ID that is an active (not guest or deactivated) local user", "repo": "girlbossceo/conduwuit", "path": "src/admin/utils.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/admin/utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef6a0ba20e6af0c933770c6cf7d530961c901800ce548f93c41347623aa70993"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process\n\nDocumentation:\nAll the getters and iterators from src/database/key_value/appservice.rs\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn process(subcommand: AppserviceCommand, context: &Command<'_>) -> Result {\n\tlet services = context.services;\n\n\tmatch subcommand {\n\t\t| AppserviceCommand::GetRegistration { appservice_id } => {\n\t\t\tlet timer = tokio::time::Instant::now();\n\t\t\tlet results = services.appservice.get_registration(&appservice_id).await;\n\n\t\t\tlet query_time = timer.elapsed();\n\n\t\t\twrite!(context, \"Query completed in {query_time:?}:\\n\\n```rs\\n{results:#?}\\n```\")\n\t\t},\n\t\t| AppserviceCommand::All => {\n\t\t\tlet timer = tokio::time::Instant::now();\n\t\t\tlet results = services.appservice.all().await;\n\t\t\tlet query_time = timer.elapsed();\n\n\t\t\twrite!(context, \"Query completed in {query_time:?}:\\n\\n```rs\\n{results:#?}\\n```\")\n\t\t},\n\t}\n\t.await\n}\n```"}], "func_name": "process", "docstring": "All the getters and iterators from src/database/key_value/appservice.rs", "repo": "girlbossceo/conduwuit", "path": "src/admin/query/appservice.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/admin/query/appservice.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c71f501e973c7b994df18b26a236bf07a0774f2bc3804dde9ca8390da67645a0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process\n\nDocumentation:\nAll the getters and iterators from src/database/key_value/globals.rs\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn process(subcommand: GlobalsCommand, context: &Command<'_>) -> Result {\n\tlet services = context.services;\n\n\tmatch subcommand {\n\t\t| GlobalsCommand::DatabaseVersion => {\n\t\t\tlet timer = tokio::time::Instant::now();\n\t\t\tlet results = services.globals.db.database_version().await;\n\t\t\tlet query_time = timer.elapsed();\n\n\t\t\twrite!(context, \"Query completed in {query_time:?}:\\n\\n```rs\\n{results:#?}\\n```\")\n\t\t},\n\t\t| GlobalsCommand::CurrentCount => {\n\t\t\tlet timer = tokio::time::Instant::now();\n\t\t\tlet results = services.globals.db.current_count();\n\t\t\tlet query_time = timer.elapsed();\n\n\t\t\twrite!(context, \"Query completed in {query_time:?}:\\n\\n```rs\\n{results:#?}\\n```\")\n\t\t},\n\t\t| GlobalsCommand::LastCheckForUpdatesId => {\n\t\t\tlet timer = tokio::time::Instant::now();\n\t\t\tlet results = services.updates.last_check_for_updates_id().await;\n\t\t\tlet query_time = timer.elapsed();\n\n\t\t\twrite!(context, \"Query completed in {query_time:?}:\\n\\n```rs\\n{results:#?}\\n```\")\n\t\t},\n\t\t| GlobalsCommand::SigningKeysFor { origin } => {\n\t\t\tlet timer = tokio::time::Instant::now();\n\t\t\tlet results = services.server_keys.verify_keys_for(&origin).await;\n\t\t\tlet query_time = timer.elapsed();\n\n\t\t\twrite!(context, \"Query completed in {query_time:?}:\\n\\n```rs\\n{results:#?}\\n```\")\n\t\t},\n\t}\n\t.await\n}\n```"}], "func_name": "process", "docstring": "All the getters and iterators from src/database/key_value/globals.rs", "repo": "girlbossceo/conduwuit", "path": "src/admin/query/globals.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/admin/query/globals.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "22f616c7db40878acf1bcd04af499bf5f726335a7775c70f342c83f8d5003964"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process\n\nDocumentation:\nAll the getters and iterators in key_value/presence.rs\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn process(subcommand: PresenceCommand, context: &Command<'_>) -> Result {\n\tlet services = context.services;\n\n\tmatch subcommand {\n\t\t| PresenceCommand::GetPresence { user_id } => {\n\t\t\tlet timer = tokio::time::Instant::now();\n\t\t\tlet results = services.presence.get_presence(&user_id).await;\n\t\t\tlet query_time = timer.elapsed();\n\n\t\t\twrite!(context, \"Query completed in {query_time:?}:\\n\\n```rs\\n{results:#?}\\n```\")\n\t\t},\n\t\t| PresenceCommand::PresenceSince { since } => {\n\t\t\tlet timer = tokio::time::Instant::now();\n\t\t\tlet results: Vec<(_, _, _)> = services\n\t\t\t\t.presence\n\t\t\t\t.presence_since(since)\n\t\t\t\t.map(|(user_id, count, bytes)| (user_id.to_owned(), count, bytes.to_vec()))\n\t\t\t\t.collect()\n\t\t\t\t.await;\n\t\t\tlet query_time = timer.elapsed();\n\n\t\t\twrite!(context, \"Query completed in {query_time:?}:\\n\\n```rs\\n{results:#?}\\n```\")\n\t\t},\n\t}\n\t.await\n}\n```"}], "func_name": "process", "docstring": "All the getters and iterators in key_value/presence.rs", "repo": "girlbossceo/conduwuit", "path": "src/admin/query/presence.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/admin/query/presence.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f62d51ed9a8da3df7fa3f4ec736724b6ec8545cc0c69533252f6434ef33a5f4b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process\n\nDocumentation:\nAll the getters and iterators in src/database/key_value/rooms/alias.rs\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn process(subcommand: RoomAliasCommand, context: &Command<'_>) -> Result {\n\tlet services = context.services;\n\n\tmatch subcommand {\n\t\t| RoomAliasCommand::ResolveLocalAlias { alias } => {\n\t\t\tlet timer = tokio::time::Instant::now();\n\t\t\tlet results = services.rooms.alias.resolve_local_alias(&alias).await;\n\t\t\tlet query_time = timer.elapsed();\n\n\t\t\twrite!(context, \"Query completed in {query_time:?}:\\n\\n```rs\\n{results:#?}\\n```\")\n\t\t},\n\t\t| RoomAliasCommand::LocalAliasesForRoom { room_id } => {\n\t\t\tlet timer = tokio::time::Instant::now();\n\t\t\tlet aliases: Vec<_> = services\n\t\t\t\t.rooms\n\t\t\t\t.alias\n\t\t\t\t.local_aliases_for_room(&room_id)\n\t\t\t\t.map(ToOwned::to_owned)\n\t\t\t\t.collect()\n\t\t\t\t.await;\n\t\t\tlet query_time = timer.elapsed();\n\n\t\t\twrite!(context, \"Query completed in {query_time:?}:\\n\\n```rs\\n{aliases:#?}\\n```\")\n\t\t},\n\t\t| RoomAliasCommand::AllLocalAliases => {\n\t\t\tlet timer = tokio::time::Instant::now();\n\t\t\tlet aliases = services\n\t\t\t\t.rooms\n\t\t\t\t.alias\n\t\t\t\t.all_local_aliases()\n\t\t\t\t.map(|(room_id, alias)| (room_id.to_owned(), alias.to_owned()))\n\t\t\t\t.collect::>()\n\t\t\t\t.await;\n\t\t\tlet query_time = timer.elapsed();\n\n\t\t\twrite!(context, \"Query completed in {query_time:?}:\\n\\n```rs\\n{aliases:#?}\\n```\")\n\t\t},\n\t}\n\t.await\n}\n```"}], "func_name": "process", "docstring": "All the getters and iterators in src/database/key_value/rooms/alias.rs", "repo": "girlbossceo/conduwuit", "path": "src/admin/query/room_alias.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/admin/query/room_alias.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ea3055ab3f9be42b1365c4e098eca6732bf549d1eb1a130141e6800a2dfc4db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process\n\nDocumentation:\nAll the getters and iterators in key_value/sending.rs\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn process(subcommand: SendingCommand, context: &Command<'_>) -> Result {\n\tlet c = reprocess(subcommand, context).await?;\n\tcontext.write_str(c.body()).await?;\n\tOk(())\n}\n```"}], "func_name": "process", "docstring": "All the getters and iterators in key_value/sending.rs", "repo": "girlbossceo/conduwuit", "path": "src/admin/query/sending.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/admin/query/sending.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "862044a3c6d56e5523c2f1804fa7103e349e387336a3af612a1f05a6c601c594"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: whoami_route\n\nDocumentation:\n# `GET _matrix/client/r0/account/whoami`\n\nGet `user_id` of the sender user.\n\nNote: Also works for Application Services\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn whoami_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\tlet device_id = body.sender_device.clone();\n\n\tOk(whoami::v3::Response {\n\t\tuser_id: sender_user.clone(),\n\t\tdevice_id,\n\t\tis_guest: services.users.is_deactivated(sender_user).await?\n\t\t\t&& body.appservice_info.is_none(),\n\t})\n}\n```"}], "func_name": "whoami_route", "docstring": "# `GET _matrix/client/r0/account/whoami`\n\nGet `user_id` of the sender user.\n\nNote: Also works for Application Services", "repo": "girlbossceo/conduwuit", "path": "src/api/client/account.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/account.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "70cc110271455c096a089a2844056b578b130861c8379385de32396c150bfdfd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: third_party_route\n\nDocumentation:\n# `GET _matrix/client/v3/account/3pid`\n\nGet a list of third party identifiers associated with this account.\n\n- Currently always returns empty list\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn third_party_route(\n\tbody: Ruma,\n) -> Result {\n\tlet _sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tOk(get_3pids::v3::Response::new(Vec::new()))\n}\n```"}], "func_name": "third_party_route", "docstring": "# `GET _matrix/client/v3/account/3pid`\n\nGet a list of third party identifiers associated with this account.\n\n- Currently always returns empty list", "repo": "girlbossceo/conduwuit", "path": "src/api/client/account.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/account.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6ec5b4a123a86821c2928c060119f4bb0de38223d2254313aacdba44d705cfd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: request_3pid_management_token_via_email_route\n\nDocumentation:\n# `POST /_matrix/client/v3/account/3pid/email/requestToken`\n\n\"This API should be used to request validation tokens when adding an email\naddress to an account\"\n\n- 403 signals that The homeserver does not allow the third party identifier\nas a contact option.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn request_3pid_management_token_via_email_route(\n\t_body: Ruma,\n) -> Result {\n\tErr!(Request(ThreepidDenied(\"Third party identifiers are not implemented\")))\n}\n```"}], "func_name": "request_3pid_management_token_via_email_route", "docstring": "# `POST /_matrix/client/v3/account/3pid/email/requestToken`\n\n\"This API should be used to request validation tokens when adding an email\naddress to an account\"\n\n- 403 signals that The homeserver does not allow the third party identifier\nas a contact option.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/account.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/account.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f14342f40fab960362daf83c42a871fcb4a1356d23100bc96dc9d73971bd488e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: request_3pid_management_token_via_msisdn_route\n\nDocumentation:\n# `POST /_matrix/client/v3/account/3pid/msisdn/requestToken`\n\n\"This API should be used to request validation tokens when adding an phone\nnumber to an account\"\n\n- 403 signals that The homeserver does not allow the third party identifier\nas a contact option.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn request_3pid_management_token_via_msisdn_route(\n\t_body: Ruma,\n) -> Result {\n\tErr!(Request(ThreepidDenied(\"Third party identifiers are not implemented\")))\n}\n```"}], "func_name": "request_3pid_management_token_via_msisdn_route", "docstring": "# `POST /_matrix/client/v3/account/3pid/msisdn/requestToken`\n\n\"This API should be used to request validation tokens when adding an phone\nnumber to an account\"\n\n- 403 signals that The homeserver does not allow the third party identifier\nas a contact option.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/account.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/account.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ece333183cda6e540396012ceaf0ae7f643a404b6e6a52ff5be44a6b269b7c23"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: full_user_deactivate\n\nDocumentation:\nRuns through all the deactivation steps:\n\n- Mark as deactivated\n- Removing display name\n- Removing avatar URL and blurhash\n- Removing all profile data\n- Leaving all rooms (and forgets all of them)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn full_user_deactivate(\n\tservices: &Services,\n\tuser_id: &UserId,\n\tall_joined_rooms: &[OwnedRoomId],\n) -> Result<()> {\n\tservices.users.deactivate_account(user_id).await.ok();\n\tsuper::update_displayname(services, user_id, None, all_joined_rooms).await;\n\tsuper::update_avatar_url(services, user_id, None, None, all_joined_rooms).await;\n\n\tservices\n\t\t.users\n\t\t.all_profile_keys(user_id)\n\t\t.ready_for_each(|(profile_key, _)| {\n\t\t\tservices.users.set_profile_key(user_id, &profile_key, None);\n\t\t})\n\t\t.await;\n\n\tfor room_id in all_joined_rooms {\n\t\tlet state_lock = services.rooms.state.mutex.lock(room_id).await;\n\n\t\tlet room_power_levels = services\n\t\t\t.rooms\n\t\t\t.state_accessor\n\t\t\t.room_state_get_content::(\n\t\t\t\troom_id,\n\t\t\t\t&StateEventType::RoomPowerLevels,\n\t\t\t\t\"\",\n\t\t\t)\n\t\t\t.await\n\t\t\t.ok();\n\n\t\tlet user_can_demote_self =\n\t\t\troom_power_levels\n\t\t\t\t.as_ref()\n\t\t\t\t.is_some_and(|power_levels_content| {\n\t\t\t\t\tRoomPowerLevels::from(power_levels_content.clone())\n\t\t\t\t\t\t.user_can_change_user_power_level(user_id, user_id)\n\t\t\t\t}) || services\n\t\t\t\t.rooms\n\t\t\t\t.state_accessor\n\t\t\t\t.room_state_get(room_id, &StateEventType::RoomCreate, \"\")\n\t\t\t\t.await\n\t\t\t\t.is_ok_and(|event| event.sender == user_id);\n\n\t\tif user_can_demote_self {\n\t\t\tlet mut power_levels_content = room_power_levels.unwrap_or_default();\n\t\t\tpower_levels_content.users.remove(user_id);\n\n\t\t\t// ignore errors so deactivation doesn't fail\n\t\t\tmatch services\n\t\t\t\t.rooms\n\t\t\t\t.timeline\n\t\t\t\t.build_and_append_pdu(\n\t\t\t\t\tPduBuilder::state(String::new(), &power_levels_content),\n\t\t\t\t\tuser_id,\n\t\t\t\t\troom_id,\n\t\t\t\t\t&state_lock,\n\t\t\t\t)\n\t\t\t\t.await\n\t\t\t{\n\t\t\t\t| Err(e) => {\n\t\t\t\t\twarn!(%room_id, %user_id, \"Failed to demote user's own power level: {e}\");\n\t\t\t\t},\n\t\t\t\t| _ => {\n\t\t\t\t\tinfo!(\"Demoted {user_id} in {room_id} as part of account deactivation\");\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\n\tsuper::leave_all_rooms(services, user_id).await;\n\n\tOk(())\n}\n```"}], "func_name": "full_user_deactivate", "docstring": "Runs through all the deactivation steps:\n\n- Mark as deactivated\n- Removing display name\n- Removing avatar URL and blurhash\n- Removing all profile data\n- Leaving all rooms (and forgets all of them)", "repo": "girlbossceo/conduwuit", "path": "src/api/client/account.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/account.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9899688d758054f4524849edbf9fa1ea63cdecd5cd8881933b55034ca6cdae3e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_global_account_data_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/user/{userId}/account_data/{type}`\n\nSets some account data for the sender user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn set_global_account_data_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\n\tif sender_user != body.user_id && body.appservice_info.is_none() {\n\t\treturn Err!(Request(Forbidden(\"You cannot set account data for other users.\")));\n\t}\n\n\tset_account_data(\n\t\t&services,\n\t\tNone,\n\t\t&body.user_id,\n\t\t&body.event_type.to_string(),\n\t\tbody.data.json(),\n\t)\n\t.await?;\n\n\tOk(set_global_account_data::v3::Response {})\n}\n```"}], "func_name": "set_global_account_data_route", "docstring": "# `PUT /_matrix/client/r0/user/{userId}/account_data/{type}`\n\nSets some account data for the sender user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/account_data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/account_data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a45e0ad9aea4e946bf1e20f6fd6a821cb11c5563cfe86a8844bc1caa1ecb735f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_room_account_data_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}`\n\nSets some room account data for the sender user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn set_room_account_data_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\n\tif sender_user != body.user_id && body.appservice_info.is_none() {\n\t\treturn Err!(Request(Forbidden(\"You cannot set account data for other users.\")));\n\t}\n\n\tset_account_data(\n\t\t&services,\n\t\tSome(&body.room_id),\n\t\t&body.user_id,\n\t\t&body.event_type.to_string(),\n\t\tbody.data.json(),\n\t)\n\t.await?;\n\n\tOk(set_room_account_data::v3::Response {})\n}\n```"}], "func_name": "set_room_account_data_route", "docstring": "# `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}`\n\nSets some room account data for the sender user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/account_data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/account_data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e294868ef0a3d34931f57a43e050fbf63ddad39b74799208575271aa07abcc5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_global_account_data_route\n\nDocumentation:\n# `GET /_matrix/client/r0/user/{userId}/account_data/{type}`\n\nGets some account data for the sender user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_global_account_data_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\n\tif sender_user != body.user_id && body.appservice_info.is_none() {\n\t\treturn Err!(Request(Forbidden(\"You cannot get account data of other users.\")));\n\t}\n\n\tlet account_data: ExtractGlobalEventContent = services\n\t\t.account_data\n\t\t.get_global(&body.user_id, body.event_type.clone())\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"Data not found.\"))))?;\n\n\tOk(get_global_account_data::v3::Response { account_data: account_data.content })\n}\n```"}], "func_name": "get_global_account_data_route", "docstring": "# `GET /_matrix/client/r0/user/{userId}/account_data/{type}`\n\nGets some account data for the sender user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/account_data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/account_data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e37047d129e165a022833eea967bddd4cd8904be5886897b04d22418a043ea56"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_room_account_data_route\n\nDocumentation:\n# `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}`\n\nGets some room account data for the sender user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_room_account_data_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\n\tif sender_user != body.user_id && body.appservice_info.is_none() {\n\t\treturn Err!(Request(Forbidden(\"You cannot get account data of other users.\")));\n\t}\n\n\tlet account_data: ExtractRoomEventContent = services\n\t\t.account_data\n\t\t.get_room(&body.room_id, &body.user_id, body.event_type.clone())\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"Data not found.\"))))?;\n\n\tOk(get_room_account_data::v3::Response { account_data: account_data.content })\n}\n```"}], "func_name": "get_room_account_data_route", "docstring": "# `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}`\n\nGets some room account data for the sender user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/account_data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/account_data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "857885d1d461dd01dd5f44d13e4b05d672d65e207218280664528d03576d8cc4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_alias_route\n\nDocumentation:\n# `PUT /_matrix/client/v3/directory/room/{roomAlias}`\n\nCreates a new room alias on this server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn create_alias_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tservices\n\t\t.rooms\n\t\t.alias\n\t\t.appservice_checks(&body.room_alias, &body.appservice_info)\n\t\t.await?;\n\n\t// this isn't apart of alias_checks or delete alias route because we should\n\t// allow removing forbidden room aliases\n\tif services\n\t\t.globals\n\t\t.forbidden_alias_names()\n\t\t.is_match(body.room_alias.alias())\n\t{\n\t\treturn Err!(Request(Forbidden(\"Room alias is forbidden.\")));\n\t}\n\n\tif services\n\t\t.rooms\n\t\t.alias\n\t\t.resolve_local_alias(&body.room_alias)\n\t\t.await\n\t\t.is_ok()\n\t{\n\t\treturn Err!(Conflict(\"Alias already exists.\"));\n\t}\n\n\tservices\n\t\t.rooms\n\t\t.alias\n\t\t.set_alias(&body.room_alias, &body.room_id, sender_user)?;\n\n\tOk(create_alias::v3::Response::new())\n}\n```"}], "func_name": "create_alias_route", "docstring": "# `PUT /_matrix/client/v3/directory/room/{roomAlias}`\n\nCreates a new room alias on this server.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/alias.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/alias.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "931d547f9b4605b523524bd2d96c0fe8a925913601ba53bf52eda2655e5175fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_alias_route\n\nDocumentation:\n# `DELETE /_matrix/client/v3/directory/room/{roomAlias}`\n\nDeletes a room alias from this server.\n\n- TODO: Update canonical alias event\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn delete_alias_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tservices\n\t\t.rooms\n\t\t.alias\n\t\t.appservice_checks(&body.room_alias, &body.appservice_info)\n\t\t.await?;\n\n\tservices\n\t\t.rooms\n\t\t.alias\n\t\t.remove_alias(&body.room_alias, sender_user)\n\t\t.await?;\n\n\t// TODO: update alt_aliases?\n\n\tOk(delete_alias::v3::Response::new())\n}\n```"}], "func_name": "delete_alias_route", "docstring": "# `DELETE /_matrix/client/v3/directory/room/{roomAlias}`\n\nDeletes a room alias from this server.\n\n- TODO: Update canonical alias event", "repo": "girlbossceo/conduwuit", "path": "src/api/client/alias.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/alias.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0776fb10a438ed0ca0ca439b686208a0fb4a64571677edfd65c507ac8bd7702f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_alias_route\n\nDocumentation:\n# `GET /_matrix/client/v3/directory/room/{roomAlias}`\n\nResolve an alias locally or over federation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_alias_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet room_alias = body.body.room_alias;\n\n\tlet Ok((room_id, servers)) = services.rooms.alias.resolve_alias(&room_alias, None).await\n\telse {\n\t\treturn Err!(Request(NotFound(\"Room with alias not found.\")));\n\t};\n\n\tlet servers = room_available_servers(&services, &room_id, &room_alias, servers).await;\n\tdebug!(?room_alias, ?room_id, \"available servers: {servers:?}\");\n\n\tOk(get_alias::v3::Response::new(room_id, servers))\n}\n```"}], "func_name": "get_alias_route", "docstring": "# `GET /_matrix/client/v3/directory/room/{roomAlias}`\n\nResolve an alias locally or over federation.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/alias.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/alias.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "87eed89ecf6cc01e064b49d180dba0c203080f5974d7678dd7f43d2936cc60cc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: appservice_ping\n\nDocumentation:\n# `POST /_matrix/client/v1/appservice/{appserviceId}/ping`\n\nAsk the homeserver to ping the application service to ensure the connection\nworks.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn appservice_ping(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet appservice_info = body.appservice_info.as_ref().ok_or_else(|| {\n\t\terr!(Request(Forbidden(\"This endpoint can only be called by appservices.\")))\n\t})?;\n\n\tif body.appservice_id != appservice_info.registration.id {\n\t\treturn Err!(Request(Forbidden(\n\t\t\t\"Appservices can only ping themselves (wrong appservice ID).\"\n\t\t)));\n\t}\n\n\tif appservice_info.registration.url.is_none()\n\t\t|| appservice_info\n\t\t\t.registration\n\t\t\t.url\n\t\t\t.as_ref()\n\t\t\t.is_some_and(|url| url.is_empty() || url == \"null\")\n\t{\n\t\treturn Err!(Request(UrlNotSet(\n\t\t\t\"Appservice does not have a URL set, there is nothing to ping.\"\n\t\t)));\n\t}\n\n\tlet timer = tokio::time::Instant::now();\n\n\tlet _response = services\n\t\t.sending\n\t\t.send_appservice_request(\n\t\t\tappservice_info.registration.clone(),\n\t\t\tping::send_ping::v1::Request {\n\t\t\t\ttransaction_id: body.transaction_id.clone(),\n\t\t\t},\n\t\t)\n\t\t.await?\n\t\t.expect(\"We already validated if an appservice URL exists above\");\n\n\tOk(request_ping::v1::Response { duration: timer.elapsed() })\n}\n```"}], "func_name": "appservice_ping", "docstring": "# `POST /_matrix/client/v1/appservice/{appserviceId}/ping`\n\nAsk the homeserver to ping the application service to ensure the connection\nworks.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/appservice.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/appservice.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5871f3b66f9ac1d33d7c2c2ecc51573505fa35aef0ccf4f46eb941f907155527"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_backup_version_route\n\nDocumentation:\n# `POST /_matrix/client/r0/room_keys/version`\n\nCreates a new backup.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn create_backup_version_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet version = services\n\t\t.key_backups\n\t\t.create_backup(body.sender_user(), &body.algorithm)?;\n\n\tOk(create_backup_version::v3::Response { version })\n}\n```"}], "func_name": "create_backup_version_route", "docstring": "# `POST /_matrix/client/r0/room_keys/version`\n\nCreates a new backup.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0fd31b53a54a2d80d0bbaaee8d21fd15e603859ef1900f013094aaf562d56ef3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_backup_version_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/room_keys/version/{version}`\n\nUpdate information about an existing backup. Only `auth_data` can be\nmodified.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn update_backup_version_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tservices\n\t\t.key_backups\n\t\t.update_backup(body.sender_user(), &body.version, &body.algorithm)\n\t\t.await?;\n\n\tOk(update_backup_version::v3::Response {})\n}\n```"}], "func_name": "update_backup_version_route", "docstring": "# `PUT /_matrix/client/r0/room_keys/version/{version}`\n\nUpdate information about an existing backup. Only `auth_data` can be\nmodified.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "015054407251f9cd496598bf03e9c83774e592d61170ce2d17ef970513163679"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_latest_backup_info_route\n\nDocumentation:\n# `GET /_matrix/client/r0/room_keys/version`\n\nGet information about the latest backup version.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_latest_backup_info_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet (version, algorithm) = services\n\t\t.key_backups\n\t\t.get_latest_backup(body.sender_user())\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"Key backup does not exist.\"))))?;\n\n\tOk(get_latest_backup_info::v3::Response {\n\t\talgorithm,\n\t\tcount: (UInt::try_from(\n\t\t\tservices\n\t\t\t\t.key_backups\n\t\t\t\t.count_keys(body.sender_user(), &version)\n\t\t\t\t.await,\n\t\t)\n\t\t.expect(\"user backup keys count should not be that high\")),\n\t\tetag: services\n\t\t\t.key_backups\n\t\t\t.get_etag(body.sender_user(), &version)\n\t\t\t.await,\n\t\tversion,\n\t})\n}\n```"}], "func_name": "get_latest_backup_info_route", "docstring": "# `GET /_matrix/client/r0/room_keys/version`\n\nGet information about the latest backup version.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2457487fc01b02df9842486ac049cfba001ecb8816429a862665e91d883ab605"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_backup_info_route\n\nDocumentation:\n# `GET /_matrix/client/v3/room_keys/version/{version}`\n\nGet information about an existing backup.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_backup_info_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet algorithm = services\n\t\t.key_backups\n\t\t.get_backup(body.sender_user(), &body.version)\n\t\t.await\n\t\t.map_err(|_| {\n\t\t\terr!(Request(NotFound(\"Key backup does not exist at version {:?}\", body.version)))\n\t\t})?;\n\n\tOk(get_backup_info::v3::Response {\n\t\talgorithm,\n\t\tcount: services\n\t\t\t.key_backups\n\t\t\t.count_keys(body.sender_user(), &body.version)\n\t\t\t.await\n\t\t\t.try_into()?,\n\t\tetag: services\n\t\t\t.key_backups\n\t\t\t.get_etag(body.sender_user(), &body.version)\n\t\t\t.await,\n\t\tversion: body.version.clone(),\n\t})\n}\n```"}], "func_name": "get_backup_info_route", "docstring": "# `GET /_matrix/client/v3/room_keys/version/{version}`\n\nGet information about an existing backup.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dd84c4febe01803f154521bd53718c261a27c4a84521d6a50c4f1a6dade6e0d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_backup_version_route\n\nDocumentation:\n# `DELETE /_matrix/client/r0/room_keys/version/{version}`\n\nDelete an existing key backup.\n\n- Deletes both information about the backup, as well as all key data related\nto the backup\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn delete_backup_version_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tservices\n\t\t.key_backups\n\t\t.delete_backup(body.sender_user(), &body.version)\n\t\t.await;\n\n\tOk(delete_backup_version::v3::Response {})\n}\n```"}], "func_name": "delete_backup_version_route", "docstring": "# `DELETE /_matrix/client/r0/room_keys/version/{version}`\n\nDelete an existing key backup.\n\n- Deletes both information about the backup, as well as all key data related\nto the backup", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9bddad079abf59ea9adcbbea9042dbb8269acb9384ac9edcaaa366e6fb7f83fc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_backup_keys_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/room_keys/keys`\n\nAdd the received backup keys to the database.\n\n- Only manipulating the most recently created version of the backup is\nallowed\n- Adds the keys to the backup\n- Returns the new number of keys in this backup and the etag\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn add_backup_keys_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif services\n\t\t.key_backups\n\t\t.get_latest_backup_version(body.sender_user())\n\t\t.await\n\t\t.is_ok_and(|version| version != body.version)\n\t{\n\t\treturn Err!(Request(InvalidParam(\n\t\t\t\"You may only manipulate the most recently created version of the backup.\"\n\t\t)));\n\t}\n\n\tfor (room_id, room) in &body.rooms {\n\t\tfor (session_id, key_data) in &room.sessions {\n\t\t\tservices\n\t\t\t\t.key_backups\n\t\t\t\t.add_key(body.sender_user(), &body.version, room_id, session_id, key_data)\n\t\t\t\t.await?;\n\t\t}\n\t}\n\n\tOk(add_backup_keys::v3::Response {\n\t\tcount: services\n\t\t\t.key_backups\n\t\t\t.count_keys(body.sender_user(), &body.version)\n\t\t\t.await\n\t\t\t.try_into()?,\n\t\tetag: services\n\t\t\t.key_backups\n\t\t\t.get_etag(body.sender_user(), &body.version)\n\t\t\t.await,\n\t})\n}\n```"}], "func_name": "add_backup_keys_route", "docstring": "# `PUT /_matrix/client/r0/room_keys/keys`\n\nAdd the received backup keys to the database.\n\n- Only manipulating the most recently created version of the backup is\nallowed\n- Adds the keys to the backup\n- Returns the new number of keys in this backup and the etag", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f3f2b686b85a7a019e380d74cfe71d427a199b88bacdd26d31f2e4d363a961d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_backup_keys_for_room_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/room_keys/keys/{roomId}`\n\nAdd the received backup keys to the database.\n\n- Only manipulating the most recently created version of the backup is\nallowed\n- Adds the keys to the backup\n- Returns the new number of keys in this backup and the etag\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn add_backup_keys_for_room_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif services\n\t\t.key_backups\n\t\t.get_latest_backup_version(body.sender_user())\n\t\t.await\n\t\t.is_ok_and(|version| version != body.version)\n\t{\n\t\treturn Err!(Request(InvalidParam(\n\t\t\t\"You may only manipulate the most recently created version of the backup.\"\n\t\t)));\n\t}\n\n\tfor (session_id, key_data) in &body.sessions {\n\t\tservices\n\t\t\t.key_backups\n\t\t\t.add_key(body.sender_user(), &body.version, &body.room_id, session_id, key_data)\n\t\t\t.await?;\n\t}\n\n\tOk(add_backup_keys_for_room::v3::Response {\n\t\tcount: services\n\t\t\t.key_backups\n\t\t\t.count_keys(body.sender_user(), &body.version)\n\t\t\t.await\n\t\t\t.try_into()?,\n\t\tetag: services\n\t\t\t.key_backups\n\t\t\t.get_etag(body.sender_user(), &body.version)\n\t\t\t.await,\n\t})\n}\n```"}], "func_name": "add_backup_keys_for_room_route", "docstring": "# `PUT /_matrix/client/r0/room_keys/keys/{roomId}`\n\nAdd the received backup keys to the database.\n\n- Only manipulating the most recently created version of the backup is\nallowed\n- Adds the keys to the backup\n- Returns the new number of keys in this backup and the etag", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d83fc027358735864c043cc1770052058d4a98a11427cecae9407f560f80dc9a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_backup_keys_for_session_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`\n\nAdd the received backup key to the database.\n\n- Only manipulating the most recently created version of the backup is\nallowed\n- Adds the keys to the backup\n- Returns the new number of keys in this backup and the etag\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn add_backup_keys_for_session_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif services\n\t\t.key_backups\n\t\t.get_latest_backup_version(body.sender_user())\n\t\t.await\n\t\t.is_ok_and(|version| version != body.version)\n\t{\n\t\treturn Err!(Request(InvalidParam(\n\t\t\t\"You may only manipulate the most recently created version of the backup.\"\n\t\t)));\n\t}\n\n\t// Check if we already have a better key\n\tlet mut ok_to_replace = true;\n\tif let Some(old_key) = &services\n\t\t.key_backups\n\t\t.get_session(body.sender_user(), &body.version, &body.room_id, &body.session_id)\n\t\t.await\n\t\t.ok()\n\t{\n\t\tlet old_is_verified = old_key\n\t\t\t.get_field::(\"is_verified\")?\n\t\t\t.unwrap_or_default();\n\n\t\tlet new_is_verified = body\n\t\t\t.session_data\n\t\t\t.get_field::(\"is_verified\")?\n\t\t\t.ok_or_else(|| err!(Request(BadJson(\"`is_verified` field should exist\"))))?;\n\n\t\t// Prefer key that `is_verified`\n\t\tif old_is_verified != new_is_verified {\n\t\t\tif old_is_verified {\n\t\t\t\tok_to_replace = false;\n\t\t\t}\n\t\t} else {\n\t\t\t// If both have same `is_verified`, prefer the one with lower\n\t\t\t// `first_message_index`\n\t\t\tlet old_first_message_index = old_key\n\t\t\t\t.get_field::(\"first_message_index\")?\n\t\t\t\t.unwrap_or(UInt::MAX);\n\n\t\t\tlet new_first_message_index = body\n\t\t\t\t.session_data\n\t\t\t\t.get_field::(\"first_message_index\")?\n\t\t\t\t.ok_or_else(|| {\n\t\t\t\t\terr!(Request(BadJson(\"`first_message_index` field should exist\")))\n\t\t\t\t})?;\n\n\t\t\tok_to_replace = match new_first_message_index.cmp(&old_first_message_index) {\n\t\t\t\t| Ordering::Less => true,\n\t\t\t\t| Ordering::Greater => false,\n\t\t\t\t| Ordering::Equal => {\n\t\t\t\t\t// If both have same `first_message_index`, prefer the one with lower\n\t\t\t\t\t// `forwarded_count`\n\t\t\t\t\tlet old_forwarded_count = old_key\n\t\t\t\t\t\t.get_field::(\"forwarded_count\")?\n\t\t\t\t\t\t.unwrap_or(UInt::MAX);\n\n\t\t\t\t\tlet new_forwarded_count = body\n\t\t\t\t\t\t.session_data\n\t\t\t\t\t\t.get_field::(\"forwarded_count\")?\n\t\t\t\t\t\t.ok_or_else(|| {\n\t\t\t\t\t\t\terr!(Request(BadJson(\"`forwarded_count` field should exist\")))\n\t\t\t\t\t\t})?;\n\n\t\t\t\t\tnew_forwarded_count < old_forwarded_count\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\tif ok_to_replace {\n\t\tservices\n\t\t\t.key_backups\n\t\t\t.add_key(\n\t\t\t\tbody.sender_user(),\n\t\t\t\t&body.version,\n\t\t\t\t&body.room_id,\n\t\t\t\t&body.session_id,\n\t\t\t\t&body.session_data,\n\t\t\t)\n\t\t\t.await?;\n\t}\n\n\tOk(add_backup_keys_for_session::v3::Response {\n\t\tcount: services\n\t\t\t.key_backups\n\t\t\t.count_keys(body.sender_user(), &body.version)\n\t\t\t.await\n\t\t\t.try_into()?,\n\t\tetag: services\n\t\t\t.key_backups\n\t\t\t.get_etag(body.sender_user(), &body.version)\n\t\t\t.await,\n\t})\n}\n```"}], "func_name": "add_backup_keys_for_session_route", "docstring": "# `PUT /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`\n\nAdd the received backup key to the database.\n\n- Only manipulating the most recently created version of the backup is\nallowed\n- Adds the keys to the backup\n- Returns the new number of keys in this backup and the etag", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1dd196e1bacf11596da6c19b0fcb75a710215318d30d6810a6e63fa3b920d9e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_backup_keys_route\n\nDocumentation:\n# `GET /_matrix/client/r0/room_keys/keys`\n\nRetrieves all keys from the backup.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_backup_keys_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet rooms = services\n\t\t.key_backups\n\t\t.get_all(body.sender_user(), &body.version)\n\t\t.await;\n\n\tOk(get_backup_keys::v3::Response { rooms })\n}\n```"}], "func_name": "get_backup_keys_route", "docstring": "# `GET /_matrix/client/r0/room_keys/keys`\n\nRetrieves all keys from the backup.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fb8455e03fe01f5211de9386890cd4324ac220635670b4b84f55c509d89b3294"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_backup_keys_for_room_route\n\nDocumentation:\n# `GET /_matrix/client/r0/room_keys/keys/{roomId}`\n\nRetrieves all keys from the backup for a given room.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_backup_keys_for_room_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sessions = services\n\t\t.key_backups\n\t\t.get_room(body.sender_user(), &body.version, &body.room_id)\n\t\t.await;\n\n\tOk(get_backup_keys_for_room::v3::Response { sessions })\n}\n```"}], "func_name": "get_backup_keys_for_room_route", "docstring": "# `GET /_matrix/client/r0/room_keys/keys/{roomId}`\n\nRetrieves all keys from the backup for a given room.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f005e704dd6c5ef875e92a8bee60b5734819f53de04c856d294bc0b73421de41"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_backup_keys_for_session_route\n\nDocumentation:\n# `GET /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`\n\nRetrieves a key from the backup.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_backup_keys_for_session_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet key_data = services\n\t\t.key_backups\n\t\t.get_session(body.sender_user(), &body.version, &body.room_id, &body.session_id)\n\t\t.await\n\t\t.map_err(|_| {\n\t\t\terr!(Request(NotFound(debug_error!(\"Backup key not found for this user's session.\"))))\n\t\t})?;\n\n\tOk(get_backup_keys_for_session::v3::Response { key_data })\n}\n```"}], "func_name": "get_backup_keys_for_session_route", "docstring": "# `GET /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`\n\nRetrieves a key from the backup.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3495da7ab555da77facdf4ce6a7695270670c358d6607340633b54882ca67434"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_backup_keys_route\n\nDocumentation:\n# `DELETE /_matrix/client/r0/room_keys/keys`\n\nDelete the keys from the backup.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn delete_backup_keys_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tservices\n\t\t.key_backups\n\t\t.delete_all_keys(body.sender_user(), &body.version)\n\t\t.await;\n\n\tOk(delete_backup_keys::v3::Response {\n\t\tcount: services\n\t\t\t.key_backups\n\t\t\t.count_keys(body.sender_user(), &body.version)\n\t\t\t.await\n\t\t\t.try_into()?,\n\t\tetag: services\n\t\t\t.key_backups\n\t\t\t.get_etag(body.sender_user(), &body.version)\n\t\t\t.await,\n\t})\n}\n```"}], "func_name": "delete_backup_keys_route", "docstring": "# `DELETE /_matrix/client/r0/room_keys/keys`\n\nDelete the keys from the backup.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "616ab56eccbdc4345a0478fd3163df925c5d1f982cf5d82755c48fe0ee558610"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_backup_keys_for_room_route\n\nDocumentation:\n# `DELETE /_matrix/client/r0/room_keys/keys/{roomId}`\n\nDelete the keys from the backup for a given room.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn delete_backup_keys_for_room_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tservices\n\t\t.key_backups\n\t\t.delete_room_keys(body.sender_user(), &body.version, &body.room_id)\n\t\t.await;\n\n\tOk(delete_backup_keys_for_room::v3::Response {\n\t\tcount: services\n\t\t\t.key_backups\n\t\t\t.count_keys(body.sender_user(), &body.version)\n\t\t\t.await\n\t\t\t.try_into()?,\n\t\tetag: services\n\t\t\t.key_backups\n\t\t\t.get_etag(body.sender_user(), &body.version)\n\t\t\t.await,\n\t})\n}\n```"}], "func_name": "delete_backup_keys_for_room_route", "docstring": "# `DELETE /_matrix/client/r0/room_keys/keys/{roomId}`\n\nDelete the keys from the backup for a given room.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "430a5e715c04bbd10d4391d99220e483924dcbf89acdaa9279a7080bb5d73d31"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_backup_keys_for_session_route\n\nDocumentation:\n# `DELETE /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`\n\nDelete a key from the backup.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn delete_backup_keys_for_session_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tservices\n\t\t.key_backups\n\t\t.delete_room_key(body.sender_user(), &body.version, &body.room_id, &body.session_id)\n\t\t.await;\n\n\tOk(delete_backup_keys_for_session::v3::Response {\n\t\tcount: services\n\t\t\t.key_backups\n\t\t\t.count_keys(body.sender_user(), &body.version)\n\t\t\t.await\n\t\t\t.try_into()?,\n\t\tetag: services\n\t\t\t.key_backups\n\t\t\t.get_etag(body.sender_user(), &body.version)\n\t\t\t.await,\n\t})\n}\n```"}], "func_name": "delete_backup_keys_for_session_route", "docstring": "# `DELETE /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`\n\nDelete a key from the backup.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/backup.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/backup.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "42fa22f61d2a4bf00d199ff740fc452772cd46207be337a87f42b9e5702800ae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_capabilities_route\n\nDocumentation:\n# `GET /_matrix/client/v3/capabilities`\n\nGet information on the supported feature set and other relevent capabilities\nof this server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_capabilities_route(\n\tState(services): State,\n\t_body: Ruma,\n) -> Result {\n\tlet available: BTreeMap =\n\t\tServer::available_room_versions().collect();\n\n\tlet mut capabilities = Capabilities::default();\n\tcapabilities.room_versions = RoomVersionsCapability {\n\t\tdefault: services.server.config.default_room_version.clone(),\n\t\tavailable,\n\t};\n\n\t// we do not implement 3PID stuff\n\tcapabilities.thirdparty_id_changes = ThirdPartyIdChangesCapability { enabled: false };\n\n\tcapabilities.get_login_token = GetLoginTokenCapability {\n\t\tenabled: services.server.config.login_via_existing_session,\n\t};\n\n\t// MSC4133 capability\n\tcapabilities\n\t\t.set(\"uk.tcpip.msc4133.profile_fields\", json!({\"enabled\": true}))\n\t\t.expect(\"this is valid JSON we created\");\n\n\tcapabilities\n\t\t.set(\n\t\t\t\"org.matrix.msc4267.forget_forced_upon_leave\",\n\t\t\tjson!({\"enabled\": services.config.forget_forced_upon_leave}),\n\t\t)\n\t\t.expect(\"valid JSON we created\");\n\n\tOk(get_capabilities::v3::Response { capabilities })\n}\n```"}], "func_name": "get_capabilities_route", "docstring": "# `GET /_matrix/client/v3/capabilities`\n\nGet information on the supported feature set and other relevent capabilities\nof this server.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/capabilities.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/capabilities.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6c0ba34cfe4cfd18932822bd2f180478c1c352251183db87014e64a3d6e4de4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_context_route\n\nDocumentation:\n# `GET /_matrix/client/r0/rooms/{roomId}/context/{eventId}`\n\nAllows loading room history around an event.\n\n- Only works if the user is joined (TODO: always allow, but only show events\nif the user was joined, depending on history_visibility)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_context_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender = body.sender();\n\tlet (sender_user, sender_device) = sender;\n\tlet room_id = &body.room_id;\n\tlet event_id = &body.event_id;\n\tlet filter = &body.filter;\n\n\tif !services.rooms.metadata.exists(room_id).await {\n\t\treturn Err!(Request(Forbidden(\"Room does not exist to this server\")));\n\t}\n\n\t// Use limit or else 10, with maximum 100\n\tlet limit: usize = body\n\t\t.limit\n\t\t.try_into()\n\t\t.unwrap_or(LIMIT_DEFAULT)\n\t\t.min(LIMIT_MAX);\n\n\tlet base_id = services\n\t\t.rooms\n\t\t.timeline\n\t\t.get_pdu_id(event_id)\n\t\t.map_err(|_| err!(Request(NotFound(\"Event not found.\"))));\n\n\tlet base_pdu = services\n\t\t.rooms\n\t\t.timeline\n\t\t.get_pdu(event_id)\n\t\t.map_err(|_| err!(Request(NotFound(\"Base event not found.\"))));\n\n\tlet visible = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.user_can_see_event(sender_user, room_id, event_id)\n\t\t.map(Ok);\n\n\tlet (base_id, base_pdu, visible) = try_join3(base_id, base_pdu, visible).await?;\n\n\tif base_pdu.room_id != *room_id || base_pdu.event_id != *event_id {\n\t\treturn Err!(Request(NotFound(\"Base event not found.\")));\n\t}\n\n\tif !visible {\n\t\tdebug_warn!(req_evt = ?event_id, ?base_id, ?room_id, \"Event requested by {sender_user} but is not allowed to see it, returning 404\");\n\t\treturn Err!(Request(NotFound(\"Event not found.\")));\n\t}\n\n\tlet base_count = base_id.pdu_count();\n\n\tlet base_event = ignored_filter(&services, (base_count, base_pdu), sender_user);\n\n\tlet events_before = services\n\t\t.rooms\n\t\t.timeline\n\t\t.pdus_rev(Some(sender_user), room_id, Some(base_count))\n\t\t.ignore_err()\n\t\t.ready_filter_map(|item| event_filter(item, filter))\n\t\t.wide_filter_map(|item| ignored_filter(&services, item, sender_user))\n\t\t.wide_filter_map(|item| visibility_filter(&services, item, sender_user))\n\t\t.take(limit / 2)\n\t\t.collect();\n\n\tlet events_after = services\n\t\t.rooms\n\t\t.timeline\n\t\t.pdus(Some(sender_user), room_id, Some(base_count))\n\t\t.ignore_err()\n\t\t.ready_filter_map(|item| event_filter(item, filter))\n\t\t.wide_filter_map(|item| ignored_filter(&services, item, sender_user))\n\t\t.wide_filter_map(|item| visibility_filter(&services, item, sender_user))\n\t\t.take(limit / 2)\n\t\t.collect();\n\n\tlet (base_event, events_before, events_after): (_, Vec<_>, Vec<_>) =\n\t\tjoin3(base_event, events_before, events_after).boxed().await;\n\n\tlet lazy_loading_context = lazy_loading::Context {\n\t\tuser_id: sender_user,\n\t\tdevice_id: sender_device,\n\t\troom_id,\n\t\ttoken: Some(base_count.into_unsigned()),\n\t\toptions: Some(&filter.lazy_load_options),\n\t};\n\n\tlet lazy_loading_witnessed: OptionFuture<_> = filter\n\t\t.lazy_load_options\n\t\t.is_enabled()\n\t\t.then_some(\n\t\t\tbase_event\n\t\t\t\t.iter()\n\t\t\t\t.chain(events_before.iter())\n\t\t\t\t.chain(events_after.iter()),\n\t\t)\n\t\t.map(|witnessed| lazy_loading_witness(&services, &lazy_loading_context, witnessed))\n\t\t.into();\n\n\tlet state_at = events_after\n\t\t.last()\n\t\t.map(ref_at!(1))\n\t\t.map_or(body.event_id.as_ref(), |pdu| pdu.event_id.as_ref());\n\n\tlet state_ids = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.pdu_shortstatehash(state_at)\n\t\t.or_else(|_| services.rooms.state.get_room_shortstatehash(room_id))\n\t\t.map_ok(|shortstatehash| {\n\t\t\tservices\n\t\t\t\t.rooms\n\t\t\t\t.state_accessor\n\t\t\t\t.state_full_ids(shortstatehash)\n\t\t\t\t.map(Ok)\n\t\t})\n\t\t.map_err(|e| err!(Database(\"State not found: {e}\")))\n\t\t.try_flatten_stream()\n\t\t.try_collect()\n\t\t.boxed();\n\n\tlet (lazy_loading_witnessed, state_ids) = join(lazy_loading_witnessed, state_ids).await;\n\n\tlet state_ids: Vec<(ShortStateKey, OwnedEventId)> = state_ids?;\n\tlet shortstatekeys = state_ids.iter().map(at!(0)).stream();\n\tlet shorteventids = state_ids.iter().map(ref_at!(1)).stream();\n\tlet lazy_loading_witnessed = lazy_loading_witnessed.unwrap_or_default();\n\tlet state: Vec<_> = services\n\t\t.rooms\n\t\t.short\n\t\t.multi_get_statekey_from_short(shortstatekeys)\n\t\t.zip(shorteventids)\n\t\t.ready_filter_map(|item| Some((item.0.ok()?, item.1)))\n\t\t.ready_filter_map(|((event_type, state_key), event_id)| {\n\t\t\tif filter.lazy_load_options.is_enabled()\n\t\t\t\t&& event_type == StateEventType::RoomMember\n\t\t\t\t&& state_key\n\t\t\t\t\t.as_str()\n\t\t\t\t\t.try_into()\n\t\t\t\t\t.is_ok_and(|user_id: &UserId| !lazy_loading_witnessed.contains(user_id))\n\t\t\t{\n\t\t\t\treturn None;\n\t\t\t}\n\n\t\t\tSome(event_id)\n\t\t})\n\t\t.broad_filter_map(|event_id: &OwnedEventId| {\n\t\t\tservices.rooms.timeline.get_pdu(event_id.as_ref()).ok()\n\t\t})\n\t\t.map(PduEvent::into_state_event)\n\t\t.collect()\n\t\t.await;\n\n\tOk(get_context::v3::Response {\n\t\tevent: base_event.map(at!(1)).map(PduEvent::into_room_event),\n\n\t\tstart: events_before\n\t\t\t.last()\n\t\t\t.map(at!(0))\n\t\t\t.or(Some(base_count))\n\t\t\t.as_ref()\n\t\t\t.map(ToString::to_string),\n\n\t\tend: events_after\n\t\t\t.last()\n\t\t\t.map(at!(0))\n\t\t\t.or(Some(base_count))\n\t\t\t.as_ref()\n\t\t\t.map(ToString::to_string),\n\n\t\tevents_before: events_before\n\t\t\t.into_iter()\n\t\t\t.map(at!(1))\n\t\t\t.map(PduEvent::into_room_event)\n\t\t\t.collect(),\n\n\t\tevents_after: events_after\n\t\t\t.into_iter()\n\t\t\t.map(at!(1))\n\t\t\t.map(PduEvent::into_room_event)\n\t\t\t.collect(),\n\n\t\tstate,\n\t})\n}\n```"}], "func_name": "get_context_route", "docstring": "# `GET /_matrix/client/r0/rooms/{roomId}/context/{eventId}`\n\nAllows loading room history around an event.\n\n- Only works if the user is joined (TODO: always allow, but only show events\nif the user was joined, depending on history_visibility)", "repo": "girlbossceo/conduwuit", "path": "src/api/client/context.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c25a3872ac84ef54a1d12382d81a9e48674cb9071d595052939285b7f4a5ce6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_devices_route\n\nDocumentation:\n# `GET /_matrix/client/r0/devices`\n\nGet metadata on all devices of the sender user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_devices_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tlet devices: Vec = services\n\t\t.users\n\t\t.all_devices_metadata(sender_user)\n\t\t.collect()\n\t\t.await;\n\n\tOk(get_devices::v3::Response { devices })\n}\n```"}], "func_name": "get_devices_route", "docstring": "# `GET /_matrix/client/r0/devices`\n\nGet metadata on all devices of the sender user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/device.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "35a8d08b50d24debdac32c3bed8bfd925f88801f23dcaca7e7fc10db0032ba24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_device_route\n\nDocumentation:\n# `GET /_matrix/client/r0/devices/{deviceId}`\n\nGet metadata on a single device of the sender user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_device_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tlet device = services\n\t\t.users\n\t\t.get_device_metadata(sender_user, &body.body.device_id)\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"Device not found.\"))))?;\n\n\tOk(get_device::v3::Response { device })\n}\n```"}], "func_name": "get_device_route", "docstring": "# `GET /_matrix/client/r0/devices/{deviceId}`\n\nGet metadata on a single device of the sender user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/device.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fe19548ca9d045aa2a8b8f3b02b415161427e2e676005c3a439405128629089c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_device_route\n\nDocumentation:\n# `DELETE /_matrix/client/r0/devices/{deviceId}`\n\nDeletes the given device.\n\n- Requires UIAA to verify user password\n- Invalidates access token\n- Deletes device metadata (device id, device display name, last seen ip,\nlast seen ts)\n- Forgets to-device events\n- Triggers device list updates\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn delete_device_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet (sender_user, sender_device) = body.sender();\n\tlet appservice = body.appservice_info.as_ref();\n\n\tif appservice.is_some_and(|appservice| appservice.registration.device_management) {\n\t\tdebug!(\n\t\t\t\"Skipping UIAA for {sender_user} as this is from an appservice and MSC4190 is \\\n\t\t\t enabled\"\n\t\t);\n\t\tservices\n\t\t\t.users\n\t\t\t.remove_device(sender_user, &body.device_id)\n\t\t\t.await;\n\n\t\treturn Ok(delete_device::v3::Response {});\n\t}\n\n\t// UIAA\n\tlet mut uiaainfo = UiaaInfo {\n\t\tflows: vec![AuthFlow { stages: vec![AuthType::Password] }],\n\t\tcompleted: Vec::new(),\n\t\tparams: Box::default(),\n\t\tsession: None,\n\t\tauth_error: None,\n\t};\n\n\tmatch &body.auth {\n\t\t| Some(auth) => {\n\t\t\tlet (worked, uiaainfo) = services\n\t\t\t\t.uiaa\n\t\t\t\t.try_auth(sender_user, sender_device, auth, &uiaainfo)\n\t\t\t\t.await?;\n\n\t\t\tif !worked {\n\t\t\t\treturn Err!(Uiaa(uiaainfo));\n\t\t\t}\n\t\t\t// Success!\n\t\t},\n\t\t| _ => match body.json_body {\n\t\t\t| Some(ref json) => {\n\t\t\t\tuiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));\n\t\t\t\tservices\n\t\t\t\t\t.uiaa\n\t\t\t\t\t.create(sender_user, sender_device, &uiaainfo, json);\n\n\t\t\t\treturn Err!(Uiaa(uiaainfo));\n\t\t\t},\n\t\t\t| _ => {\n\t\t\t\treturn Err!(Request(NotJson(\"Not json.\")));\n\t\t\t},\n\t\t},\n\t}\n\n\tservices\n\t\t.users\n\t\t.remove_device(sender_user, &body.device_id)\n\t\t.await;\n\n\tOk(delete_device::v3::Response {})\n}\n```"}], "func_name": "delete_device_route", "docstring": "# `DELETE /_matrix/client/r0/devices/{deviceId}`\n\nDeletes the given device.\n\n- Requires UIAA to verify user password\n- Invalidates access token\n- Deletes device metadata (device id, device display name, last seen ip,\nlast seen ts)\n- Forgets to-device events\n- Triggers device list updates", "repo": "girlbossceo/conduwuit", "path": "src/api/client/device.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09c5389326c8ad0ac0a49441c762eae66885db39fe9fc7e3617b5519e24596e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_devices_route\n\nDocumentation:\n# `POST /_matrix/client/v3/delete_devices`\n\nDeletes the given list of devices.\n\n- Requires UIAA to verify user password unless from an appservice with\nMSC4190 enabled.\n\nFor each device:\n- Invalidates access token\n- Deletes device metadata (device id, device display name, last seen ip,\nlast seen ts)\n- Forgets to-device events\n- Triggers device list updates\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn delete_devices_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet (sender_user, sender_device) = body.sender();\n\tlet appservice = body.appservice_info.as_ref();\n\n\tif appservice.is_some_and(|appservice| appservice.registration.device_management) {\n\t\tdebug!(\n\t\t\t\"Skipping UIAA for {sender_user} as this is from an appservice and MSC4190 is \\\n\t\t\t enabled\"\n\t\t);\n\t\tfor device_id in &body.devices {\n\t\t\tservices.users.remove_device(sender_user, device_id).await;\n\t\t}\n\n\t\treturn Ok(delete_devices::v3::Response {});\n\t}\n\n\t// UIAA\n\tlet mut uiaainfo = UiaaInfo {\n\t\tflows: vec![AuthFlow { stages: vec![AuthType::Password] }],\n\t\tcompleted: Vec::new(),\n\t\tparams: Box::default(),\n\t\tsession: None,\n\t\tauth_error: None,\n\t};\n\n\tmatch &body.auth {\n\t\t| Some(auth) => {\n\t\t\tlet (worked, uiaainfo) = services\n\t\t\t\t.uiaa\n\t\t\t\t.try_auth(sender_user, sender_device, auth, &uiaainfo)\n\t\t\t\t.await?;\n\n\t\t\tif !worked {\n\t\t\t\treturn Err(Error::Uiaa(uiaainfo));\n\t\t\t}\n\t\t\t// Success!\n\t\t},\n\t\t| _ => match body.json_body {\n\t\t\t| Some(ref json) => {\n\t\t\t\tuiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));\n\t\t\t\tservices\n\t\t\t\t\t.uiaa\n\t\t\t\t\t.create(sender_user, sender_device, &uiaainfo, json);\n\n\t\t\t\treturn Err(Error::Uiaa(uiaainfo));\n\t\t\t},\n\t\t\t| _ => {\n\t\t\t\treturn Err(Error::BadRequest(ErrorKind::NotJson, \"Not json.\"));\n\t\t\t},\n\t\t},\n\t}\n\n\tfor device_id in &body.devices {\n\t\tservices.users.remove_device(sender_user, device_id).await;\n\t}\n\n\tOk(delete_devices::v3::Response {})\n}\n```"}], "func_name": "delete_devices_route", "docstring": "# `POST /_matrix/client/v3/delete_devices`\n\nDeletes the given list of devices.\n\n- Requires UIAA to verify user password unless from an appservice with\nMSC4190 enabled.\n\nFor each device:\n- Invalidates access token\n- Deletes device metadata (device id, device display name, last seen ip,\nlast seen ts)\n- Forgets to-device events\n- Triggers device list updates", "repo": "girlbossceo/conduwuit", "path": "src/api/client/device.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "780f7b9624a22e7bf356b7b57abc7bd06b2792e8f66cdc26bdb5e8c070e3a4ed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_room_visibility_route\n\nDocumentation:\n# `GET /_matrix/client/r0/directory/list/room/{roomId}`\n\nGets the visibility of a given room in the room directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_room_visibility_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif !services.rooms.metadata.exists(&body.room_id).await {\n\t\t// Return 404 if the room doesn't exist\n\t\treturn Err!(Request(NotFound(\"Room not found\")));\n\t}\n\n\tOk(get_room_visibility::v3::Response {\n\t\tvisibility: if services.rooms.directory.is_public_room(&body.room_id).await {\n\t\t\troom::Visibility::Public\n\t\t} else {\n\t\t\troom::Visibility::Private\n\t\t},\n\t})\n}\n```"}], "func_name": "get_room_visibility_route", "docstring": "# `GET /_matrix/client/r0/directory/list/room/{roomId}`\n\nGets the visibility of a given room in the room directory.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/directory.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/directory.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6cdc7a347fc02586a1849850c33aea82a4cdb368afd415619c8fd188cedae374"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: user_can_publish_room\n\nDocumentation:\nCheck whether the user can publish to the room directory via power levels of\nroom history visibility event or room creator\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn user_can_publish_room(\n\tservices: &Services,\n\tuser_id: &UserId,\n\troom_id: &RoomId,\n) -> Result {\n\tmatch services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.room_state_get(room_id, &StateEventType::RoomPowerLevels, \"\")\n\t\t.await\n\t{\n\t\t| Ok(event) => serde_json::from_str(event.content.get())\n\t\t\t.map_err(|_| err!(Database(\"Invalid event content for m.room.power_levels\")))\n\t\t\t.map(|content: RoomPowerLevelsEventContent| {\n\t\t\t\tRoomPowerLevels::from(content)\n\t\t\t\t\t.user_can_send_state(user_id, StateEventType::RoomHistoryVisibility)\n\t\t\t}),\n\t\t| _ => {\n\t\t\tmatch services\n\t\t\t\t.rooms\n\t\t\t\t.state_accessor\n\t\t\t\t.room_state_get(room_id, &StateEventType::RoomCreate, \"\")\n\t\t\t\t.await\n\t\t\t{\n\t\t\t\t| Ok(event) => Ok(event.sender == user_id),\n\t\t\t\t| _ => Err!(Request(Forbidden(\"User is not allowed to publish this room\"))),\n\t\t\t}\n\t\t},\n\t}\n}\n```"}], "func_name": "user_can_publish_room", "docstring": "Check whether the user can publish to the room directory via power levels of\nroom history visibility event or room creator", "repo": "girlbossceo/conduwuit", "path": "src/api/client/directory.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/directory.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "50230122a76763a056c520e40dca13448503e424ebcf7bda4e8534aeba74cfa8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_filter_route\n\nDocumentation:\n# `GET /_matrix/client/r0/user/{userId}/filter/{filterId}`\n\nLoads a filter that was previously created.\n\n- A user can only access their own filters\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_filter_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tservices\n\t\t.users\n\t\t.get_filter(sender_user, &body.filter_id)\n\t\t.await\n\t\t.map(get_filter::v3::Response::new)\n\t\t.map_err(|_| err!(Request(NotFound(\"Filter not found.\"))))\n}\n```"}], "func_name": "get_filter_route", "docstring": "# `GET /_matrix/client/r0/user/{userId}/filter/{filterId}`\n\nLoads a filter that was previously created.\n\n- A user can only access their own filters", "repo": "girlbossceo/conduwuit", "path": "src/api/client/filter.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/filter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54e5a0ba4820f7a4de6236501ac46fcc613e9e4d610db4a67c6504e828778c69"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_filter_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/user/{userId}/filter`\n\nCreates a new filter to be used by other endpoints.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn create_filter_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tlet filter_id = services.users.create_filter(sender_user, &body.filter);\n\n\tOk(create_filter::v3::Response::new(filter_id))\n}\n```"}], "func_name": "create_filter_route", "docstring": "# `PUT /_matrix/client/r0/user/{userId}/filter`\n\nCreates a new filter to be used by other endpoints.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/filter.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/filter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9f601e344ce87ccba4c2e0b283fcf8ff77ebf55a159188c4d69aa02cf3bbbb1a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: upload_keys_route\n\nDocumentation:\n# `POST /_matrix/client/r0/keys/upload`\n\nPublish end-to-end encryption keys for the sender device.\n\n- Adds one time keys\n- If there are no device keys yet: Adds device keys (TODO: merge with\nexisting keys?)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn upload_keys_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet (sender_user, sender_device) = body.sender();\n\n\tfor (key_id, one_time_key) in &body.one_time_keys {\n\t\tif one_time_key\n\t\t\t.deserialize()\n\t\t\t.inspect_err(|e| {\n\t\t\t\tdebug_warn!(\n\t\t\t\t\t?key_id,\n\t\t\t\t\t?one_time_key,\n\t\t\t\t\t\"Invalid one time key JSON submitted by client, skipping: {e}\"\n\t\t\t\t);\n\t\t\t})\n\t\t\t.is_err()\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tservices\n\t\t\t.users\n\t\t\t.add_one_time_key(sender_user, sender_device, key_id, one_time_key)\n\t\t\t.await?;\n\t}\n\n\tif let Some(device_keys) = &body.device_keys {\n\t\tlet deser_device_keys = device_keys.deserialize().map_err(|e| {\n\t\t\terr!(Request(BadJson(debug_warn!(\n\t\t\t\t?device_keys,\n\t\t\t\t\"Invalid device keys JSON uploaded by client: {e}\"\n\t\t\t))))\n\t\t})?;\n\n\t\tif deser_device_keys.user_id != sender_user {\n\t\t\treturn Err!(Request(Unknown(\n\t\t\t\t\"User ID in keys uploaded does not match your own user ID\"\n\t\t\t)));\n\t\t}\n\t\tif deser_device_keys.device_id != sender_device {\n\t\t\treturn Err!(Request(Unknown(\n\t\t\t\t\"Device ID in keys uploaded does not match your own device ID\"\n\t\t\t)));\n\t\t}\n\n\t\tif let Ok(existing_keys) = services\n\t\t\t.users\n\t\t\t.get_device_keys(sender_user, sender_device)\n\t\t\t.await\n\t\t{\n\t\t\tif existing_keys.json().get() == device_keys.json().get() {\n\t\t\t\tdebug!(\n\t\t\t\t\t?sender_user,\n\t\t\t\t\t?sender_device,\n\t\t\t\t\t?device_keys,\n\t\t\t\t\t\"Ignoring user uploaded keys as they are an exact copy already in the \\\n\t\t\t\t\t database\"\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tservices\n\t\t\t\t\t.users\n\t\t\t\t\t.add_device_keys(sender_user, sender_device, device_keys)\n\t\t\t\t\t.await;\n\t\t\t}\n\t\t} else {\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.add_device_keys(sender_user, sender_device, device_keys)\n\t\t\t\t.await;\n\t\t}\n\t}\n\n\tOk(upload_keys::v3::Response {\n\t\tone_time_key_counts: services\n\t\t\t.users\n\t\t\t.count_one_time_keys(sender_user, sender_device)\n\t\t\t.await,\n\t})\n}\n```"}], "func_name": "upload_keys_route", "docstring": "# `POST /_matrix/client/r0/keys/upload`\n\nPublish end-to-end encryption keys for the sender device.\n\n- Adds one time keys\n- If there are no device keys yet: Adds device keys (TODO: merge with\nexisting keys?)", "repo": "girlbossceo/conduwuit", "path": "src/api/client/keys.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/keys.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b44bcc3c6cb6c20f052fb4d180323a44265b91b718cbd94b11f5984c3c1288ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_keys_route\n\nDocumentation:\n# `POST /_matrix/client/r0/keys/query`\n\nGet end-to-end encryption keys for the given users.\n\n- Always fetches users from other servers over federation\n- Gets master keys, self-signing keys, user signing keys and device keys.\n- The master and self-signing keys contain signatures that the user is\nallowed to see\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_keys_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tget_keys_helper(\n\t\t&services,\n\t\tSome(sender_user),\n\t\t&body.device_keys,\n\t\t|u| u == sender_user,\n\t\ttrue, // Always allow local users to see device names of other local users\n\t)\n\t.await\n}\n```"}], "func_name": "get_keys_route", "docstring": "# `POST /_matrix/client/r0/keys/query`\n\nGet end-to-end encryption keys for the given users.\n\n- Always fetches users from other servers over federation\n- Gets master keys, self-signing keys, user signing keys and device keys.\n- The master and self-signing keys contain signatures that the user is\nallowed to see", "repo": "girlbossceo/conduwuit", "path": "src/api/client/keys.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/keys.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0db99a80e4eba6dd7f46868952d55a2c47987d0de5ca35b78216565a9ba8253b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: claim_keys_route\n\nDocumentation:\n# `POST /_matrix/client/r0/keys/claim`\n\nClaims one-time keys\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn claim_keys_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tclaim_keys_helper(&services, &body.one_time_keys).await\n}\n```"}], "func_name": "claim_keys_route", "docstring": "# `POST /_matrix/client/r0/keys/claim`\n\nClaims one-time keys", "repo": "girlbossceo/conduwuit", "path": "src/api/client/keys.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/keys.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "03219b97d51eb0fecc36feab3497ffe4fe0d49103fbbdd44b00be692aba1ffb4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: upload_signing_keys_route\n\nDocumentation:\n# `POST /_matrix/client/r0/keys/device_signing/upload`\n\nUploads end-to-end key information for the sender user.\n\n- Requires UIAA to verify password\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn upload_signing_keys_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\tlet sender_device = body.sender_device.as_ref().expect(\"user is authenticated\");\n\n\t// UIAA\n\tlet mut uiaainfo = UiaaInfo {\n\t\tflows: vec![AuthFlow { stages: vec![AuthType::Password] }],\n\t\tcompleted: Vec::new(),\n\t\tparams: Box::default(),\n\t\tsession: None,\n\t\tauth_error: None,\n\t};\n\n\tmatch check_for_new_keys(\n\t\tservices,\n\t\tsender_user,\n\t\tbody.self_signing_key.as_ref(),\n\t\tbody.user_signing_key.as_ref(),\n\t\tbody.master_key.as_ref(),\n\t)\n\t.await\n\t.inspect_err(|e| debug!(?e))\n\t{\n\t\t| Ok(exists) => {\n\t\t\tif let Some(result) = exists {\n\t\t\t\t// No-op, they tried to reupload the same set of keys\n\t\t\t\t// (lost connection for example)\n\t\t\t\treturn Ok(result);\n\t\t\t}\n\t\t\tdebug!(\n\t\t\t\t\"Skipping UIA in accordance with MSC3967, the user didn't have any existing keys\"\n\t\t\t);\n\t\t\t// Some of the keys weren't found, so we let them upload\n\t\t},\n\t\t| _ => {\n\t\t\tmatch &body.auth {\n\t\t\t\t| Some(auth) => {\n\t\t\t\t\tlet (worked, uiaainfo) = services\n\t\t\t\t\t\t.uiaa\n\t\t\t\t\t\t.try_auth(sender_user, sender_device, auth, &uiaainfo)\n\t\t\t\t\t\t.await?;\n\n\t\t\t\t\tif !worked {\n\t\t\t\t\t\treturn Err(Error::Uiaa(uiaainfo));\n\t\t\t\t\t}\n\t\t\t\t\t// Success!\n\t\t\t\t},\n\t\t\t\t| _ => match body.json_body {\n\t\t\t\t\t| Some(json) => {\n\t\t\t\t\t\tuiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));\n\t\t\t\t\t\tservices\n\t\t\t\t\t\t\t.uiaa\n\t\t\t\t\t\t\t.create(sender_user, sender_device, &uiaainfo, &json);\n\n\t\t\t\t\t\treturn Err(Error::Uiaa(uiaainfo));\n\t\t\t\t\t},\n\t\t\t\t\t| _ => {\n\t\t\t\t\t\treturn Err(Error::BadRequest(ErrorKind::NotJson, \"Not json.\"));\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t}\n\n\tservices\n\t\t.users\n\t\t.add_cross_signing_keys(\n\t\t\tsender_user,\n\t\t\t&body.master_key,\n\t\t\t&body.self_signing_key,\n\t\t\t&body.user_signing_key,\n\t\t\ttrue, // notify so that other users see the new keys\n\t\t)\n\t\t.await?;\n\n\tOk(upload_signing_keys::v3::Response {})\n}\n```"}], "func_name": "upload_signing_keys_route", "docstring": "# `POST /_matrix/client/r0/keys/device_signing/upload`\n\nUploads end-to-end key information for the sender user.\n\n- Requires UIAA to verify password", "repo": "girlbossceo/conduwuit", "path": "src/api/client/keys.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/keys.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1732b2b8630a6c52e3b9dc7ec56fc6a0f4cc1039b15c2373c895530094160b00"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: upload_signatures_route\n\nDocumentation:\n# `POST /_matrix/client/r0/keys/signatures/upload`\n\nUploads end-to-end key signatures from the sender user.\n\nTODO: clean this timo-code up more and integrate failures. tried to improve\nit a bit to stop exploding the entire request on bad sigs, but needs way\nmore work.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn upload_signatures_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif body.signed_keys.is_empty() {\n\t\tdebug!(\"Empty signed_keys sent in key signature upload\");\n\t\treturn Ok(upload_signatures::v3::Response::new());\n\t}\n\n\tlet sender_user = body.sender_user();\n\n\tfor (user_id, keys) in &body.signed_keys {\n\t\tfor (key_id, key) in keys {\n\t\t\tlet Ok(key) = serde_json::to_value(key)\n\t\t\t\t.inspect_err(|e| debug_warn!(?key_id, \"Invalid \\\"key\\\" JSON: {e}\"))\n\t\t\telse {\n\t\t\t\tcontinue;\n\t\t\t};\n\n\t\t\tlet Some(signatures) = key.get(\"signatures\") else {\n\t\t\t\tcontinue;\n\t\t\t};\n\n\t\t\tlet Some(sender_user_val) = signatures.get(sender_user.to_string()) else {\n\t\t\t\tcontinue;\n\t\t\t};\n\n\t\t\tlet Some(sender_user_object) = sender_user_val.as_object() else {\n\t\t\t\tcontinue;\n\t\t\t};\n\n\t\t\tfor (signature, val) in sender_user_object.clone() {\n\t\t\t\tlet Some(val) = val.as_str().map(ToOwned::to_owned) else {\n\t\t\t\t\tcontinue;\n\t\t\t\t};\n\t\t\t\tlet signature = (signature, val);\n\n\t\t\t\tif let Err(_e) = services\n\t\t\t\t\t.users\n\t\t\t\t\t.sign_key(user_id, key_id, signature, sender_user)\n\t\t\t\t\t.await\n\t\t\t\t\t.inspect_err(|e| debug_warn!(\"{e}\"))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tOk(upload_signatures::v3::Response { failures: BTreeMap::new() })\n}\n```"}], "func_name": "upload_signatures_route", "docstring": "# `POST /_matrix/client/r0/keys/signatures/upload`\n\nUploads end-to-end key signatures from the sender user.\n\nTODO: clean this timo-code up more and integrate failures. tried to improve\nit a bit to stop exploding the entire request on bad sigs, but needs way\nmore work.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/keys.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/keys.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b741497cf1ab09ee6dba3c0d9edd7824d314facfa5f598d236628bca12f1437"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_key_changes_route\n\nDocumentation:\n# `POST /_matrix/client/r0/keys/changes`\n\nGets a list of users who have updated their device identity keys since the\nprevious sync token.\n\n- TODO: left users\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_key_changes_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tlet mut device_list_updates = HashSet::new();\n\n\tlet from = body\n\t\t.from\n\t\t.parse()\n\t\t.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, \"Invalid `from`.\"))?;\n\n\tlet to = body\n\t\t.to\n\t\t.parse()\n\t\t.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, \"Invalid `to`.\"))?;\n\n\tdevice_list_updates.extend(\n\t\tservices\n\t\t\t.users\n\t\t\t.keys_changed(sender_user, from, Some(to))\n\t\t\t.map(ToOwned::to_owned)\n\t\t\t.collect::>()\n\t\t\t.await,\n\t);\n\n\tlet mut rooms_joined = services.rooms.state_cache.rooms_joined(sender_user).boxed();\n\n\twhile let Some(room_id) = rooms_joined.next().await {\n\t\tdevice_list_updates.extend(\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.room_keys_changed(room_id, from, Some(to))\n\t\t\t\t.map(|(user_id, _)| user_id)\n\t\t\t\t.map(ToOwned::to_owned)\n\t\t\t\t.collect::>()\n\t\t\t\t.await,\n\t\t);\n\t}\n\n\tOk(get_key_changes::v3::Response {\n\t\tchanged: device_list_updates.into_iter().collect(),\n\t\tleft: Vec::new(), // TODO\n\t})\n}\n```"}], "func_name": "get_key_changes_route", "docstring": "# `POST /_matrix/client/r0/keys/changes`\n\nGets a list of users who have updated their device identity keys since the\nprevious sync token.\n\n- TODO: left users", "repo": "girlbossceo/conduwuit", "path": "src/api/client/keys.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/keys.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8d365c0f2b28183ce31466b1262a7246f0d6af39fe7f4c7a32416abedc52ad3e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_media_config_legacy_route\n\nDocumentation:\n# `GET /_matrix/media/v3/config`\n\nReturns max upload size.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_media_config_legacy_route(\n\tState(services): State,\n\t_body: Ruma,\n) -> Result {\n\tOk(get_media_config::v3::Response {\n\t\tupload_size: ruma_from_usize(services.server.config.max_request_size),\n\t})\n}\n```"}], "func_name": "get_media_config_legacy_route", "docstring": "# `GET /_matrix/media/v3/config`\n\nReturns max upload size.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/media_legacy.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/media_legacy.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "504963e35cf5502a2d00154cccff1906af3f530ecc0f4d96f5129aaac9c992f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_media_config_legacy_legacy_route\n\nDocumentation:\n# `GET /_matrix/media/v1/config`\n\nThis is a legacy endpoint (\"/v1/\") that some very old homeservers and/or\nclients may call. conduwuit adds these for compatibility purposes.\nSee \n\nReturns max upload size.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_media_config_legacy_legacy_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result> {\n\tget_media_config_legacy_route(State(services), body)\n\t\t.await\n\t\t.map(RumaResponse)\n}\n```"}], "func_name": "get_media_config_legacy_legacy_route", "docstring": "# `GET /_matrix/media/v1/config`\n\nThis is a legacy endpoint (\"/v1/\") that some very old homeservers and/or\nclients may call. conduwuit adds these for compatibility purposes.\nSee \n\nReturns max upload size.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/media_legacy.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/media_legacy.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54cda38e1a4ac7250720ca61996fbf1c3f8d64d76bfb0f9d0c9883858b2b0bbf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_media_preview_legacy_legacy_route\n\nDocumentation:\n# `GET /_matrix/media/v1/preview_url`\n\nThis is a legacy endpoint (\"/v1/\") that some very old homeservers and/or\nclients may call. conduwuit adds these for compatibility purposes.\nSee \n\nReturns URL preview.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_media_preview_legacy_legacy_route(\n\tState(services): State,\n\tInsecureClientIp(client): InsecureClientIp,\n\tbody: Ruma,\n) -> Result> {\n\tget_media_preview_legacy_route(State(services), InsecureClientIp(client), body)\n\t\t.await\n\t\t.map(RumaResponse)\n}\n```"}], "func_name": "get_media_preview_legacy_legacy_route", "docstring": "# `GET /_matrix/media/v1/preview_url`\n\nThis is a legacy endpoint (\"/v1/\") that some very old homeservers and/or\nclients may call. conduwuit adds these for compatibility purposes.\nSee \n\nReturns URL preview.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/media_legacy.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/media_legacy.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3d8494c534331a59f6765531e61eb417cdf9d606d64be6a2487f57c32a07138c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_content_legacy_route\n\nDocumentation:\n# `POST /_matrix/media/v1/upload`\n\nPermanently save media in the server.\n\nThis is a legacy endpoint (\"/v1/\") that some very old homeservers and/or\nclients may call. conduwuit adds these for compatibility purposes.\nSee \n\n- Some metadata will be saved in the database\n- Media will be saved in the media/ directory\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn create_content_legacy_route(\n\tState(services): State,\n\tInsecureClientIp(client): InsecureClientIp,\n\tbody: Ruma,\n) -> Result> {\n\tcreate_content_route(State(services), InsecureClientIp(client), body)\n\t\t.await\n\t\t.map(RumaResponse)\n}\n```"}], "func_name": "create_content_legacy_route", "docstring": "# `POST /_matrix/media/v1/upload`\n\nPermanently save media in the server.\n\nThis is a legacy endpoint (\"/v1/\") that some very old homeservers and/or\nclients may call. conduwuit adds these for compatibility purposes.\nSee \n\n- Some metadata will be saved in the database\n- Media will be saved in the media/ directory", "repo": "girlbossceo/conduwuit", "path": "src/api/client/media_legacy.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/media_legacy.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1d3d8ad9a4eb810c5aafe3fb15c9fb34098ac3e234053a83dd7ff88473fc17b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_content_thumbnail_legacy_legacy_route\n\nDocumentation:\n# `GET /_matrix/media/v1/thumbnail/{serverName}/{mediaId}`\n\nLoad media thumbnail from our server or over federation.\n\nThis is a legacy endpoint (\"/v1/\") that some very old homeservers and/or\nclients may call. conduwuit adds these for compatibility purposes.\nSee \n\n- Only allows federation if `allow_remote` is true\n- Only redirects if `allow_redirect` is true\n- Uses client-provided `timeout_ms` if available, else defaults to 20\nseconds\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_content_thumbnail_legacy_legacy_route(\n\tState(services): State,\n\tInsecureClientIp(client): InsecureClientIp,\n\tbody: Ruma,\n) -> Result> {\n\tget_content_thumbnail_legacy_route(State(services), InsecureClientIp(client), body)\n\t\t.await\n\t\t.map(RumaResponse)\n}\n```"}], "func_name": "get_content_thumbnail_legacy_legacy_route", "docstring": "# `GET /_matrix/media/v1/thumbnail/{serverName}/{mediaId}`\n\nLoad media thumbnail from our server or over federation.\n\nThis is a legacy endpoint (\"/v1/\") that some very old homeservers and/or\nclients may call. conduwuit adds these for compatibility purposes.\nSee \n\n- Only allows federation if `allow_remote` is true\n- Only redirects if `allow_redirect` is true\n- Uses client-provided `timeout_ms` if available, else defaults to 20\nseconds", "repo": "girlbossceo/conduwuit", "path": "src/api/client/media_legacy.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/media_legacy.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "749eb06ef32b5529504a56adece5356030f419b942b36a9c958e8edaae416322"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: leave_room_route\n\nDocumentation:\n# `POST /_matrix/client/v3/rooms/{roomId}/leave`\n\nTries to leave the sender user from a room.\n\n- This should always work if the user is currently joined.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn leave_room_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tleave_room(&services, body.sender_user(), &body.room_id, body.reason.clone())\n\t\t.await\n\t\t.map(|()| leave_room::v3::Response::new())\n}\n```"}], "func_name": "leave_room_route", "docstring": "# `POST /_matrix/client/v3/rooms/{roomId}/leave`\n\nTries to leave the sender user from a room.\n\n- This should always work if the user is currently joined.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/membership.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/membership.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3db89b0da69c44bb8d94b7e69560c97f312902bf32e7c943291ca5286c3e09fd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: kick_user_route\n\nDocumentation:\n# `POST /_matrix/client/r0/rooms/{roomId}/kick`\n\nTries to send a kick event into the room.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn kick_user_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet state_lock = services.rooms.state.mutex.lock(&body.room_id).await;\n\n\tlet Ok(event) = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.get_member(&body.room_id, &body.user_id)\n\t\t.await\n\telse {\n\t\t// copy synapse's behaviour of returning 200 without any change to the state\n\t\t// instead of erroring on left users\n\t\treturn Ok(kick_user::v3::Response::new());\n\t};\n\n\tif !matches!(\n\t\tevent.membership,\n\t\tMembershipState::Invite | MembershipState::Knock | MembershipState::Join,\n\t) {\n\t\treturn Err!(Request(Forbidden(\n\t\t\t\"Cannot kick a user who is not apart of the room (current membership: {})\",\n\t\t\tevent.membership\n\t\t)));\n\t}\n\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(body.user_id.to_string(), &RoomMemberEventContent {\n\t\t\t\tmembership: MembershipState::Leave,\n\t\t\t\treason: body.reason.clone(),\n\t\t\t\tis_direct: None,\n\t\t\t\tjoin_authorized_via_users_server: None,\n\t\t\t\tthird_party_invite: None,\n\t\t\t\t..event\n\t\t\t}),\n\t\t\tbody.sender_user(),\n\t\t\t&body.room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\tdrop(state_lock);\n\n\tOk(kick_user::v3::Response::new())\n}\n```"}], "func_name": "kick_user_route", "docstring": "# `POST /_matrix/client/r0/rooms/{roomId}/kick`\n\nTries to send a kick event into the room.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/membership.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/membership.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "75340abc1ae516f921a09dbdcfc2a46fb2f8b31f9a7ae6e68bf93d9683ca2582"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ban_user_route\n\nDocumentation:\n# `POST /_matrix/client/r0/rooms/{roomId}/ban`\n\nTries to send a ban event into the room.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn ban_user_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\n\tif sender_user == body.user_id {\n\t\treturn Err!(Request(Forbidden(\"You cannot ban yourself.\")));\n\t}\n\n\tlet state_lock = services.rooms.state.mutex.lock(&body.room_id).await;\n\n\tlet current_member_content = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.get_member(&body.room_id, &body.user_id)\n\t\t.await\n\t\t.unwrap_or_else(|_| RoomMemberEventContent::new(MembershipState::Ban));\n\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(body.user_id.to_string(), &RoomMemberEventContent {\n\t\t\t\tmembership: MembershipState::Ban,\n\t\t\t\treason: body.reason.clone(),\n\t\t\t\tdisplayname: None, // display name may be offensive\n\t\t\t\tavatar_url: None, // avatar may be offensive\n\t\t\t\tis_direct: None,\n\t\t\t\tjoin_authorized_via_users_server: None,\n\t\t\t\tthird_party_invite: None,\n\t\t\t\t..current_member_content\n\t\t\t}),\n\t\t\tsender_user,\n\t\t\t&body.room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\tdrop(state_lock);\n\n\tOk(ban_user::v3::Response::new())\n}\n```"}], "func_name": "ban_user_route", "docstring": "# `POST /_matrix/client/r0/rooms/{roomId}/ban`\n\nTries to send a ban event into the room.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/membership.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/membership.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "01a8c38f41e682ef3ca4f6a0330deafc2c123b3f2a7265d2a79f210e0c8c4f31"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unban_user_route\n\nDocumentation:\n# `POST /_matrix/client/r0/rooms/{roomId}/unban`\n\nTries to send an unban event into the room.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn unban_user_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet state_lock = services.rooms.state.mutex.lock(&body.room_id).await;\n\n\tlet current_member_content = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.get_member(&body.room_id, &body.user_id)\n\t\t.await\n\t\t.unwrap_or_else(|_| RoomMemberEventContent::new(MembershipState::Leave));\n\n\tif current_member_content.membership != MembershipState::Ban {\n\t\treturn Err!(Request(Forbidden(\n\t\t\t\"Cannot unban a user who is not banned (current membership: {})\",\n\t\t\tcurrent_member_content.membership\n\t\t)));\n\t}\n\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(body.user_id.to_string(), &RoomMemberEventContent {\n\t\t\t\tmembership: MembershipState::Leave,\n\t\t\t\treason: body.reason.clone(),\n\t\t\t\tjoin_authorized_via_users_server: None,\n\t\t\t\tthird_party_invite: None,\n\t\t\t\tis_direct: None,\n\t\t\t\t..current_member_content\n\t\t\t}),\n\t\t\tbody.sender_user(),\n\t\t\t&body.room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\tdrop(state_lock);\n\n\tOk(unban_user::v3::Response::new())\n}\n```"}], "func_name": "unban_user_route", "docstring": "# `POST /_matrix/client/r0/rooms/{roomId}/unban`\n\nTries to send an unban event into the room.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/membership.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/membership.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf2c9c2665f8ce3e2e56a58e978c91b15431ce17c09a552482bd27d42bd95b3c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: forget_room_route\n\nDocumentation:\n# `POST /_matrix/client/v3/rooms/{roomId}/forget`\n\nForgets about a room.\n\n- If the sender user currently left the room: Stops sender user from\nreceiving information about the room\n\nNote: Other devices of the user have no way of knowing the room was\nforgotten, so this has to be called from every device\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn forget_room_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet user_id = body.sender_user();\n\tlet room_id = &body.room_id;\n\n\tlet joined = services.rooms.state_cache.is_joined(user_id, room_id);\n\tlet knocked = services.rooms.state_cache.is_knocked(user_id, room_id);\n\tlet left = services.rooms.state_cache.is_left(user_id, room_id);\n\tlet invited = services.rooms.state_cache.is_invited(user_id, room_id);\n\n\tlet (joined, knocked, left, invited) = join4(joined, knocked, left, invited).await;\n\n\tif joined || knocked || invited {\n\t\treturn Err!(Request(Unknown(\"You must leave the room before forgetting it\")));\n\t}\n\n\tlet membership = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.get_member(room_id, user_id)\n\t\t.await;\n\n\tif membership.is_not_found() {\n\t\treturn Err!(Request(Unknown(\"No membership event was found, room was never joined\")));\n\t}\n\n\tif left\n\t\t|| membership.is_ok_and(|member| {\n\t\t\tmember.membership == MembershipState::Leave\n\t\t\t\t|| member.membership == MembershipState::Ban\n\t\t}) {\n\t\tservices.rooms.state_cache.forget(room_id, user_id);\n\t}\n\n\tOk(forget_room::v3::Response::new())\n}\n```"}], "func_name": "forget_room_route", "docstring": "# `POST /_matrix/client/v3/rooms/{roomId}/forget`\n\nForgets about a room.\n\n- If the sender user currently left the room: Stops sender user from\nreceiving information about the room\n\nNote: Other devices of the user have no way of knowing the room was\nforgotten, so this has to be called from every device", "repo": "girlbossceo/conduwuit", "path": "src/api/client/membership.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/membership.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5ed3d6f8d2f7798c5fe50a5f9102b7ce81768000fe2330c52062f33ad949c142"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: joined_rooms_route\n\nDocumentation:\n# `POST /_matrix/client/r0/joined_rooms`\n\nLists all rooms the user has joined.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn joined_rooms_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tOk(joined_rooms::v3::Response {\n\t\tjoined_rooms: services\n\t\t\t.rooms\n\t\t\t.state_cache\n\t\t\t.rooms_joined(body.sender_user())\n\t\t\t.map(ToOwned::to_owned)\n\t\t\t.collect()\n\t\t\t.await,\n\t})\n}\n```"}], "func_name": "joined_rooms_route", "docstring": "# `POST /_matrix/client/r0/joined_rooms`\n\nLists all rooms the user has joined.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/membership.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/membership.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0a44a1e0f403376649f28197460281191dcc949223763df0daddbbbe489998dd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_member_events_route\n\nDocumentation:\n# `POST /_matrix/client/r0/rooms/{roomId}/members`\n\nLists all joined users in a room (TODO: at a specific point in time, with a\nspecific membership).\n\n- Only works if the user is currently joined\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_member_events_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\tlet membership = body.membership.as_ref();\n\tlet not_membership = body.not_membership.as_ref();\n\n\tif !services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.user_can_see_state_events(sender_user, &body.room_id)\n\t\t.await\n\t{\n\t\treturn Err!(Request(Forbidden(\"You don't have permission to view this room.\")));\n\t}\n\n\tOk(get_member_events::v3::Response {\n\t\tchunk: services\n\t\t\t.rooms\n\t\t\t.state_accessor\n\t\t\t.room_state_full(&body.room_id)\n\t\t\t.ready_filter_map(Result::ok)\n\t\t\t.ready_filter(|((ty, _), _)| *ty == StateEventType::RoomMember)\n\t\t\t.map(at!(1))\n\t\t\t.ready_filter_map(|pdu| membership_filter(pdu, membership, not_membership))\n\t\t\t.map(PduEvent::into_member_event)\n\t\t\t.collect()\n\t\t\t.await,\n\t})\n}\n```"}], "func_name": "get_member_events_route", "docstring": "# `POST /_matrix/client/r0/rooms/{roomId}/members`\n\nLists all joined users in a room (TODO: at a specific point in time, with a\nspecific membership).\n\n- Only works if the user is currently joined", "repo": "girlbossceo/conduwuit", "path": "src/api/client/membership.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/membership.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "21b36ed05995985b9376a566900ee7411eaee235cb9d27e84dc8c41ca96465bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: joined_members_route\n\nDocumentation:\n# `POST /_matrix/client/r0/rooms/{roomId}/joined_members`\n\nLists all members of a room.\n\n- The sender user must be in the room\n- TODO: An appservice just needs a puppet joined\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn joined_members_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\n\tif !services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.user_can_see_state_events(sender_user, &body.room_id)\n\t\t.await\n\t{\n\t\treturn Err!(Request(Forbidden(\"You don't have permission to view this room.\")));\n\t}\n\n\tlet joined: BTreeMap = services\n\t\t.rooms\n\t\t.state_cache\n\t\t.room_members(&body.room_id)\n\t\t.map(ToOwned::to_owned)\n\t\t.then(|user| async move {\n\t\t\t(user.clone(), RoomMember {\n\t\t\t\tdisplay_name: services.users.displayname(&user).await.ok(),\n\t\t\t\tavatar_url: services.users.avatar_url(&user).await.ok(),\n\t\t\t})\n\t\t})\n\t\t.collect()\n\t\t.await;\n\n\tOk(joined_members::v3::Response { joined })\n}\n```"}], "func_name": "joined_members_route", "docstring": "# `POST /_matrix/client/r0/rooms/{roomId}/joined_members`\n\nLists all members of a room.\n\n- The sender user must be in the room\n- TODO: An appservice just needs a puppet joined", "repo": "girlbossceo/conduwuit", "path": "src/api/client/membership.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/membership.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc3f96faa0a149ad3a9c2cfe16d573560dfda070531469bcf6b0a880c3d86b52"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_message_events_route\n\nDocumentation:\n# `GET /_matrix/client/r0/rooms/{roomId}/messages`\n\nAllows paginating through room history.\n\n- Only works if the user is joined (TODO: always allow, but only show events\nwhere the user was joined, depending on `history_visibility`)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_message_events_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tdebug_assert!(IGNORED_MESSAGE_TYPES.is_sorted(), \"IGNORED_MESSAGE_TYPES is not sorted\");\n\tlet sender = body.sender();\n\tlet (sender_user, sender_device) = sender;\n\tlet room_id = &body.room_id;\n\tlet filter = &body.filter;\n\n\tif !services.rooms.metadata.exists(room_id).await {\n\t\treturn Err!(Request(Forbidden(\"Room does not exist to this server\")));\n\t}\n\n\tlet from: PduCount = body\n\t\t.from\n\t\t.as_deref()\n\t\t.map(str::parse)\n\t\t.transpose()?\n\t\t.unwrap_or_else(|| match body.dir {\n\t\t\t| Direction::Forward => PduCount::min(),\n\t\t\t| Direction::Backward => PduCount::max(),\n\t\t});\n\n\tlet to: Option = body.to.as_deref().map(str::parse).flat_ok();\n\n\tlet limit: usize = body\n\t\t.limit\n\t\t.try_into()\n\t\t.unwrap_or(LIMIT_DEFAULT)\n\t\t.min(LIMIT_MAX);\n\n\tif matches!(body.dir, Direction::Backward) {\n\t\tservices\n\t\t\t.rooms\n\t\t\t.timeline\n\t\t\t.backfill_if_required(room_id, from)\n\t\t\t.boxed()\n\t\t\t.await\n\t\t\t.log_err()\n\t\t\t.ok();\n\t}\n\n\tlet it = match body.dir {\n\t\t| Direction::Forward => services\n\t\t\t.rooms\n\t\t\t.timeline\n\t\t\t.pdus(Some(sender_user), room_id, Some(from))\n\t\t\t.ignore_err()\n\t\t\t.boxed(),\n\n\t\t| Direction::Backward => services\n\t\t\t.rooms\n\t\t\t.timeline\n\t\t\t.pdus_rev(Some(sender_user), room_id, Some(from))\n\t\t\t.ignore_err()\n\t\t\t.boxed(),\n\t};\n\n\tlet events: Vec<_> = it\n\t\t.ready_take_while(|(count, _)| Some(*count) != to)\n\t\t.ready_filter_map(|item| event_filter(item, filter))\n\t\t.wide_filter_map(|item| ignored_filter(&services, item, sender_user))\n\t\t.wide_filter_map(|item| visibility_filter(&services, item, sender_user))\n\t\t.take(limit)\n\t\t.collect()\n\t\t.await;\n\n\tlet lazy_loading_context = lazy_loading::Context {\n\t\tuser_id: sender_user,\n\t\tdevice_id: sender_device,\n\t\troom_id,\n\t\ttoken: Some(from.into_unsigned()),\n\t\toptions: Some(&filter.lazy_load_options),\n\t};\n\n\tlet witness: OptionFuture<_> = filter\n\t\t.lazy_load_options\n\t\t.is_enabled()\n\t\t.then(|| lazy_loading_witness(&services, &lazy_loading_context, events.iter()))\n\t\t.into();\n\n\tlet state = witness\n\t\t.map(Option::into_iter)\n\t\t.map(|option| option.flat_map(Witness::into_iter))\n\t\t.map(IterStream::stream)\n\t\t.into_stream()\n\t\t.flatten()\n\t\t.broad_filter_map(|user_id| async move {\n\t\t\tget_member_event(&services, room_id, &user_id).await\n\t\t})\n\t\t.collect()\n\t\t.await;\n\n\tlet next_token = events.last().map(at!(0));\n\n\tlet chunk = events\n\t\t.into_iter()\n\t\t.map(at!(1))\n\t\t.map(PduEvent::into_room_event)\n\t\t.collect();\n\n\tOk(get_message_events::v3::Response {\n\t\tstart: from.to_string(),\n\t\tend: next_token.as_ref().map(ToString::to_string),\n\t\tchunk,\n\t\tstate,\n\t})\n}\n```"}], "func_name": "get_message_events_route", "docstring": "# `GET /_matrix/client/r0/rooms/{roomId}/messages`\n\nAllows paginating through room history.\n\n- Only works if the user is joined (TODO: always allow, but only show events\nwhere the user was joined, depending on `history_visibility`)", "repo": "girlbossceo/conduwuit", "path": "src/api/client/message.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2c07142206e889460386392c7b2a521247039dc5b7e94ad000bdf98245820234"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_openid_token_route\n\nDocumentation:\n# `POST /_matrix/client/v3/user/{userId}/openid/request_token`\n\nRequest an OpenID token to verify identity with third-party services.\n\n- The token generated is only valid for the OpenID API\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn create_openid_token_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tif sender_user != &body.user_id {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::InvalidParam,\n\t\t\t\"Not allowed to request OpenID tokens on behalf of other users\",\n\t\t));\n\t}\n\n\tlet access_token = utils::random_string(TOKEN_LENGTH);\n\n\tlet expires_in = services\n\t\t.users\n\t\t.create_openid_token(&body.user_id, &access_token)?;\n\n\tOk(account::request_openid_token::v3::Response {\n\t\taccess_token,\n\t\ttoken_type: TokenType::Bearer,\n\t\tmatrix_server_name: services.server.name.clone(),\n\t\texpires_in: Duration::from_secs(expires_in),\n\t})\n}\n```"}], "func_name": "create_openid_token_route", "docstring": "# `POST /_matrix/client/v3/user/{userId}/openid/request_token`\n\nRequest an OpenID token to verify identity with third-party services.\n\n- The token generated is only valid for the OpenID API", "repo": "girlbossceo/conduwuit", "path": "src/api/client/openid.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/openid.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8a58b95437d830d184b7a3c7b6094d0742fba38113f05b24820fd94ad41de4c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_presence_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/presence/{userId}/status`\n\nSets the presence state of the sender user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn set_presence_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif !services.config.allow_local_presence {\n\t\treturn Err!(Request(Forbidden(\"Presence is disabled on this server\")));\n\t}\n\n\tif body.sender_user() != body.user_id && body.appservice_info.is_none() {\n\t\treturn Err!(Request(InvalidParam(\"Not allowed to set presence of other users\")));\n\t}\n\n\tservices\n\t\t.presence\n\t\t.set_presence(body.sender_user(), &body.presence, None, None, body.status_msg.clone())\n\t\t.await?;\n\n\tOk(set_presence::v3::Response {})\n}\n```"}], "func_name": "set_presence_route", "docstring": "# `PUT /_matrix/client/r0/presence/{userId}/status`\n\nSets the presence state of the sender user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/presence.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/presence.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c5e217140c0409f2774cea29ebdfa0f8873620b99c6f5458654f5ec37a6185f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_presence_route\n\nDocumentation:\n# `GET /_matrix/client/r0/presence/{userId}/status`\n\nGets the presence state of the given user.\n\n- Only works if you share a room with the user\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_presence_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif !services.config.allow_local_presence {\n\t\treturn Err!(Request(Forbidden(\"Presence is disabled on this server\",)));\n\t}\n\n\tlet mut presence_event = None;\n\tlet has_shared_rooms = services\n\t\t.rooms\n\t\t.state_cache\n\t\t.user_sees_user(body.sender_user(), &body.user_id)\n\t\t.await;\n\n\tif has_shared_rooms {\n\t\tif let Ok(presence) = services.presence.get_presence(&body.user_id).await {\n\t\t\tpresence_event = Some(presence);\n\t\t}\n\t}\n\n\tmatch presence_event {\n\t\t| Some(presence) => {\n\t\t\tlet status_msg = if presence\n\t\t\t\t.content\n\t\t\t\t.status_msg\n\t\t\t\t.as_ref()\n\t\t\t\t.is_some_and(String::is_empty)\n\t\t\t{\n\t\t\t\tNone\n\t\t\t} else {\n\t\t\t\tpresence.content.status_msg\n\t\t\t};\n\n\t\t\tlet last_active_ago = match presence.content.currently_active {\n\t\t\t\t| Some(true) => None,\n\t\t\t\t| _ => presence\n\t\t\t\t\t.content\n\t\t\t\t\t.last_active_ago\n\t\t\t\t\t.map(|millis| Duration::from_millis(millis.into())),\n\t\t\t};\n\n\t\t\tOk(get_presence::v3::Response {\n\t\t\t\t// TODO: Should ruma just use the presenceeventcontent type here?\n\t\t\t\tstatus_msg,\n\t\t\t\tcurrently_active: presence.content.currently_active,\n\t\t\t\tlast_active_ago,\n\t\t\t\tpresence: presence.content.presence,\n\t\t\t})\n\t\t},\n\t\t| _ => Err!(Request(NotFound(\"Presence state for this user was not found\"))),\n\t}\n}\n```"}], "func_name": "get_presence_route", "docstring": "# `GET /_matrix/client/r0/presence/{userId}/status`\n\nGets the presence state of the given user.\n\n- Only works if you share a room with the user", "repo": "girlbossceo/conduwuit", "path": "src/api/client/presence.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/presence.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7d3b5022f4c0bddf2b79b629729eed5153c04bb44ccc22b33cfee2d85b98301a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_displayname_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/profile/{userId}/displayname`\n\nUpdates the displayname.\n\n- Also makes sure other users receive the update using presence EDUs\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn set_displayname_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tif *sender_user != body.user_id && body.appservice_info.is_none() {\n\t\treturn Err!(Request(Forbidden(\"You cannot update the profile of another user\")));\n\t}\n\n\tlet all_joined_rooms: Vec = services\n\t\t.rooms\n\t\t.state_cache\n\t\t.rooms_joined(&body.user_id)\n\t\t.map(ToOwned::to_owned)\n\t\t.collect()\n\t\t.await;\n\n\tupdate_displayname(&services, &body.user_id, body.displayname.clone(), &all_joined_rooms)\n\t\t.await;\n\n\tif services.config.allow_local_presence {\n\t\t// Presence update\n\t\tservices\n\t\t\t.presence\n\t\t\t.ping_presence(&body.user_id, &PresenceState::Online)\n\t\t\t.await?;\n\t}\n\n\tOk(set_display_name::v3::Response {})\n}\n```"}], "func_name": "set_displayname_route", "docstring": "# `PUT /_matrix/client/r0/profile/{userId}/displayname`\n\nUpdates the displayname.\n\n- Also makes sure other users receive the update using presence EDUs", "repo": "girlbossceo/conduwuit", "path": "src/api/client/profile.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/profile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5169a91b6ce639ae952874322b7644a8572f07137203d40eca6ce5f58a9d2aac"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_displayname_route\n\nDocumentation:\n# `GET /_matrix/client/v3/profile/{userId}/displayname`\n\nReturns the displayname of the user.\n\n- If user is on another server and we do not have a local copy already fetch\ndisplayname over federation\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_displayname_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif !services.globals.user_is_local(&body.user_id) {\n\t\t// Create and update our local copy of the user\n\t\tif let Ok(response) = services\n\t\t\t.sending\n\t\t\t.send_federation_request(\n\t\t\t\tbody.user_id.server_name(),\n\t\t\t\tfederation::query::get_profile_information::v1::Request {\n\t\t\t\t\tuser_id: body.user_id.clone(),\n\t\t\t\t\tfield: None, // we want the full user's profile to update locally too\n\t\t\t\t},\n\t\t\t)\n\t\t\t.await\n\t\t{\n\t\t\tif !services.users.exists(&body.user_id).await {\n\t\t\t\tservices.users.create(&body.user_id, None)?;\n\t\t\t}\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_displayname(&body.user_id, response.displayname.clone());\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_avatar_url(&body.user_id, response.avatar_url.clone());\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_blurhash(&body.user_id, response.blurhash.clone());\n\n\t\t\treturn Ok(get_display_name::v3::Response { displayname: response.displayname });\n\t\t}\n\t}\n\n\tif !services.users.exists(&body.user_id).await {\n\t\t// Return 404 if this user doesn't exist and we couldn't fetch it over\n\t\t// federation\n\t\treturn Err(Error::BadRequest(ErrorKind::NotFound, \"Profile was not found.\"));\n\t}\n\n\tOk(get_display_name::v3::Response {\n\t\tdisplayname: services.users.displayname(&body.user_id).await.ok(),\n\t})\n}\n```"}], "func_name": "get_displayname_route", "docstring": "# `GET /_matrix/client/v3/profile/{userId}/displayname`\n\nReturns the displayname of the user.\n\n- If user is on another server and we do not have a local copy already fetch\ndisplayname over federation", "repo": "girlbossceo/conduwuit", "path": "src/api/client/profile.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/profile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3b8abc8701df6e0addee3be75520df653109169451636e050f4b794a6be2837c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_avatar_url_route\n\nDocumentation:\n# `PUT /_matrix/client/v3/profile/{userId}/avatar_url`\n\nUpdates the `avatar_url` and `blurhash`.\n\n- Also makes sure other users receive the update using presence EDUs\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn set_avatar_url_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tif *sender_user != body.user_id && body.appservice_info.is_none() {\n\t\treturn Err!(Request(Forbidden(\"You cannot update the profile of another user\")));\n\t}\n\n\tlet all_joined_rooms: Vec = services\n\t\t.rooms\n\t\t.state_cache\n\t\t.rooms_joined(&body.user_id)\n\t\t.map(ToOwned::to_owned)\n\t\t.collect()\n\t\t.await;\n\n\tupdate_avatar_url(\n\t\t&services,\n\t\t&body.user_id,\n\t\tbody.avatar_url.clone(),\n\t\tbody.blurhash.clone(),\n\t\t&all_joined_rooms,\n\t)\n\t.await;\n\n\tif services.config.allow_local_presence {\n\t\t// Presence update\n\t\tservices\n\t\t\t.presence\n\t\t\t.ping_presence(&body.user_id, &PresenceState::Online)\n\t\t\t.await\n\t\t\t.ok();\n\t}\n\n\tOk(set_avatar_url::v3::Response {})\n}\n```"}], "func_name": "set_avatar_url_route", "docstring": "# `PUT /_matrix/client/v3/profile/{userId}/avatar_url`\n\nUpdates the `avatar_url` and `blurhash`.\n\n- Also makes sure other users receive the update using presence EDUs", "repo": "girlbossceo/conduwuit", "path": "src/api/client/profile.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/profile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c2e438ddfbe9e9b41550d37d45098e4b99e3d88a680b1964d923b04968b627d6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_avatar_url_route\n\nDocumentation:\n# `GET /_matrix/client/v3/profile/{userId}/avatar_url`\n\nReturns the `avatar_url` and `blurhash` of the user.\n\n- If user is on another server and we do not have a local copy already fetch\n`avatar_url` and blurhash over federation\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_avatar_url_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif !services.globals.user_is_local(&body.user_id) {\n\t\t// Create and update our local copy of the user\n\t\tif let Ok(response) = services\n\t\t\t.sending\n\t\t\t.send_federation_request(\n\t\t\t\tbody.user_id.server_name(),\n\t\t\t\tfederation::query::get_profile_information::v1::Request {\n\t\t\t\t\tuser_id: body.user_id.clone(),\n\t\t\t\t\tfield: None, // we want the full user's profile to update locally as well\n\t\t\t\t},\n\t\t\t)\n\t\t\t.await\n\t\t{\n\t\t\tif !services.users.exists(&body.user_id).await {\n\t\t\t\tservices.users.create(&body.user_id, None)?;\n\t\t\t}\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_displayname(&body.user_id, response.displayname.clone());\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_avatar_url(&body.user_id, response.avatar_url.clone());\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_blurhash(&body.user_id, response.blurhash.clone());\n\n\t\t\treturn Ok(get_avatar_url::v3::Response {\n\t\t\t\tavatar_url: response.avatar_url,\n\t\t\t\tblurhash: response.blurhash,\n\t\t\t});\n\t\t}\n\t}\n\n\tif !services.users.exists(&body.user_id).await {\n\t\t// Return 404 if this user doesn't exist and we couldn't fetch it over\n\t\t// federation\n\t\treturn Err(Error::BadRequest(ErrorKind::NotFound, \"Profile was not found.\"));\n\t}\n\n\tOk(get_avatar_url::v3::Response {\n\t\tavatar_url: services.users.avatar_url(&body.user_id).await.ok(),\n\t\tblurhash: services.users.blurhash(&body.user_id).await.ok(),\n\t})\n}\n```"}], "func_name": "get_avatar_url_route", "docstring": "# `GET /_matrix/client/v3/profile/{userId}/avatar_url`\n\nReturns the `avatar_url` and `blurhash` of the user.\n\n- If user is on another server and we do not have a local copy already fetch\n`avatar_url` and blurhash over federation", "repo": "girlbossceo/conduwuit", "path": "src/api/client/profile.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/profile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3772135990d4e67be23be934f3a7308827f8427c8838cd410444b885df157fd3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_profile_route\n\nDocumentation:\n# `GET /_matrix/client/v3/profile/{userId}`\n\nReturns the displayname, avatar_url, blurhash, and tz of the user.\n\n- If user is on another server and we do not have a local copy already,\nfetch profile over federation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_profile_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif !services.globals.user_is_local(&body.user_id) {\n\t\t// Create and update our local copy of the user\n\t\tif let Ok(response) = services\n\t\t\t.sending\n\t\t\t.send_federation_request(\n\t\t\t\tbody.user_id.server_name(),\n\t\t\t\tfederation::query::get_profile_information::v1::Request {\n\t\t\t\t\tuser_id: body.user_id.clone(),\n\t\t\t\t\tfield: None,\n\t\t\t\t},\n\t\t\t)\n\t\t\t.await\n\t\t{\n\t\t\tif !services.users.exists(&body.user_id).await {\n\t\t\t\tservices.users.create(&body.user_id, None)?;\n\t\t\t}\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_displayname(&body.user_id, response.displayname.clone());\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_avatar_url(&body.user_id, response.avatar_url.clone());\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_blurhash(&body.user_id, response.blurhash.clone());\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_timezone(&body.user_id, response.tz.clone());\n\n\t\t\tfor (profile_key, profile_key_value) in &response.custom_profile_fields {\n\t\t\t\tservices.users.set_profile_key(\n\t\t\t\t\t&body.user_id,\n\t\t\t\t\tprofile_key,\n\t\t\t\t\tSome(profile_key_value.clone()),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn Ok(get_profile::v3::Response {\n\t\t\t\tdisplayname: response.displayname,\n\t\t\t\tavatar_url: response.avatar_url,\n\t\t\t\tblurhash: response.blurhash,\n\t\t\t\ttz: response.tz,\n\t\t\t\tcustom_profile_fields: response.custom_profile_fields,\n\t\t\t});\n\t\t}\n\t}\n\n\tif !services.users.exists(&body.user_id).await {\n\t\t// Return 404 if this user doesn't exist and we couldn't fetch it over\n\t\t// federation\n\t\treturn Err(Error::BadRequest(ErrorKind::NotFound, \"Profile was not found.\"));\n\t}\n\n\tlet mut custom_profile_fields: BTreeMap = services\n\t\t.users\n\t\t.all_profile_keys(&body.user_id)\n\t\t.collect()\n\t\t.await;\n\n\t// services.users.timezone will collect the MSC4175 timezone key if it exists\n\tcustom_profile_fields.remove(\"us.cloke.msc4175.tz\");\n\tcustom_profile_fields.remove(\"m.tz\");\n\n\tOk(get_profile::v3::Response {\n\t\tavatar_url: services.users.avatar_url(&body.user_id).await.ok(),\n\t\tblurhash: services.users.blurhash(&body.user_id).await.ok(),\n\t\tdisplayname: services.users.displayname(&body.user_id).await.ok(),\n\t\ttz: services.users.timezone(&body.user_id).await.ok(),\n\t\tcustom_profile_fields,\n\t})\n}\n```"}], "func_name": "get_profile_route", "docstring": "# `GET /_matrix/client/v3/profile/{userId}`\n\nReturns the displayname, avatar_url, blurhash, and tz of the user.\n\n- If user is on another server and we do not have a local copy already,\nfetch profile over federation.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/profile.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/profile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2c16c1d8614733484a41a11c4ebae3559c7475af98f5fb827605eaf27b4f021a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_pushrules_all_route\n\nDocumentation:\n# `GET /_matrix/client/r0/pushrules/`\n\nRetrieves the push rules event for this user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_pushrules_all_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\n\tlet Some(content_value) = services\n\t\t.account_data\n\t\t.get_global::(sender_user, GlobalAccountDataEventType::PushRules)\n\t\t.await\n\t\t.ok()\n\t\t.and_then(|event| event.get(\"content\").cloned())\n\t\t.filter(CanonicalJsonValue::is_object)\n\telse {\n\t\t// user somehow has non-existent push rule event. recreate it and return server\n\t\t// default silently\n\t\treturn recreate_push_rules_and_return(&services, sender_user).await;\n\t};\n\n\tlet account_data_content =\n\t\tserde_json::from_value::(content_value.into()).map_err(|e| {\n\t\t\terr!(Database(warn!(\"Invalid push rules account data event in database: {e}\")))\n\t\t})?;\n\n\tlet mut global_ruleset = account_data_content.global;\n\n\t// remove old deprecated mentions push rules as per MSC4210\n\t// and update the stored server default push rules\n\t#[allow(deprecated)]\n\t{\n\t\tuse ruma::push::RuleKind::*;\n\t\tif global_ruleset\n\t\t\t.get(Override, PredefinedOverrideRuleId::ContainsDisplayName.as_str())\n\t\t\t.is_some()\n\t\t\t|| global_ruleset\n\t\t\t\t.get(Override, PredefinedOverrideRuleId::RoomNotif.as_str())\n\t\t\t\t.is_some()\n\t\t\t|| global_ruleset\n\t\t\t\t.get(Content, PredefinedContentRuleId::ContainsUserName.as_str())\n\t\t\t\t.is_some()\n\t\t{\n\t\t\tglobal_ruleset\n\t\t\t\t.remove(Override, PredefinedOverrideRuleId::ContainsDisplayName)\n\t\t\t\t.ok();\n\t\t\tglobal_ruleset\n\t\t\t\t.remove(Override, PredefinedOverrideRuleId::RoomNotif)\n\t\t\t\t.ok();\n\t\t\tglobal_ruleset\n\t\t\t\t.remove(Content, PredefinedContentRuleId::ContainsUserName)\n\t\t\t\t.ok();\n\n\t\t\tglobal_ruleset.update_with_server_default(Ruleset::server_default(sender_user));\n\n\t\t\tservices\n\t\t\t\t.account_data\n\t\t\t\t.update(\n\t\t\t\t\tNone,\n\t\t\t\t\tsender_user,\n\t\t\t\t\tGlobalAccountDataEventType::PushRules.to_string().into(),\n\t\t\t\t\t&serde_json::to_value(PushRulesEvent {\n\t\t\t\t\t\tcontent: PushRulesEventContent { global: global_ruleset.clone() },\n\t\t\t\t\t})\n\t\t\t\t\t.expect(\"to json always works\"),\n\t\t\t\t)\n\t\t\t\t.await?;\n\t\t}\n\t};\n\n\tOk(get_pushrules_all::v3::Response { global: global_ruleset })\n}\n```"}], "func_name": "get_pushrules_all_route", "docstring": "# `GET /_matrix/client/r0/pushrules/`\n\nRetrieves the push rules event for this user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/push.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/push.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3675845f7053a5e493e02beaafa0ea50a4cfaff12086660f610e908e73757cd3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_pushrules_global_route\n\nDocumentation:\n# `GET /_matrix/client/r0/pushrules/global/`\n\nRetrieves the push rules event for this user.\n\nThis appears to be the exact same as `GET /_matrix/client/r0/pushrules/`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_pushrules_global_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tlet Some(content_value) = services\n\t\t.account_data\n\t\t.get_global::(sender_user, GlobalAccountDataEventType::PushRules)\n\t\t.await\n\t\t.ok()\n\t\t.and_then(|event| event.get(\"content\").cloned())\n\t\t.filter(CanonicalJsonValue::is_object)\n\telse {\n\t\t// user somehow has non-existent push rule event. recreate it and return server\n\t\t// default silently\n\t\tservices\n\t\t\t.account_data\n\t\t\t.update(\n\t\t\t\tNone,\n\t\t\t\tsender_user,\n\t\t\t\tGlobalAccountDataEventType::PushRules.to_string().into(),\n\t\t\t\t&serde_json::to_value(PushRulesEvent {\n\t\t\t\t\tcontent: PushRulesEventContent {\n\t\t\t\t\t\tglobal: Ruleset::server_default(sender_user),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\t.expect(\"to json always works\"),\n\t\t\t)\n\t\t\t.await?;\n\n\t\treturn Ok(get_pushrules_global_scope::v3::Response {\n\t\t\tglobal: Ruleset::server_default(sender_user),\n\t\t});\n\t};\n\n\tlet account_data_content =\n\t\tserde_json::from_value::(content_value.into()).map_err(|e| {\n\t\t\terr!(Database(warn!(\"Invalid push rules account data event in database: {e}\")))\n\t\t})?;\n\n\tlet mut global_ruleset = account_data_content.global;\n\n\t// remove old deprecated mentions push rules as per MSC4210\n\t// and update the stored server default push rules\n\t#[allow(deprecated)]\n\t{\n\t\tuse ruma::push::RuleKind::*;\n\t\tif global_ruleset\n\t\t\t.get(Override, PredefinedOverrideRuleId::ContainsDisplayName.as_str())\n\t\t\t.is_some()\n\t\t\t|| global_ruleset\n\t\t\t\t.get(Override, PredefinedOverrideRuleId::RoomNotif.as_str())\n\t\t\t\t.is_some()\n\t\t\t|| global_ruleset\n\t\t\t\t.get(Content, PredefinedContentRuleId::ContainsUserName.as_str())\n\t\t\t\t.is_some()\n\t\t{\n\t\t\tglobal_ruleset\n\t\t\t\t.remove(Override, PredefinedOverrideRuleId::ContainsDisplayName)\n\t\t\t\t.ok();\n\t\t\tglobal_ruleset\n\t\t\t\t.remove(Override, PredefinedOverrideRuleId::RoomNotif)\n\t\t\t\t.ok();\n\t\t\tglobal_ruleset\n\t\t\t\t.remove(Content, PredefinedContentRuleId::ContainsUserName)\n\t\t\t\t.ok();\n\n\t\t\tglobal_ruleset.update_with_server_default(Ruleset::server_default(sender_user));\n\n\t\t\tservices\n\t\t\t\t.account_data\n\t\t\t\t.update(\n\t\t\t\t\tNone,\n\t\t\t\t\tsender_user,\n\t\t\t\t\tGlobalAccountDataEventType::PushRules.to_string().into(),\n\t\t\t\t\t&serde_json::to_value(PushRulesEvent {\n\t\t\t\t\t\tcontent: PushRulesEventContent { global: global_ruleset.clone() },\n\t\t\t\t\t})\n\t\t\t\t\t.expect(\"to json always works\"),\n\t\t\t\t)\n\t\t\t\t.await?;\n\t\t}\n\t};\n\n\tOk(get_pushrules_global_scope::v3::Response { global: global_ruleset })\n}\n```"}], "func_name": "get_pushrules_global_route", "docstring": "# `GET /_matrix/client/r0/pushrules/global/`\n\nRetrieves the push rules event for this user.\n\nThis appears to be the exact same as `GET /_matrix/client/r0/pushrules/`.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/push.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/push.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "693aa34e476f096c565e6c94751f3baf8f76bfbfa56a91ac81e2921c7f963f2f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_pushrule_route\n\nDocumentation:\n# `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`\n\nRetrieves a single specified push rule for this user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_pushrule_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\t// remove old deprecated mentions push rules as per MSC4210\n\t#[allow(deprecated)]\n\tif body.rule_id.as_str() == PredefinedContentRuleId::ContainsUserName.as_str()\n\t\t|| body.rule_id.as_str() == PredefinedOverrideRuleId::ContainsDisplayName.as_str()\n\t\t|| body.rule_id.as_str() == PredefinedOverrideRuleId::RoomNotif.as_str()\n\t{\n\t\treturn Err!(Request(NotFound(\"Push rule not found.\")));\n\t}\n\n\tlet event: PushRulesEvent = services\n\t\t.account_data\n\t\t.get_global(sender_user, GlobalAccountDataEventType::PushRules)\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"PushRules event not found.\"))))?;\n\n\tlet rule = event\n\t\t.content\n\t\t.global\n\t\t.get(body.kind.clone(), &body.rule_id)\n\t\t.map(Into::into);\n\n\tif let Some(rule) = rule {\n\t\tOk(get_pushrule::v3::Response { rule })\n\t} else {\n\t\tErr(Error::BadRequest(ErrorKind::NotFound, \"Push rule not found.\"))\n\t}\n}\n```"}], "func_name": "get_pushrule_route", "docstring": "# `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`\n\nRetrieves a single specified push rule for this user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/push.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/push.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f31dbe197f9bd3bab915e592f5e5022815ff033b33818035c8c1a24f57b7e404"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_pushrule_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/pushrules/global/{kind}/{ruleId}`\n\nCreates a single specified push rule for this user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn set_pushrule_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\tlet body = body.body;\n\n\tlet mut account_data: PushRulesEvent = services\n\t\t.account_data\n\t\t.get_global(sender_user, GlobalAccountDataEventType::PushRules)\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"PushRules event not found.\"))))?;\n\n\tif let Err(error) = account_data.content.global.insert(\n\t\tbody.rule.clone(),\n\t\tbody.after.as_deref(),\n\t\tbody.before.as_deref(),\n\t) {\n\t\tlet err = match error {\n\t\t\t| InsertPushRuleError::ServerDefaultRuleId => Error::BadRequest(\n\t\t\t\tErrorKind::InvalidParam,\n\t\t\t\t\"Rule IDs starting with a dot are reserved for server-default rules.\",\n\t\t\t),\n\t\t\t| InsertPushRuleError::InvalidRuleId => Error::BadRequest(\n\t\t\t\tErrorKind::InvalidParam,\n\t\t\t\t\"Rule ID containing invalid characters.\",\n\t\t\t),\n\t\t\t| InsertPushRuleError::RelativeToServerDefaultRule => Error::BadRequest(\n\t\t\t\tErrorKind::InvalidParam,\n\t\t\t\t\"Can't place a push rule relatively to a server-default rule.\",\n\t\t\t),\n\t\t\t| InsertPushRuleError::UnknownRuleId => Error::BadRequest(\n\t\t\t\tErrorKind::NotFound,\n\t\t\t\t\"The before or after rule could not be found.\",\n\t\t\t),\n\t\t\t| InsertPushRuleError::BeforeHigherThanAfter => Error::BadRequest(\n\t\t\t\tErrorKind::InvalidParam,\n\t\t\t\t\"The before rule has a higher priority than the after rule.\",\n\t\t\t),\n\t\t\t| _ => Error::BadRequest(ErrorKind::InvalidParam, \"Invalid data.\"),\n\t\t};\n\n\t\treturn Err(err);\n\t}\n\n\tservices\n\t\t.account_data\n\t\t.update(\n\t\t\tNone,\n\t\t\tsender_user,\n\t\t\tGlobalAccountDataEventType::PushRules.to_string().into(),\n\t\t\t&serde_json::to_value(account_data).expect(\"to json value always works\"),\n\t\t)\n\t\t.await?;\n\n\tOk(set_pushrule::v3::Response {})\n}\n```"}], "func_name": "set_pushrule_route", "docstring": "# `PUT /_matrix/client/r0/pushrules/global/{kind}/{ruleId}`\n\nCreates a single specified push rule for this user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/push.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/push.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a32ed26b505b4781a7a4175c90a2c5675cd89c9f3ce5f96712c6c61f2f135032"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_pushrule_actions_route\n\nDocumentation:\n# `GET /_matrix/client/r0/pushrules/global/{kind}/{ruleId}/actions`\n\nGets the actions of a single specified push rule for this user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_pushrule_actions_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\t// remove old deprecated mentions push rules as per MSC4210\n\t#[allow(deprecated)]\n\tif body.rule_id.as_str() == PredefinedContentRuleId::ContainsUserName.as_str()\n\t\t|| body.rule_id.as_str() == PredefinedOverrideRuleId::ContainsDisplayName.as_str()\n\t\t|| body.rule_id.as_str() == PredefinedOverrideRuleId::RoomNotif.as_str()\n\t{\n\t\treturn Err!(Request(NotFound(\"Push rule not found.\")));\n\t}\n\n\tlet event: PushRulesEvent = services\n\t\t.account_data\n\t\t.get_global(sender_user, GlobalAccountDataEventType::PushRules)\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"PushRules event not found.\"))))?;\n\n\tlet actions = event\n\t\t.content\n\t\t.global\n\t\t.get(body.kind.clone(), &body.rule_id)\n\t\t.map(|rule| rule.actions().to_owned())\n\t\t.ok_or_else(|| err!(Request(NotFound(\"Push rule not found.\"))))?;\n\n\tOk(get_pushrule_actions::v3::Response { actions })\n}\n```"}], "func_name": "get_pushrule_actions_route", "docstring": "# `GET /_matrix/client/r0/pushrules/global/{kind}/{ruleId}/actions`\n\nGets the actions of a single specified push rule for this user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/push.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/push.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ff058ba1571a5389303a8492f323f6c371e6ef25f3184a66007f1e58b2f93ce"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_pushrule_actions_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/pushrules/global/{kind}/{ruleId}/actions`\n\nSets the actions of a single specified push rule for this user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn set_pushrule_actions_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tlet mut account_data: PushRulesEvent = services\n\t\t.account_data\n\t\t.get_global(sender_user, GlobalAccountDataEventType::PushRules)\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"PushRules event not found.\"))))?;\n\n\tif account_data\n\t\t.content\n\t\t.global\n\t\t.set_actions(body.kind.clone(), &body.rule_id, body.actions.clone())\n\t\t.is_err()\n\t{\n\t\treturn Err(Error::BadRequest(ErrorKind::NotFound, \"Push rule not found.\"));\n\t}\n\n\tservices\n\t\t.account_data\n\t\t.update(\n\t\t\tNone,\n\t\t\tsender_user,\n\t\t\tGlobalAccountDataEventType::PushRules.to_string().into(),\n\t\t\t&serde_json::to_value(account_data).expect(\"to json value always works\"),\n\t\t)\n\t\t.await?;\n\n\tOk(set_pushrule_actions::v3::Response {})\n}\n```"}], "func_name": "set_pushrule_actions_route", "docstring": "# `PUT /_matrix/client/r0/pushrules/global/{kind}/{ruleId}/actions`\n\nSets the actions of a single specified push rule for this user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/push.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/push.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f94179c1e050da1d63364c2769a679adbddf4892c9a85a0c6591b77190541545"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_pushrule_enabled_route\n\nDocumentation:\n# `GET /_matrix/client/r0/pushrules/global/{kind}/{ruleId}/enabled`\n\nGets the enabled status of a single specified push rule for this user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_pushrule_enabled_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\t// remove old deprecated mentions push rules as per MSC4210\n\t#[allow(deprecated)]\n\tif body.rule_id.as_str() == PredefinedContentRuleId::ContainsUserName.as_str()\n\t\t|| body.rule_id.as_str() == PredefinedOverrideRuleId::ContainsDisplayName.as_str()\n\t\t|| body.rule_id.as_str() == PredefinedOverrideRuleId::RoomNotif.as_str()\n\t{\n\t\treturn Ok(get_pushrule_enabled::v3::Response { enabled: false });\n\t}\n\n\tlet event: PushRulesEvent = services\n\t\t.account_data\n\t\t.get_global(sender_user, GlobalAccountDataEventType::PushRules)\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"PushRules event not found.\"))))?;\n\n\tlet enabled = event\n\t\t.content\n\t\t.global\n\t\t.get(body.kind.clone(), &body.rule_id)\n\t\t.map(ruma::push::AnyPushRuleRef::enabled)\n\t\t.ok_or_else(|| err!(Request(NotFound(\"Push rule not found.\"))))?;\n\n\tOk(get_pushrule_enabled::v3::Response { enabled })\n}\n```"}], "func_name": "get_pushrule_enabled_route", "docstring": "# `GET /_matrix/client/r0/pushrules/global/{kind}/{ruleId}/enabled`\n\nGets the enabled status of a single specified push rule for this user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/push.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/push.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dc28f4d98fbe8f248f19bcb943317f0a7f9555eaf63921ef5a175751e166e990"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_pushrule_enabled_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/pushrules/global/{kind}/{ruleId}/enabled`\n\nSets the enabled status of a single specified push rule for this user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn set_pushrule_enabled_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tlet mut account_data: PushRulesEvent = services\n\t\t.account_data\n\t\t.get_global(sender_user, GlobalAccountDataEventType::PushRules)\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"PushRules event not found.\"))))?;\n\n\tif account_data\n\t\t.content\n\t\t.global\n\t\t.set_enabled(body.kind.clone(), &body.rule_id, body.enabled)\n\t\t.is_err()\n\t{\n\t\treturn Err(Error::BadRequest(ErrorKind::NotFound, \"Push rule not found.\"));\n\t}\n\n\tservices\n\t\t.account_data\n\t\t.update(\n\t\t\tNone,\n\t\t\tsender_user,\n\t\t\tGlobalAccountDataEventType::PushRules.to_string().into(),\n\t\t\t&serde_json::to_value(account_data).expect(\"to json value always works\"),\n\t\t)\n\t\t.await?;\n\n\tOk(set_pushrule_enabled::v3::Response {})\n}\n```"}], "func_name": "set_pushrule_enabled_route", "docstring": "# `PUT /_matrix/client/r0/pushrules/global/{kind}/{ruleId}/enabled`\n\nSets the enabled status of a single specified push rule for this user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/push.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/push.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa88eab819cdaf5a29cccd61d8aba22d32999f5bad99c81c07e73d669250fbdf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_pushrule_route\n\nDocumentation:\n# `DELETE /_matrix/client/r0/pushrules/global/{kind}/{ruleId}`\n\nDeletes a single specified push rule for this user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn delete_pushrule_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tlet mut account_data: PushRulesEvent = services\n\t\t.account_data\n\t\t.get_global(sender_user, GlobalAccountDataEventType::PushRules)\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"PushRules event not found.\"))))?;\n\n\tif let Err(error) = account_data\n\t\t.content\n\t\t.global\n\t\t.remove(body.kind.clone(), &body.rule_id)\n\t{\n\t\tlet err = match error {\n\t\t\t| RemovePushRuleError::ServerDefault => Error::BadRequest(\n\t\t\t\tErrorKind::InvalidParam,\n\t\t\t\t\"Cannot delete a server-default pushrule.\",\n\t\t\t),\n\t\t\t| RemovePushRuleError::NotFound =>\n\t\t\t\tError::BadRequest(ErrorKind::NotFound, \"Push rule not found.\"),\n\t\t\t| _ => Error::BadRequest(ErrorKind::InvalidParam, \"Invalid data.\"),\n\t\t};\n\n\t\treturn Err(err);\n\t}\n\n\tservices\n\t\t.account_data\n\t\t.update(\n\t\t\tNone,\n\t\t\tsender_user,\n\t\t\tGlobalAccountDataEventType::PushRules.to_string().into(),\n\t\t\t&serde_json::to_value(account_data).expect(\"to json value always works\"),\n\t\t)\n\t\t.await?;\n\n\tOk(delete_pushrule::v3::Response {})\n}\n```"}], "func_name": "delete_pushrule_route", "docstring": "# `DELETE /_matrix/client/r0/pushrules/global/{kind}/{ruleId}`\n\nDeletes a single specified push rule for this user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/push.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/push.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9798c1f5ecedff5befa68ada8edeb9e49c4ee32f0ba8ef68415d048aea8c5be0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_pushers_route\n\nDocumentation:\n# `GET /_matrix/client/r0/pushers`\n\nGets all currently active pushers for the sender user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_pushers_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tOk(get_pushers::v3::Response {\n\t\tpushers: services.pusher.get_pushers(sender_user).await,\n\t})\n}\n```"}], "func_name": "get_pushers_route", "docstring": "# `GET /_matrix/client/r0/pushers`\n\nGets all currently active pushers for the sender user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/push.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/push.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac27565e141d769c8af7a31637af5d866b42623d05a9cb365f5d7e3ba3e8b1c0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_pushers_route\n\nDocumentation:\n# `POST /_matrix/client/r0/pushers/set`\n\nAdds a pusher for the sender user.\n\n- TODO: Handle `append`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn set_pushers_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tservices\n\t\t.pusher\n\t\t.set_pusher(sender_user, body.sender_device(), &body.action)\n\t\t.await?;\n\n\tOk(set_pusher::v3::Response::new())\n}\n```"}], "func_name": "set_pushers_route", "docstring": "# `POST /_matrix/client/r0/pushers/set`\n\nAdds a pusher for the sender user.\n\n- TODO: Handle `append`", "repo": "girlbossceo/conduwuit", "path": "src/api/client/push.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/push.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e5ffc834c3c33477e76b92161ae55336d35a9f1d7989e458b9a2b01ce84fc539"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: recreate_push_rules_and_return\n\nDocumentation:\nuser somehow has bad push rules, these must always exist per spec.\nso recreate it and return server default silently\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn recreate_push_rules_and_return(\n\tservices: &Services,\n\tsender_user: &ruma::UserId,\n) -> Result {\n\tservices\n\t\t.account_data\n\t\t.update(\n\t\t\tNone,\n\t\t\tsender_user,\n\t\t\tGlobalAccountDataEventType::PushRules.to_string().into(),\n\t\t\t&serde_json::to_value(PushRulesEvent {\n\t\t\t\tcontent: PushRulesEventContent {\n\t\t\t\t\tglobal: Ruleset::server_default(sender_user),\n\t\t\t\t},\n\t\t\t})\n\t\t\t.expect(\"to json always works\"),\n\t\t)\n\t\t.await?;\n\n\tOk(get_pushrules_all::v3::Response {\n\t\tglobal: Ruleset::server_default(sender_user),\n\t})\n}\n```"}], "func_name": "recreate_push_rules_and_return", "docstring": "user somehow has bad push rules, these must always exist per spec.\nso recreate it and return server default silently", "repo": "girlbossceo/conduwuit", "path": "src/api/client/push.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/push.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "47d19c256e902b52d8f8a0368dd596c74d6ea2b0ccefa7fd70cd12af3337052b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_read_marker_route\n\nDocumentation:\n# `POST /_matrix/client/r0/rooms/{roomId}/read_markers`\n\nSets different types of read markers.\n\n- Updates fully-read account data event to `fully_read`\n- If `read_receipt` is set: Update private marker and public read receipt\nEDU\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn set_read_marker_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\n\tif let Some(event) = &body.fully_read {\n\t\tlet fully_read_event = ruma::events::fully_read::FullyReadEvent {\n\t\t\tcontent: ruma::events::fully_read::FullyReadEventContent { event_id: event.clone() },\n\t\t};\n\n\t\tservices\n\t\t\t.account_data\n\t\t\t.update(\n\t\t\t\tSome(&body.room_id),\n\t\t\t\tsender_user,\n\t\t\t\tRoomAccountDataEventType::FullyRead,\n\t\t\t\t&serde_json::to_value(fully_read_event).expect(\"to json value always works\"),\n\t\t\t)\n\t\t\t.await?;\n\t}\n\n\tif body.private_read_receipt.is_some() || body.read_receipt.is_some() {\n\t\tservices\n\t\t\t.rooms\n\t\t\t.user\n\t\t\t.reset_notification_counts(sender_user, &body.room_id);\n\t}\n\n\t// ping presence\n\tif services.config.allow_local_presence {\n\t\tservices\n\t\t\t.presence\n\t\t\t.ping_presence(sender_user, &ruma::presence::PresenceState::Online)\n\t\t\t.await?;\n\t}\n\n\tif let Some(event) = &body.read_receipt {\n\t\tlet receipt_content = BTreeMap::from_iter([(\n\t\t\tevent.to_owned(),\n\t\t\tBTreeMap::from_iter([(\n\t\t\t\tReceiptType::Read,\n\t\t\t\tBTreeMap::from_iter([(sender_user.to_owned(), ruma::events::receipt::Receipt {\n\t\t\t\t\tts: Some(MilliSecondsSinceUnixEpoch::now()),\n\t\t\t\t\tthread: ReceiptThread::Unthreaded,\n\t\t\t\t})]),\n\t\t\t)]),\n\t\t)]);\n\n\t\tservices\n\t\t\t.rooms\n\t\t\t.read_receipt\n\t\t\t.readreceipt_update(\n\t\t\t\tsender_user,\n\t\t\t\t&body.room_id,\n\t\t\t\t&ruma::events::receipt::ReceiptEvent {\n\t\t\t\t\tcontent: ruma::events::receipt::ReceiptEventContent(receipt_content),\n\t\t\t\t\troom_id: body.room_id.clone(),\n\t\t\t\t},\n\t\t\t)\n\t\t\t.await;\n\t}\n\n\tif let Some(event) = &body.private_read_receipt {\n\t\tlet count = services\n\t\t\t.rooms\n\t\t\t.timeline\n\t\t\t.get_pdu_count(event)\n\t\t\t.await\n\t\t\t.map_err(|_| err!(Request(NotFound(\"Event not found.\"))))?;\n\n\t\tlet PduCount::Normal(count) = count else {\n\t\t\treturn Err!(Request(InvalidParam(\n\t\t\t\t\"Event is a backfilled PDU and cannot be marked as read.\"\n\t\t\t)));\n\t\t};\n\n\t\tservices\n\t\t\t.rooms\n\t\t\t.read_receipt\n\t\t\t.private_read_set(&body.room_id, sender_user, count);\n\t}\n\n\tOk(set_read_marker::v3::Response {})\n}\n```"}], "func_name": "set_read_marker_route", "docstring": "# `POST /_matrix/client/r0/rooms/{roomId}/read_markers`\n\nSets different types of read markers.\n\n- Updates fully-read account data event to `fully_read`\n- If `read_receipt` is set: Update private marker and public read receipt\nEDU", "repo": "girlbossceo/conduwuit", "path": "src/api/client/read_marker.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/read_marker.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e931e62f7af26d7b95aabec523f512e745fd4a2592735bce820af136d05dc1f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_receipt_route\n\nDocumentation:\n# `POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}`\n\nSets private read marker and public read receipt EDU.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn create_receipt_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\n\tif matches!(\n\t\t&body.receipt_type,\n\t\tcreate_receipt::v3::ReceiptType::Read | create_receipt::v3::ReceiptType::ReadPrivate\n\t) {\n\t\tservices\n\t\t\t.rooms\n\t\t\t.user\n\t\t\t.reset_notification_counts(sender_user, &body.room_id);\n\t}\n\n\t// ping presence\n\tif services.config.allow_local_presence {\n\t\tservices\n\t\t\t.presence\n\t\t\t.ping_presence(sender_user, &ruma::presence::PresenceState::Online)\n\t\t\t.await?;\n\t}\n\n\tmatch body.receipt_type {\n\t\t| create_receipt::v3::ReceiptType::FullyRead => {\n\t\t\tlet fully_read_event = ruma::events::fully_read::FullyReadEvent {\n\t\t\t\tcontent: ruma::events::fully_read::FullyReadEventContent {\n\t\t\t\t\tevent_id: body.event_id.clone(),\n\t\t\t\t},\n\t\t\t};\n\t\t\tservices\n\t\t\t\t.account_data\n\t\t\t\t.update(\n\t\t\t\t\tSome(&body.room_id),\n\t\t\t\t\tsender_user,\n\t\t\t\t\tRoomAccountDataEventType::FullyRead,\n\t\t\t\t\t&serde_json::to_value(fully_read_event).expect(\"to json value always works\"),\n\t\t\t\t)\n\t\t\t\t.await?;\n\t\t},\n\t\t| create_receipt::v3::ReceiptType::Read => {\n\t\t\tlet receipt_content = BTreeMap::from_iter([(\n\t\t\t\tbody.event_id.clone(),\n\t\t\t\tBTreeMap::from_iter([(\n\t\t\t\t\tReceiptType::Read,\n\t\t\t\t\tBTreeMap::from_iter([(\n\t\t\t\t\t\tsender_user.to_owned(),\n\t\t\t\t\t\truma::events::receipt::Receipt {\n\t\t\t\t\t\t\tts: Some(MilliSecondsSinceUnixEpoch::now()),\n\t\t\t\t\t\t\tthread: ReceiptThread::Unthreaded,\n\t\t\t\t\t\t},\n\t\t\t\t\t)]),\n\t\t\t\t)]),\n\t\t\t)]);\n\n\t\t\tservices\n\t\t\t\t.rooms\n\t\t\t\t.read_receipt\n\t\t\t\t.readreceipt_update(\n\t\t\t\t\tsender_user,\n\t\t\t\t\t&body.room_id,\n\t\t\t\t\t&ruma::events::receipt::ReceiptEvent {\n\t\t\t\t\t\tcontent: ruma::events::receipt::ReceiptEventContent(receipt_content),\n\t\t\t\t\t\troom_id: body.room_id.clone(),\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t\t.await;\n\t\t},\n\t\t| create_receipt::v3::ReceiptType::ReadPrivate => {\n\t\t\tlet count = services\n\t\t\t\t.rooms\n\t\t\t\t.timeline\n\t\t\t\t.get_pdu_count(&body.event_id)\n\t\t\t\t.await\n\t\t\t\t.map_err(|_| err!(Request(NotFound(\"Event not found.\"))))?;\n\n\t\t\tlet PduCount::Normal(count) = count else {\n\t\t\t\treturn Err!(Request(InvalidParam(\n\t\t\t\t\t\"Event is a backfilled PDU and cannot be marked as read.\"\n\t\t\t\t)));\n\t\t\t};\n\n\t\t\tservices\n\t\t\t\t.rooms\n\t\t\t\t.read_receipt\n\t\t\t\t.private_read_set(&body.room_id, sender_user, count);\n\t\t},\n\t\t| _ => {\n\t\t\treturn Err!(Request(InvalidParam(warn!(\n\t\t\t\t\"Received unknown read receipt type: {}\",\n\t\t\t\t&body.receipt_type\n\t\t\t))));\n\t\t},\n\t}\n\n\tOk(create_receipt::v3::Response {})\n}\n```"}], "func_name": "create_receipt_route", "docstring": "# `POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}`\n\nSets private read marker and public read receipt EDU.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/read_marker.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/read_marker.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a52351d05aca19a63f843e2d2b84191a3fd2cb8e6fab9dc728f964b31da9d6b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: redact_event_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/rooms/{roomId}/redact/{eventId}/{txnId}`\n\nTries to send a redaction event into the room.\n\n- TODO: Handle txn id\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn redact_event_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\tlet body = body.body;\n\n\tlet state_lock = services.rooms.state.mutex.lock(&body.room_id).await;\n\n\tlet event_id = services\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder {\n\t\t\t\tredacts: Some(body.event_id.clone()),\n\t\t\t\t..PduBuilder::timeline(&RoomRedactionEventContent {\n\t\t\t\t\tredacts: Some(body.event_id.clone()),\n\t\t\t\t\treason: body.reason.clone(),\n\t\t\t\t})\n\t\t\t},\n\t\t\tsender_user,\n\t\t\t&body.room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\tdrop(state_lock);\n\n\tOk(redact_event::v3::Response { event_id })\n}\n```"}], "func_name": "redact_event_route", "docstring": "# `PUT /_matrix/client/r0/rooms/{roomId}/redact/{eventId}/{txnId}`\n\nTries to send a redaction event into the room.\n\n- TODO: Handle txn id", "repo": "girlbossceo/conduwuit", "path": "src/api/client/redact.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/redact.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f4afbbefcb1297335305a859b14f2e5830665768ab3dadaeaa2cd4b8a22f579f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_relating_events_with_rel_type_and_event_type_route\n\nDocumentation:\n# `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}/{eventType}`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_relating_events_with_rel_type_and_event_type_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tpaginate_relations_with_filter(\n\t\t&services,\n\t\tbody.sender_user(),\n\t\t&body.room_id,\n\t\t&body.event_id,\n\t\tbody.event_type.clone().into(),\n\t\tbody.rel_type.clone().into(),\n\t\tbody.from.as_deref(),\n\t\tbody.to.as_deref(),\n\t\tbody.limit,\n\t\tbody.recurse,\n\t\tbody.dir,\n\t)\n\t.await\n\t.map(|res| get_relating_events_with_rel_type_and_event_type::v1::Response {\n\t\tchunk: res.chunk,\n\t\tnext_batch: res.next_batch,\n\t\tprev_batch: res.prev_batch,\n\t\trecursion_depth: res.recursion_depth,\n\t})\n}\n```"}], "func_name": "get_relating_events_with_rel_type_and_event_type_route", "docstring": "# `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}/{eventType}`", "repo": "girlbossceo/conduwuit", "path": "src/api/client/relations.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/relations.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25b3cf55264f3725ce21d6a2b7be2d5e98d36e2caaefbe4363ab0a0602bc23f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_relating_events_with_rel_type_route\n\nDocumentation:\n# `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_relating_events_with_rel_type_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tpaginate_relations_with_filter(\n\t\t&services,\n\t\tbody.sender_user(),\n\t\t&body.room_id,\n\t\t&body.event_id,\n\t\tNone,\n\t\tbody.rel_type.clone().into(),\n\t\tbody.from.as_deref(),\n\t\tbody.to.as_deref(),\n\t\tbody.limit,\n\t\tbody.recurse,\n\t\tbody.dir,\n\t)\n\t.await\n\t.map(|res| get_relating_events_with_rel_type::v1::Response {\n\t\tchunk: res.chunk,\n\t\tnext_batch: res.next_batch,\n\t\tprev_batch: res.prev_batch,\n\t\trecursion_depth: res.recursion_depth,\n\t})\n}\n```"}], "func_name": "get_relating_events_with_rel_type_route", "docstring": "# `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}`", "repo": "girlbossceo/conduwuit", "path": "src/api/client/relations.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/relations.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27fd8572b5d9541637bdd749c100689392323bf85b6f3eae6720b474570c5ff5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_relating_events_route\n\nDocumentation:\n# `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_relating_events_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tpaginate_relations_with_filter(\n\t\t&services,\n\t\tbody.sender_user(),\n\t\t&body.room_id,\n\t\t&body.event_id,\n\t\tNone,\n\t\tNone,\n\t\tbody.from.as_deref(),\n\t\tbody.to.as_deref(),\n\t\tbody.limit,\n\t\tbody.recurse,\n\t\tbody.dir,\n\t)\n\t.await\n}\n```"}], "func_name": "get_relating_events_route", "docstring": "# `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}`", "repo": "girlbossceo/conduwuit", "path": "src/api/client/relations.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/relations.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "55712298f9fb725764c1cf6a18a0e6a94b3026a91826272e14a235d6c8ea7f9b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_event_report_valid\n\nDocumentation:\nin the following order:\n\ncheck if the room ID from the URI matches the PDU's room ID\ncheck if score is in valid range\ncheck if report reasoning is less than or equal to 750 characters\ncheck if reporting user is in the reporting room\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn is_event_report_valid(\n\tservices: &Services,\n\tevent_id: &EventId,\n\troom_id: &RoomId,\n\tsender_user: &UserId,\n\treason: Option<&String>,\n\tscore: Option,\n\tpdu: &PduEvent,\n) -> Result<()> {\n\tdebug_info!(\n\t\t\"Checking if report from user {sender_user} for event {event_id} in room {room_id} is \\\n\t\t valid\"\n\t);\n\n\tif room_id != pdu.room_id {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::NotFound,\n\t\t\t\"Event ID does not belong to the reported room\",\n\t\t));\n\t}\n\n\tif score.is_some_and(|s| s > int!(0) || s < int!(-100)) {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::InvalidParam,\n\t\t\t\"Invalid score, must be within 0 to -100\",\n\t\t));\n\t}\n\n\tif reason.as_ref().is_some_and(|s| s.len() > 750) {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::InvalidParam,\n\t\t\t\"Reason too long, should be 750 characters or fewer\",\n\t\t));\n\t}\n\n\tif !services\n\t\t.rooms\n\t\t.state_cache\n\t\t.room_members(room_id)\n\t\t.ready_any(|user_id| user_id == sender_user)\n\t\t.await\n\t{\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::NotFound,\n\t\t\t\"You are not in the room you are reporting.\",\n\t\t));\n\t}\n\n\tOk(())\n}\n```"}], "func_name": "is_event_report_valid", "docstring": "in the following order:\n\ncheck if the room ID from the URI matches the PDU's room ID\ncheck if score is in valid range\ncheck if report reasoning is less than or equal to 750 characters\ncheck if reporting user is in the reporting room", "repo": "girlbossceo/conduwuit", "path": "src/api/client/report.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ec70ce022398137098dc0e2521f3014deb5257088ba6dd1706682fb63d65672a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delay_response\n\nDocumentation:\neven though this is kinda security by obscurity, let's still make a small\nrandom delay sending a response per spec suggestion regarding\nenumerating for potential events existing in our server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn delay_response() {\n\tlet time_to_wait = rand::thread_rng().gen_range(2..5);\n\tdebug_info!(\n\t\t\"Got successful /report request, waiting {time_to_wait} seconds before sending \\\n\t\t successful response.\"\n\t);\n\tsleep(Duration::from_secs(time_to_wait)).await;\n}\n```"}], "func_name": "delay_response", "docstring": "even though this is kinda security by obscurity, let's still make a small\nrandom delay sending a response per spec suggestion regarding\nenumerating for potential events existing in our server.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/report.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "26792a76e63d136e112c114f6afca7b8a59c5b62f05c8bf7624c195ad736b614"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: search_events_route\n\nDocumentation:\n# `POST /_matrix/client/r0/search`\n\nSearches rooms for messages.\n\n- Only works if the user is currently joined to the room (TODO: Respect\nhistory visibility)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn search_events_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\tlet next_batch = body.next_batch.as_deref();\n\tlet room_events_result: OptionFuture<_> = body\n\t\t.search_categories\n\t\t.room_events\n\t\t.as_ref()\n\t\t.map(|criteria| category_room_events(&services, sender_user, next_batch, criteria))\n\t\t.into();\n\n\tOk(Response {\n\t\tsearch_categories: ResultCategories {\n\t\t\troom_events: room_events_result\n\t\t\t\t.await\n\t\t\t\t.unwrap_or_else(|| Ok(ResultRoomEvents::default()))?,\n\t\t},\n\t})\n}\n```"}], "func_name": "search_events_route", "docstring": "# `POST /_matrix/client/r0/search`\n\nSearches rooms for messages.\n\n- Only works if the user is currently joined to the room (TODO: Respect\nhistory visibility)", "repo": "girlbossceo/conduwuit", "path": "src/api/client/search.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/search.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0c732b50afc28441c34269279ba42213a6ad12843c60d5c48f0cb96bf62670f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_message_event_route\n\nDocumentation:\n# `PUT /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId}`\n\nSend a message event into the room.\n\n- Is a NOOP if the txn id was already used before and returns the same event\nid again\n- The only requirement for the content is that it has to be valid json\n- Tries to send the event into the room, auth rules will determine if it is\nallowed\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn send_message_event_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\tlet sender_device = body.sender_device.as_deref();\n\tlet appservice_info = body.appservice_info.as_ref();\n\n\t// Forbid m.room.encrypted if encryption is disabled\n\tif MessageLikeEventType::RoomEncrypted == body.event_type && !services.config.allow_encryption\n\t{\n\t\treturn Err!(Request(Forbidden(\"Encryption has been disabled\")));\n\t}\n\n\tlet state_lock = services.rooms.state.mutex.lock(&body.room_id).await;\n\n\tif body.event_type == MessageLikeEventType::CallInvite\n\t\t&& services.rooms.directory.is_public_room(&body.room_id).await\n\t{\n\t\treturn Err!(Request(Forbidden(\"Room call invites are not allowed in public rooms\")));\n\t}\n\n\t// Check if this is a new transaction id\n\tif let Ok(response) = services\n\t\t.transaction_ids\n\t\t.existing_txnid(sender_user, sender_device, &body.txn_id)\n\t\t.await\n\t{\n\t\t// The client might have sent a txnid of the /sendToDevice endpoint\n\t\t// This txnid has no response associated with it\n\t\tif response.is_empty() {\n\t\t\treturn Err!(Request(InvalidParam(\n\t\t\t\t\"Tried to use txn id already used for an incompatible endpoint.\"\n\t\t\t)));\n\t\t}\n\n\t\treturn Ok(send_message_event::v3::Response {\n\t\t\tevent_id: utils::string_from_bytes(&response)\n\t\t\t\t.map(TryInto::try_into)\n\t\t\t\t.map_err(|e| err!(Database(\"Invalid event_id in txnid data: {e:?}\")))??,\n\t\t});\n\t}\n\n\tlet mut unsigned = BTreeMap::new();\n\tunsigned.insert(\"transaction_id\".to_owned(), body.txn_id.to_string().into());\n\n\tlet content = from_str(body.body.body.json().get())\n\t\t.map_err(|e| err!(Request(BadJson(\"Invalid JSON body: {e}\"))))?;\n\n\tlet event_id = services\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder {\n\t\t\t\tevent_type: body.event_type.clone().into(),\n\t\t\t\tcontent,\n\t\t\t\tunsigned: Some(unsigned),\n\t\t\t\ttimestamp: appservice_info.and(body.timestamp),\n\t\t\t\t..Default::default()\n\t\t\t},\n\t\t\tsender_user,\n\t\t\t&body.room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\tservices.transaction_ids.add_txnid(\n\t\tsender_user,\n\t\tsender_device,\n\t\t&body.txn_id,\n\t\tevent_id.as_bytes(),\n\t);\n\n\tdrop(state_lock);\n\n\tOk(send_message_event::v3::Response { event_id })\n}\n```"}], "func_name": "send_message_event_route", "docstring": "# `PUT /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId}`\n\nSend a message event into the room.\n\n- Is a NOOP if the txn id was already used before and returns the same event\nid again\n- The only requirement for the content is that it has to be valid json\n- Tries to send the event into the room, auth rules will determine if it is\nallowed", "repo": "girlbossceo/conduwuit", "path": "src/api/client/send.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/send.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "11cbc076c5ec3ddeb7766b569c92dd96591591c32618cdaf089437650f833e2b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_hierarchy_route\n\nDocumentation:\n# `GET /_matrix/client/v1/rooms/{room_id}/hierarchy`\n\nPaginates over the space tree in a depth-first manner to locate child rooms\nof a given space.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_hierarchy_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet limit = body\n\t\t.limit\n\t\t.unwrap_or_else(|| UInt::from(10_u32))\n\t\t.min(UInt::from(100_u32));\n\n\tlet max_depth = body\n\t\t.max_depth\n\t\t.unwrap_or_else(|| UInt::from(3_u32))\n\t\t.min(UInt::from(10_u32));\n\n\tlet key = body\n\t\t.from\n\t\t.as_ref()\n\t\t.and_then(|s| PaginationToken::from_str(s).ok());\n\n\t// Should prevent unexpeded behaviour in (bad) clients\n\tif let Some(ref token) = key {\n\t\tif token.suggested_only != body.suggested_only || token.max_depth != max_depth {\n\t\t\treturn Err!(Request(InvalidParam(\n\t\t\t\t\"suggested_only and max_depth cannot change on paginated requests\"\n\t\t\t)));\n\t\t}\n\t}\n\n\tget_client_hierarchy(\n\t\t&services,\n\t\tbody.sender_user(),\n\t\t&body.room_id,\n\t\tlimit.try_into().unwrap_or(10),\n\t\tmax_depth.try_into().unwrap_or(usize::MAX),\n\t\tbody.suggested_only,\n\t\tkey.as_ref()\n\t\t\t.into_iter()\n\t\t\t.flat_map(|t| t.short_room_ids.iter()),\n\t)\n\t.await\n}\n```"}], "func_name": "get_hierarchy_route", "docstring": "# `GET /_matrix/client/v1/rooms/{room_id}/hierarchy`\n\nPaginates over the space tree in a depth-first manner to locate child rooms\nof a given space.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/space.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/space.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "546b6d14b991f30b97bbe85be556af2d20d60b5d26bd6033d92dc0d508c98392"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_state_event_for_key_route\n\nDocumentation:\n# `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}/{stateKey}`\n\nSends a state event into the room.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn send_state_event_for_key_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\n\tOk(send_state_event::v3::Response {\n\t\tevent_id: send_state_event_for_key_helper(\n\t\t\t&services,\n\t\t\tsender_user,\n\t\t\t&body.room_id,\n\t\t\t&body.event_type,\n\t\t\t&body.body.body,\n\t\t\t&body.state_key,\n\t\t\tif body.appservice_info.is_some() {\n\t\t\t\tbody.timestamp\n\t\t\t} else {\n\t\t\t\tNone\n\t\t\t},\n\t\t)\n\t\t.await?,\n\t})\n}\n```"}], "func_name": "send_state_event_for_key_route", "docstring": "# `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}/{stateKey}`\n\nSends a state event into the room.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/state.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "87b1331d4889792677b525e95c4a05bd0977fb7ea10ca2d5e7ad1b9053e91665"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_state_event_for_empty_key_route\n\nDocumentation:\n# `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}`\n\nSends a state event into the room.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn send_state_event_for_empty_key_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result> {\n\tsend_state_event_for_key_route(State(services), body)\n\t\t.await\n\t\t.map(RumaResponse)\n}\n```"}], "func_name": "send_state_event_for_empty_key_route", "docstring": "# `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}`\n\nSends a state event into the room.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/state.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5ecc7b2c8a017deb9ea2af1d1a484e24bade11b9b9918defb16da87029651104"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_state_events_route\n\nDocumentation:\n# `GET /_matrix/client/v3/rooms/{roomid}/state`\n\nGet all state events for a room.\n\n- If not joined: Only works if current room history visibility is world\nreadable\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_state_events_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tif !services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.user_can_see_state_events(sender_user, &body.room_id)\n\t\t.await\n\t{\n\t\treturn Err!(Request(Forbidden(\"You don't have permission to view the room state.\")));\n\t}\n\n\tOk(get_state_events::v3::Response {\n\t\troom_state: services\n\t\t\t.rooms\n\t\t\t.state_accessor\n\t\t\t.room_state_full_pdus(&body.room_id)\n\t\t\t.map_ok(PduEvent::into_state_event)\n\t\t\t.try_collect()\n\t\t\t.await?,\n\t})\n}\n```"}], "func_name": "get_state_events_route", "docstring": "# `GET /_matrix/client/v3/rooms/{roomid}/state`\n\nGet all state events for a room.\n\n- If not joined: Only works if current room history visibility is world\nreadable", "repo": "girlbossceo/conduwuit", "path": "src/api/client/state.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f3df4706ce879d113a7856e1e8e925344628c00a8e1d68dbc650650eea8df347"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_state_events_for_key_route\n\nDocumentation:\n# `GET /_matrix/client/v3/rooms/{roomid}/state/{eventType}/{stateKey}`\n\nGet single state event of a room with the specified state key.\nThe optional query parameter `?format=event|content` allows returning the\nfull room state event or just the state event's content (default behaviour)\n\n- If not joined: Only works if current room history visibility is world\nreadable\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_state_events_for_key_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\n\tif !services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.user_can_see_state_events(sender_user, &body.room_id)\n\t\t.await\n\t{\n\t\treturn Err!(Request(NotFound(debug_warn!(\n\t\t\t\"You don't have permission to view the room state.\"\n\t\t))));\n\t}\n\n\tlet event = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.room_state_get(&body.room_id, &body.event_type, &body.state_key)\n\t\t.await\n\t\t.map_err(|_| {\n\t\t\terr!(Request(NotFound(debug_warn!(\n\t\t\t\t\troom_id = ?body.room_id,\n\t\t\t\t\tevent_type = ?body.event_type,\n\t\t\t\t\t\"State event not found in room.\",\n\t\t\t))))\n\t\t})?;\n\n\tlet event_format = body\n\t\t.format\n\t\t.as_ref()\n\t\t.is_some_and(|f| f.to_lowercase().eq(\"event\"));\n\n\tOk(get_state_events_for_key::v3::Response {\n\t\tcontent: event_format.or(|| event.get_content_as_value()),\n\t\tevent: event_format.then(|| event.into_state_event_value()),\n\t})\n}\n```"}], "func_name": "get_state_events_for_key_route", "docstring": "# `GET /_matrix/client/v3/rooms/{roomid}/state/{eventType}/{stateKey}`\n\nGet single state event of a room with the specified state key.\nThe optional query parameter `?format=event|content` allows returning the\nfull room state event or just the state event's content (default behaviour)\n\n- If not joined: Only works if current room history visibility is world\nreadable", "repo": "girlbossceo/conduwuit", "path": "src/api/client/state.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b6cb1098036b20841ffa9c6fe66ab558c313988788ffbb2732add3489c2ba66e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_state_events_for_empty_key_route\n\nDocumentation:\n# `GET /_matrix/client/v3/rooms/{roomid}/state/{eventType}`\n\nGet single state event of a room.\nThe optional query parameter `?format=event|content` allows returning the\nfull room state event or just the state event's content (default behaviour)\n\n- If not joined: Only works if current room history visibility is world\nreadable\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_state_events_for_empty_key_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result> {\n\tget_state_events_for_key_route(State(services), body)\n\t\t.await\n\t\t.map(RumaResponse)\n}\n```"}], "func_name": "get_state_events_for_empty_key_route", "docstring": "# `GET /_matrix/client/v3/rooms/{roomid}/state/{eventType}`\n\nGet single state event of a room.\nThe optional query parameter `?format=event|content` allows returning the\nfull room state event or just the state event's content (default behaviour)\n\n- If not joined: Only works if current room history visibility is world\nreadable", "repo": "girlbossceo/conduwuit", "path": "src/api/client/state.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "658a51710e953f1169ca17cff43a64ccb9f83362a01cb0933faf145c9e1e68cc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_tag_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags/{tag}`\n\nAdds a tag to the room.\n\n- Inserts the tag into the tag event of the room account data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn update_tag_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tlet mut tags_event = services\n\t\t.account_data\n\t\t.get_room(&body.room_id, sender_user, RoomAccountDataEventType::Tag)\n\t\t.await\n\t\t.unwrap_or(TagEvent {\n\t\t\tcontent: TagEventContent { tags: BTreeMap::new() },\n\t\t});\n\n\ttags_event\n\t\t.content\n\t\t.tags\n\t\t.insert(body.tag.clone().into(), body.tag_info.clone());\n\n\tservices\n\t\t.account_data\n\t\t.update(\n\t\t\tSome(&body.room_id),\n\t\t\tsender_user,\n\t\t\tRoomAccountDataEventType::Tag,\n\t\t\t&serde_json::to_value(tags_event).expect(\"to json value always works\"),\n\t\t)\n\t\t.await?;\n\n\tOk(create_tag::v3::Response {})\n}\n```"}], "func_name": "update_tag_route", "docstring": "# `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags/{tag}`\n\nAdds a tag to the room.\n\n- Inserts the tag into the tag event of the room account data.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/tag.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/tag.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25d04bf5bc4c7bdf362570461730504e8570863aaee2144414657ec8e1745ede"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_tag_route\n\nDocumentation:\n# `DELETE /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags/{tag}`\n\nDeletes a tag from the room.\n\n- Removes the tag from the tag event of the room account data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn delete_tag_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tlet mut tags_event = services\n\t\t.account_data\n\t\t.get_room(&body.room_id, sender_user, RoomAccountDataEventType::Tag)\n\t\t.await\n\t\t.unwrap_or(TagEvent {\n\t\t\tcontent: TagEventContent { tags: BTreeMap::new() },\n\t\t});\n\n\ttags_event.content.tags.remove(&body.tag.clone().into());\n\n\tservices\n\t\t.account_data\n\t\t.update(\n\t\t\tSome(&body.room_id),\n\t\t\tsender_user,\n\t\t\tRoomAccountDataEventType::Tag,\n\t\t\t&serde_json::to_value(tags_event).expect(\"to json value always works\"),\n\t\t)\n\t\t.await?;\n\n\tOk(delete_tag::v3::Response {})\n}\n```"}], "func_name": "delete_tag_route", "docstring": "# `DELETE /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags/{tag}`\n\nDeletes a tag from the room.\n\n- Removes the tag from the tag event of the room account data.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/tag.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/tag.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8b2050d86a32da65f9a5ef4a87fcb7a56c2855a097f7b27ef24ca2d796dda2d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_tags_route\n\nDocumentation:\n# `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags`\n\nReturns tags on the room.\n\n- Gets the tag event of the room account data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_tags_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tlet tags_event = services\n\t\t.account_data\n\t\t.get_room(&body.room_id, sender_user, RoomAccountDataEventType::Tag)\n\t\t.await\n\t\t.unwrap_or(TagEvent {\n\t\t\tcontent: TagEventContent { tags: BTreeMap::new() },\n\t\t});\n\n\tOk(get_tags::v3::Response { tags: tags_event.content.tags })\n}\n```"}], "func_name": "get_tags_route", "docstring": "# `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags`\n\nReturns tags on the room.\n\n- Gets the tag event of the room account data.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/tag.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/tag.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "78612e0225870c052503794e627da6ac62c447da8d2cec31320282129659ce91"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_protocols_route\n\nDocumentation:\n# `GET /_matrix/client/r0/thirdparty/protocols`\n\nTODO: Fetches all metadata about protocols supported by the homeserver.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_protocols_route(\n\t_body: Ruma,\n) -> Result {\n\t// TODO\n\tOk(get_protocols::v3::Response { protocols: BTreeMap::new() })\n}\n```"}], "func_name": "get_protocols_route", "docstring": "# `GET /_matrix/client/r0/thirdparty/protocols`\n\nTODO: Fetches all metadata about protocols supported by the homeserver.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/thirdparty.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/thirdparty.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "acc7afccccddd8fec190fa698e2e832c21e6f74943ef6c8ba83d5cfc7237faf9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_protocols_route_unstable\n\nDocumentation:\n# `GET /_matrix/client/unstable/thirdparty/protocols`\n\nSame as `get_protocols_route`, except for some reason Element Android legacy\ncalls this\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_protocols_route_unstable(\n\tbody: Ruma,\n) -> Result> {\n\tget_protocols_route(body).await.map(RumaResponse)\n}\n```"}], "func_name": "get_protocols_route_unstable", "docstring": "# `GET /_matrix/client/unstable/thirdparty/protocols`\n\nSame as `get_protocols_route`, except for some reason Element Android legacy\ncalls this", "repo": "girlbossceo/conduwuit", "path": "src/api/client/thirdparty.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/thirdparty.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "24c04dbd1afce40b7f58434b824c663f21a9cf8c58451b7936f09c239d563d87"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_event_to_device_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/sendToDevice/{eventType}/{txnId}`\n\nSend a to-device event to a set of client devices.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn send_event_to_device_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\tlet sender_device = body.sender_device.as_deref();\n\n\t// Check if this is a new transaction id\n\tif services\n\t\t.transaction_ids\n\t\t.existing_txnid(sender_user, sender_device, &body.txn_id)\n\t\t.await\n\t\t.is_ok()\n\t{\n\t\treturn Ok(send_event_to_device::v3::Response {});\n\t}\n\n\tfor (target_user_id, map) in &body.messages {\n\t\tfor (target_device_id_maybe, event) in map {\n\t\t\tif !services.globals.user_is_local(target_user_id) {\n\t\t\t\tlet mut map = BTreeMap::new();\n\t\t\t\tmap.insert(target_device_id_maybe.clone(), event.clone());\n\t\t\t\tlet mut messages = BTreeMap::new();\n\t\t\t\tmessages.insert(target_user_id.clone(), map);\n\t\t\t\tlet count = services.globals.next_count()?;\n\n\t\t\t\tlet mut buf = EduBuf::new();\n\t\t\t\tserde_json::to_writer(\n\t\t\t\t\t&mut buf,\n\t\t\t\t\t&federation::transactions::edu::Edu::DirectToDevice(DirectDeviceContent {\n\t\t\t\t\t\tsender: sender_user.clone(),\n\t\t\t\t\t\tev_type: body.event_type.clone(),\n\t\t\t\t\t\tmessage_id: count.to_string().into(),\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.expect(\"DirectToDevice EDU can be serialized\");\n\n\t\t\t\tservices\n\t\t\t\t\t.sending\n\t\t\t\t\t.send_edu_server(target_user_id.server_name(), buf)?;\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tlet event_type = &body.event_type.to_string();\n\n\t\t\tlet event = event\n\t\t\t\t.deserialize_as()\n\t\t\t\t.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, \"Event is invalid\"))?;\n\n\t\t\tmatch target_device_id_maybe {\n\t\t\t\t| DeviceIdOrAllDevices::DeviceId(target_device_id) => {\n\t\t\t\t\tservices\n\t\t\t\t\t\t.users\n\t\t\t\t\t\t.add_to_device_event(\n\t\t\t\t\t\t\tsender_user,\n\t\t\t\t\t\t\ttarget_user_id,\n\t\t\t\t\t\t\ttarget_device_id,\n\t\t\t\t\t\t\tevent_type,\n\t\t\t\t\t\t\tevent,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.await;\n\t\t\t\t},\n\n\t\t\t\t| DeviceIdOrAllDevices::AllDevices => {\n\t\t\t\t\tlet (event_type, event) = (&event_type, &event);\n\t\t\t\t\tservices\n\t\t\t\t\t\t.users\n\t\t\t\t\t\t.all_device_ids(target_user_id)\n\t\t\t\t\t\t.for_each(|target_device_id| {\n\t\t\t\t\t\t\tservices.users.add_to_device_event(\n\t\t\t\t\t\t\t\tsender_user,\n\t\t\t\t\t\t\t\ttarget_user_id,\n\t\t\t\t\t\t\t\ttarget_device_id,\n\t\t\t\t\t\t\t\tevent_type,\n\t\t\t\t\t\t\t\tevent.clone(),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.await;\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\n\t// Save transaction id with empty data\n\tservices\n\t\t.transaction_ids\n\t\t.add_txnid(sender_user, sender_device, &body.txn_id, &[]);\n\n\tOk(send_event_to_device::v3::Response {})\n}\n```"}], "func_name": "send_event_to_device_route", "docstring": "# `PUT /_matrix/client/r0/sendToDevice/{eventType}/{txnId}`\n\nSend a to-device event to a set of client devices.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/to_device.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/to_device.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bca033afe0839c424b181bf485210f926c4dea6b3bee70007b08c991ce71844e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_typing_event_route\n\nDocumentation:\n# `PUT /_matrix/client/r0/rooms/{roomId}/typing/{userId}`\n\nSets the typing state of the sender user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn create_typing_event_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tuse create_typing_event::v3::Typing;\n\tlet sender_user = body.sender_user();\n\n\tif sender_user != body.user_id && body.appservice_info.is_none() {\n\t\treturn Err!(Request(Forbidden(\"You cannot update typing status of other users.\")));\n\t}\n\n\tif !services\n\t\t.rooms\n\t\t.state_cache\n\t\t.is_joined(sender_user, &body.room_id)\n\t\t.await\n\t{\n\t\treturn Err!(Request(Forbidden(\"You are not in this room.\")));\n\t}\n\n\tmatch body.state {\n\t\t| Typing::Yes(duration) => {\n\t\t\tlet duration = utils::clamp(\n\t\t\t\tduration.as_millis().try_into().unwrap_or(u64::MAX),\n\t\t\t\tservices\n\t\t\t\t\t.server\n\t\t\t\t\t.config\n\t\t\t\t\t.typing_client_timeout_min_s\n\t\t\t\t\t.try_mul(1000)?,\n\t\t\t\tservices\n\t\t\t\t\t.server\n\t\t\t\t\t.config\n\t\t\t\t\t.typing_client_timeout_max_s\n\t\t\t\t\t.try_mul(1000)?,\n\t\t\t);\n\t\t\tservices\n\t\t\t\t.rooms\n\t\t\t\t.typing\n\t\t\t\t.typing_add(\n\t\t\t\t\tsender_user,\n\t\t\t\t\t&body.room_id,\n\t\t\t\t\tutils::millis_since_unix_epoch()\n\t\t\t\t\t\t.checked_add(duration)\n\t\t\t\t\t\t.expect(\"user typing timeout should not get this high\"),\n\t\t\t\t)\n\t\t\t\t.await?;\n\t\t},\n\t\t| _ => {\n\t\t\tservices\n\t\t\t\t.rooms\n\t\t\t\t.typing\n\t\t\t\t.typing_remove(sender_user, &body.room_id)\n\t\t\t\t.await?;\n\t\t},\n\t}\n\n\t// ping presence\n\tif services.config.allow_local_presence {\n\t\tservices\n\t\t\t.presence\n\t\t\t.ping_presence(&body.user_id, &ruma::presence::PresenceState::Online)\n\t\t\t.await?;\n\t}\n\n\tOk(create_typing_event::v3::Response {})\n}\n```"}], "func_name": "create_typing_event_route", "docstring": "# `PUT /_matrix/client/r0/rooms/{roomId}/typing/{userId}`\n\nSets the typing state of the sender user.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/typing.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/typing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ceb571bbba55c7eee50192cd2e0808790be5bc0101cb8ffc330c2abd2f0665e8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_timezone_key_route\n\nDocumentation:\n# `DELETE /_matrix/client/unstable/uk.tcpip.msc4133/profile/:user_id/us.cloke.msc4175.tz`\n\nDeletes the `tz` (timezone) of a user, as per MSC4133 and MSC4175.\n\n- Also makes sure other users receive the update using presence EDUs\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn delete_timezone_key_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tif *sender_user != body.user_id && body.appservice_info.is_none() {\n\t\treturn Err!(Request(Forbidden(\"You cannot update the profile of another user\")));\n\t}\n\n\tservices.users.set_timezone(&body.user_id, None);\n\n\tif services.config.allow_local_presence {\n\t\t// Presence update\n\t\tservices\n\t\t\t.presence\n\t\t\t.ping_presence(&body.user_id, &PresenceState::Online)\n\t\t\t.await?;\n\t}\n\n\tOk(delete_timezone_key::unstable::Response {})\n}\n```"}], "func_name": "delete_timezone_key_route", "docstring": "# `DELETE /_matrix/client/unstable/uk.tcpip.msc4133/profile/:user_id/us.cloke.msc4175.tz`\n\nDeletes the `tz` (timezone) of a user, as per MSC4133 and MSC4175.\n\n- Also makes sure other users receive the update using presence EDUs", "repo": "girlbossceo/conduwuit", "path": "src/api/client/unstable.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/unstable.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f8a8eac550bfb225d959f75f9579fc0b90fe74f0472f81067856828ffa665549"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_timezone_key_route\n\nDocumentation:\n# `PUT /_matrix/client/unstable/uk.tcpip.msc4133/profile/:user_id/us.cloke.msc4175.tz`\n\nUpdates the `tz` (timezone) of a user, as per MSC4133 and MSC4175.\n\n- Also makes sure other users receive the update using presence EDUs\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn set_timezone_key_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tif *sender_user != body.user_id && body.appservice_info.is_none() {\n\t\treturn Err!(Request(Forbidden(\"You cannot update the profile of another user\")));\n\t}\n\n\tservices.users.set_timezone(&body.user_id, body.tz.clone());\n\n\tif services.config.allow_local_presence {\n\t\t// Presence update\n\t\tservices\n\t\t\t.presence\n\t\t\t.ping_presence(&body.user_id, &PresenceState::Online)\n\t\t\t.await?;\n\t}\n\n\tOk(set_timezone_key::unstable::Response {})\n}\n```"}], "func_name": "set_timezone_key_route", "docstring": "# `PUT /_matrix/client/unstable/uk.tcpip.msc4133/profile/:user_id/us.cloke.msc4175.tz`\n\nUpdates the `tz` (timezone) of a user, as per MSC4133 and MSC4175.\n\n- Also makes sure other users receive the update using presence EDUs", "repo": "girlbossceo/conduwuit", "path": "src/api/client/unstable.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/unstable.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94d9d966cb0ade70e4a82ab76ff501091592ff7252353d376f6f4cdb30e537af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_profile_key_route\n\nDocumentation:\n# `PUT /_matrix/client/unstable/uk.tcpip.msc4133/profile/{user_id}/{field}`\n\nUpdates the profile key-value field of a user, as per MSC4133.\n\nThis also handles the avatar_url and displayname being updated.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn set_profile_key_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tif *sender_user != body.user_id && body.appservice_info.is_none() {\n\t\treturn Err!(Request(Forbidden(\"You cannot update the profile of another user\")));\n\t}\n\n\tif body.kv_pair.is_empty() {\n\t\treturn Err!(Request(BadJson(\n\t\t\t\"The key-value pair JSON body is empty. Use DELETE to delete a key\"\n\t\t)));\n\t}\n\n\tif body.kv_pair.len() > 1 {\n\t\t// TODO: support PATCH or \"recursively\" adding keys in some sort\n\t\treturn Err!(Request(BadJson(\n\t\t\t\"This endpoint can only take one key-value pair at a time\"\n\t\t)));\n\t}\n\n\tlet Some(profile_key_value) = body.kv_pair.get(&body.key_name) else {\n\t\treturn Err!(Request(BadJson(\n\t\t\t\"The key does not match the URL field key, or JSON body is empty (use DELETE)\"\n\t\t)));\n\t};\n\n\tif body\n\t\t.kv_pair\n\t\t.keys()\n\t\t.any(|key| key.starts_with(\"u.\") && !profile_key_value.is_string())\n\t{\n\t\treturn Err!(Request(BadJson(\"u.* profile key fields must be strings\")));\n\t}\n\n\tif body.kv_pair.keys().any(|key| key.len() > 128) {\n\t\treturn Err!(Request(BadJson(\"Key names cannot be longer than 128 bytes\")));\n\t}\n\n\tif body.key_name == \"displayname\" {\n\t\tlet all_joined_rooms: Vec = services\n\t\t\t.rooms\n\t\t\t.state_cache\n\t\t\t.rooms_joined(&body.user_id)\n\t\t\t.map(Into::into)\n\t\t\t.collect()\n\t\t\t.await;\n\n\t\tupdate_displayname(\n\t\t\t&services,\n\t\t\t&body.user_id,\n\t\t\tSome(profile_key_value.to_string()),\n\t\t\t&all_joined_rooms,\n\t\t)\n\t\t.await;\n\t} else if body.key_name == \"avatar_url\" {\n\t\tlet mxc = ruma::OwnedMxcUri::from(profile_key_value.to_string());\n\n\t\tlet all_joined_rooms: Vec = services\n\t\t\t.rooms\n\t\t\t.state_cache\n\t\t\t.rooms_joined(&body.user_id)\n\t\t\t.map(Into::into)\n\t\t\t.collect()\n\t\t\t.await;\n\n\t\tupdate_avatar_url(&services, &body.user_id, Some(mxc), None, &all_joined_rooms).await;\n\t} else {\n\t\tservices.users.set_profile_key(\n\t\t\t&body.user_id,\n\t\t\t&body.key_name,\n\t\t\tSome(profile_key_value.clone()),\n\t\t);\n\t}\n\n\tif services.config.allow_local_presence {\n\t\t// Presence update\n\t\tservices\n\t\t\t.presence\n\t\t\t.ping_presence(&body.user_id, &PresenceState::Online)\n\t\t\t.await?;\n\t}\n\n\tOk(set_profile_key::unstable::Response {})\n}\n```"}], "func_name": "set_profile_key_route", "docstring": "# `PUT /_matrix/client/unstable/uk.tcpip.msc4133/profile/{user_id}/{field}`\n\nUpdates the profile key-value field of a user, as per MSC4133.\n\nThis also handles the avatar_url and displayname being updated.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/unstable.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/unstable.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8103cd1ff1acf05b1fcae74160c89ac2d5c0594effe4609706c7cbc18d0c4f82"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_profile_key_route\n\nDocumentation:\n# `DELETE /_matrix/client/unstable/uk.tcpip.msc4133/profile/{user_id}/{field}`\n\nDeletes the profile key-value field of a user, as per MSC4133.\n\nThis also handles the avatar_url and displayname being updated.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn delete_profile_key_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tif *sender_user != body.user_id && body.appservice_info.is_none() {\n\t\treturn Err!(Request(Forbidden(\"You cannot update the profile of another user\")));\n\t}\n\n\tif body.kv_pair.len() > 1 {\n\t\t// TODO: support PATCH or \"recursively\" adding keys in some sort\n\t\treturn Err!(Request(BadJson(\n\t\t\t\"This endpoint can only take one key-value pair at a time\"\n\t\t)));\n\t}\n\n\tif body.key_name == \"displayname\" {\n\t\tlet all_joined_rooms: Vec = services\n\t\t\t.rooms\n\t\t\t.state_cache\n\t\t\t.rooms_joined(&body.user_id)\n\t\t\t.map(Into::into)\n\t\t\t.collect()\n\t\t\t.await;\n\n\t\tupdate_displayname(&services, &body.user_id, None, &all_joined_rooms).await;\n\t} else if body.key_name == \"avatar_url\" {\n\t\tlet all_joined_rooms: Vec = services\n\t\t\t.rooms\n\t\t\t.state_cache\n\t\t\t.rooms_joined(&body.user_id)\n\t\t\t.map(Into::into)\n\t\t\t.collect()\n\t\t\t.await;\n\n\t\tupdate_avatar_url(&services, &body.user_id, None, None, &all_joined_rooms).await;\n\t} else {\n\t\tservices\n\t\t\t.users\n\t\t\t.set_profile_key(&body.user_id, &body.key_name, None);\n\t}\n\n\tif services.config.allow_local_presence {\n\t\t// Presence update\n\t\tservices\n\t\t\t.presence\n\t\t\t.ping_presence(&body.user_id, &PresenceState::Online)\n\t\t\t.await?;\n\t}\n\n\tOk(delete_profile_key::unstable::Response {})\n}\n```"}], "func_name": "delete_profile_key_route", "docstring": "# `DELETE /_matrix/client/unstable/uk.tcpip.msc4133/profile/{user_id}/{field}`\n\nDeletes the profile key-value field of a user, as per MSC4133.\n\nThis also handles the avatar_url and displayname being updated.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/unstable.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/unstable.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6a8f9421bed7432470b69fed0c755e0edee46cb740f6c3544b3886557dc65eb3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_timezone_key_route\n\nDocumentation:\n# `GET /_matrix/client/unstable/uk.tcpip.msc4133/profile/:user_id/us.cloke.msc4175.tz`\n\nReturns the `timezone` of the user as per MSC4133 and MSC4175.\n\n- If user is on another server and we do not have a local copy already fetch\n`timezone` over federation\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_timezone_key_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif !services.globals.user_is_local(&body.user_id) {\n\t\t// Create and update our local copy of the user\n\t\tif let Ok(response) = services\n\t\t\t.sending\n\t\t\t.send_federation_request(\n\t\t\t\tbody.user_id.server_name(),\n\t\t\t\tfederation::query::get_profile_information::v1::Request {\n\t\t\t\t\tuser_id: body.user_id.clone(),\n\t\t\t\t\tfield: None, // we want the full user's profile to update locally as well\n\t\t\t\t},\n\t\t\t)\n\t\t\t.await\n\t\t{\n\t\t\tif !services.users.exists(&body.user_id).await {\n\t\t\t\tservices.users.create(&body.user_id, None)?;\n\t\t\t}\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_displayname(&body.user_id, response.displayname.clone());\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_avatar_url(&body.user_id, response.avatar_url.clone());\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_blurhash(&body.user_id, response.blurhash.clone());\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_timezone(&body.user_id, response.tz.clone());\n\n\t\t\treturn Ok(get_timezone_key::unstable::Response { tz: response.tz });\n\t\t}\n\t}\n\n\tif !services.users.exists(&body.user_id).await {\n\t\t// Return 404 if this user doesn't exist and we couldn't fetch it over\n\t\t// federation\n\t\treturn Err(Error::BadRequest(ErrorKind::NotFound, \"Profile was not found.\"));\n\t}\n\n\tOk(get_timezone_key::unstable::Response {\n\t\ttz: services.users.timezone(&body.user_id).await.ok(),\n\t})\n}\n```"}], "func_name": "get_timezone_key_route", "docstring": "# `GET /_matrix/client/unstable/uk.tcpip.msc4133/profile/:user_id/us.cloke.msc4175.tz`\n\nReturns the `timezone` of the user as per MSC4133 and MSC4175.\n\n- If user is on another server and we do not have a local copy already fetch\n`timezone` over federation", "repo": "girlbossceo/conduwuit", "path": "src/api/client/unstable.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/unstable.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c69948ae22f10534a1f51a4b2e1f424d3d3f2e3e69bfee49d09f5e61045c183"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_profile_key_route\n\nDocumentation:\n# `GET /_matrix/client/unstable/uk.tcpip.msc4133/profile/{userId}/{field}}`\n\nGets the profile key-value field of a user, as per MSC4133.\n\n- If user is on another server and we do not have a local copy already fetch\n`timezone` over federation\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_profile_key_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet mut profile_key_value: BTreeMap = BTreeMap::new();\n\n\tif !services.globals.user_is_local(&body.user_id) {\n\t\t// Create and update our local copy of the user\n\t\tif let Ok(response) = services\n\t\t\t.sending\n\t\t\t.send_federation_request(\n\t\t\t\tbody.user_id.server_name(),\n\t\t\t\tfederation::query::get_profile_information::v1::Request {\n\t\t\t\t\tuser_id: body.user_id.clone(),\n\t\t\t\t\tfield: None, // we want the full user's profile to update locally as well\n\t\t\t\t},\n\t\t\t)\n\t\t\t.await\n\t\t{\n\t\t\tif !services.users.exists(&body.user_id).await {\n\t\t\t\tservices.users.create(&body.user_id, None)?;\n\t\t\t}\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_displayname(&body.user_id, response.displayname.clone());\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_avatar_url(&body.user_id, response.avatar_url.clone());\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_blurhash(&body.user_id, response.blurhash.clone());\n\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.set_timezone(&body.user_id, response.tz.clone());\n\n\t\t\tmatch response.custom_profile_fields.get(&body.key_name) {\n\t\t\t\t| Some(value) => {\n\t\t\t\t\tprofile_key_value.insert(body.key_name.clone(), value.clone());\n\t\t\t\t\tservices.users.set_profile_key(\n\t\t\t\t\t\t&body.user_id,\n\t\t\t\t\t\t&body.key_name,\n\t\t\t\t\t\tSome(value.clone()),\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\t| _ => {\n\t\t\t\t\treturn Err!(Request(NotFound(\"The requested profile key does not exist.\")));\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tif profile_key_value.is_empty() {\n\t\t\t\treturn Err!(Request(NotFound(\"The requested profile key does not exist.\")));\n\t\t\t}\n\n\t\t\treturn Ok(get_profile_key::unstable::Response { value: profile_key_value });\n\t\t}\n\t}\n\n\tif !services.users.exists(&body.user_id).await {\n\t\t// Return 404 if this user doesn't exist and we couldn't fetch it over\n\t\t// federation\n\t\treturn Err!(Request(NotFound(\"Profile was not found.\")));\n\t}\n\n\tmatch services\n\t\t.users\n\t\t.profile_key(&body.user_id, &body.key_name)\n\t\t.await\n\t{\n\t\t| Ok(value) => {\n\t\t\tprofile_key_value.insert(body.key_name.clone(), value);\n\t\t},\n\t\t| _ => {\n\t\t\treturn Err!(Request(NotFound(\"The requested profile key does not exist.\")));\n\t\t},\n\t}\n\n\tif profile_key_value.is_empty() {\n\t\treturn Err!(Request(NotFound(\"The requested profile key does not exist.\")));\n\t}\n\n\tOk(get_profile_key::unstable::Response { value: profile_key_value })\n}\n```"}], "func_name": "get_profile_key_route", "docstring": "# `GET /_matrix/client/unstable/uk.tcpip.msc4133/profile/{userId}/{field}}`\n\nGets the profile key-value field of a user, as per MSC4133.\n\n- If user is on another server and we do not have a local copy already fetch\n`timezone` over federation", "repo": "girlbossceo/conduwuit", "path": "src/api/client/unstable.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/unstable.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3c841194e6b8c35c26a1b6cd3dc2946a20938d9ce871a09d864898f64a1a611a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_supported_versions_route\n\nDocumentation:\n# `GET /_matrix/client/versions`\n\nGet the versions of the specification and unstable features supported by\nthis server.\n\n- Versions take the form MAJOR.MINOR.PATCH\n- Only the latest PATCH release will be reported for each MAJOR.MINOR value\n- Unstable features are namespaced and may include version information in\ntheir name\n\nNote: Unstable features are used while developing new features. Clients\nshould avoid using unstable features in their stable releases\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_supported_versions_route(\n\t_body: Ruma,\n) -> Result {\n\tlet resp = get_supported_versions::Response {\n\t\tversions: vec![\n\t\t\t\"r0.0.1\".to_owned(),\n\t\t\t\"r0.1.0\".to_owned(),\n\t\t\t\"r0.2.0\".to_owned(),\n\t\t\t\"r0.3.0\".to_owned(),\n\t\t\t\"r0.4.0\".to_owned(),\n\t\t\t\"r0.5.0\".to_owned(),\n\t\t\t\"r0.6.0\".to_owned(),\n\t\t\t\"r0.6.1\".to_owned(),\n\t\t\t\"v1.1\".to_owned(),\n\t\t\t\"v1.2\".to_owned(),\n\t\t\t\"v1.3\".to_owned(),\n\t\t\t\"v1.4\".to_owned(),\n\t\t\t\"v1.5\".to_owned(),\n\t\t\t\"v1.11\".to_owned(),\n\t\t],\n\t\tunstable_features: BTreeMap::from_iter([\n\t\t\t(\"org.matrix.e2e_cross_signing\".to_owned(), true),\n\t\t\t(\"org.matrix.msc2285.stable\".to_owned(), true), /* private read receipts (https://github.com/matrix-org/matrix-spec-proposals/pull/2285) */\n\t\t\t(\"uk.half-shot.msc2666.query_mutual_rooms\".to_owned(), true), /* query mutual rooms (https://github.com/matrix-org/matrix-spec-proposals/pull/2666) */\n\t\t\t(\"org.matrix.msc2836\".to_owned(), true), /* threading/threads (https://github.com/matrix-org/matrix-spec-proposals/pull/2836) */\n\t\t\t(\"org.matrix.msc2946\".to_owned(), true), /* spaces/hierarchy summaries (https://github.com/matrix-org/matrix-spec-proposals/pull/2946) */\n\t\t\t(\"org.matrix.msc3026.busy_presence\".to_owned(), true), /* busy presence status (https://github.com/matrix-org/matrix-spec-proposals/pull/3026) */\n\t\t\t(\"org.matrix.msc3827\".to_owned(), true), /* filtering of /publicRooms by room type (https://github.com/matrix-org/matrix-spec-proposals/pull/3827) */\n\t\t\t(\"org.matrix.msc3952_intentional_mentions\".to_owned(), true), /* intentional mentions (https://github.com/matrix-org/matrix-spec-proposals/pull/3952) */\n\t\t\t(\"org.matrix.msc3575\".to_owned(), true), /* sliding sync (https://github.com/matrix-org/matrix-spec-proposals/pull/3575/files#r1588877046) */\n\t\t\t(\"org.matrix.msc3916.stable\".to_owned(), true), /* authenticated media (https://github.com/matrix-org/matrix-spec-proposals/pull/3916) */\n\t\t\t(\"org.matrix.msc4180\".to_owned(), true), /* stable flag for 3916 (https://github.com/matrix-org/matrix-spec-proposals/pull/4180) */\n\t\t\t(\"uk.tcpip.msc4133\".to_owned(), true), /* Extending User Profile API with Key:Value Pairs (https://github.com/matrix-org/matrix-spec-proposals/pull/4133) */\n\t\t\t(\"us.cloke.msc4175\".to_owned(), true), /* Profile field for user time zone (https://github.com/matrix-org/matrix-spec-proposals/pull/4175) */\n\t\t\t(\"org.matrix.simplified_msc3575\".to_owned(), true), /* Simplified Sliding sync (https://github.com/matrix-org/matrix-spec-proposals/pull/4186) */\n\t\t]),\n\t};\n\n\tOk(resp)\n}\n```"}], "func_name": "get_supported_versions_route", "docstring": "# `GET /_matrix/client/versions`\n\nGet the versions of the specification and unstable features supported by\nthis server.\n\n- Versions take the form MAJOR.MINOR.PATCH\n- Only the latest PATCH release will be reported for each MAJOR.MINOR value\n- Unstable features are namespaced and may include version information in\ntheir name\n\nNote: Unstable features are used while developing new features. Clients\nshould avoid using unstable features in their stable releases", "repo": "girlbossceo/conduwuit", "path": "src/api/client/unversioned.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/unversioned.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9c93b512217adc6cb01b5af65ea68029e1a1442efa46914b2731bb6b1ae1b8d7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: conduwuit_server_version\n\nDocumentation:\n# `GET /_conduwuit/server_version`\n\nConduwuit-specific API to get the server version, results akin to\n`/_matrix/federation/v1/version`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn conduwuit_server_version() -> Result {\n\tOk(Json(serde_json::json!({\n\t\t\"name\": conduwuit::version::name(),\n\t\t\"version\": conduwuit::version::version(),\n\t})))\n}\n```"}], "func_name": "conduwuit_server_version", "docstring": "# `GET /_conduwuit/server_version`\n\nConduwuit-specific API to get the server version, results akin to\n`/_matrix/federation/v1/version`", "repo": "girlbossceo/conduwuit", "path": "src/api/client/unversioned.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/unversioned.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8d5fa07558bbbb63b29f24eba2543e97cd83e815f6603fe96283833e183e2b3e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: conduwuit_local_user_count\n\nDocumentation:\n# `GET /_conduwuit/local_user_count`\n\nconduwuit-specific API to return the amount of users registered on this\nhomeserver. Endpoint is disabled if federation is disabled for privacy. This\nonly includes active users (not deactivated, no guests, etc)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn conduwuit_local_user_count(\n\tState(services): State,\n) -> Result {\n\tlet user_count = services.users.list_local_users().count().await;\n\n\tOk(Json(serde_json::json!({\n\t\t\"count\": user_count\n\t})))\n}\n```"}], "func_name": "conduwuit_local_user_count", "docstring": "# `GET /_conduwuit/local_user_count`\n\nconduwuit-specific API to return the amount of users registered on this\nhomeserver. Endpoint is disabled if federation is disabled for privacy. This\nonly includes active users (not deactivated, no guests, etc)", "repo": "girlbossceo/conduwuit", "path": "src/api/client/unversioned.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/unversioned.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "70e37ea15c86a2bdb039b6e04efdb343630761620aca55798f72d765b0f3b45d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: search_users_route\n\nDocumentation:\n# `POST /_matrix/client/r0/user_directory/search`\n\nSearches all known users for a match.\n\n- Hides any local users that aren't in any public rooms (i.e. those that\nhave the join rule set to public) and don't share a room with the sender\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn search_users_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user();\n\tlet limit = usize::try_from(body.limit)\n\t\t.map_or(LIMIT_DEFAULT, usize::from)\n\t\t.min(LIMIT_MAX);\n\n\tlet mut users = services\n\t\t.users\n\t\t.stream()\n\t\t.map(ToOwned::to_owned)\n\t\t.broad_filter_map(async |user_id| {\n\t\t\tlet user = search_users::v3::User {\n\t\t\t\tuser_id: user_id.clone(),\n\t\t\t\tdisplay_name: services.users.displayname(&user_id).await.ok(),\n\t\t\t\tavatar_url: services.users.avatar_url(&user_id).await.ok(),\n\t\t\t};\n\n\t\t\tlet user_id_matches = user\n\t\t\t\t.user_id\n\t\t\t\t.as_str()\n\t\t\t\t.to_lowercase()\n\t\t\t\t.contains(&body.search_term.to_lowercase());\n\n\t\t\tlet user_displayname_matches = user.display_name.as_ref().is_some_and(|name| {\n\t\t\t\tname.to_lowercase()\n\t\t\t\t\t.contains(&body.search_term.to_lowercase())\n\t\t\t});\n\n\t\t\tif !user_id_matches && !user_displayname_matches {\n\t\t\t\treturn None;\n\t\t\t}\n\n\t\t\tlet user_in_public_room = services\n\t\t\t\t.rooms\n\t\t\t\t.state_cache\n\t\t\t\t.rooms_joined(&user_id)\n\t\t\t\t.map(ToOwned::to_owned)\n\t\t\t\t.any(|room| async move {\n\t\t\t\t\tservices\n\t\t\t\t\t\t.rooms\n\t\t\t\t\t\t.state_accessor\n\t\t\t\t\t\t.get_join_rules(&room)\n\t\t\t\t\t\t.map(|rule| matches!(rule, JoinRule::Public))\n\t\t\t\t\t\t.await\n\t\t\t\t});\n\n\t\t\tlet user_sees_user = services\n\t\t\t\t.rooms\n\t\t\t\t.state_cache\n\t\t\t\t.user_sees_user(sender_user, &user_id);\n\n\t\t\tpin_mut!(user_in_public_room, user_sees_user);\n\n\t\t\tuser_in_public_room.or(user_sees_user).await.then_some(user)\n\t\t});\n\n\tlet results = users.by_ref().take(limit).collect().await;\n\tlet limited = users.next().await.is_some();\n\n\tOk(search_users::v3::Response { results, limited })\n}\n```"}], "func_name": "search_users_route", "docstring": "# `POST /_matrix/client/r0/user_directory/search`\n\nSearches all known users for a match.\n\n- Hides any local users that aren't in any public rooms (i.e. those that\nhave the join rule set to public) and don't share a room with the sender", "repo": "girlbossceo/conduwuit", "path": "src/api/client/user_directory.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/user_directory.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27c139c62e86637e63cc2147d87cbab611d45134c5575cb046e4135d072b2902"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: turn_server_route\n\nDocumentation:\n# `GET /_matrix/client/r0/voip/turnServer`\n\nTODO: Returns information about the recommended turn server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn turn_server_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\t// MSC4166: return M_NOT_FOUND 404 if no TURN URIs are specified in any way\n\tif services.server.config.turn_uris.is_empty() {\n\t\treturn Err!(Request(NotFound(\"Not Found\")));\n\t}\n\n\tlet turn_secret = services.globals.turn_secret.clone();\n\n\tlet (username, password) = if !turn_secret.is_empty() {\n\t\tlet expiry = SecondsSinceUnixEpoch::from_system_time(\n\t\t\tSystemTime::now()\n\t\t\t\t.checked_add(Duration::from_secs(services.globals.turn_ttl()))\n\t\t\t\t.expect(\"TURN TTL should not get this high\"),\n\t\t)\n\t\t.expect(\"time is valid\");\n\n\t\tlet user = body.sender_user.unwrap_or_else(|| {\n\t\t\tUserId::parse_with_server_name(\n\t\t\t\tutils::random_string(RANDOM_USER_ID_LENGTH).to_lowercase(),\n\t\t\t\t&services.server.name,\n\t\t\t)\n\t\t\t.unwrap()\n\t\t});\n\n\t\tlet username: String = format!(\"{}:{}\", expiry.get(), user);\n\n\t\tlet mut mac = HmacSha1::new_from_slice(turn_secret.as_bytes())\n\t\t\t.expect(\"HMAC can take key of any size\");\n\t\tmac.update(username.as_bytes());\n\n\t\tlet password: String = general_purpose::STANDARD.encode(mac.finalize().into_bytes());\n\n\t\t(username, password)\n\t} else {\n\t\t(\n\t\t\tservices.globals.turn_username().clone(),\n\t\t\tservices.globals.turn_password().clone(),\n\t\t)\n\t};\n\n\tOk(get_turn_server_info::v3::Response {\n\t\tusername,\n\t\tpassword,\n\t\turis: services.globals.turn_uris().to_vec(),\n\t\tttl: Duration::from_secs(services.globals.turn_ttl()),\n\t})\n}\n```"}], "func_name": "turn_server_route", "docstring": "# `GET /_matrix/client/r0/voip/turnServer`\n\nTODO: Returns information about the recommended turn server.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/voip.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/voip.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a099cf7385d8e00388445621980a22cf838c0723208576829dfbb69599b60229"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: well_known_client\n\nDocumentation:\n# `GET /.well-known/matrix/client`\n\nReturns the .well-known URL if it is configured, otherwise returns 404.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn well_known_client(\n\tState(services): State,\n\t_body: Ruma,\n) -> Result {\n\tlet client_url = match services.server.config.well_known.client.as_ref() {\n\t\t| Some(url) => url.to_string(),\n\t\t| None => return Err(Error::BadRequest(ErrorKind::NotFound, \"Not found.\")),\n\t};\n\n\tOk(discover_homeserver::Response {\n\t\thomeserver: HomeserverInfo { base_url: client_url.clone() },\n\t\tidentity_server: None,\n\t\tsliding_sync_proxy: Some(SlidingSyncProxyInfo { url: client_url }),\n\t\ttile_server: None,\n\t})\n}\n```"}], "func_name": "well_known_client", "docstring": "# `GET /.well-known/matrix/client`\n\nReturns the .well-known URL if it is configured, otherwise returns 404.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/well_known.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/well_known.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3c075f60ea04dcd9cd2672b4f1a1dad7995bd2416dce90939f941fe914e5cd45"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: well_known_support\n\nDocumentation:\n# `GET /.well-known/matrix/support`\n\nServer support contact and support page of a homeserver's domain.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn well_known_support(\n\tState(services): State,\n\t_body: Ruma,\n) -> Result {\n\tlet support_page = services\n\t\t.server\n\t\t.config\n\t\t.well_known\n\t\t.support_page\n\t\t.as_ref()\n\t\t.map(ToString::to_string);\n\n\tlet role = services.server.config.well_known.support_role.clone();\n\n\t// support page or role must be either defined for this to be valid\n\tif support_page.is_none() && role.is_none() {\n\t\treturn Err(Error::BadRequest(ErrorKind::NotFound, \"Not found.\"));\n\t}\n\n\tlet email_address = services.server.config.well_known.support_email.clone();\n\tlet matrix_id = services.server.config.well_known.support_mxid.clone();\n\n\t// if a role is specified, an email address or matrix id is required\n\tif role.is_some() && (email_address.is_none() && matrix_id.is_none()) {\n\t\treturn Err(Error::BadRequest(ErrorKind::NotFound, \"Not found.\"));\n\t}\n\n\t// TOOD: support defining multiple contacts in the config\n\tlet mut contacts: Vec = vec![];\n\n\tif let Some(role) = role {\n\t\tlet contact = Contact { role, email_address, matrix_id };\n\n\t\tcontacts.push(contact);\n\t}\n\n\t// support page or role+contacts must be either defined for this to be valid\n\tif contacts.is_empty() && support_page.is_none() {\n\t\treturn Err(Error::BadRequest(ErrorKind::NotFound, \"Not found.\"));\n\t}\n\n\tOk(discover_support::Response { contacts, support_page })\n}\n```"}], "func_name": "well_known_support", "docstring": "# `GET /.well-known/matrix/support`\n\nServer support contact and support page of a homeserver's domain.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/well_known.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/well_known.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "91447cb2af9d3f9002d840749b59190120ee0b3cb193e5fcc29e25f8ef8e57af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: syncv3_client_server_json\n\nDocumentation:\n# `GET /client/server.json`\n\nEndpoint provided by sliding sync proxy used by some clients such as Element\nWeb as a non-standard health check.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn syncv3_client_server_json(\n\tState(services): State,\n) -> Result {\n\tlet server_url = match services.server.config.well_known.client.as_ref() {\n\t\t| Some(url) => url.to_string(),\n\t\t| None => match services.server.config.well_known.server.as_ref() {\n\t\t\t| Some(url) => url.to_string(),\n\t\t\t| None => return Err(Error::BadRequest(ErrorKind::NotFound, \"Not found.\")),\n\t\t},\n\t};\n\n\tOk(Json(serde_json::json!({\n\t\t\"server\": server_url,\n\t\t\"version\": conduwuit::version(),\n\t})))\n}\n```"}], "func_name": "syncv3_client_server_json", "docstring": "# `GET /client/server.json`\n\nEndpoint provided by sliding sync proxy used by some clients such as Element\nWeb as a non-standard health check.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/well_known.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/well_known.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "665ee88f334d35cfe74ac8e9f5afae38920dadc845a96a1f8d6f49d463ae9b9c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_room_aliases_route\n\nDocumentation:\n# `GET /_matrix/client/r0/rooms/{roomId}/aliases`\n\nLists all aliases of the room.\n\n- Only users joined to the room are allowed to call this, or if\n`history_visibility` is world readable in the room\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_room_aliases_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tif !services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.user_can_see_state_events(sender_user, &body.room_id)\n\t\t.await\n\t{\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::forbidden(),\n\t\t\t\"You don't have permission to view this room.\",\n\t\t));\n\t}\n\n\tOk(aliases::v3::Response {\n\t\taliases: services\n\t\t\t.rooms\n\t\t\t.alias\n\t\t\t.local_aliases_for_room(&body.room_id)\n\t\t\t.map(ToOwned::to_owned)\n\t\t\t.collect()\n\t\t\t.await,\n\t})\n}\n```"}], "func_name": "get_room_aliases_route", "docstring": "# `GET /_matrix/client/r0/rooms/{roomId}/aliases`\n\nLists all aliases of the room.\n\n- Only users joined to the room are allowed to call this, or if\n`history_visibility` is world readable in the room", "repo": "girlbossceo/conduwuit", "path": "src/api/client/room/aliases.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/room/aliases.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "29bd877ffe74c38172acf8a363617c5f30a0c859afbf7a72c409f076058076fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_power_levels_content\n\nDocumentation:\ncreates the power_levels_content for the PDU builder\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn default_power_levels_content(\n\tpower_level_content_override: Option<&Raw>,\n\tvisibility: &room::Visibility,\n\tusers: BTreeMap,\n) -> Result {\n\tlet mut power_levels_content =\n\t\tserde_json::to_value(RoomPowerLevelsEventContent { users, ..Default::default() })\n\t\t\t.expect(\"event is valid, we just created it\");\n\n\t// secure proper defaults of sensitive/dangerous permissions that moderators\n\t// (power level 50) should not have easy access to\n\tpower_levels_content[\"events\"][\"m.room.power_levels\"] =\n\t\tserde_json::to_value(100).expect(\"100 is valid Value\");\n\tpower_levels_content[\"events\"][\"m.room.server_acl\"] =\n\t\tserde_json::to_value(100).expect(\"100 is valid Value\");\n\tpower_levels_content[\"events\"][\"m.room.tombstone\"] =\n\t\tserde_json::to_value(100).expect(\"100 is valid Value\");\n\tpower_levels_content[\"events\"][\"m.room.encryption\"] =\n\t\tserde_json::to_value(100).expect(\"100 is valid Value\");\n\tpower_levels_content[\"events\"][\"m.room.history_visibility\"] =\n\t\tserde_json::to_value(100).expect(\"100 is valid Value\");\n\n\t// always allow users to respond (not post new) to polls. this is primarily\n\t// useful in read-only announcement rooms that post a public poll.\n\tpower_levels_content[\"events\"][\"org.matrix.msc3381.poll.response\"] =\n\t\tserde_json::to_value(0).expect(\"0 is valid Value\");\n\tpower_levels_content[\"events\"][\"m.poll.response\"] =\n\t\tserde_json::to_value(0).expect(\"0 is valid Value\");\n\n\t// synapse does this too. clients do not expose these permissions. it prevents\n\t// default users from calling public rooms, for obvious reasons.\n\tif *visibility == room::Visibility::Public {\n\t\tpower_levels_content[\"events\"][\"m.call.invite\"] =\n\t\t\tserde_json::to_value(50).expect(\"50 is valid Value\");\n\t\tpower_levels_content[\"events\"][\"m.call\"] =\n\t\t\tserde_json::to_value(50).expect(\"50 is valid Value\");\n\t\tpower_levels_content[\"events\"][\"m.call.member\"] =\n\t\t\tserde_json::to_value(50).expect(\"50 is valid Value\");\n\t\tpower_levels_content[\"events\"][\"org.matrix.msc3401.call\"] =\n\t\t\tserde_json::to_value(50).expect(\"50 is valid Value\");\n\t\tpower_levels_content[\"events\"][\"org.matrix.msc3401.call.member\"] =\n\t\t\tserde_json::to_value(50).expect(\"50 is valid Value\");\n\t}\n\n\tif let Some(power_level_content_override) = power_level_content_override {\n\t\tlet json: JsonObject = serde_json::from_str(power_level_content_override.json().get())\n\t\t\t.map_err(|_| {\n\t\t\t\tError::BadRequest(ErrorKind::BadJson, \"Invalid power_level_content_override.\")\n\t\t\t})?;\n\n\t\tfor (key, value) in json {\n\t\t\tpower_levels_content[key] = value;\n\t\t}\n\t}\n\n\tOk(power_levels_content)\n}\n```"}], "func_name": "default_power_levels_content", "docstring": "creates the power_levels_content for the PDU builder", "repo": "girlbossceo/conduwuit", "path": "src/api/client/room/create.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/room/create.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0aa84b0549b8f59d4c0ad289bb6d1a01ea50203f93417005def09a209db69524"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: room_alias_check\n\nDocumentation:\nif a room is being created with a room alias, run our checks\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn room_alias_check(\n\tservices: &Services,\n\troom_alias_name: &str,\n\tappservice_info: Option<&RegistrationInfo>,\n) -> Result {\n\t// Basic checks on the room alias validity\n\tif room_alias_name.contains(':') {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::InvalidParam,\n\t\t\t\"Room alias contained `:` which is not allowed. Please note that this expects a \\\n\t\t\t localpart, not the full room alias.\",\n\t\t));\n\t} else if room_alias_name.contains(char::is_whitespace) {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::InvalidParam,\n\t\t\t\"Room alias contained spaces which is not a valid room alias.\",\n\t\t));\n\t}\n\n\t// check if room alias is forbidden\n\tif services\n\t\t.globals\n\t\t.forbidden_alias_names()\n\t\t.is_match(room_alias_name)\n\t{\n\t\treturn Err(Error::BadRequest(ErrorKind::Unknown, \"Room alias name is forbidden.\"));\n\t}\n\n\tlet server_name = services.globals.server_name();\n\tlet full_room_alias = OwnedRoomAliasId::parse(format!(\"#{room_alias_name}:{server_name}\"))\n\t\t.map_err(|e| {\n\t\t\terr!(Request(InvalidParam(debug_error!(\n\t\t\t\t?e,\n\t\t\t\t?room_alias_name,\n\t\t\t\t\"Failed to parse room alias.\",\n\t\t\t))))\n\t\t})?;\n\n\tif services\n\t\t.rooms\n\t\t.alias\n\t\t.resolve_local_alias(&full_room_alias)\n\t\t.await\n\t\t.is_ok()\n\t{\n\t\treturn Err(Error::BadRequest(ErrorKind::RoomInUse, \"Room alias already exists.\"));\n\t}\n\n\tif let Some(info) = appservice_info {\n\t\tif !info.aliases.is_match(full_room_alias.as_str()) {\n\t\t\treturn Err(Error::BadRequest(\n\t\t\t\tErrorKind::Exclusive,\n\t\t\t\t\"Room alias is not in namespace.\",\n\t\t\t));\n\t\t}\n\t} else if services\n\t\t.appservice\n\t\t.is_exclusive_alias(&full_room_alias)\n\t\t.await\n\t{\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::Exclusive,\n\t\t\t\"Room alias reserved by appservice.\",\n\t\t));\n\t}\n\n\tdebug_info!(\"Full room alias: {full_room_alias}\");\n\n\tOk(full_room_alias)\n}\n```"}], "func_name": "room_alias_check", "docstring": "if a room is being created with a room alias, run our checks", "repo": "girlbossceo/conduwuit", "path": "src/api/client/room/create.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/room/create.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54f257fa1a6e3ccc81c5500538a8568037a16676976df93032271f6119cb22c3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: custom_room_id_check\n\nDocumentation:\nif a room is being created with a custom room ID, run our checks against it\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn custom_room_id_check(services: &Services, custom_room_id: &str) -> Result {\n\t// apply forbidden room alias checks to custom room IDs too\n\tif services\n\t\t.globals\n\t\t.forbidden_alias_names()\n\t\t.is_match(custom_room_id)\n\t{\n\t\treturn Err(Error::BadRequest(ErrorKind::Unknown, \"Custom room ID is forbidden.\"));\n\t}\n\n\tif custom_room_id.contains(':') {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::InvalidParam,\n\t\t\t\"Custom room ID contained `:` which is not allowed. Please note that this expects a \\\n\t\t\t localpart, not the full room ID.\",\n\t\t));\n\t} else if custom_room_id.contains(char::is_whitespace) {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::InvalidParam,\n\t\t\t\"Custom room ID contained spaces which is not valid.\",\n\t\t));\n\t}\n\n\tlet server_name = services.globals.server_name();\n\tlet full_room_id = format!(\"!{custom_room_id}:{server_name}\");\n\n\tOwnedRoomId::parse(full_room_id)\n\t\t.map_err(Into::into)\n\t\t.inspect(|full_room_id| debug_info!(?full_room_id, \"Full custom room ID\"))\n\t\t.inspect_err(|e| warn!(?e, ?custom_room_id, \"Failed to create room with custom room ID\",))\n}\n```"}], "func_name": "custom_room_id_check", "docstring": "if a room is being created with a custom room ID, run our checks against it", "repo": "girlbossceo/conduwuit", "path": "src/api/client/room/create.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/room/create.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8148f0faa3577c5d7d3f7c23e43ecccd254d07116bb8855b1331dfadd3c3247b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_room_event_route\n\nDocumentation:\n# `GET /_matrix/client/r0/rooms/{roomId}/event/{eventId}`\n\nGets a single event.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_room_event_route(\n\tState(ref services): State,\n\tref body: Ruma,\n) -> Result {\n\tlet event_id = &body.event_id;\n\tlet room_id = &body.room_id;\n\n\tlet event = services\n\t\t.rooms\n\t\t.timeline\n\t\t.get_pdu(event_id)\n\t\t.map_err(|_| err!(Request(NotFound(\"Event {} not found.\", event_id))));\n\n\tlet visible = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.user_can_see_event(body.sender_user(), room_id, event_id)\n\t\t.map(Ok);\n\n\tlet (mut event, visible) = try_join(event, visible).await?;\n\n\tif !visible || is_ignored_pdu(services, &event, body.sender_user()).await {\n\t\treturn Err!(Request(Forbidden(\"You don't have permission to view this event.\")));\n\t}\n\n\tdebug_assert!(\n\t\tevent.event_id() == event_id && event.room_id() == room_id,\n\t\t\"Fetched PDU must match requested\"\n\t);\n\n\tevent.add_age().ok();\n\n\tOk(get_room_event::v3::Response { event: event.into_room_event() })\n}\n```"}], "func_name": "get_room_event_route", "docstring": "# `GET /_matrix/client/r0/rooms/{roomId}/event/{eventId}`\n\nGets a single event.", "repo": "girlbossceo/conduwuit", "path": "src/api/client/room/event.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/room/event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9337fb0a34a74403d01240891b9fbe119d1da4a07b3b622d6baf10e66d67fe6a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_room_summary_legacy\n\nDocumentation:\n# `GET /_matrix/client/unstable/im.nheko.summary/rooms/{roomIdOrAlias}/summary`\n\nReturns a short description of the state of a room.\n\nThis is the \"wrong\" endpoint that some implementations/clients may use\naccording to the MSC. Request and response bodies are the same as\n`get_room_summary`.\n\nAn implementation of [MSC3266](https://github.com/matrix-org/matrix-spec-proposals/pull/3266)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_room_summary_legacy(\n\tState(services): State,\n\tInsecureClientIp(client): InsecureClientIp,\n\tbody: Ruma,\n) -> Result> {\n\tget_room_summary(State(services), InsecureClientIp(client), body)\n\t\t.boxed()\n\t\t.await\n\t\t.map(RumaResponse)\n}\n```"}], "func_name": "get_room_summary_legacy", "docstring": "# `GET /_matrix/client/unstable/im.nheko.summary/rooms/{roomIdOrAlias}/summary`\n\nReturns a short description of the state of a room.\n\nThis is the \"wrong\" endpoint that some implementations/clients may use\naccording to the MSC. Request and response bodies are the same as\n`get_room_summary`.\n\nAn implementation of [MSC3266](https://github.com/matrix-org/matrix-spec-proposals/pull/3266)", "repo": "girlbossceo/conduwuit", "path": "src/api/client/room/summary.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/room/summary.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f79eec34d1ea3a762a31262a1108a737aa22f0c1cb225b37f7ed053e717d6b7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remote_room_summary_hierarchy_response\n\nDocumentation:\nused by MSC3266 to fetch a room's info if we do not know about it\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn remote_room_summary_hierarchy_response(\n\tservices: &Services,\n\troom_id: &RoomId,\n\tservers: &[OwnedServerName],\n\tsender_user: Option<&UserId>,\n) -> Result {\n\ttrace!(?sender_user, ?servers, \"Sending remote room summary response for {room_id:?}\");\n\tif !services.config.allow_federation {\n\t\treturn Err!(Request(Forbidden(\"Federation is disabled.\")));\n\t}\n\n\tif services.rooms.metadata.is_disabled(room_id).await {\n\t\treturn Err!(Request(Forbidden(\n\t\t\t\"Federaton of room {room_id} is currently disabled on this server.\"\n\t\t)));\n\t}\n\n\tlet request = get_hierarchy::v1::Request::new(room_id.to_owned());\n\n\tlet mut requests: FuturesUnordered<_> = servers\n\t\t.iter()\n\t\t.map(|server| {\n\t\t\tservices\n\t\t\t\t.sending\n\t\t\t\t.send_federation_request(server, request.clone())\n\t\t})\n\t\t.collect();\n\n\twhile let Some(Ok(response)) = requests.next().await {\n\t\ttrace!(\"{response:?}\");\n\t\tlet room = response.room.clone();\n\t\tif room.room_id != room_id {\n\t\t\tdebug_warn!(\n\t\t\t\t\"Room ID {} returned does not belong to the requested room ID {}\",\n\t\t\t\troom.room_id,\n\t\t\t\troom_id\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn user_can_see_summary(\n\t\t\tservices,\n\t\t\troom_id,\n\t\t\t&room.join_rule,\n\t\t\troom.guest_can_join,\n\t\t\troom.world_readable,\n\t\t\troom.allowed_room_ids.iter().map(AsRef::as_ref),\n\t\t\tsender_user,\n\t\t)\n\t\t.await\n\t\t.map(|()| room);\n\t}\n\n\tErr!(Request(NotFound(\n\t\t\"Room is unknown to this server and was unable to fetch over federation with the \\\n\t\t provided servers available\"\n\t)))\n}\n```"}], "func_name": "remote_room_summary_hierarchy_response", "docstring": "used by MSC3266 to fetch a room's info if we do not know about it", "repo": "girlbossceo/conduwuit", "path": "src/api/client/room/summary.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/room/summary.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f09df5ee9bfdb56293c4083b63f7c66e5e68c8b349963389ae3674c56e89ed48"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: upgrade_room_route\n\nDocumentation:\n# `POST /_matrix/client/r0/rooms/{roomId}/upgrade`\n\nUpgrades the room.\n\n- Creates a replacement room\n- Sends a tombstone event into the current room\n- Sender user joins the room\n- Transfers some state events\n- Moves local aliases\n- Modifies old room power levels to prevent users from speaking\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn upgrade_room_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tdebug_assert!(\n\t\tTRANSFERABLE_STATE_EVENTS.is_sorted(),\n\t\t\"TRANSFERABLE_STATE_EVENTS is not sorted\"\n\t);\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\n\tif !services.server.supported_room_version(&body.new_version) {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::UnsupportedRoomVersion,\n\t\t\t\"This server does not support that room version.\",\n\t\t));\n\t}\n\n\t// Create a replacement room\n\tlet replacement_room = RoomId::new(services.globals.server_name());\n\n\tlet _short_id = services\n\t\t.rooms\n\t\t.short\n\t\t.get_or_create_shortroomid(&replacement_room)\n\t\t.await;\n\n\tlet state_lock = services.rooms.state.mutex.lock(&body.room_id).await;\n\n\t// Send a m.room.tombstone event to the old room to indicate that it is not\n\t// intended to be used any further Fail if the sender does not have the required\n\t// permissions\n\tlet tombstone_event_id = services\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(StateKey::new(), &RoomTombstoneEventContent {\n\t\t\t\tbody: \"This room has been replaced\".to_owned(),\n\t\t\t\treplacement_room: replacement_room.clone(),\n\t\t\t}),\n\t\t\tsender_user,\n\t\t\t&body.room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\t// Change lock to replacement room\n\tdrop(state_lock);\n\tlet state_lock = services.rooms.state.mutex.lock(&replacement_room).await;\n\n\t// Get the old room creation event\n\tlet mut create_event_content: CanonicalJsonObject = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.room_state_get_content(&body.room_id, &StateEventType::RoomCreate, \"\")\n\t\t.await\n\t\t.map_err(|_| err!(Database(\"Found room without m.room.create event.\")))?;\n\n\t// Use the m.room.tombstone event as the predecessor\n\tlet predecessor = Some(ruma::events::room::create::PreviousRoom::new(\n\t\tbody.room_id.clone(),\n\t\tSome(tombstone_event_id),\n\t));\n\n\t// Send a m.room.create event containing a predecessor field and the applicable\n\t// room_version\n\t{\n\t\tuse RoomVersionId::*;\n\t\tmatch body.new_version {\n\t\t\t| V1 | V2 | V3 | V4 | V5 | V6 | V7 | V8 | V9 | V10 => {\n\t\t\t\tcreate_event_content.insert(\n\t\t\t\t\t\"creator\".into(),\n\t\t\t\t\tjson!(&sender_user).try_into().map_err(|e| {\n\t\t\t\t\t\tinfo!(\"Error forming creation event: {e}\");\n\t\t\t\t\t\tError::BadRequest(ErrorKind::BadJson, \"Error forming creation event\")\n\t\t\t\t\t})?,\n\t\t\t\t);\n\t\t\t},\n\t\t\t| _ => {\n\t\t\t\t// \"creator\" key no longer exists in V11+ rooms\n\t\t\t\tcreate_event_content.remove(\"creator\");\n\t\t\t},\n\t\t}\n\t}\n\n\tcreate_event_content.insert(\n\t\t\"room_version\".into(),\n\t\tjson!(&body.new_version)\n\t\t\t.try_into()\n\t\t\t.map_err(|_| Error::BadRequest(ErrorKind::BadJson, \"Error forming creation event\"))?,\n\t);\n\tcreate_event_content.insert(\n\t\t\"predecessor\".into(),\n\t\tjson!(predecessor)\n\t\t\t.try_into()\n\t\t\t.map_err(|_| Error::BadRequest(ErrorKind::BadJson, \"Error forming creation event\"))?,\n\t);\n\n\t// Validate creation event content\n\tif serde_json::from_str::(\n\t\tto_raw_value(&create_event_content)\n\t\t\t.expect(\"Error forming creation event\")\n\t\t\t.get(),\n\t)\n\t.is_err()\n\t{\n\t\treturn Err(Error::BadRequest(ErrorKind::BadJson, \"Error forming creation event\"));\n\t}\n\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder {\n\t\t\t\tevent_type: TimelineEventType::RoomCreate,\n\t\t\t\tcontent: to_raw_value(&create_event_content)\n\t\t\t\t\t.expect(\"event is valid, we just created it\"),\n\t\t\t\tunsigned: None,\n\t\t\t\tstate_key: Some(StateKey::new()),\n\t\t\t\tredacts: None,\n\t\t\t\ttimestamp: None,\n\t\t\t},\n\t\t\tsender_user,\n\t\t\t&replacement_room,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\t// Join the new room\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder {\n\t\t\t\tevent_type: TimelineEventType::RoomMember,\n\t\t\t\tcontent: to_raw_value(&RoomMemberEventContent {\n\t\t\t\t\tmembership: MembershipState::Join,\n\t\t\t\t\tdisplayname: services.users.displayname(sender_user).await.ok(),\n\t\t\t\t\tavatar_url: services.users.avatar_url(sender_user).await.ok(),\n\t\t\t\t\tis_direct: None,\n\t\t\t\t\tthird_party_invite: None,\n\t\t\t\t\tblurhash: services.users.blurhash(sender_user).await.ok(),\n\t\t\t\t\treason: None,\n\t\t\t\t\tjoin_authorized_via_users_server: None,\n\t\t\t\t})\n\t\t\t\t.expect(\"event is valid, we just created it\"),\n\t\t\t\tunsigned: None,\n\t\t\t\tstate_key: Some(sender_user.as_str().into()),\n\t\t\t\tredacts: None,\n\t\t\t\ttimestamp: None,\n\t\t\t},\n\t\t\tsender_user,\n\t\t\t&replacement_room,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\t// Replicate transferable state events to the new room\n\tfor event_type in TRANSFERABLE_STATE_EVENTS {\n\t\tlet event_content = match services\n\t\t\t.rooms\n\t\t\t.state_accessor\n\t\t\t.room_state_get(&body.room_id, event_type, \"\")\n\t\t\t.await\n\t\t{\n\t\t\t| Ok(v) => v.content.clone(),\n\t\t\t| Err(_) => continue, // Skipping missing events.\n\t\t};\n\n\t\tservices\n\t\t\t.rooms\n\t\t\t.timeline\n\t\t\t.build_and_append_pdu(\n\t\t\t\tPduBuilder {\n\t\t\t\t\tevent_type: event_type.to_string().into(),\n\t\t\t\t\tcontent: event_content,\n\t\t\t\t\tstate_key: Some(StateKey::new()),\n\t\t\t\t\t..Default::default()\n\t\t\t\t},\n\t\t\t\tsender_user,\n\t\t\t\t&replacement_room,\n\t\t\t\t&state_lock,\n\t\t\t)\n\t\t\t.await?;\n\t}\n\n\t// Moves any local aliases to the new room\n\tlet mut local_aliases = services\n\t\t.rooms\n\t\t.alias\n\t\t.local_aliases_for_room(&body.room_id)\n\t\t.boxed();\n\n\twhile let Some(alias) = local_aliases.next().await {\n\t\tservices\n\t\t\t.rooms\n\t\t\t.alias\n\t\t\t.remove_alias(alias, sender_user)\n\t\t\t.await?;\n\n\t\tservices\n\t\t\t.rooms\n\t\t\t.alias\n\t\t\t.set_alias(alias, &replacement_room, sender_user)?;\n\t}\n\n\t// Get the old room power levels\n\tlet power_levels_event_content: RoomPowerLevelsEventContent = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.room_state_get_content(&body.room_id, &StateEventType::RoomPowerLevels, \"\")\n\t\t.await\n\t\t.map_err(|_| err!(Database(\"Found room without m.room.power_levels event.\")))?;\n\n\t// Setting events_default and invite to the greater of 50 and users_default + 1\n\tlet new_level = max(\n\t\tint!(50),\n\t\tpower_levels_event_content\n\t\t\t.users_default\n\t\t\t.checked_add(int!(1))\n\t\t\t.ok_or_else(|| {\n\t\t\t\terr!(Request(BadJson(\"users_default power levels event content is not valid\")))\n\t\t\t})?,\n\t);\n\n\t// Modify the power levels in the old room to prevent sending of events and\n\t// inviting new users\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(StateKey::new(), &RoomPowerLevelsEventContent {\n\t\t\t\tevents_default: new_level,\n\t\t\t\tinvite: new_level,\n\t\t\t\t..power_levels_event_content\n\t\t\t}),\n\t\t\tsender_user,\n\t\t\t&body.room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\tdrop(state_lock);\n\n\t// Return the replacement room id\n\tOk(upgrade_room::v3::Response { replacement_room })\n}\n```"}], "func_name": "upgrade_room_route", "docstring": "# `POST /_matrix/client/r0/rooms/{roomId}/upgrade`\n\nUpgrades the room.\n\n- Creates a replacement room\n- Sends a tombstone event into the current room\n- Sender user joins the room\n- Transfers some state events\n- Moves local aliases\n- Modifies old room power levels to prevent users from speaking", "repo": "girlbossceo/conduwuit", "path": "src/api/client/room/upgrade.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/room/upgrade.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "45273022ae018fa9173a2a9c1d7fabb4c8d7165a286bbfadf72fe8ca0d609112"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sync_events_v4_route\n\nDocumentation:\nPOST `/_matrix/client/unstable/org.matrix.msc3575/sync`\n\nSliding Sync endpoint (future endpoint: `/_matrix/client/v4/sync`)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn sync_events_v4_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tdebug_assert!(DEFAULT_BUMP_TYPES.is_sorted(), \"DEFAULT_BUMP_TYPES is not sorted\");\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\tlet sender_device = body.sender_device.expect(\"user is authenticated\");\n\tlet mut body = body.body;\n\t// Setup watchers, so if there's no response, we can wait for them\n\tlet watcher = services.sync.watch(sender_user, &sender_device);\n\n\tlet next_batch = services.globals.next_count()?;\n\n\tlet conn_id = body\n\t\t.conn_id\n\t\t.clone()\n\t\t.unwrap_or_else(|| SINGLE_CONNECTION_SYNC.to_owned());\n\n\tlet globalsince = body\n\t\t.pos\n\t\t.as_ref()\n\t\t.and_then(|string| string.parse().ok())\n\t\t.unwrap_or(0);\n\n\tif globalsince != 0\n\t\t&& !services\n\t\t\t.sync\n\t\t\t.remembered(sender_user.clone(), sender_device.clone(), conn_id.clone())\n\t{\n\t\tdebug!(\"Restarting sync stream because it was gone from the database\");\n\t\treturn Err(Error::Request(\n\t\t\tErrorKind::UnknownPos,\n\t\t\t\"Connection data lost since last time\".into(),\n\t\t\thttp::StatusCode::BAD_REQUEST,\n\t\t));\n\t}\n\n\tif globalsince == 0 {\n\t\tservices.sync.forget_sync_request_connection(\n\t\t\tsender_user.clone(),\n\t\t\tsender_device.clone(),\n\t\t\tconn_id.clone(),\n\t\t);\n\t}\n\n\t// Get sticky parameters from cache\n\tlet known_rooms = services.sync.update_sync_request_with_cache(\n\t\tsender_user.clone(),\n\t\tsender_device.clone(),\n\t\t&mut body,\n\t);\n\n\tlet all_joined_rooms: Vec<_> = services\n\t\t.rooms\n\t\t.state_cache\n\t\t.rooms_joined(sender_user)\n\t\t.map(ToOwned::to_owned)\n\t\t.collect()\n\t\t.await;\n\n\tlet all_invited_rooms: Vec<_> = services\n\t\t.rooms\n\t\t.state_cache\n\t\t.rooms_invited(sender_user)\n\t\t.map(|r| r.0)\n\t\t.collect()\n\t\t.await;\n\n\tlet all_knocked_rooms: Vec<_> = services\n\t\t.rooms\n\t\t.state_cache\n\t\t.rooms_knocked(sender_user)\n\t\t.map(|r| r.0)\n\t\t.collect()\n\t\t.await;\n\n\tlet all_invited_rooms: Vec<&RoomId> = all_invited_rooms.iter().map(AsRef::as_ref).collect();\n\tlet all_knocked_rooms: Vec<&RoomId> = all_knocked_rooms.iter().map(AsRef::as_ref).collect();\n\n\tlet all_rooms: Vec<&RoomId> = all_joined_rooms\n\t\t.iter()\n\t\t.map(AsRef::as_ref)\n\t\t.chain(all_invited_rooms.iter().map(AsRef::as_ref))\n\t\t.chain(all_knocked_rooms.iter().map(AsRef::as_ref))\n\t\t.collect();\n\n\tlet all_joined_rooms = all_joined_rooms.iter().map(AsRef::as_ref).collect();\n\tlet all_invited_rooms = all_invited_rooms.iter().map(AsRef::as_ref).collect();\n\n\tif body.extensions.to_device.enabled.unwrap_or(false) {\n\t\tservices\n\t\t\t.users\n\t\t\t.remove_to_device_events(sender_user, &sender_device, globalsince)\n\t\t\t.await;\n\t}\n\n\tlet mut left_encrypted_users = HashSet::new(); // Users that have left any encrypted rooms the sender was in\n\tlet mut device_list_changes = HashSet::new();\n\tlet mut device_list_left = HashSet::new();\n\n\tlet mut receipts = sync_events::v4::Receipts { rooms: BTreeMap::new() };\n\n\tlet mut account_data = sync_events::v4::AccountData {\n\t\tglobal: Vec::new(),\n\t\trooms: BTreeMap::new(),\n\t};\n\tif body.extensions.account_data.enabled.unwrap_or(false) {\n\t\taccount_data.global = services\n\t\t\t.account_data\n\t\t\t.changes_since(None, sender_user, globalsince, Some(next_batch))\n\t\t\t.ready_filter_map(|e| extract_variant!(e, AnyRawAccountDataEvent::Global))\n\t\t\t.collect()\n\t\t\t.await;\n\n\t\tif let Some(rooms) = body.extensions.account_data.rooms {\n\t\t\tfor room in rooms {\n\t\t\t\taccount_data.rooms.insert(\n\t\t\t\t\troom.clone(),\n\t\t\t\t\tservices\n\t\t\t\t\t\t.account_data\n\t\t\t\t\t\t.changes_since(Some(&room), sender_user, globalsince, Some(next_batch))\n\t\t\t\t\t\t.ready_filter_map(|e| extract_variant!(e, AnyRawAccountDataEvent::Room))\n\t\t\t\t\t\t.collect()\n\t\t\t\t\t\t.await,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tif body.extensions.e2ee.enabled.unwrap_or(false) {\n\t\t// Look for device list updates of this account\n\t\tdevice_list_changes.extend(\n\t\t\tservices\n\t\t\t\t.users\n\t\t\t\t.keys_changed(sender_user, globalsince, None)\n\t\t\t\t.map(ToOwned::to_owned)\n\t\t\t\t.collect::>()\n\t\t\t\t.await,\n\t\t);\n\n\t\tfor room_id in &all_joined_rooms {\n\t\t\tlet room_id: &&RoomId = room_id;\n\t\t\tlet Ok(current_shortstatehash) =\n\t\t\t\tservices.rooms.state.get_room_shortstatehash(room_id).await\n\t\t\telse {\n\t\t\t\terror!(\"Room {room_id} has no state\");\n\t\t\t\tcontinue;\n\t\t\t};\n\n\t\t\tlet since_shortstatehash = services\n\t\t\t\t.rooms\n\t\t\t\t.user\n\t\t\t\t.get_token_shortstatehash(room_id, globalsince)\n\t\t\t\t.await\n\t\t\t\t.ok();\n\n\t\t\tlet encrypted_room = services\n\t\t\t\t.rooms\n\t\t\t\t.state_accessor\n\t\t\t\t.state_get(current_shortstatehash, &StateEventType::RoomEncryption, \"\")\n\t\t\t\t.await\n\t\t\t\t.is_ok();\n\n\t\t\tif let Some(since_shortstatehash) = since_shortstatehash {\n\t\t\t\t// Skip if there are only timeline changes\n\t\t\t\tif since_shortstatehash == current_shortstatehash {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tlet since_encryption = services\n\t\t\t\t\t.rooms\n\t\t\t\t\t.state_accessor\n\t\t\t\t\t.state_get(since_shortstatehash, &StateEventType::RoomEncryption, \"\")\n\t\t\t\t\t.await;\n\n\t\t\t\tlet since_sender_member: Option = services\n\t\t\t\t\t.rooms\n\t\t\t\t\t.state_accessor\n\t\t\t\t\t.state_get_content(\n\t\t\t\t\t\tsince_shortstatehash,\n\t\t\t\t\t\t&StateEventType::RoomMember,\n\t\t\t\t\t\tsender_user.as_str(),\n\t\t\t\t\t)\n\t\t\t\t\t.ok()\n\t\t\t\t\t.await;\n\n\t\t\t\tlet joined_since_last_sync = since_sender_member\n\t\t\t\t\t.as_ref()\n\t\t\t\t\t.is_none_or(|member| member.membership != MembershipState::Join);\n\n\t\t\t\tlet new_encrypted_room = encrypted_room && since_encryption.is_err();\n\n\t\t\t\tif encrypted_room {\n\t\t\t\t\tlet current_state_ids: HashMap<_, OwnedEventId> = services\n\t\t\t\t\t\t.rooms\n\t\t\t\t\t\t.state_accessor\n\t\t\t\t\t\t.state_full_ids(current_shortstatehash)\n\t\t\t\t\t\t.collect()\n\t\t\t\t\t\t.await;\n\n\t\t\t\t\tlet since_state_ids: HashMap<_, _> = services\n\t\t\t\t\t\t.rooms\n\t\t\t\t\t\t.state_accessor\n\t\t\t\t\t\t.state_full_ids(since_shortstatehash)\n\t\t\t\t\t\t.collect()\n\t\t\t\t\t\t.await;\n\n\t\t\t\t\tfor (key, id) in current_state_ids {\n\t\t\t\t\t\tif since_state_ids.get(&key) != Some(&id) {\n\t\t\t\t\t\t\tlet Ok(pdu) = services.rooms.timeline.get_pdu(&id).await else {\n\t\t\t\t\t\t\t\terror!(\"Pdu in state not found: {id}\");\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tif pdu.kind == RoomMember {\n\t\t\t\t\t\t\t\tif let Some(Ok(user_id)) =\n\t\t\t\t\t\t\t\t\tpdu.state_key.as_deref().map(UserId::parse)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif user_id == *sender_user {\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tlet content: RoomMemberEventContent = pdu.get_content()?;\n\t\t\t\t\t\t\t\t\tmatch content.membership {\n\t\t\t\t\t\t\t\t\t\t| MembershipState::Join => {\n\t\t\t\t\t\t\t\t\t\t\t// A new user joined an encrypted room\n\t\t\t\t\t\t\t\t\t\t\tif !share_encrypted_room(\n\t\t\t\t\t\t\t\t\t\t\t\t&services,\n\t\t\t\t\t\t\t\t\t\t\t\tsender_user,\n\t\t\t\t\t\t\t\t\t\t\t\tuser_id,\n\t\t\t\t\t\t\t\t\t\t\t\tSome(room_id),\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t.await\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tdevice_list_changes.insert(user_id.to_owned());\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t| MembershipState::Leave => {\n\t\t\t\t\t\t\t\t\t\t\t// Write down users that have left encrypted rooms we\n\t\t\t\t\t\t\t\t\t\t\t// are in\n\t\t\t\t\t\t\t\t\t\t\tleft_encrypted_users.insert(user_id.to_owned());\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t| _ => {},\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif joined_since_last_sync || new_encrypted_room {\n\t\t\t\t\t\t// If the user is in a new encrypted room, give them all joined users\n\t\t\t\t\t\tdevice_list_changes.extend(\n\t\t\t\t\t\t\tservices\n\t\t\t\t\t\t\t\t.rooms\n\t\t\t\t\t\t\t\t.state_cache\n\t\t\t\t\t\t\t\t.room_members(room_id)\n\t\t\t\t\t\t\t\t// Don't send key updates from the sender to the sender\n\t\t\t\t\t\t\t\t.ready_filter(|user_id| sender_user != user_id)\n\t\t\t\t\t\t\t\t// Only send keys if the sender doesn't share an encrypted room with the target\n\t\t\t\t\t\t\t\t// already\n\t\t\t\t\t\t\t\t.filter_map(|user_id| {\n\t\t\t\t\t\t\t\t\tshare_encrypted_room(&services, sender_user, user_id, Some(room_id))\n\t\t\t\t\t\t\t\t\t\t.map(|res| res.or_some(user_id.to_owned()))\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.collect::>()\n\t\t\t\t\t\t\t\t.await,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Look for device list updates in this room\n\t\t\tdevice_list_changes.extend(\n\t\t\t\tservices\n\t\t\t\t\t.users\n\t\t\t\t\t.room_keys_changed(room_id, globalsince, None)\n\t\t\t\t\t.map(|(user_id, _)| user_id)\n\t\t\t\t\t.map(ToOwned::to_owned)\n\t\t\t\t\t.collect::>()\n\t\t\t\t\t.await,\n\t\t\t);\n\t\t}\n\n\t\tfor user_id in left_encrypted_users {\n\t\t\tlet dont_share_encrypted_room =\n\t\t\t\t!share_encrypted_room(&services, sender_user, &user_id, None).await;\n\n\t\t\t// If the user doesn't share an encrypted room with the target anymore, we need\n\t\t\t// to tell them\n\t\t\tif dont_share_encrypted_room {\n\t\t\t\tdevice_list_left.insert(user_id);\n\t\t\t}\n\t\t}\n\t}\n\n\tlet mut lists = BTreeMap::new();\n\tlet mut todo_rooms: TodoRooms = BTreeMap::new(); // and required state\n\n\tfor (list_id, list) in &body.lists {\n\t\tlet active_rooms = match list.filters.clone().and_then(|f| f.is_invite) {\n\t\t\t| Some(true) => &all_invited_rooms,\n\t\t\t| Some(false) => &all_joined_rooms,\n\t\t\t| None => &all_rooms,\n\t\t};\n\n\t\tlet active_rooms = match list.filters.clone().map(|f| f.not_room_types) {\n\t\t\t| Some(filter) if filter.is_empty() => active_rooms.clone(),\n\t\t\t| Some(value) => filter_rooms(&services, active_rooms, &value, true).await,\n\t\t\t| None => active_rooms.clone(),\n\t\t};\n\n\t\tlet active_rooms = match list.filters.clone().map(|f| f.room_types) {\n\t\t\t| Some(filter) if filter.is_empty() => active_rooms.clone(),\n\t\t\t| Some(value) => filter_rooms(&services, &active_rooms, &value, false).await,\n\t\t\t| None => active_rooms,\n\t\t};\n\n\t\tlet mut new_known_rooms: BTreeSet = BTreeSet::new();\n\n\t\tlet ranges = list.ranges.clone();\n\t\tlists.insert(list_id.clone(), sync_events::v4::SyncList {\n\t\t\tops: ranges\n\t\t\t\t.into_iter()\n\t\t\t\t.map(|mut r| {\n\t\t\t\t\tr.0 = r.0.clamp(\n\t\t\t\t\t\tuint!(0),\n\t\t\t\t\t\tUInt::try_from(active_rooms.len().saturating_sub(1)).unwrap_or(UInt::MAX),\n\t\t\t\t\t);\n\t\t\t\t\tr.1 = r.1.clamp(\n\t\t\t\t\t\tr.0,\n\t\t\t\t\t\tUInt::try_from(active_rooms.len().saturating_sub(1)).unwrap_or(UInt::MAX),\n\t\t\t\t\t);\n\n\t\t\t\t\tlet room_ids = if !active_rooms.is_empty() {\n\t\t\t\t\t\tactive_rooms[usize_from_ruma(r.0)..=usize_from_ruma(r.1)].to_vec()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tVec::new()\n\t\t\t\t\t};\n\n\t\t\t\t\tnew_known_rooms.extend(room_ids.clone().into_iter().map(ToOwned::to_owned));\n\t\t\t\t\tfor room_id in &room_ids {\n\t\t\t\t\t\tlet todo_room = todo_rooms.entry((*room_id).to_owned()).or_insert((\n\t\t\t\t\t\t\tBTreeSet::new(),\n\t\t\t\t\t\t\t0_usize,\n\t\t\t\t\t\t\tu64::MAX,\n\t\t\t\t\t\t));\n\n\t\t\t\t\t\tlet limit: usize = list\n\t\t\t\t\t\t\t.room_details\n\t\t\t\t\t\t\t.timeline_limit\n\t\t\t\t\t\t\t.map(u64::from)\n\t\t\t\t\t\t\t.map_or(10, usize_from_u64_truncated)\n\t\t\t\t\t\t\t.min(100);\n\n\t\t\t\t\t\ttodo_room.0.extend(\n\t\t\t\t\t\t\tlist.room_details\n\t\t\t\t\t\t\t\t.required_state\n\t\t\t\t\t\t\t\t.iter()\n\t\t\t\t\t\t\t\t.map(|(ty, sk)| (ty.clone(), sk.as_str().into())),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\ttodo_room.1 = todo_room.1.max(limit);\n\t\t\t\t\t\t// 0 means unknown because it got out of date\n\t\t\t\t\t\ttodo_room.2 = todo_room.2.min(\n\t\t\t\t\t\t\tknown_rooms\n\t\t\t\t\t\t\t\t.get(list_id.as_str())\n\t\t\t\t\t\t\t\t.and_then(|k| k.get(*room_id))\n\t\t\t\t\t\t\t\t.copied()\n\t\t\t\t\t\t\t\t.unwrap_or(0),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tsync_events::v4::SyncOp {\n\t\t\t\t\t\top: SlidingOp::Sync,\n\t\t\t\t\t\trange: Some(r),\n\t\t\t\t\t\tindex: None,\n\t\t\t\t\t\troom_ids: room_ids.into_iter().map(ToOwned::to_owned).collect(),\n\t\t\t\t\t\troom_id: None,\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.collect(),\n\t\t\tcount: ruma_from_usize(active_rooms.len()),\n\t\t});\n\n\t\tif let Some(conn_id) = &body.conn_id {\n\t\t\tservices.sync.update_sync_known_rooms(\n\t\t\t\tsender_user,\n\t\t\t\t&sender_device,\n\t\t\t\tconn_id.clone(),\n\t\t\t\tlist_id.clone(),\n\t\t\t\tnew_known_rooms,\n\t\t\t\tglobalsince,\n\t\t\t);\n\t\t}\n\t}\n\n\tlet mut known_subscription_rooms = BTreeSet::new();\n\tfor (room_id, room) in &body.room_subscriptions {\n\t\tif !services.rooms.metadata.exists(room_id).await\n\t\t\t|| services.rooms.metadata.is_disabled(room_id).await\n\t\t\t|| services.rooms.metadata.is_banned(room_id).await\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tlet todo_room =\n\t\t\ttodo_rooms\n\t\t\t\t.entry(room_id.clone())\n\t\t\t\t.or_insert((BTreeSet::new(), 0_usize, u64::MAX));\n\n\t\tlet limit: usize = room\n\t\t\t.timeline_limit\n\t\t\t.map(u64::from)\n\t\t\t.map_or(10, usize_from_u64_truncated)\n\t\t\t.min(100);\n\n\t\ttodo_room.0.extend(\n\t\t\troom.required_state\n\t\t\t\t.iter()\n\t\t\t\t.map(|(ty, sk)| (ty.clone(), sk.as_str().into())),\n\t\t);\n\t\ttodo_room.1 = todo_room.1.max(limit);\n\t\t// 0 means unknown because it got out of date\n\t\ttodo_room.2 = todo_room.2.min(\n\t\t\tknown_rooms\n\t\t\t\t.get(\"subscriptions\")\n\t\t\t\t.and_then(|k| k.get(room_id))\n\t\t\t\t.copied()\n\t\t\t\t.unwrap_or(0),\n\t\t);\n\t\tknown_subscription_rooms.insert(room_id.clone());\n\t}\n\n\tfor r in body.unsubscribe_rooms {\n\t\tknown_subscription_rooms.remove(&r);\n\t\tbody.room_subscriptions.remove(&r);\n\t}\n\n\tif let Some(conn_id) = &body.conn_id {\n\t\tservices.sync.update_sync_known_rooms(\n\t\t\tsender_user,\n\t\t\t&sender_device,\n\t\t\tconn_id.clone(),\n\t\t\t\"subscriptions\".to_owned(),\n\t\t\tknown_subscription_rooms,\n\t\t\tglobalsince,\n\t\t);\n\t}\n\n\tif let Some(conn_id) = &body.conn_id {\n\t\tservices.sync.update_sync_subscriptions(\n\t\t\tsender_user.clone(),\n\t\t\tsender_device.clone(),\n\t\t\tconn_id.clone(),\n\t\t\tbody.room_subscriptions,\n\t\t);\n\t}\n\n\tlet mut rooms = BTreeMap::new();\n\tfor (room_id, (required_state_request, timeline_limit, roomsince)) in &todo_rooms {\n\t\tlet roomsincecount = PduCount::Normal(*roomsince);\n\n\t\tlet mut timestamp: Option<_> = None;\n\t\tlet mut invite_state = None;\n\t\tlet (timeline_pdus, limited);\n\t\tlet new_room_id: &RoomId = (*room_id).as_ref();\n\t\tif all_invited_rooms.contains(&new_room_id) {\n\t\t\t// TODO: figure out a timestamp we can use for remote invites\n\t\t\tinvite_state = services\n\t\t\t\t.rooms\n\t\t\t\t.state_cache\n\t\t\t\t.invite_state(sender_user, room_id)\n\t\t\t\t.await\n\t\t\t\t.ok();\n\n\t\t\t(timeline_pdus, limited) = (Vec::new(), true);\n\t\t} else {\n\t\t\t(timeline_pdus, limited) = match load_timeline(\n\t\t\t\t&services,\n\t\t\t\tsender_user,\n\t\t\t\troom_id,\n\t\t\t\troomsincecount,\n\t\t\t\tNone,\n\t\t\t\t*timeline_limit,\n\t\t\t)\n\t\t\t.await\n\t\t\t{\n\t\t\t\t| Ok(value) => value,\n\t\t\t\t| Err(err) => {\n\t\t\t\t\twarn!(\"Encountered missing timeline in {}, error {}\", room_id, err);\n\t\t\t\t\tcontinue;\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\taccount_data.rooms.insert(\n\t\t\troom_id.to_owned(),\n\t\t\tservices\n\t\t\t\t.account_data\n\t\t\t\t.changes_since(Some(room_id), sender_user, *roomsince, Some(next_batch))\n\t\t\t\t.ready_filter_map(|e| extract_variant!(e, AnyRawAccountDataEvent::Room))\n\t\t\t\t.collect()\n\t\t\t\t.await,\n\t\t);\n\n\t\tlet last_privateread_update = services\n\t\t\t.rooms\n\t\t\t.read_receipt\n\t\t\t.last_privateread_update(sender_user, room_id)\n\t\t\t.await > *roomsince;\n\n\t\tlet private_read_event = if last_privateread_update {\n\t\t\tservices\n\t\t\t\t.rooms\n\t\t\t\t.read_receipt\n\t\t\t\t.private_read_get(room_id, sender_user)\n\t\t\t\t.await\n\t\t\t\t.ok()\n\t\t} else {\n\t\t\tNone\n\t\t};\n\n\t\tlet mut vector: Vec> = services\n\t\t\t.rooms\n\t\t\t.read_receipt\n\t\t\t.readreceipts_since(room_id, *roomsince)\n\t\t\t.filter_map(|(read_user, _ts, v)| async move {\n\t\t\t\tservices\n\t\t\t\t\t.users\n\t\t\t\t\t.user_is_ignored(read_user, sender_user)\n\t\t\t\t\t.await\n\t\t\t\t\t.or_some(v)\n\t\t\t})\n\t\t\t.collect()\n\t\t\t.await;\n\n\t\tif let Some(private_read_event) = private_read_event {\n\t\t\tvector.push(private_read_event);\n\t\t}\n\n\t\tlet receipt_size = vector.len();\n\t\treceipts\n\t\t\t.rooms\n\t\t\t.insert(room_id.clone(), pack_receipts(Box::new(vector.into_iter())));\n\n\t\tif roomsince != &0\n\t\t\t&& timeline_pdus.is_empty()\n\t\t\t&& account_data.rooms.get(room_id).is_some_and(Vec::is_empty)\n\t\t\t&& receipt_size == 0\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet prev_batch = timeline_pdus\n\t\t\t.first()\n\t\t\t.map_or(Ok::<_, Error>(None), |(pdu_count, _)| {\n\t\t\t\tOk(Some(match pdu_count {\n\t\t\t\t\t| PduCount::Backfilled(_) => {\n\t\t\t\t\t\terror!(\"timeline in backfill state?!\");\n\t\t\t\t\t\t\"0\".to_owned()\n\t\t\t\t\t},\n\t\t\t\t\t| PduCount::Normal(c) => c.to_string(),\n\t\t\t\t}))\n\t\t\t})?\n\t\t\t.or_else(|| {\n\t\t\t\tif roomsince != &0 {\n\t\t\t\t\tSome(roomsince.to_string())\n\t\t\t\t} else {\n\t\t\t\t\tNone\n\t\t\t\t}\n\t\t\t});\n\n\t\tlet room_events: Vec<_> = timeline_pdus\n\t\t\t.iter()\n\t\t\t.stream()\n\t\t\t.filter_map(|item| ignored_filter(&services, item.clone(), sender_user))\n\t\t\t.map(|(_, pdu)| pdu.to_sync_room_event())\n\t\t\t.collect()\n\t\t\t.await;\n\n\t\tfor (_, pdu) in timeline_pdus {\n\t\t\tlet ts = MilliSecondsSinceUnixEpoch(pdu.origin_server_ts);\n\t\t\tif DEFAULT_BUMP_TYPES.binary_search(&pdu.kind).is_ok()\n\t\t\t\t&& timestamp.is_none_or(|time| time <= ts)\n\t\t\t{\n\t\t\t\ttimestamp = Some(ts);\n\t\t\t}\n\t\t}\n\n\t\tlet required_state = required_state_request\n\t\t\t.iter()\n\t\t\t.stream()\n\t\t\t.filter_map(|state| async move {\n\t\t\t\tservices\n\t\t\t\t\t.rooms\n\t\t\t\t\t.state_accessor\n\t\t\t\t\t.room_state_get(room_id, &state.0, &state.1)\n\t\t\t\t\t.await\n\t\t\t\t\t.map(PduEvent::into_sync_state_event)\n\t\t\t\t\t.ok()\n\t\t\t})\n\t\t\t.collect()\n\t\t\t.await;\n\n\t\t// Heroes\n\t\tlet heroes: Vec<_> = services\n\t\t\t.rooms\n\t\t\t.state_cache\n\t\t\t.room_members(room_id)\n\t\t\t.ready_filter(|member| member != sender_user)\n\t\t\t.filter_map(|user_id| {\n\t\t\t\tservices\n\t\t\t\t\t.rooms\n\t\t\t\t\t.state_accessor\n\t\t\t\t\t.get_member(room_id, user_id)\n\t\t\t\t\t.map_ok(|memberevent| SlidingSyncRoomHero {\n\t\t\t\t\t\tuser_id: user_id.into(),\n\t\t\t\t\t\tname: memberevent.displayname,\n\t\t\t\t\t\tavatar: memberevent.avatar_url,\n\t\t\t\t\t})\n\t\t\t\t\t.ok()\n\t\t\t})\n\t\t\t.take(5)\n\t\t\t.collect()\n\t\t\t.await;\n\n\t\tlet name = match heroes.len().cmp(&(1_usize)) {\n\t\t\t| Ordering::Greater => {\n\t\t\t\tlet firsts = heroes[1..]\n\t\t\t\t\t.iter()\n\t\t\t\t\t.map(|h| h.name.clone().unwrap_or_else(|| h.user_id.to_string()))\n\t\t\t\t\t.collect::>()\n\t\t\t\t\t.join(\", \");\n\n\t\t\t\tlet last = heroes[0]\n\t\t\t\t\t.name\n\t\t\t\t\t.clone()\n\t\t\t\t\t.unwrap_or_else(|| heroes[0].user_id.to_string());\n\n\t\t\t\tSome(format!(\"{firsts} and {last}\"))\n\t\t\t},\n\t\t\t| Ordering::Equal => Some(\n\t\t\t\theroes[0]\n\t\t\t\t\t.name\n\t\t\t\t\t.clone()\n\t\t\t\t\t.unwrap_or_else(|| heroes[0].user_id.to_string()),\n\t\t\t),\n\t\t\t| Ordering::Less => None,\n\t\t};\n\n\t\tlet heroes_avatar = if heroes.len() == 1 {\n\t\t\theroes[0].avatar.clone()\n\t\t} else {\n\t\t\tNone\n\t\t};\n\n\t\trooms.insert(room_id.clone(), sync_events::v4::SlidingSyncRoom {\n\t\t\tname: services\n\t\t\t\t.rooms\n\t\t\t\t.state_accessor\n\t\t\t\t.get_name(room_id)\n\t\t\t\t.await\n\t\t\t\t.ok()\n\t\t\t\t.or(name),\n\t\t\tavatar: match heroes_avatar {\n\t\t\t\t| Some(heroes_avatar) => ruma::JsOption::Some(heroes_avatar),\n\t\t\t\t| _ => match services.rooms.state_accessor.get_avatar(room_id).await {\n\t\t\t\t\t| ruma::JsOption::Some(avatar) => ruma::JsOption::from_option(avatar.url),\n\t\t\t\t\t| ruma::JsOption::Null => ruma::JsOption::Null,\n\t\t\t\t\t| ruma::JsOption::Undefined => ruma::JsOption::Undefined,\n\t\t\t\t},\n\t\t\t},\n\t\t\tinitial: Some(roomsince == &0),\n\t\t\tis_dm: None,\n\t\t\tinvite_state,\n\t\t\tunread_notifications: UnreadNotificationsCount {\n\t\t\t\thighlight_count: Some(\n\t\t\t\t\tservices\n\t\t\t\t\t\t.rooms\n\t\t\t\t\t\t.user\n\t\t\t\t\t\t.highlight_count(sender_user, room_id)\n\t\t\t\t\t\t.await\n\t\t\t\t\t\t.try_into()\n\t\t\t\t\t\t.expect(\"notification count can't go that high\"),\n\t\t\t\t),\n\t\t\t\tnotification_count: Some(\n\t\t\t\t\tservices\n\t\t\t\t\t\t.rooms\n\t\t\t\t\t\t.user\n\t\t\t\t\t\t.notification_count(sender_user, room_id)\n\t\t\t\t\t\t.await\n\t\t\t\t\t\t.try_into()\n\t\t\t\t\t\t.expect(\"notification count can't go that high\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\ttimeline: room_events,\n\t\t\trequired_state,\n\t\t\tprev_batch,\n\t\t\tlimited,\n\t\t\tjoined_count: Some(\n\t\t\t\tservices\n\t\t\t\t\t.rooms\n\t\t\t\t\t.state_cache\n\t\t\t\t\t.room_joined_count(room_id)\n\t\t\t\t\t.await\n\t\t\t\t\t.unwrap_or(0)\n\t\t\t\t\t.try_into()\n\t\t\t\t\t.unwrap_or_else(|_| uint!(0)),\n\t\t\t),\n\t\t\tinvited_count: Some(\n\t\t\t\tservices\n\t\t\t\t\t.rooms\n\t\t\t\t\t.state_cache\n\t\t\t\t\t.room_invited_count(room_id)\n\t\t\t\t\t.await\n\t\t\t\t\t.unwrap_or(0)\n\t\t\t\t\t.try_into()\n\t\t\t\t\t.unwrap_or_else(|_| uint!(0)),\n\t\t\t),\n\t\t\tnum_live: None, // Count events in timeline greater than global sync counter\n\t\t\ttimestamp,\n\t\t\theroes: Some(heroes),\n\t\t});\n\t}\n\n\tif rooms.iter().all(|(id, r)| {\n\t\tr.timeline.is_empty() && r.required_state.is_empty() && !receipts.rooms.contains_key(id)\n\t}) {\n\t\t// Hang a few seconds so requests are not spammed\n\t\t// Stop hanging if new info arrives\n\t\tlet default = Duration::from_secs(30);\n\t\tlet duration = cmp::min(body.timeout.unwrap_or(default), default);\n\t\t_ = tokio::time::timeout(duration, watcher).await;\n\t}\n\n\tOk(sync_events::v4::Response {\n\t\tinitial: globalsince == 0,\n\t\ttxn_id: body.txn_id.clone(),\n\t\tpos: next_batch.to_string(),\n\t\tlists,\n\t\trooms,\n\t\textensions: sync_events::v4::Extensions {\n\t\t\tto_device: if body.extensions.to_device.enabled.unwrap_or(false) {\n\t\t\t\tSome(sync_events::v4::ToDevice {\n\t\t\t\t\tevents: services\n\t\t\t\t\t\t.users\n\t\t\t\t\t\t.get_to_device_events(\n\t\t\t\t\t\t\tsender_user,\n\t\t\t\t\t\t\t&sender_device,\n\t\t\t\t\t\t\tSome(globalsince),\n\t\t\t\t\t\t\tSome(next_batch),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.collect()\n\t\t\t\t\t\t.await,\n\t\t\t\t\tnext_batch: next_batch.to_string(),\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tNone\n\t\t\t},\n\t\t\te2ee: sync_events::v4::E2EE {\n\t\t\t\tdevice_lists: DeviceLists {\n\t\t\t\t\tchanged: device_list_changes.into_iter().collect(),\n\t\t\t\t\tleft: device_list_left.into_iter().collect(),\n\t\t\t\t},\n\t\t\t\tdevice_one_time_keys_count: services\n\t\t\t\t\t.users\n\t\t\t\t\t.count_one_time_keys(sender_user, &sender_device)\n\t\t\t\t\t.await,\n\t\t\t\t// Fallback keys are not yet supported\n\t\t\t\tdevice_unused_fallback_key_types: None,\n\t\t\t},\n\t\t\taccount_data,\n\t\t\treceipts,\n\t\t\ttyping: sync_events::v4::Typing { rooms: BTreeMap::new() },\n\t\t},\n\t\tdelta_token: None,\n\t})\n}\n```"}], "func_name": "sync_events_v4_route", "docstring": "POST `/_matrix/client/unstable/org.matrix.msc3575/sync`\n\nSliding Sync endpoint (future endpoint: `/_matrix/client/v4/sync`)", "repo": "girlbossceo/conduwuit", "path": "src/api/client/sync/v4.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/sync/v4.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa59c961f3b8fbd11fe0d522520480e7ae144c4e6d294904a934351b8d94b421"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sync_events_v5_route\n\nDocumentation:\n`POST /_matrix/client/unstable/org.matrix.simplified_msc3575/sync`\n([MSC4186])\n\nA simplified version of sliding sync ([MSC3575]).\n\nGet all new events in a sliding window of rooms since the last sync or a\ngiven point in time.\n\n[MSC3575]: https://github.com/matrix-org/matrix-spec-proposals/pull/3575\n[MSC4186]: https://github.com/matrix-org/matrix-spec-proposals/pull/4186\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn sync_events_v5_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tdebug_assert!(DEFAULT_BUMP_TYPES.is_sorted(), \"DEFAULT_BUMP_TYPES is not sorted\");\n\tlet sender_user = body.sender_user.as_ref().expect(\"user is authenticated\");\n\tlet sender_device = body.sender_device.as_ref().expect(\"user is authenticated\");\n\tlet mut body = body.body;\n\n\t// Setup watchers, so if there's no response, we can wait for them\n\tlet watcher = services.sync.watch(sender_user, sender_device);\n\n\tlet next_batch = services.globals.next_count()?;\n\n\tlet conn_id = body.conn_id.clone();\n\n\tlet globalsince = body\n\t\t.pos\n\t\t.as_ref()\n\t\t.and_then(|string| string.parse().ok())\n\t\t.unwrap_or(0);\n\n\tif globalsince != 0\n\t\t&& !services.sync.snake_connection_cached(\n\t\t\tsender_user.clone(),\n\t\t\tsender_device.clone(),\n\t\t\tconn_id.clone(),\n\t\t) {\n\t\tdebug!(\"Restarting sync stream because it was gone from the database\");\n\t\treturn Err(Error::Request(\n\t\t\tErrorKind::UnknownPos,\n\t\t\t\"Connection data lost since last time\".into(),\n\t\t\thttp::StatusCode::BAD_REQUEST,\n\t\t));\n\t}\n\n\t// Client / User requested an initial sync\n\tif globalsince == 0 {\n\t\tservices.sync.forget_snake_sync_connection(\n\t\t\tsender_user.clone(),\n\t\t\tsender_device.clone(),\n\t\t\tconn_id.clone(),\n\t\t);\n\t}\n\n\t// Get sticky parameters from cache\n\tlet known_rooms = services.sync.update_snake_sync_request_with_cache(\n\t\tsender_user.clone(),\n\t\tsender_device.clone(),\n\t\t&mut body,\n\t);\n\n\tlet all_joined_rooms: Vec<_> = services\n\t\t.rooms\n\t\t.state_cache\n\t\t.rooms_joined(sender_user)\n\t\t.map(ToOwned::to_owned)\n\t\t.collect()\n\t\t.await;\n\n\tlet all_invited_rooms: Vec<_> = services\n\t\t.rooms\n\t\t.state_cache\n\t\t.rooms_invited(sender_user)\n\t\t.map(|r| r.0)\n\t\t.collect()\n\t\t.await;\n\n\tlet all_knocked_rooms: Vec<_> = services\n\t\t.rooms\n\t\t.state_cache\n\t\t.rooms_knocked(sender_user)\n\t\t.map(|r| r.0)\n\t\t.collect()\n\t\t.await;\n\n\tlet all_rooms: Vec<&RoomId> = all_joined_rooms\n\t\t.iter()\n\t\t.map(AsRef::as_ref)\n\t\t.chain(all_invited_rooms.iter().map(AsRef::as_ref))\n\t\t.chain(all_knocked_rooms.iter().map(AsRef::as_ref))\n\t\t.collect();\n\n\tlet all_joined_rooms = all_joined_rooms.iter().map(AsRef::as_ref).collect();\n\tlet all_invited_rooms = all_invited_rooms.iter().map(AsRef::as_ref).collect();\n\n\tlet pos = next_batch.clone().to_string();\n\n\tlet mut todo_rooms: TodoRooms = BTreeMap::new();\n\n\tlet sync_info: SyncInfo<'_> = (sender_user, sender_device, globalsince, &body);\n\tlet mut response = sync_events::v5::Response {\n\t\ttxn_id: body.txn_id.clone(),\n\t\tpos,\n\t\tlists: BTreeMap::new(),\n\t\trooms: BTreeMap::new(),\n\t\textensions: sync_events::v5::response::Extensions {\n\t\t\taccount_data: collect_account_data(services, sync_info).await,\n\t\t\te2ee: collect_e2ee(services, sync_info, &all_joined_rooms).await?,\n\t\t\tto_device: collect_to_device(services, sync_info, next_batch).await,\n\t\t\treceipts: collect_receipts(services).await,\n\t\t\ttyping: sync_events::v5::response::Typing::default(),\n\t\t},\n\t};\n\n\thandle_lists(\n\t\tservices,\n\t\tsync_info,\n\t\t&all_invited_rooms,\n\t\t&all_joined_rooms,\n\t\t&all_rooms,\n\t\t&mut todo_rooms,\n\t\t&known_rooms,\n\t\t&mut response,\n\t)\n\t.await;\n\n\tfetch_subscriptions(services, sync_info, &known_rooms, &mut todo_rooms).await;\n\n\tresponse.rooms = process_rooms(\n\t\tservices,\n\t\tsender_user,\n\t\tnext_batch,\n\t\t&all_invited_rooms,\n\t\t&todo_rooms,\n\t\t&mut response,\n\t\t&body,\n\t)\n\t.await?;\n\n\tif response.rooms.iter().all(|(id, r)| {\n\t\tr.timeline.is_empty()\n\t\t\t&& r.required_state.is_empty()\n\t\t\t&& !response.extensions.receipts.rooms.contains_key(id)\n\t}) && response\n\t\t.extensions\n\t\t.to_device\n\t\t.clone()\n\t\t.is_none_or(|to| to.events.is_empty())\n\t{\n\t\t// Hang a few seconds so requests are not spammed\n\t\t// Stop hanging if new info arrives\n\t\tlet default = Duration::from_secs(30);\n\t\tlet duration = cmp::min(body.timeout.unwrap_or(default), default);\n\t\t_ = tokio::time::timeout(duration, watcher).await;\n\t}\n\n\ttrace!(\n\t\trooms=?response.rooms.len(),\n\t\taccount_data=?response.extensions.account_data.rooms.len(),\n\t\treceipts=?response.extensions.receipts.rooms.len(),\n\t\t\"responding to request with\"\n\t);\n\tOk(response)\n}\n```"}], "func_name": "sync_events_v5_route", "docstring": "`POST /_matrix/client/unstable/org.matrix.simplified_msc3575/sync`\n([MSC4186])\n\nA simplified version of sliding sync ([MSC3575]).\n\nGet all new events in a sliding window of rooms since the last sync or a\ngiven point in time.\n\n[MSC3575]: https://github.com/matrix-org/matrix-spec-proposals/pull/3575\n[MSC4186]: https://github.com/matrix-org/matrix-spec-proposals/pull/4186", "repo": "girlbossceo/conduwuit", "path": "src/api/client/sync/v5.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/client/sync/v5.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fd5ea96f9cfa5b7ce8026be70d133bcb30ead1cad87f1dc9f76edd101e11aac4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_backfill_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/backfill/`\n\nRetrieves events from before the sender joined the room, if the room's\nhistory visibility allows.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_backfill_route(\n\tState(services): State,\n\tref body: Ruma,\n) -> Result {\n\tAccessCheck {\n\t\tservices: &services,\n\t\torigin: body.origin(),\n\t\troom_id: &body.room_id,\n\t\tevent_id: None,\n\t}\n\t.check()\n\t.await?;\n\n\tlet limit = body\n\t\t.limit\n\t\t.try_into()\n\t\t.unwrap_or(LIMIT_DEFAULT)\n\t\t.min(LIMIT_MAX);\n\n\tlet from = body\n\t\t.v\n\t\t.iter()\n\t\t.stream()\n\t\t.filter_map(|event_id| {\n\t\t\tservices\n\t\t\t\t.rooms\n\t\t\t\t.timeline\n\t\t\t\t.get_pdu_count(event_id)\n\t\t\t\t.map(Result::ok)\n\t\t})\n\t\t.ready_fold(PduCount::min(), cmp::max)\n\t\t.await;\n\n\tOk(get_backfill::v1::Response {\n\t\torigin_server_ts: MilliSecondsSinceUnixEpoch::now(),\n\n\t\torigin: services.globals.server_name().to_owned(),\n\n\t\tpdus: services\n\t\t\t.rooms\n\t\t\t.timeline\n\t\t\t.pdus_rev(None, &body.room_id, Some(from.saturating_add(1)))\n\t\t\t.try_take(limit)\n\t\t\t.try_filter_map(|(_, pdu)| async move {\n\t\t\t\tOk(services\n\t\t\t\t\t.rooms\n\t\t\t\t\t.state_accessor\n\t\t\t\t\t.server_can_see_event(body.origin(), &pdu.room_id, &pdu.event_id)\n\t\t\t\t\t.await\n\t\t\t\t\t.then_some(pdu))\n\t\t\t})\n\t\t\t.try_filter_map(|pdu| async move {\n\t\t\t\tOk(services\n\t\t\t\t\t.rooms\n\t\t\t\t\t.timeline\n\t\t\t\t\t.get_pdu_json(&pdu.event_id)\n\t\t\t\t\t.await\n\t\t\t\t\t.ok())\n\t\t\t})\n\t\t\t.and_then(|pdu| {\n\t\t\t\tservices\n\t\t\t\t\t.sending\n\t\t\t\t\t.convert_to_outgoing_federation_event(pdu)\n\t\t\t\t\t.map(Ok)\n\t\t\t})\n\t\t\t.try_collect()\n\t\t\t.await?,\n\t})\n}\n```"}], "func_name": "get_backfill_route", "docstring": "# `GET /_matrix/federation/v1/backfill/`\n\nRetrieves events from before the sender joined the room, if the room's\nhistory visibility allows.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/backfill.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/backfill.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2fb5fd5c4eb64b3e2b999573a0b7fe90cc0e98d3cf8517182024239295ad36aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_event_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/event/{eventId}`\n\nRetrieves a single event from the server.\n\n- Only works if a user of this server is currently invited or joined the\nroom\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_event_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet event = services\n\t\t.rooms\n\t\t.timeline\n\t\t.get_pdu_json(&body.event_id)\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"Event not found.\"))))?;\n\n\tlet room_id: &RoomId = event\n\t\t.get(\"room_id\")\n\t\t.and_then(|val| val.as_str())\n\t\t.ok_or_else(|| err!(Database(\"Invalid event in database.\")))?\n\t\t.try_into()\n\t\t.map_err(|_| err!(Database(\"Invalid room_id in event in database.\")))?;\n\n\tAccessCheck {\n\t\tservices: &services,\n\t\torigin: body.origin(),\n\t\troom_id,\n\t\tevent_id: Some(&body.event_id),\n\t}\n\t.check()\n\t.await?;\n\n\tOk(get_event::v1::Response {\n\t\torigin: services.globals.server_name().to_owned(),\n\t\torigin_server_ts: MilliSecondsSinceUnixEpoch::now(),\n\t\tpdu: services\n\t\t\t.sending\n\t\t\t.convert_to_outgoing_federation_event(event)\n\t\t\t.await,\n\t})\n}\n```"}], "func_name": "get_event_route", "docstring": "# `GET /_matrix/federation/v1/event/{eventId}`\n\nRetrieves a single event from the server.\n\n- Only works if a user of this server is currently invited or joined the\nroom", "repo": "girlbossceo/conduwuit", "path": "src/api/server/event.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8f1a60b4f5c491f8cfde67221369b1bede2b2386d6d880fdcae224397e082d7c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_event_authorization_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/event_auth/{roomId}/{eventId}`\n\nRetrieves the auth chain for a given event.\n\n- This does not include the event itself\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_event_authorization_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tAccessCheck {\n\t\tservices: &services,\n\t\torigin: body.origin(),\n\t\troom_id: &body.room_id,\n\t\tevent_id: None,\n\t}\n\t.check()\n\t.await?;\n\n\tlet event = services\n\t\t.rooms\n\t\t.timeline\n\t\t.get_pdu_json(&body.event_id)\n\t\t.await\n\t\t.map_err(|_| Error::BadRequest(ErrorKind::NotFound, \"Event not found.\"))?;\n\n\tlet room_id_str = event\n\t\t.get(\"room_id\")\n\t\t.and_then(|val| val.as_str())\n\t\t.ok_or_else(|| Error::bad_database(\"Invalid event in database.\"))?;\n\n\tlet room_id = <&RoomId>::try_from(room_id_str)\n\t\t.map_err(|_| Error::bad_database(\"Invalid room_id in event in database.\"))?;\n\n\tlet auth_chain = services\n\t\t.rooms\n\t\t.auth_chain\n\t\t.event_ids_iter(room_id, once(body.event_id.borrow()))\n\t\t.ready_filter_map(Result::ok)\n\t\t.filter_map(|id| async move { services.rooms.timeline.get_pdu_json(&id).await.ok() })\n\t\t.then(|pdu| services.sending.convert_to_outgoing_federation_event(pdu))\n\t\t.collect()\n\t\t.await;\n\n\tOk(get_event_authorization::v1::Response { auth_chain })\n}\n```"}], "func_name": "get_event_authorization_route", "docstring": "# `GET /_matrix/federation/v1/event_auth/{roomId}/{eventId}`\n\nRetrieves the auth chain for a given event.\n\n- This does not include the event itself", "repo": "girlbossceo/conduwuit", "path": "src/api/server/event_auth.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/event_auth.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17b28bd7214f479bba61a73c9fbeac7801f746d2d0f35cedfc9a781cf081386f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_missing_events_route\n\nDocumentation:\n# `POST /_matrix/federation/v1/get_missing_events/{roomId}`\n\nRetrieves events that the sender is missing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_missing_events_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tAccessCheck {\n\t\tservices: &services,\n\t\torigin: body.origin(),\n\t\troom_id: &body.room_id,\n\t\tevent_id: None,\n\t}\n\t.check()\n\t.await?;\n\n\tlet limit = body\n\t\t.limit\n\t\t.try_into()\n\t\t.unwrap_or(LIMIT_DEFAULT)\n\t\t.min(LIMIT_MAX);\n\n\tlet mut queued_events = body.latest_events.clone();\n\t// the vec will never have more entries the limit\n\tlet mut events = Vec::with_capacity(limit);\n\n\tlet mut i: usize = 0;\n\twhile i < queued_events.len() && events.len() < limit {\n\t\tlet Ok(pdu) = services.rooms.timeline.get_pdu(&queued_events[i]).await else {\n\t\t\tdebug!(\n\t\t\t\t?body.origin,\n\t\t\t\t\"Event {} does not exist locally, skipping\", &queued_events[i]\n\t\t\t);\n\t\t\ti = i.saturating_add(1);\n\t\t\tcontinue;\n\t\t};\n\n\t\tif body.earliest_events.contains(&queued_events[i]) {\n\t\t\ti = i.saturating_add(1);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif !services\n\t\t\t.rooms\n\t\t\t.state_accessor\n\t\t\t.server_can_see_event(body.origin(), &body.room_id, &queued_events[i])\n\t\t\t.await\n\t\t{\n\t\t\tdebug!(\n\t\t\t\t?body.origin,\n\t\t\t\t\"Server cannot see {:?} in {:?}, skipping\", pdu.event_id, pdu.room_id\n\t\t\t);\n\t\t\ti = i.saturating_add(1);\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet Ok(event) = to_canonical_object(&pdu) else {\n\t\t\tdebug_error!(\n\t\t\t\t?body.origin,\n\t\t\t\t\"Failed to convert PDU in database to canonical JSON: {pdu:?}\"\n\t\t\t);\n\t\t\ti = i.saturating_add(1);\n\t\t\tcontinue;\n\t\t};\n\n\t\tlet prev_events = pdu.prev_events.iter().map(ToOwned::to_owned);\n\n\t\tlet event = services\n\t\t\t.sending\n\t\t\t.convert_to_outgoing_federation_event(event)\n\t\t\t.await;\n\n\t\tqueued_events.extend(prev_events);\n\t\tevents.push(event);\n\t}\n\n\tOk(get_missing_events::v1::Response { events })\n}\n```"}], "func_name": "get_missing_events_route", "docstring": "# `POST /_matrix/federation/v1/get_missing_events/{roomId}`\n\nRetrieves events that the sender is missing.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/get_missing_events.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/get_missing_events.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "76bd683cfbea565c7e6149c2a11d5f366b0861004173e36779227e6b1211c9a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_hierarchy_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/hierarchy/{roomId}`\n\nGets the space tree in a depth-first manner to locate child rooms of a given\nspace.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_hierarchy_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif !services.rooms.metadata.exists(&body.room_id).await {\n\t\treturn Err!(Request(NotFound(\"Room does not exist.\")));\n\t}\n\n\tlet room_id = &body.room_id;\n\tlet suggested_only = body.suggested_only;\n\tlet ref identifier = Identifier::ServerName(body.origin());\n\tmatch services\n\t\t.rooms\n\t\t.spaces\n\t\t.get_summary_and_children_local(room_id, identifier)\n\t\t.await?\n\t{\n\t\t| None => Err!(Request(NotFound(\"The requested room was not found\"))),\n\n\t\t| Some(SummaryAccessibility::Inaccessible) => {\n\t\t\tErr!(Request(NotFound(\"The requested room is inaccessible\")))\n\t\t},\n\n\t\t| Some(SummaryAccessibility::Accessible(room)) => {\n\t\t\tlet (children, inaccessible_children) =\n\t\t\t\tget_parent_children_via(&room, suggested_only)\n\t\t\t\t\t.stream()\n\t\t\t\t\t.broad_filter_map(|(child, _via)| async move {\n\t\t\t\t\t\tmatch services\n\t\t\t\t\t\t\t.rooms\n\t\t\t\t\t\t\t.spaces\n\t\t\t\t\t\t\t.get_summary_and_children_local(&child, identifier)\n\t\t\t\t\t\t\t.await\n\t\t\t\t\t\t\t.ok()?\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t| None => None,\n\n\t\t\t\t\t\t\t| Some(SummaryAccessibility::Inaccessible) =>\n\t\t\t\t\t\t\t\tSome((None, Some(child))),\n\n\t\t\t\t\t\t\t| Some(SummaryAccessibility::Accessible(summary)) =>\n\t\t\t\t\t\t\t\tSome((Some(summary), None)),\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.unzip()\n\t\t\t\t\t.map(|(children, inaccessible_children): (Vec<_>, Vec<_>)| {\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tchildren.into_iter().flatten().map(Into::into).collect(),\n\t\t\t\t\t\t\tinaccessible_children.into_iter().flatten().collect(),\n\t\t\t\t\t\t)\n\t\t\t\t\t})\n\t\t\t\t\t.await;\n\n\t\t\tOk(get_hierarchy::v1::Response { room, children, inaccessible_children })\n\t\t},\n\t}\n}\n```"}], "func_name": "get_hierarchy_route", "docstring": "# `GET /_matrix/federation/v1/hierarchy/{roomId}`\n\nGets the space tree in a depth-first manner to locate child rooms of a given\nspace.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/hierarchy.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/hierarchy.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0de2c1fce780f602cdbc35750bf81aec14d168f1c788cf975601e8c459b1b431"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_server_keys_deprecated_route\n\nDocumentation:\n# `GET /_matrix/key/v2/server/{keyId}`\n\nGets the public signing keys of this server.\n\n- Matrix does not support invalidating public keys, so the key returned by\nthis will be valid forever.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_server_keys_deprecated_route(\n\tState(services): State,\n) -> impl IntoResponse {\n\tget_server_keys_route(State(services)).await\n}\n```"}], "func_name": "get_server_keys_deprecated_route", "docstring": "# `GET /_matrix/key/v2/server/{keyId}`\n\nGets the public signing keys of this server.\n\n- Matrix does not support invalidating public keys, so the key returned by\nthis will be valid forever.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/key.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/key.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d7a660ac69a021b58ef91982c697b493bdd8a67e3f02a2672984652561b85b29"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_join_event_template_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/make_join/{roomId}/{userId}`\n\nCreates a join template.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn create_join_event_template_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif !services.rooms.metadata.exists(&body.room_id).await {\n\t\treturn Err!(Request(NotFound(\"Room is unknown to this server.\")));\n\t}\n\n\tif body.user_id.server_name() != body.origin() {\n\t\treturn Err!(Request(BadJson(\"Not allowed to join on behalf of another server/user.\")));\n\t}\n\n\t// ACL check origin server\n\tservices\n\t\t.rooms\n\t\t.event_handler\n\t\t.acl_check(body.origin(), &body.room_id)\n\t\t.await?;\n\n\tif services\n\t\t.config\n\t\t.forbidden_remote_server_names\n\t\t.is_match(body.origin().host())\n\t{\n\t\twarn!(\n\t\t\t\"Server {} for remote user {} tried joining room ID {} which has a server name that \\\n\t\t\t is globally forbidden. Rejecting.\",\n\t\t\tbody.origin(),\n\t\t\t&body.user_id,\n\t\t\t&body.room_id,\n\t\t);\n\t\treturn Err!(Request(Forbidden(\"Server is banned on this homeserver.\")));\n\t}\n\n\tif let Some(server) = body.room_id.server_name() {\n\t\tif services\n\t\t\t.config\n\t\t\t.forbidden_remote_server_names\n\t\t\t.is_match(server.host())\n\t\t{\n\t\t\treturn Err!(Request(Forbidden(warn!(\n\t\t\t\t\"Room ID server name {server} is banned on this homeserver.\"\n\t\t\t))));\n\t\t}\n\t}\n\n\tlet room_version_id = services.rooms.state.get_room_version(&body.room_id).await?;\n\tif !body.ver.contains(&room_version_id) {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::IncompatibleRoomVersion { room_version: room_version_id },\n\t\t\t\"Room version not supported.\",\n\t\t));\n\t}\n\n\tlet state_lock = services.rooms.state.mutex.lock(&body.room_id).await;\n\n\tlet join_authorized_via_users_server: Option = {\n\t\tuse RoomVersionId::*;\n\t\tif matches!(room_version_id, V1 | V2 | V3 | V4 | V5 | V6 | V7) {\n\t\t\t// room version does not support restricted join rules\n\t\t\tNone\n\t\t} else if user_can_perform_restricted_join(\n\t\t\t&services,\n\t\t\t&body.user_id,\n\t\t\t&body.room_id,\n\t\t\t&room_version_id,\n\t\t)\n\t\t.await?\n\t\t{\n\t\t\tlet Some(auth_user) = services\n\t\t\t\t.rooms\n\t\t\t\t.state_cache\n\t\t\t\t.local_users_in_room(&body.room_id)\n\t\t\t\t.filter(|user| {\n\t\t\t\t\tservices.rooms.state_accessor.user_can_invite(\n\t\t\t\t\t\t&body.room_id,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\t&body.user_id,\n\t\t\t\t\t\t&state_lock,\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t\t.boxed()\n\t\t\t\t.next()\n\t\t\t\t.await\n\t\t\t\t.map(ToOwned::to_owned)\n\t\t\telse {\n\t\t\t\treturn Err!(Request(UnableToGrantJoin(\n\t\t\t\t\t\"No user on this server is able to assist in joining.\"\n\t\t\t\t)));\n\t\t\t};\n\t\t\tSome(auth_user)\n\t\t} else {\n\t\t\tNone\n\t\t}\n\t};\n\n\tlet (_pdu, mut pdu_json) = services\n\t\t.rooms\n\t\t.timeline\n\t\t.create_hash_and_sign_event(\n\t\t\tPduBuilder::state(body.user_id.to_string(), &RoomMemberEventContent {\n\t\t\t\tjoin_authorized_via_users_server,\n\t\t\t\t..RoomMemberEventContent::new(MembershipState::Join)\n\t\t\t}),\n\t\t\t&body.user_id,\n\t\t\t&body.room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\tdrop(state_lock);\n\n\t// room v3 and above removed the \"event_id\" field from remote PDU format\n\tmaybe_strip_event_id(&mut pdu_json, &room_version_id)?;\n\n\tOk(prepare_join_event::v1::Response {\n\t\troom_version: Some(room_version_id),\n\t\tevent: to_raw_value(&pdu_json).expect(\"CanonicalJson can be serialized to JSON\"),\n\t})\n}\n```"}], "func_name": "create_join_event_template_route", "docstring": "# `GET /_matrix/federation/v1/make_join/{roomId}/{userId}`\n\nCreates a join template.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/make_join.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/make_join.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f6f058b0abc7514524909eedbdddb935198fec081aaf88813a9b4f9a3c20c485"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: user_can_perform_restricted_join\n\nDocumentation:\nChecks whether the given user can join the given room via a restricted join.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn user_can_perform_restricted_join(\n\tservices: &Services,\n\tuser_id: &UserId,\n\troom_id: &RoomId,\n\troom_version_id: &RoomVersionId,\n) -> Result {\n\tuse RoomVersionId::*;\n\n\t// restricted rooms are not supported on <=v7\n\tif matches!(room_version_id, V1 | V2 | V3 | V4 | V5 | V6 | V7) {\n\t\treturn Ok(false);\n\t}\n\n\tif services.rooms.state_cache.is_joined(user_id, room_id).await {\n\t\t// joining user is already joined, there is nothing we need to do\n\t\treturn Ok(false);\n\t}\n\n\tlet Ok(join_rules_event_content) = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.room_state_get_content::(\n\t\t\troom_id,\n\t\t\t&StateEventType::RoomJoinRules,\n\t\t\t\"\",\n\t\t)\n\t\t.await\n\telse {\n\t\treturn Ok(false);\n\t};\n\n\tlet (JoinRule::Restricted(r) | JoinRule::KnockRestricted(r)) =\n\t\tjoin_rules_event_content.join_rule\n\telse {\n\t\treturn Ok(false);\n\t};\n\n\tif r.allow.is_empty() {\n\t\tdebug_info!(\"{room_id} is restricted but the allow key is empty\");\n\t\treturn Ok(false);\n\t}\n\n\tif r.allow\n\t\t.iter()\n\t\t.filter_map(|rule| {\n\t\t\tif let AllowRule::RoomMembership(membership) = rule {\n\t\t\t\tSome(membership)\n\t\t\t} else {\n\t\t\t\tNone\n\t\t\t}\n\t\t})\n\t\t.stream()\n\t\t.any(|m| services.rooms.state_cache.is_joined(user_id, &m.room_id))\n\t\t.await\n\t{\n\t\tOk(true)\n\t} else {\n\t\tErr!(Request(UnableToAuthorizeJoin(\n\t\t\t\"Joining user is not known to be in any required room.\"\n\t\t)))\n\t}\n}\n```"}], "func_name": "user_can_perform_restricted_join", "docstring": "Checks whether the given user can join the given room via a restricted join.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/make_join.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/make_join.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e7b213af006a72e8c4394c2c34cfdd3a12b811f8653a5e800b7a3d26c01b6417"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_knock_event_template_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/make_knock/{roomId}/{userId}`\n\nCreates a knock template.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn create_knock_event_template_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif !services.rooms.metadata.exists(&body.room_id).await {\n\t\treturn Err!(Request(NotFound(\"Room is unknown to this server.\")));\n\t}\n\n\tif body.user_id.server_name() != body.origin() {\n\t\treturn Err!(Request(BadJson(\"Not allowed to knock on behalf of another server/user.\")));\n\t}\n\n\t// ACL check origin server\n\tservices\n\t\t.rooms\n\t\t.event_handler\n\t\t.acl_check(body.origin(), &body.room_id)\n\t\t.await?;\n\n\tif services\n\t\t.config\n\t\t.forbidden_remote_server_names\n\t\t.is_match(body.origin().host())\n\t{\n\t\twarn!(\n\t\t\t\"Server {} for remote user {} tried knocking room ID {} which has a server name \\\n\t\t\t that is globally forbidden. Rejecting.\",\n\t\t\tbody.origin(),\n\t\t\t&body.user_id,\n\t\t\t&body.room_id,\n\t\t);\n\t\treturn Err!(Request(Forbidden(\"Server is banned on this homeserver.\")));\n\t}\n\n\tif let Some(server) = body.room_id.server_name() {\n\t\tif services\n\t\t\t.config\n\t\t\t.forbidden_remote_server_names\n\t\t\t.is_match(server.host())\n\t\t{\n\t\t\treturn Err!(Request(Forbidden(\"Server is banned on this homeserver.\")));\n\t\t}\n\t}\n\n\tlet room_version_id = services.rooms.state.get_room_version(&body.room_id).await?;\n\n\tif matches!(room_version_id, V1 | V2 | V3 | V4 | V5 | V6) {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::IncompatibleRoomVersion { room_version: room_version_id },\n\t\t\t\"Room version does not support knocking.\",\n\t\t));\n\t}\n\n\tif !body.ver.contains(&room_version_id) {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::IncompatibleRoomVersion { room_version: room_version_id },\n\t\t\t\"Your homeserver does not support the features required to knock on this room.\",\n\t\t));\n\t}\n\n\tlet state_lock = services.rooms.state.mutex.lock(&body.room_id).await;\n\n\tif let Ok(membership) = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.get_member(&body.room_id, &body.user_id)\n\t\t.await\n\t{\n\t\tif membership.membership == MembershipState::Ban {\n\t\t\tdebug_warn!(\n\t\t\t\t\"Remote user {} is banned from {} but attempted to knock\",\n\t\t\t\t&body.user_id,\n\t\t\t\t&body.room_id\n\t\t\t);\n\t\t\treturn Err!(Request(Forbidden(\"You cannot knock on a room you are banned from.\")));\n\t\t}\n\t}\n\n\tlet (_pdu, mut pdu_json) = services\n\t\t.rooms\n\t\t.timeline\n\t\t.create_hash_and_sign_event(\n\t\t\tPduBuilder::state(\n\t\t\t\tbody.user_id.to_string(),\n\t\t\t\t&RoomMemberEventContent::new(MembershipState::Knock),\n\t\t\t),\n\t\t\t&body.user_id,\n\t\t\t&body.room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\tdrop(state_lock);\n\n\t// room v3 and above removed the \"event_id\" field from remote PDU format\n\tsuper::maybe_strip_event_id(&mut pdu_json, &room_version_id)?;\n\n\tOk(create_knock_event_template::v1::Response {\n\t\troom_version: room_version_id,\n\t\tevent: to_raw_value(&pdu_json).expect(\"CanonicalJson can be serialized to JSON\"),\n\t})\n}\n```"}], "func_name": "create_knock_event_template_route", "docstring": "# `GET /_matrix/federation/v1/make_knock/{roomId}/{userId}`\n\nCreates a knock template.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/make_knock.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/make_knock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ebcb5171c5b63afffc59c349f50479e7a32be90cddb79b027b378dd850612324"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_leave_event_template_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/make_leave/{roomId}/{eventId}`\n\nCreates a leave template.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn create_leave_event_template_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif !services.rooms.metadata.exists(&body.room_id).await {\n\t\treturn Err!(Request(NotFound(\"Room is unknown to this server.\")));\n\t}\n\n\tif body.user_id.server_name() != body.origin() {\n\t\treturn Err!(Request(Forbidden(\n\t\t\t\"Not allowed to leave on behalf of another server/user.\"\n\t\t)));\n\t}\n\n\t// ACL check origin\n\tservices\n\t\t.rooms\n\t\t.event_handler\n\t\t.acl_check(body.origin(), &body.room_id)\n\t\t.await?;\n\n\tlet room_version_id = services.rooms.state.get_room_version(&body.room_id).await?;\n\tlet state_lock = services.rooms.state.mutex.lock(&body.room_id).await;\n\n\tlet (_pdu, mut pdu_json) = services\n\t\t.rooms\n\t\t.timeline\n\t\t.create_hash_and_sign_event(\n\t\t\tPduBuilder::state(\n\t\t\t\tbody.user_id.to_string(),\n\t\t\t\t&RoomMemberEventContent::new(MembershipState::Leave),\n\t\t\t),\n\t\t\t&body.user_id,\n\t\t\t&body.room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\tdrop(state_lock);\n\n\t// room v3 and above removed the \"event_id\" field from remote PDU format\n\tmaybe_strip_event_id(&mut pdu_json, &room_version_id)?;\n\n\tOk(prepare_leave_event::v1::Response {\n\t\troom_version: Some(room_version_id),\n\t\tevent: to_raw_value(&pdu_json).expect(\"CanonicalJson can be serialized to JSON\"),\n\t})\n}\n```"}], "func_name": "create_leave_event_template_route", "docstring": "# `GET /_matrix/federation/v1/make_leave/{roomId}/{eventId}`\n\nCreates a leave template.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/make_leave.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/make_leave.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb111ccb4db393bd9d0c8b445435781e53eb67a46fa1922a2191a4358057dc73"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_openid_userinfo_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/openid/userinfo`\n\nGet information about the user that generated the OpenID token.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_openid_userinfo_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tOk(get_openid_userinfo::v1::Response::new(\n\t\tservices\n\t\t\t.users\n\t\t\t.find_from_openid_token(&body.access_token)\n\t\t\t.await?,\n\t))\n}\n```"}], "func_name": "get_openid_userinfo_route", "docstring": "# `GET /_matrix/federation/v1/openid/userinfo`\n\nGet information about the user that generated the OpenID token.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/openid.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/openid.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "34c40593ba1f8e01b04fd7a6b11ca577ec2745f9eeb4842ccae60211f2b12208"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_room_information_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/query/directory`\n\nResolve a room alias to a room id.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_room_information_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tlet room_id = services\n\t\t.rooms\n\t\t.alias\n\t\t.resolve_local_alias(&body.room_alias)\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"Room alias not found.\"))))?;\n\n\tlet mut servers: Vec = services\n\t\t.rooms\n\t\t.state_cache\n\t\t.room_servers(&room_id)\n\t\t.map(ToOwned::to_owned)\n\t\t.collect()\n\t\t.await;\n\n\tservers.sort_unstable();\n\tservers.dedup();\n\n\tservers.shuffle(&mut rand::thread_rng());\n\n\t// insert our server as the very first choice if in list\n\tif let Some(server_index) = servers\n\t\t.iter()\n\t\t.position(|server| server == services.globals.server_name())\n\t{\n\t\tservers.swap_remove(server_index);\n\t\tservers.insert(0, services.globals.server_name().to_owned());\n\t}\n\n\tOk(get_room_information::v1::Response { room_id, servers })\n}\n```"}], "func_name": "get_room_information_route", "docstring": "# `GET /_matrix/federation/v1/query/directory`\n\nResolve a room alias to a room id.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/query.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/query.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "74dd3a83431ce7b6f961cd59cd567d253267a431686c9982ff2e23311b6867d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_profile_information_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/query/profile`\n\n\nGets information on a profile.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_profile_information_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif !services\n\t\t.server\n\t\t.config\n\t\t.allow_inbound_profile_lookup_federation_requests\n\t{\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::forbidden(),\n\t\t\t\"Profile lookup over federation is not allowed on this homeserver.\",\n\t\t));\n\t}\n\n\tif !services.globals.server_is_ours(body.user_id.server_name()) {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::InvalidParam,\n\t\t\t\"User does not belong to this server.\",\n\t\t));\n\t}\n\n\tlet mut displayname = None;\n\tlet mut avatar_url = None;\n\tlet mut blurhash = None;\n\tlet mut tz = None;\n\tlet mut custom_profile_fields = BTreeMap::new();\n\n\tmatch &body.field {\n\t\t| Some(ProfileField::DisplayName) => {\n\t\t\tdisplayname = services.users.displayname(&body.user_id).await.ok();\n\t\t},\n\t\t| Some(ProfileField::AvatarUrl) => {\n\t\t\tavatar_url = services.users.avatar_url(&body.user_id).await.ok();\n\t\t\tblurhash = services.users.blurhash(&body.user_id).await.ok();\n\t\t},\n\t\t| Some(custom_field) => {\n\t\t\tif let Ok(value) = services\n\t\t\t\t.users\n\t\t\t\t.profile_key(&body.user_id, custom_field.as_str())\n\t\t\t\t.await\n\t\t\t{\n\t\t\t\tcustom_profile_fields.insert(custom_field.to_string(), value);\n\t\t\t}\n\t\t},\n\t\t| None => {\n\t\t\tdisplayname = services.users.displayname(&body.user_id).await.ok();\n\t\t\tavatar_url = services.users.avatar_url(&body.user_id).await.ok();\n\t\t\tblurhash = services.users.blurhash(&body.user_id).await.ok();\n\t\t\ttz = services.users.timezone(&body.user_id).await.ok();\n\t\t\tcustom_profile_fields = services\n\t\t\t\t.users\n\t\t\t\t.all_profile_keys(&body.user_id)\n\t\t\t\t.collect()\n\t\t\t\t.await;\n\t\t},\n\t}\n\n\t// services.users.timezone will collect the MSC4175 timezone key if it exists\n\tcustom_profile_fields.remove(\"us.cloke.msc4175.tz\");\n\tcustom_profile_fields.remove(\"m.tz\");\n\n\tOk(get_profile_information::v1::Response {\n\t\tdisplayname,\n\t\tavatar_url,\n\t\tblurhash,\n\t\ttz,\n\t\tcustom_profile_fields,\n\t})\n}\n```"}], "func_name": "get_profile_information_route", "docstring": "# `GET /_matrix/federation/v1/query/profile`\n\n\nGets information on a profile.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/query.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/query.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "07df5ebbfec137232edd2b70611d148f9e499143eaa39b1b74ce168abcb6000e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_room_state_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/state/{roomId}`\n\nRetrieves a snapshot of a room's state at a given event.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_room_state_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tAccessCheck {\n\t\tservices: &services,\n\t\torigin: body.origin(),\n\t\troom_id: &body.room_id,\n\t\tevent_id: None,\n\t}\n\t.check()\n\t.await?;\n\n\tlet shortstatehash = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.pdu_shortstatehash(&body.event_id)\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"PDU state not found.\"))))?;\n\n\tlet state_ids: Vec = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.state_full_ids(shortstatehash)\n\t\t.map(at!(1))\n\t\t.collect()\n\t\t.await;\n\n\tlet pdus = state_ids\n\t\t.iter()\n\t\t.try_stream()\n\t\t.and_then(|id| services.rooms.timeline.get_pdu_json(id))\n\t\t.and_then(|pdu| {\n\t\t\tservices\n\t\t\t\t.sending\n\t\t\t\t.convert_to_outgoing_federation_event(pdu)\n\t\t\t\t.map(Ok)\n\t\t})\n\t\t.try_collect()\n\t\t.await?;\n\n\tlet auth_chain = services\n\t\t.rooms\n\t\t.auth_chain\n\t\t.event_ids_iter(&body.room_id, once(body.event_id.borrow()))\n\t\t.and_then(|id| async move { services.rooms.timeline.get_pdu_json(&id).await })\n\t\t.and_then(|pdu| {\n\t\t\tservices\n\t\t\t\t.sending\n\t\t\t\t.convert_to_outgoing_federation_event(pdu)\n\t\t\t\t.map(Ok)\n\t\t})\n\t\t.try_collect()\n\t\t.await?;\n\n\tOk(get_room_state::v1::Response { auth_chain, pdus })\n}\n```"}], "func_name": "get_room_state_route", "docstring": "# `GET /_matrix/federation/v1/state/{roomId}`\n\nRetrieves a snapshot of a room's state at a given event.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/state.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1d6a8805347bb6482a15a9e6424eecfbec124aa5f071b05782761da55428ab60"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_room_state_ids_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/state_ids/{roomId}`\n\nRetrieves a snapshot of a room's state at a given event, in the form of\nevent IDs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_room_state_ids_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tAccessCheck {\n\t\tservices: &services,\n\t\torigin: body.origin(),\n\t\troom_id: &body.room_id,\n\t\tevent_id: None,\n\t}\n\t.check()\n\t.await?;\n\n\tlet shortstatehash = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.pdu_shortstatehash(&body.event_id)\n\t\t.await\n\t\t.map_err(|_| err!(Request(NotFound(\"Pdu state not found.\"))))?;\n\n\tlet pdu_ids: Vec = services\n\t\t.rooms\n\t\t.state_accessor\n\t\t.state_full_ids(shortstatehash)\n\t\t.map(at!(1))\n\t\t.collect()\n\t\t.await;\n\n\tlet auth_chain_ids = services\n\t\t.rooms\n\t\t.auth_chain\n\t\t.event_ids_iter(&body.room_id, once(body.event_id.borrow()))\n\t\t.try_collect()\n\t\t.await?;\n\n\tOk(get_room_state_ids::v1::Response { auth_chain_ids, pdu_ids })\n}\n```"}], "func_name": "get_room_state_ids_route", "docstring": "# `GET /_matrix/federation/v1/state_ids/{roomId}`\n\nRetrieves a snapshot of a room's state at a given event, in the form of\nevent IDs.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/state_ids.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/state_ids.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "43ac86c3efaa4569d6c91c8e7295f20a26653cff0470a1b40991090b5e68638d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_devices_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/user/devices/{userId}`\n\nGets information on all devices of the user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_devices_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif !services.globals.user_is_local(&body.user_id) {\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::InvalidParam,\n\t\t\t\"Tried to access user from other server.\",\n\t\t));\n\t}\n\n\tlet user_id = &body.user_id;\n\tOk(get_devices::v1::Response {\n\t\tuser_id: user_id.clone(),\n\t\tstream_id: services\n\t\t\t.users\n\t\t\t.get_devicelist_version(user_id)\n\t\t\t.await\n\t\t\t.unwrap_or(0)\n\t\t\t.try_into()?,\n\t\tdevices: services\n\t\t\t.users\n\t\t\t.all_devices_metadata(user_id)\n\t\t\t.filter_map(|metadata| async move {\n\t\t\t\tlet device_id = metadata.device_id.clone();\n\t\t\t\tlet device_id_clone = device_id.clone();\n\t\t\t\tlet device_id_string = device_id.as_str().to_owned();\n\t\t\t\tlet device_display_name = if services.globals.allow_device_name_federation() {\n\t\t\t\t\tmetadata.display_name.clone()\n\t\t\t\t} else {\n\t\t\t\t\tSome(device_id_string)\n\t\t\t\t};\n\n\t\t\t\tservices\n\t\t\t\t\t.users\n\t\t\t\t\t.get_device_keys(user_id, &device_id_clone)\n\t\t\t\t\t.map_ok(|keys| UserDevice { device_id, keys, device_display_name })\n\t\t\t\t\t.map(Result::ok)\n\t\t\t\t\t.await\n\t\t\t})\n\t\t\t.collect()\n\t\t\t.await,\n\t\tmaster_key: services\n\t\t\t.users\n\t\t\t.get_master_key(None, &body.user_id, &|u| u.server_name() == body.origin())\n\t\t\t.await\n\t\t\t.ok(),\n\t\tself_signing_key: services\n\t\t\t.users\n\t\t\t.get_self_signing_key(None, &body.user_id, &|u| u.server_name() == body.origin())\n\t\t\t.await\n\t\t\t.ok(),\n\t})\n}\n```"}], "func_name": "get_devices_route", "docstring": "# `GET /_matrix/federation/v1/user/devices/{userId}`\n\nGets information on all devices of the user.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/user.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/user.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f7da35d85f3cae566b3f826f23d14a91ee74a905af421bad4ae404f9f8d16f4d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_keys_route\n\nDocumentation:\n# `POST /_matrix/federation/v1/user/keys/query`\n\nGets devices and identity keys for the given users.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_keys_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif body\n\t\t.device_keys\n\t\t.iter()\n\t\t.any(|(u, _)| !services.globals.user_is_local(u))\n\t{\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::InvalidParam,\n\t\t\t\"User does not belong to this server.\",\n\t\t));\n\t}\n\n\tlet result = get_keys_helper(\n\t\t&services,\n\t\tNone,\n\t\t&body.device_keys,\n\t\t|u| Some(u.server_name()) == body.origin.as_deref(),\n\t\tservices.globals.allow_device_name_federation(),\n\t)\n\t.await?;\n\n\tOk(get_keys::v1::Response {\n\t\tdevice_keys: result.device_keys,\n\t\tmaster_keys: result.master_keys,\n\t\tself_signing_keys: result.self_signing_keys,\n\t})\n}\n```"}], "func_name": "get_keys_route", "docstring": "# `POST /_matrix/federation/v1/user/keys/query`\n\nGets devices and identity keys for the given users.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/user.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/user.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aeec0de466e9adda9e34ecf7234003ccd18cf61484ce1e0df0806cec4330901c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: claim_keys_route\n\nDocumentation:\n# `POST /_matrix/federation/v1/user/keys/claim`\n\nClaims one-time keys.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn claim_keys_route(\n\tState(services): State,\n\tbody: Ruma,\n) -> Result {\n\tif body\n\t\t.one_time_keys\n\t\t.iter()\n\t\t.any(|(u, _)| !services.globals.user_is_local(u))\n\t{\n\t\treturn Err(Error::BadRequest(\n\t\t\tErrorKind::InvalidParam,\n\t\t\t\"Tried to access user from other server.\",\n\t\t));\n\t}\n\n\tlet result = claim_keys_helper(&services, &body.one_time_keys).await?;\n\n\tOk(claim_keys::v1::Response { one_time_keys: result.one_time_keys })\n}\n```"}], "func_name": "claim_keys_route", "docstring": "# `POST /_matrix/federation/v1/user/keys/claim`\n\nClaims one-time keys.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/user.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/user.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f85c23e86a00dd5c816c22914da5c845108bcf8f10a3881d2a35fab89927d1aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_server_version_route\n\nDocumentation:\n# `GET /_matrix/federation/v1/version`\n\nGet version information on this server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_server_version_route(\n\t_body: Ruma,\n) -> Result {\n\tOk(get_server_version::v1::Response {\n\t\tserver: Some(get_server_version::v1::Server {\n\t\t\tname: Some(conduwuit::version::name().into()),\n\t\t\tversion: Some(conduwuit::version::version().into()),\n\t\t}),\n\t})\n}\n```"}], "func_name": "get_server_version_route", "docstring": "# `GET /_matrix/federation/v1/version`\n\nGet version information on this server.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/version.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/version.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7f9d25ce5be331e3f76c9e51e2812ff4c6f8960f8aefaf8016703c2ccb2438f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: well_known_server\n\nDocumentation:\n# `GET /.well-known/matrix/server`\n\nReturns the .well-known URL if it is configured, otherwise returns 404.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn well_known_server(\n\tState(services): State,\n\t_body: Ruma,\n) -> Result {\n\tOk(discover_homeserver::Response {\n\t\tserver: match services.server.config.well_known.server.as_ref() {\n\t\t\t| Some(server_name) => server_name.to_owned(),\n\t\t\t| None => return Err(Error::BadRequest(ErrorKind::NotFound, \"Not found.\")),\n\t\t},\n\t})\n}\n```"}], "func_name": "well_known_server", "docstring": "# `GET /.well-known/matrix/server`\n\nReturns the .well-known URL if it is configured, otherwise returns 404.", "repo": "girlbossceo/conduwuit", "path": "src/api/server/well_known.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/api/server/well_known.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ece2bfe68030e3a2456b3da1031255cb95c6e90ff781e49050e8381650c08fa0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reload\n\nDocumentation:\nPerforms check() with additional checks specific to reloading old config\nwith new config.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reload(old: &Config, new: &Config) -> Result {\n\tcheck(new)?;\n\n\tif new.server_name != old.server_name {\n\t\treturn Err!(Config(\n\t\t\t\"server_name\",\n\t\t\t\"You can't change the server's name from {:?}.\",\n\t\t\told.server_name\n\t\t));\n\t}\n\n\tOk(())\n}\n```"}], "func_name": "reload", "docstring": "Performs check() with additional checks specific to reloading old config\nwith new config.", "repo": "girlbossceo/conduwuit", "path": "src/core/config/check.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/config/check.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "96b0d56d78886253788b361560fc13184b0c388a1dd305877cd6071600932b90"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: warn_deprecated\n\nDocumentation:\nIterates over all the keys in the config file and warns if there is a\ndeprecated key specified\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn warn_deprecated(config: &Config) {\n\tdebug!(\"Checking for deprecated config keys\");\n\tlet mut was_deprecated = false;\n\tfor key in config\n\t\t.catchall\n\t\t.keys()\n\t\t.filter(|key| DEPRECATED_KEYS.iter().any(|s| s == key))\n\t{\n\t\twarn!(\"Config parameter \\\"{}\\\" is deprecated, ignoring.\", key);\n\t\twas_deprecated = true;\n\t}\n\n\tif was_deprecated {\n\t\twarn!(\n\t\t\t\"Read conduwuit config documentation at https://conduwuit.puppyirl.gay/configuration.html and check your \\\n\t\t\t configuration if any new configuration parameters should be adjusted\"\n\t\t);\n\t}\n}\n```"}], "func_name": "warn_deprecated", "docstring": "Iterates over all the keys in the config file and warns if there is a\ndeprecated key specified", "repo": "girlbossceo/conduwuit", "path": "src/core/config/check.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/config/check.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ae1c839c8bd6d1827e2ac22b695fee76867b4cfa22af66f826fabb50a712f137"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: warn_unknown_key\n\nDocumentation:\niterates over all the catchall keys (unknown config options) and warns\nif there are any.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn warn_unknown_key(config: &Config) {\n\tdebug!(\"Checking for unknown config keys\");\n\tfor key in config\n\t\t.catchall\n\t\t.keys()\n\t\t.filter(|key| \"config\".to_owned().ne(key.to_owned()) /* \"config\" is expected */)\n\t{\n\t\twarn!(\"Config parameter \\\"{}\\\" is unknown to conduwuit, ignoring.\", key);\n\t}\n}\n```"}], "func_name": "warn_unknown_key", "docstring": "iterates over all the catchall keys (unknown config options) and warns\nif there are any.", "repo": "girlbossceo/conduwuit", "path": "src/core/config/check.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/config/check.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "834d3ab21aeedac614635a86fa477ec7b234db66499f3ff224699fa3df16b70e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_dual_listening\n\nDocumentation:\nChecks the presence of the `address` and `unix_socket_path` keys in the\nraw_config, exiting the process if both keys were detected.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn is_dual_listening(raw_config: &Figment) -> Result<()> {\n\tlet contains_address = raw_config.contains(\"address\");\n\tlet contains_unix_socket = raw_config.contains(\"unix_socket_path\");\n\tif contains_address && contains_unix_socket {\n\t\treturn Err!(\n\t\t\t\"TOML keys \\\"address\\\" and \\\"unix_socket_path\\\" were both defined. Please specify \\\n\t\t\t only one option.\"\n\t\t);\n\t}\n\n\tOk(())\n}\n```"}], "func_name": "is_dual_listening", "docstring": "Checks the presence of the `address` and `unix_socket_path` keys in the\nraw_config, exiting the process if both keys were detected.", "repo": "girlbossceo/conduwuit", "path": "src/core/config/check.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/config/check.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b46f593745c901e07fca2828a45d10f28a01cd59955ac60336e89cf8ce6b9238"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sanitized_message\n\nDocumentation:\nSanitizes public-facing errors that can leak sensitive information.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sanitized_message(&self) -> String {\n\t\tmatch self {\n\t\t\t| Self::Database(..) => String::from(\"Database error occurred.\"),\n\t\t\t| Self::Io(..) => String::from(\"I/O error occurred.\"),\n\t\t\t| _ => self.message(),\n\t\t}\n\t}\n```"}], "func_name": "sanitized_message", "docstring": "Sanitizes public-facing errors that can leak sensitive information.", "repo": "girlbossceo/conduwuit", "path": "src/core/error/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/error/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bccbc45a9d4172c43b223a5a3d24e3992754fad7f27b3669d8c9ba7a18a2ee93"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: status_code\n\nDocumentation:\nReturns the HTTP error code or closest approximation based on error\nvariant.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn status_code(&self) -> http::StatusCode {\n\t\tuse http::StatusCode;\n\n\t\tmatch self {\n\t\t\t| Self::Federation(_, error) | Self::Ruma(error) => error.status_code,\n\t\t\t| Self::Request(kind, _, code) => response::status_code(kind, *code),\n\t\t\t| Self::BadRequest(kind, ..) => response::bad_request_code(kind),\n\t\t\t| Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()),\n\t\t\t| Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),\n\t\t\t| Self::Conflict(_) => StatusCode::CONFLICT,\n\t\t\t| Self::Io(error) => response::io_error_code(error.kind()),\n\t\t\t| _ => StatusCode::INTERNAL_SERVER_ERROR,\n\t\t}\n\t}\n```"}], "func_name": "status_code", "docstring": "Returns the HTTP error code or closest approximation based on error\nvariant.", "repo": "girlbossceo/conduwuit", "path": "src/core/error/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/error/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6137c889264b086683e8d790adc90a8a6519666dfe6744ba05d9792bcd0955cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: features\n\nDocumentation:\nList of all possible features for the project. For *enabled* features in\nthis build see the companion function in info::rustc.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn features() -> &'static Vec {\n\tFEATURES.get_or_init(|| {\n\t\tinit_features().unwrap_or_else(|e| panic!(\"Failed initialize features: {e}\"))\n\t})\n}\n```"}], "func_name": "features", "docstring": "List of all possible features for the project. For *enabled* features in\nthis build see the companion function in info::rustc.", "repo": "girlbossceo/conduwuit", "path": "src/core/info/cargo.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/info/cargo.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "77aa372a081ed504d13a6c0bdedc99ac91c538578125333fb885200f1976da47"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: gen_event_id_canonical_json\n\nDocumentation:\nGenerates a correct eventId for the incoming pdu.\n\nReturns a tuple of the new `EventId` and the PDU as a `BTreeMap`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn gen_event_id_canonical_json(\n\tpdu: &RawJsonValue,\n\troom_version_id: &RoomVersionId,\n) -> Result<(OwnedEventId, CanonicalJsonObject)> {\n\tlet value: CanonicalJsonObject = serde_json::from_str(pdu.get())\n\t\t.map_err(|e| err!(BadServerResponse(warn!(\"Error parsing incoming event: {e:?}\"))))?;\n\n\tlet event_id = gen_event_id(&value, room_version_id)?;\n\n\tOk((event_id, value))\n}\n```"}], "func_name": "gen_event_id_canonical_json", "docstring": "Generates a correct eventId for the incoming pdu.\n\nReturns a tuple of the new `EventId` and the PDU as a `BTreeMap`.", "repo": "girlbossceo/conduwuit", "path": "src/core/matrix/pdu/event_id.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/matrix/pdu/event_id.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "10b43af89e43285af0895a599a4f3d16d37c42091fd734b37a3636865af1e6e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: gen_event_id\n\nDocumentation:\nGenerates a correct eventId for the incoming pdu.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn gen_event_id(\n\tvalue: &CanonicalJsonObject,\n\troom_version_id: &RoomVersionId,\n) -> Result {\n\tlet reference_hash = ruma::signatures::reference_hash(value, room_version_id)?;\n\tlet event_id: OwnedEventId = format!(\"${reference_hash}\").try_into()?;\n\n\tOk(event_id)\n}\n```"}], "func_name": "gen_event_id", "docstring": "Generates a correct eventId for the incoming pdu.", "repo": "girlbossceo/conduwuit", "path": "src/core/matrix/pdu/event_id.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/matrix/pdu/event_id.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81935251a16550a9df8c9938a381fb62e645ce3b3e46fd5fd9630236179467f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: auth_chain_diff\n\nDocumentation:\nReturns a vector representing the difference in auth chains of the given\n`events`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn auth_chain_diff(\n\t\t&self,\n\t\troom_id: &RoomId,\n\t\tevent_ids: Vec>,\n\t) -> Result> {\n\t\tlet mut auth_chain_sets = vec![];\n\t\tfor ids in event_ids {\n\t\t\t// TODO state store `auth_event_ids` returns self in the event ids list\n\t\t\t// when an event returns `auth_event_ids` self is not contained\n\t\t\tlet chain = self\n\t\t\t\t.auth_event_ids(room_id, ids)?\n\t\t\t\t.into_iter()\n\t\t\t\t.collect::>();\n\t\t\tauth_chain_sets.push(chain);\n\t\t}\n\n\t\tif let Some(first) = auth_chain_sets.first().cloned() {\n\t\t\tlet common = auth_chain_sets\n\t\t\t\t.iter()\n\t\t\t\t.skip(1)\n\t\t\t\t.fold(first, |a, b| a.intersection(b).cloned().collect::>());\n\n\t\t\tOk(auth_chain_sets\n\t\t\t\t.into_iter()\n\t\t\t\t.flatten()\n\t\t\t\t.filter(|id| !common.contains(id.borrow()))\n\t\t\t\t.collect())\n\t\t} else {\n\t\t\tOk(vec![])\n\t\t}\n\t}\n```"}], "func_name": "auth_chain_diff", "docstring": "Returns a vector representing the difference in auth chains of the given\n`events`.", "repo": "girlbossceo/conduwuit", "path": "src/core/matrix/state_res/benches.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/matrix/state_res/benches.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be87488fb84efd95753eca99d48fc97c973d7cc5e9d7229314a79b5a38893dd9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: auth_types_for_event\n\nDocumentation:\nFor the given event `kind` what are the relevant auth events that are needed\nto authenticate this `content`.\n\n# Errors\n\nThis function will return an error if the supplied `content` is not a JSON\nobject.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn auth_types_for_event(\n\tkind: &TimelineEventType,\n\tsender: &UserId,\n\tstate_key: Option<&str>,\n\tcontent: &RawJsonValue,\n) -> serde_json::Result> {\n\tif kind == &TimelineEventType::RoomCreate {\n\t\treturn Ok(vec![]);\n\t}\n\n\tlet mut auth_types = vec![\n\t\t(StateEventType::RoomPowerLevels, StateKey::new()),\n\t\t(StateEventType::RoomMember, sender.as_str().into()),\n\t\t(StateEventType::RoomCreate, StateKey::new()),\n\t];\n\n\tif kind == &TimelineEventType::RoomMember {\n\t\t#[derive(Deserialize)]\n\t\tstruct RoomMemberContentFields {\n\t\t\tmembership: Option>,\n\t\t\tthird_party_invite: Option>,\n\t\t\tjoin_authorised_via_users_server: Option>,\n\t\t}\n\n\t\tif let Some(state_key) = state_key {\n\t\t\tlet content: RoomMemberContentFields = from_json_str(content.get())?;\n\n\t\t\tif let Some(Ok(membership)) = content.membership.map(|m| m.deserialize()) {\n\t\t\t\tif [MembershipState::Join, MembershipState::Invite, MembershipState::Knock]\n\t\t\t\t\t.contains(&membership)\n\t\t\t\t{\n\t\t\t\t\tlet key = (StateEventType::RoomJoinRules, StateKey::new());\n\t\t\t\t\tif !auth_types.contains(&key) {\n\t\t\t\t\t\tauth_types.push(key);\n\t\t\t\t\t}\n\n\t\t\t\t\tif let Some(Ok(u)) = content\n\t\t\t\t\t\t.join_authorised_via_users_server\n\t\t\t\t\t\t.map(|m| m.deserialize())\n\t\t\t\t\t{\n\t\t\t\t\t\tlet key = (StateEventType::RoomMember, u.as_str().into());\n\t\t\t\t\t\tif !auth_types.contains(&key) {\n\t\t\t\t\t\t\tauth_types.push(key);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tlet key = (StateEventType::RoomMember, state_key.into());\n\t\t\t\tif !auth_types.contains(&key) {\n\t\t\t\t\tauth_types.push(key);\n\t\t\t\t}\n\n\t\t\t\tif membership == MembershipState::Invite {\n\t\t\t\t\tif let Some(Ok(t_id)) = content.third_party_invite.map(|t| t.deserialize()) {\n\t\t\t\t\t\tlet key =\n\t\t\t\t\t\t\t(StateEventType::RoomThirdPartyInvite, t_id.signed.token.into());\n\t\t\t\t\t\tif !auth_types.contains(&key) {\n\t\t\t\t\t\t\tauth_types.push(key);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tOk(auth_types)\n}\n```"}], "func_name": "auth_types_for_event", "docstring": "For the given event `kind` what are the relevant auth events that are needed\nto authenticate this `content`.\n\n# Errors\n\nThis function will return an error if the supplied `content` is not a JSON\nobject.", "repo": "girlbossceo/conduwuit", "path": "src/core/matrix/state_res/event_auth.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/matrix/state_res/event_auth.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d8a5ef39bcb36ae42fa603b465d5ee36a930dcc74c369d9b7328e33afa5686a9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: can_send_event\n\nDocumentation:\nIs the user allowed to send a specific event based on the rooms power\nlevels.\n\nDoes the event have the correct userId as its state_key if it's not the \"\"\nstate_key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn can_send_event(event: impl Event, ple: Option, user_level: Int) -> bool {\n\tlet event_type_power_level = get_send_level(event.event_type(), event.state_key(), ple);\n\n\tdebug!(\n\t\trequired_level = i64::from(event_type_power_level),\n\t\tuser_level = i64::from(user_level),\n\t\tstate_key = ?event.state_key(),\n\t\t\"permissions factors\",\n\t);\n\n\tif user_level < event_type_power_level {\n\t\treturn false;\n\t}\n\n\tif event.state_key().is_some_and(|k| k.starts_with('@'))\n\t\t&& event.state_key() != Some(event.sender().as_str())\n\t{\n\t\treturn false; // permission required to post in this room\n\t}\n\n\ttrue\n}\n```"}], "func_name": "can_send_event", "docstring": "Is the user allowed to send a specific event based on the rooms power\nlevels.\n\nDoes the event have the correct userId as its state_key if it's not the \"\"\nstate_key.", "repo": "girlbossceo/conduwuit", "path": "src/core/matrix/state_res/event_auth.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/matrix/state_res/event_auth.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48c9b3ebe34513d6f4fb8380fce7b6a938c78e498ce36f90c1b1820225511bb8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_power_levels\n\nDocumentation:\nConfirm that the event sender has the required power levels.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_power_levels(\n\troom_version: &RoomVersion,\n\tpower_event: impl Event,\n\tprevious_power_event: Option,\n\tuser_level: Int,\n) -> Option {\n\tmatch power_event.state_key() {\n\t\t| Some(\"\") => {},\n\t\t| Some(key) => {\n\t\t\terror!(state_key = key, \"m.room.power_levels event has non-empty state key\");\n\t\t\treturn None;\n\t\t},\n\t\t| None => {\n\t\t\terror!(\"check_power_levels requires an m.room.power_levels *state* event argument\");\n\t\t\treturn None;\n\t\t},\n\t}\n\n\t// - If any of the keys users_default, events_default, state_default, ban,\n\t// redact, kick, or invite in content are present and not an integer, reject.\n\t// - If either of the keys events or notifications in content are present and\n\t// not a dictionary with values that are integers, reject.\n\t// - If users key in content is not a dictionary with keys that are valid user\n\t// IDs with values that are integers, reject.\n\tlet user_content: RoomPowerLevelsEventContent =\n\t\tdeserialize_power_levels(power_event.content().get(), room_version)?;\n\n\t// Validation of users is done in Ruma, synapse for loops validating user_ids\n\t// and integers here\n\tdebug!(\"validation of power event finished\");\n\n\t#[allow(clippy::manual_let_else)]\n\tlet current_state = match previous_power_event {\n\t\t| Some(current_state) => current_state,\n\t\t// If there is no previous m.room.power_levels event in the room, allow\n\t\t| None => return Some(true),\n\t};\n\n\tlet current_content: RoomPowerLevelsEventContent =\n\t\tdeserialize_power_levels(current_state.content().get(), room_version)?;\n\n\tlet mut user_levels_to_check = BTreeSet::new();\n\tlet old_list = ¤t_content.users;\n\tlet user_list = &user_content.users;\n\tfor user in old_list.keys().chain(user_list.keys()) {\n\t\tlet user: &UserId = user;\n\t\tuser_levels_to_check.insert(user);\n\t}\n\n\ttrace!(set = ?user_levels_to_check, \"user levels to check\");\n\n\tlet mut event_levels_to_check = BTreeSet::new();\n\tlet old_list = ¤t_content.events;\n\tlet new_list = &user_content.events;\n\tfor ev_id in old_list.keys().chain(new_list.keys()) {\n\t\tevent_levels_to_check.insert(ev_id);\n\t}\n\n\ttrace!(set = ?event_levels_to_check, \"event levels to check\");\n\n\tlet old_state = ¤t_content;\n\tlet new_state = &user_content;\n\n\t// synapse does not have to split up these checks since we can't combine UserIds\n\t// and EventTypes we do 2 loops\n\n\t// UserId loop\n\tfor user in user_levels_to_check {\n\t\tlet old_level = old_state.users.get(user);\n\t\tlet new_level = new_state.users.get(user);\n\t\tif old_level.is_some() && new_level.is_some() && old_level == new_level {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// If the current value is equal to the sender's current power level, reject\n\t\tif user != power_event.sender() && old_level == Some(&user_level) {\n\t\t\twarn!(\"m.room.power_level cannot remove ops == to own\");\n\t\t\treturn Some(false); // cannot remove ops level == to own\n\t\t}\n\n\t\t// If the current value is higher than the sender's current power level, reject\n\t\t// If the new value is higher than the sender's current power level, reject\n\t\tlet old_level_too_big = old_level > Some(&user_level);\n\t\tlet new_level_too_big = new_level > Some(&user_level);\n\t\tif old_level_too_big || new_level_too_big {\n\t\t\twarn!(\"m.room.power_level failed to add ops > than own\");\n\t\t\treturn Some(false); // cannot add ops greater than own\n\t\t}\n\t}\n\n\t// EventType loop\n\tfor ev_type in event_levels_to_check {\n\t\tlet old_level = old_state.events.get(ev_type);\n\t\tlet new_level = new_state.events.get(ev_type);\n\t\tif old_level.is_some() && new_level.is_some() && old_level == new_level {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// If the current value is higher than the sender's current power level, reject\n\t\t// If the new value is higher than the sender's current power level, reject\n\t\tlet old_level_too_big = old_level > Some(&user_level);\n\t\tlet new_level_too_big = new_level > Some(&user_level);\n\t\tif old_level_too_big || new_level_too_big {\n\t\t\twarn!(\"m.room.power_level failed to add ops > than own\");\n\t\t\treturn Some(false); // cannot add ops greater than own\n\t\t}\n\t}\n\n\t// Notifications, currently there is only @room\n\tif room_version.limit_notifications_power_levels {\n\t\tlet old_level = old_state.notifications.room;\n\t\tlet new_level = new_state.notifications.room;\n\t\tif old_level != new_level {\n\t\t\t// If the current value is higher than the sender's current power level, reject\n\t\t\t// If the new value is higher than the sender's current power level, reject\n\t\t\tlet old_level_too_big = old_level > user_level;\n\t\t\tlet new_level_too_big = new_level > user_level;\n\t\t\tif old_level_too_big || new_level_too_big {\n\t\t\t\twarn!(\"m.room.power_level failed to add ops > than own\");\n\t\t\t\treturn Some(false); // cannot add ops greater than own\n\t\t\t}\n\t\t}\n\t}\n\n\tlet levels = [\n\t\t\"users_default\",\n\t\t\"events_default\",\n\t\t\"state_default\",\n\t\t\"ban\",\n\t\t\"redact\",\n\t\t\"kick\",\n\t\t\"invite\",\n\t];\n\tlet old_state = serde_json::to_value(old_state).unwrap();\n\tlet new_state = serde_json::to_value(new_state).unwrap();\n\tfor lvl_name in &levels {\n\t\tif let Some((old_lvl, new_lvl)) = get_deserialize_levels(&old_state, &new_state, lvl_name)\n\t\t{\n\t\t\tlet old_level_too_big = old_lvl > user_level;\n\t\t\tlet new_level_too_big = new_lvl > user_level;\n\n\t\t\tif old_level_too_big || new_level_too_big {\n\t\t\t\twarn!(\"cannot add ops > than own\");\n\t\t\t\treturn Some(false);\n\t\t\t}\n\t\t}\n\t}\n\n\tSome(true)\n}\n```"}], "func_name": "check_power_levels", "docstring": "Confirm that the event sender has the required power levels.", "repo": "girlbossceo/conduwuit", "path": "src/core/matrix/state_res/event_auth.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/matrix/state_res/event_auth.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0c7fc33a147cc04ab4714f8acb85f7790dbada02f3f4f38cc69b6b9cde181eb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_redaction\n\nDocumentation:\nDoes the event redacting come from a user with enough power to redact the\ngiven event.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_redaction(\n\t_room_version: &RoomVersion,\n\tredaction_event: impl Event,\n\tuser_level: Int,\n\tredact_level: Int,\n) -> Result {\n\tif user_level >= redact_level {\n\t\tdebug!(\"redaction allowed via power levels\");\n\t\treturn Ok(true);\n\t}\n\n\t// If the domain of the event_id of the event being redacted is the same as the\n\t// domain of the event_id of the m.room.redaction, allow\n\tif redaction_event.event_id().borrow().server_name()\n\t\t== redaction_event\n\t\t\t.redacts()\n\t\t\t.as_ref()\n\t\t\t.and_then(|&id| id.borrow().server_name())\n\t{\n\t\tdebug!(\"redaction event allowed via room version 1 rules\");\n\t\treturn Ok(true);\n\t}\n\n\tOk(false)\n}\n```"}], "func_name": "check_redaction", "docstring": "Does the event redacting come from a user with enough power to redact the\ngiven event.", "repo": "girlbossceo/conduwuit", "path": "src/core/matrix/state_res/event_auth.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/matrix/state_res/event_auth.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b24f1f8bf1c426ddbc76cb69483d7033b52523f7431b84279fc3726f6a686e36"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_send_level\n\nDocumentation:\nHelper function to fetch the power level needed to send an event of type\n`e_type` based on the rooms \"m.room.power_level\" event.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_send_level(\n\te_type: &TimelineEventType,\n\tstate_key: Option<&str>,\n\tpower_lvl: Option,\n) -> Int {\n\tpower_lvl\n\t\t.and_then(|ple| {\n\t\t\tfrom_json_str::(ple.content().get())\n\t\t\t\t.map(|content| {\n\t\t\t\t\tcontent.events.get(e_type).copied().unwrap_or_else(|| {\n\t\t\t\t\t\tif state_key.is_some() {\n\t\t\t\t\t\t\tcontent.state_default\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcontent.events_default\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t\t.ok()\n\t\t})\n\t\t.unwrap_or_else(|| if state_key.is_some() { int!(50) } else { int!(0) })\n}\n```"}], "func_name": "get_send_level", "docstring": "Helper function to fetch the power level needed to send an event of type\n`e_type` based on the rooms \"m.room.power_level\" event.", "repo": "girlbossceo/conduwuit", "path": "src/core/matrix/state_res/event_auth.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/matrix/state_res/event_auth.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54c62e5cfa102b600a1abeda952efb79056491942a1b0b8c99f8513ec019a1ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: separate\n\nDocumentation:\nSplit the events that have no conflicts from those that are conflicting.\n\nThe return tuple looks like `(unconflicted, conflicted)`.\n\nState is determined to be conflicting if for the given key (StateEventType,\nStateKey) there is not exactly one event ID. This includes missing events,\nif one state_set includes an event that none of the other have this is a\nconflicting event.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn separate<'a, Id>(\n\tstate_sets_iter: impl Iterator>,\n) -> (StateMap, StateMap>)\nwhere\n\tId: Clone + Eq + Hash + 'a,\n{\n\tlet mut state_set_count: usize = 0;\n\tlet mut occurrences = HashMap::<_, HashMap<_, _>>::new();\n\n\tlet state_sets_iter =\n\t\tstate_sets_iter.inspect(|_| state_set_count = state_set_count.saturating_add(1));\n\tfor (k, v) in state_sets_iter.flatten() {\n\t\toccurrences\n\t\t\t.entry(k)\n\t\t\t.or_default()\n\t\t\t.entry(v)\n\t\t\t.and_modify(|x: &mut usize| *x = x.saturating_add(1))\n\t\t\t.or_insert(1);\n\t}\n\n\tlet mut unconflicted_state = StateMap::new();\n\tlet mut conflicted_state = StateMap::new();\n\n\tfor (k, v) in occurrences {\n\t\tfor (id, occurrence_count) in v {\n\t\t\tif occurrence_count == state_set_count {\n\t\t\t\tunconflicted_state.insert((k.0.clone(), k.1.clone()), id.clone());\n\t\t\t} else {\n\t\t\t\tconflicted_state\n\t\t\t\t\t.entry((k.0.clone(), k.1.clone()))\n\t\t\t\t\t.and_modify(|x: &mut Vec<_>| x.push(id.clone()))\n\t\t\t\t\t.or_insert_with(|| vec![id.clone()]);\n\t\t\t}\n\t\t}\n\t}\n\n\t(unconflicted_state, conflicted_state)\n}\n```"}], "func_name": "separate", "docstring": "Split the events that have no conflicts from those that are conflicting.\n\nThe return tuple looks like `(unconflicted, conflicted)`.\n\nState is determined to be conflicting if for the given key (StateEventType,\nStateKey) there is not exactly one event ID. This includes missing events,\nif one state_set includes an event that none of the other have this is a\nconflicting event.", "repo": "girlbossceo/conduwuit", "path": "src/core/matrix/state_res/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/matrix/state_res/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a244baa492936856f2f2841058770f36cf2ec7d2f4515799d24981836145def1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prepare\n\nDocumentation:\nCalled by Module::unload() to indicate module is about to be unloaded and\nstatic destruction is intended. This will allow verifying it actually took\nplace.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn prepare() {\n\tlet count = STATIC_DTORS.fetch_sub(1, ORDERING);\n\tdebug_assert!(count <= 0, \"STATIC_DTORS should not be greater than zero.\");\n}\n```"}], "func_name": "prepare", "docstring": "Called by Module::unload() to indicate module is about to be unloaded and\nstatic destruction is intended. This will allow verifying it actually took\nplace.", "repo": "girlbossceo/conduwuit", "path": "src/core/mods/canary.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/mods/canary.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a42f7027df80ce4558908bf62c21eba51757e86aad94027f9a8e140810594c52"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_content_disposition\n\nDocumentation:\ncreates the final Content-Disposition based on whether the filename exists\nor not, or if a requested filename was specified (media download with\nfilename)\n\nif filename exists:\n`Content-Disposition: attachment/inline; filename=filename.ext`\n\nelse: `Content-Disposition: attachment/inline`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn make_content_disposition(\n\tcontent_disposition: Option<&ContentDisposition>,\n\tcontent_type: Option<&str>,\n\tfilename: Option<&str>,\n) -> ContentDisposition {\n\tContentDisposition::new(content_disposition_type(content_type)).with_filename(\n\t\tfilename\n\t\t\t.or_else(|| {\n\t\t\t\tcontent_disposition\n\t\t\t\t\t.and_then(|content_disposition| content_disposition.filename.as_deref())\n\t\t\t})\n\t\t\t.map(sanitise_filename),\n\t)\n}\n```"}], "func_name": "make_content_disposition", "docstring": "creates the final Content-Disposition based on whether the filename exists\nor not, or if a requested filename was specified (media download with\nfilename)\n\nif filename exists:\n`Content-Disposition: attachment/inline; filename=filename.ext`\n\nelse: `Content-Disposition: attachment/inline`", "repo": "girlbossceo/conduwuit", "path": "src/core/utils/content_disposition.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/utils/content_disposition.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c1c0afe4c2206a56b4d8a699f236b697a2cbe33de6e25fb11ae9f5ebc6414c17"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: slice_truncated\n\nDocumentation:\nSee [`TruncatedSlice`]. Useful for `#[instrument]`:\n\n```\nuse conduwuit_core::utils::debug::slice_truncated;\n\n#[tracing::instrument(fields(foos = slice_truncated(foos, 42)))]\nfn bar(foos: &[&str]);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn slice_truncated(\n\tslice: &[T],\n\tmax_len: usize,\n) -> tracing::field::DebugValue> {\n\ttracing::field::debug(TruncatedSlice { inner: slice, max_len })\n}\n```"}], "func_name": "slice_truncated", "docstring": "See [`TruncatedSlice`]. Useful for `#[instrument]`:\n\n```\nuse conduwuit_core::utils::debug::slice_truncated;\n\n#[tracing::instrument(fields(foos = slice_truncated(foos, 42)))]\nfn bar(foos: &[&str]);\n```", "repo": "girlbossceo/conduwuit", "path": "src/core/utils/debug.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/utils/debug.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "697a2acf0665ac285cdee1ac91441423354f1c0ac49a405a8adbf6e23a4170ef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_canonical_object\n\nDocumentation:\nFallible conversion from any value that implements `Serialize` to a\n`CanonicalJsonObject`.\n\n`value` must serialize to an `serde_json::Value::Object`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_canonical_object(\n\tvalue: T,\n) -> Result {\n\tuse serde::ser::Error;\n\n\tmatch serde_json::to_value(value).map_err(CanonicalJsonError::SerDe)? {\n\t\t| serde_json::Value::Object(map) => try_from_json_map(map),\n\t\t| _ =>\n\t\t\tErr(CanonicalJsonError::SerDe(serde_json::Error::custom(\"Value must be an object\"))),\n\t}\n}\n```"}], "func_name": "to_canonical_object", "docstring": "Fallible conversion from any value that implements `Serialize` to a\n`CanonicalJsonObject`.\n\n`value` must serialize to an `serde_json::Value::Object`.", "repo": "girlbossceo/conduwuit", "path": "src/core/utils/json.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/utils/json.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3107f6cdf70165535b851eefd39f5bf35c2ace2f2dc734af8eefde7d83988a97"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: intersection\n\nDocumentation:\nIntersection of sets\n\nOutputs the set of elements common to all input sets. Inputs do not have to\nbe sorted. If inputs are sorted a more optimized function is available in\nthis suite and should be used.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn intersection(mut input: Iters) -> impl Iterator + Send\nwhere\n\tIters: Iterator + Clone + Send,\n\tIter: Iterator + Send,\n\tItem: Eq,\n{\n\tinput.next().into_iter().flat_map(move |first| {\n\t\tlet input = input.clone();\n\t\tfirst.filter(move |targ| {\n\t\t\tinput\n\t\t\t\t.clone()\n\t\t\t\t.all(|mut other| other.any(is_equal_to!(*targ)))\n\t\t})\n\t})\n}\n```"}], "func_name": "intersection", "docstring": "Intersection of sets\n\nOutputs the set of elements common to all input sets. Inputs do not have to\nbe sorted. If inputs are sorted a more optimized function is available in\nthis suite and should be used.", "repo": "girlbossceo/conduwuit", "path": "src/core/utils/set.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/utils/set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d3c52c7267cf6f3d3eba0c77cd15bbe97c49f9275ed0c13046f4d7b044b4e903"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: intersection_sorted\n\nDocumentation:\nIntersection of sets\n\nOutputs the set of elements common to all input sets. Inputs must be sorted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn intersection_sorted(\n\tmut input: Iters,\n) -> impl Iterator + Send\nwhere\n\tIters: Iterator + Clone + Send,\n\tIter: Iterator + Send,\n\tItem: Eq + Ord,\n{\n\tinput.next().into_iter().flat_map(move |first| {\n\t\tlet mut input = input.clone().collect::>();\n\t\tfirst.filter(move |targ| {\n\t\t\tinput.iter_mut().all(|it| {\n\t\t\t\tit.by_ref()\n\t\t\t\t\t.skip_while(is_less_than!(targ))\n\t\t\t\t\t.peekable()\n\t\t\t\t\t.peek()\n\t\t\t\t\t.is_some_and(is_equal_to!(targ))\n\t\t\t})\n\t\t})\n\t})\n}\n```"}], "func_name": "intersection_sorted", "docstring": "Intersection of sets\n\nOutputs the set of elements common to all input sets. Inputs must be sorted.", "repo": "girlbossceo/conduwuit", "path": "src/core/utils/set.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/utils/set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "082cdc4703d38c383c97e4aad8b5c631f6fa576dcf7b487580d139ed6d73ca9a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: intersection_sorted_stream2\n\nDocumentation:\nIntersection of sets\n\nOutputs the set of elements common to both streams. Streams must be sorted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn intersection_sorted_stream2(a: S, b: S) -> impl Stream + Send\nwhere\n\tS: Stream + Send + Unpin,\n\tItem: Eq + PartialOrd + Send + Sync,\n{\n\tuse tokio::sync::Mutex;\n\n\tlet b = Arc::new(Mutex::new(b.peekable()));\n\ta.map(move |ai| (ai, b.clone()))\n\t\t.filter_map(|(ai, b)| async move {\n\t\t\tlet mut lock = b.lock().await;\n\t\t\twhile let Some(bi) = Pin::new(&mut *lock).next_if(|bi| *bi <= ai).await.as_ref() {\n\t\t\t\tif ai == *bi {\n\t\t\t\t\treturn Some(ai);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tNone\n\t\t})\n}\n```"}], "func_name": "intersection_sorted_stream2", "docstring": "Intersection of sets\n\nOutputs the set of elements common to both streams. Streams must be sorted.", "repo": "girlbossceo/conduwuit", "path": "src/core/utils/set.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/utils/set.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4257b487b9f50b82447f80028f4e2df93967a640bd41cc911904aa322b7d58f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: current_exe\n\nDocumentation:\nReturn a possibly corrected std::env::current_exe() even if the path is\nmarked deleted.\n\n# Safety\nThis function is declared unsafe because the original result was altered for\nsecurity purposes, and altering it back ignores those urposes and should be\nunderstood by the user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub unsafe fn current_exe() -> Result {\n\tlet exe = std::env::current_exe()?;\n\tmatch exe.to_str() {\n\t\t| None => Ok(exe),\n\t\t| Some(str) => Ok(str\n\t\t\t.strip_suffix(\" (deleted)\")\n\t\t\t.map(PathBuf::from)\n\t\t\t.unwrap_or(exe)),\n\t}\n}\n```"}], "func_name": "current_exe", "docstring": "Return a possibly corrected std::env::current_exe() even if the path is\nmarked deleted.\n\n# Safety\nThis function is declared unsafe because the original result was altered for\nsecurity purposes, and altering it back ignores those urposes and should be\nunderstood by the user.", "repo": "girlbossceo/conduwuit", "path": "src/core/utils/sys.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/utils/sys.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a9779b36c340faabe768a0dc5c756161e2e02525d632f52209bd4496ba034ba4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: smt_siblings\n\nDocumentation:\nList the cores sharing SMT-tier resources\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn smt_siblings() -> impl Iterator {\n\tfrom_mask(get_affinity().fold(0_u128, |mask, id| {\n\t\tmask | SMT_TOPOLOGY.get(id).expect(\"ID must not exceed max cpus\")\n\t}))\n}\n```"}], "func_name": "smt_siblings", "docstring": "List the cores sharing SMT-tier resources", "repo": "girlbossceo/conduwuit", "path": "src/core/utils/sys/compute.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/utils/sys/compute.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea3c4adf1efcad3b0346bb8b7eda171fd1732bcb031db06d7b53bcbd9b1879f9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: node_siblings\n\nDocumentation:\nList the cores sharing Node-tier resources relative to this threads current\naffinity.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn node_siblings() -> impl Iterator {\n\tfrom_mask(get_affinity().fold(0_u128, |mask, id| {\n\t\tmask | NODE_TOPOLOGY.get(id).expect(\"Id must not exceed max cpus\")\n\t}))\n}\n```"}], "func_name": "node_siblings", "docstring": "List the cores sharing Node-tier resources relative to this threads current\naffinity.", "repo": "girlbossceo/conduwuit", "path": "src/core/utils/sys/compute.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/utils/sys/compute.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "187ec453ff808097036258326586e063591020b8492b5cd0789991fd71d4bd70"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: queue_parallelism\n\nDocumentation:\nGet device queue characteristics by mq path on sysfs(5)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn queue_parallelism(dir: &Path) -> Queue {\n\tlet queue_id = dir.file_name();\n\n\tlet nr_tags_path = dir.join(\"nr_tags\");\n\n\tlet cpu_list_path = dir.join(\"cpu_list\");\n\n\tQueue {\n\t\tid: queue_id\n\t\t\t.and_then(OsStr::to_str)\n\t\t\t.map(str::parse)\n\t\t\t.flat_ok()\n\t\t\t.expect(\"queue has some numerical identifier\"),\n\n\t\tnr_tags: read_to_string(&nr_tags_path)\n\t\t\t.ok()\n\t\t\t.as_deref()\n\t\t\t.map(str::trim)\n\t\t\t.map(str::parse)\n\t\t\t.flat_ok(),\n\n\t\tcpu_list: read_to_string(&cpu_list_path)\n\t\t\t.iter()\n\t\t\t.flat_map(|list| list.trim().split(','))\n\t\t\t.map(str::trim)\n\t\t\t.map(str::parse)\n\t\t\t.filter_map(Result::ok)\n\t\t\t.collect(),\n\t}\n}\n```"}], "func_name": "queue_parallelism", "docstring": "Get device queue characteristics by mq path on sysfs(5)", "repo": "girlbossceo/conduwuit", "path": "src/core/utils/sys/storage.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/utils/sys/storage.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c21b57fee4533b98a068f8ecf70c31e022308bb8f14a4eab6f533b259e677638"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: name_from_path\n\nDocumentation:\nGet the name of the block device on which Path is mounted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn name_from_path(path: &Path) -> Result {\n\tuse std::io::{Error, ErrorKind::NotFound};\n\n\tlet (major, minor) = dev_from_path(path)?;\n\tlet path = block_path((major, minor)).join(\"uevent\");\n\tread_to_string(path)\n\t\t.iter()\n\t\t.map(String::as_str)\n\t\t.flat_map(str::lines)\n\t\t.map(|line| line.split_once_infallible(\"=\"))\n\t\t.find_map(|(key, val)| (key == \"DEVNAME\").then_some(val))\n\t\t.ok_or_else(|| Error::new(NotFound, \"DEVNAME not found.\"))\n\t\t.map_err(Into::into)\n\t\t.map(Into::into)\n}\n```"}], "func_name": "name_from_path", "docstring": "Get the name of the block device on which Path is mounted.", "repo": "girlbossceo/conduwuit", "path": "src/core/utils/sys/storage.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/core/utils/sys/storage.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8b9431b93291cc5fa5a8be8a99e8166dc58317651dad620b406d545e95d33738"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finished\n\nDocumentation:\nDetermine if the input was fully consumed and error if bytes remaining.\nThis is intended for debug assertions; not optimized for parsing logic.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn finished(&self) -> Result<()> {\n\t\tlet pos = self.pos;\n\t\tlet len = self.buf.len();\n\t\tlet parsed = &self.buf[0..pos];\n\t\tlet unparsed = &self.buf[pos..];\n\t\tlet remain = self.remaining()?;\n\t\tlet trailing_sep = remain == 1 && unparsed[0] == Self::SEP;\n\t\t(remain == 0 || trailing_sep)\n\t\t\t.then_some(())\n\t\t\t.ok_or(err!(SerdeDe(\n\t\t\t\t\"{remain} trailing of {len} bytes not deserialized.\\n{parsed:?}\\n{unparsed:?}\",\n\t\t\t)))\n\t}\n```"}], "func_name": "finished", "docstring": "Determine if the input was fully consumed and error if bytes remaining.\nThis is intended for debug assertions; not optimized for parsing logic.", "repo": "girlbossceo/conduwuit", "path": "src/database/de.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/database/de.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dca994360047fcbec7ef78687e222741fa93540d08c38ef247eb9ac54491503e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: property_integer\n\nDocumentation:\nQuery for database property by null-terminated name which is expected to\nhave a result with an integer representation. This is intended for\nlow-overhead programmatic use.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn property_integer(\n\t\t&self,\n\t\tcf: &impl AsColumnFamilyRef,\n\t\tname: &CStr,\n\t) -> Result {\n\t\tresult(self.db.property_int_value_cf(cf, name))\n\t\t\t.and_then(|val| val.map_or_else(|| Err!(\"Property {name:?} not found.\"), Ok))\n\t}\n```"}], "func_name": "property_integer", "docstring": "Query for database property by null-terminated name which is expected to\nhave a result with an integer representation. This is intended for\nlow-overhead programmatic use.", "repo": "girlbossceo/conduwuit", "path": "src/database/engine.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/database/engine.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "006f616307dce9141e341cfb13b05dfb10e1b79d1e50572322b97209bfbd1f80"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: property\n\nDocumentation:\nQuery for database property by name receiving the result in a string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn property(&self, cf: &impl AsColumnFamilyRef, name: &str) -> Result {\n\t\tresult(self.db.property_value_cf(cf, name))\n\t\t\t.and_then(|val| val.map_or_else(|| Err!(\"Property {name:?} not found.\"), Ok))\n\t}\n```"}], "func_name": "property", "docstring": "Query for database property by name receiving the result in a string.", "repo": "girlbossceo/conduwuit", "path": "src/database/engine.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/database/engine.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "897fd019dcee5df99449dea4d72502005436a253ecc34e48969251c1330d8218"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open\n\nDocumentation:\nLoad an existing database or create a new one.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn open(server: &Arc) -> Result> {\n\t\tlet ctx = Context::new(server)?;\n\t\tlet db = Engine::open(ctx.clone(), maps::MAPS).await?;\n\t\tOk(Arc::new(Self {\n\t\t\tmaps: maps::open(&db)?,\n\t\t\tdb: db.clone(),\n\t\t\t_ctx: ctx,\n\t\t}))\n\t}\n```"}], "func_name": "open", "docstring": "Load an existing database or create a new one.", "repo": "girlbossceo/conduwuit", "path": "src/database/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e59e1fe4422bdccc9fcd6a66e8ee8e3b2f8e46f9ff51c848a6a25cfc09327963"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cf_options\n\nDocumentation:\nAdjust options for the specific column by name. Provide the result of\ndb_options() as the argument to this function and use the return value in\nthe arguments to open the specific column.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn cf_options(ctx: &Context, opts: Options, desc: &Descriptor) -> Result {\n\tlet cache = get_cache(ctx, desc);\n\tlet config = &ctx.server.config;\n\tdescriptor_cf_options(opts, *desc, config, cache.as_ref())\n}\n```"}], "func_name": "cf_options", "docstring": "Adjust options for the specific column by name. Provide the result of\ndb_options() as the argument to this function and use the return value in\nthe arguments to open the specific column.", "repo": "girlbossceo/conduwuit", "path": "src/database/engine/cf_opts.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/database/engine/cf_opts.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "64d89abdfd348c8b4d262fb699b0a3391ab013f7255b7ba1c109fce1695e6795"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: db_options\n\nDocumentation:\nCreate database-wide options suitable for opening the database. This also\nsets our default column options in case of opening a column with the same\nresulting value. Note that we require special per-column options on some\ncolumns, therefor columns should only be opened after passing this result\nthrough cf_options().\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn db_options(config: &Config, env: &Env, row_cache: &Cache) -> Result {\n\tconst DEFAULT_STATS_LEVEL: StatsLevel = if cfg!(debug_assertions) {\n\t\tStatsLevel::ExceptDetailedTimers\n\t} else {\n\t\tStatsLevel::DisableAll\n\t};\n\n\tlet mut opts = Options::default();\n\n\t// Logging\n\tset_logging_defaults(&mut opts, config);\n\n\t// Processing\n\topts.set_max_background_jobs(num_threads::(config)?);\n\topts.set_max_subcompactions(num_threads::(config)?);\n\topts.set_avoid_unnecessary_blocking_io(true);\n\topts.set_max_file_opening_threads(0);\n\n\t// IO\n\topts.set_manual_wal_flush(true);\n\topts.set_atomic_flush(config.rocksdb_atomic_flush);\n\topts.set_enable_pipelined_write(!config.rocksdb_atomic_flush);\n\tif config.rocksdb_direct_io {\n\t\topts.set_use_direct_reads(true);\n\t\topts.set_use_direct_io_for_flush_and_compaction(true);\n\t}\n\tif config.rocksdb_optimize_for_spinning_disks {\n\t\t// speeds up opening DB on hard drives\n\t\topts.set_skip_checking_sst_file_sizes_on_db_open(true);\n\t\topts.set_skip_stats_update_on_db_open(true);\n\t\t//opts.set_max_file_opening_threads(threads.try_into().unwrap());\n\t} else {\n\t\topts.set_compaction_readahead_size(1024 * 512);\n\t}\n\n\t// Blocks\n\topts.set_row_cache(row_cache);\n\topts.set_db_write_buffer_size(cache_size_f64(\n\t\tconfig,\n\t\tconfig.db_write_buffer_capacity_mb,\n\t\t1_048_576,\n\t));\n\n\t// Files\n\topts.set_table_cache_num_shard_bits(7);\n\topts.set_wal_size_limit_mb(1024);\n\topts.set_max_total_wal_size(1024 * 1024 * 512);\n\topts.set_writable_file_max_buffer_size(1024 * 1024 * 2);\n\n\t// Misc\n\topts.set_disable_auto_compactions(!config.rocksdb_compaction);\n\topts.create_missing_column_families(true);\n\topts.create_if_missing(true);\n\n\topts.set_statistics_level(match config.rocksdb_stats_level {\n\t\t| 0 => StatsLevel::DisableAll,\n\t\t| 1 => DEFAULT_STATS_LEVEL,\n\t\t| 2 => StatsLevel::ExceptHistogramOrTimers,\n\t\t| 3 => StatsLevel::ExceptTimers,\n\t\t| 4 => StatsLevel::ExceptDetailedTimers,\n\t\t| 5 => StatsLevel::ExceptTimeForMutex,\n\t\t| 6_u8..=u8::MAX => StatsLevel::All,\n\t});\n\n\topts.set_report_bg_io_stats(match config.rocksdb_stats_level {\n\t\t| 0..=1 => false,\n\t\t| 2_u8..=u8::MAX => true,\n\t});\n\n\t// Default: https://github.com/facebook/rocksdb/wiki/WAL-Recovery-Modes#ktoleratecorruptedtailrecords\n\t//\n\t// Unclean shutdowns of a Matrix homeserver are likely to be fine when\n\t// recovered in this manner as it's likely any lost information will be\n\t// restored via federation.\n\topts.set_wal_recovery_mode(match config.rocksdb_recovery_mode {\n\t\t| 0 => DBRecoveryMode::AbsoluteConsistency,\n\t\t| 1 => DBRecoveryMode::TolerateCorruptedTailRecords,\n\t\t| 2 => DBRecoveryMode::PointInTime,\n\t\t| 3 => DBRecoveryMode::SkipAnyCorruptedRecord,\n\t\t| 4_u8..=u8::MAX => unimplemented!(),\n\t});\n\n\t// \n\t// \"We recommend to set track_and_verify_wals_in_manifest to true for\n\t// production, it has been enabled in production for the entire database cluster\n\t// serving the social graph for all Meta apps.\"\n\topts.set_track_and_verify_wals_in_manifest(true);\n\n\topts.set_paranoid_checks(config.rocksdb_paranoid_file_checks);\n\n\topts.set_env(env);\n\n\tOk(opts)\n}\n```"}], "func_name": "db_options", "docstring": "Create database-wide options suitable for opening the database. This also\nsets our default column options in case of opening a column with the same\nresulting value. Note that we require special per-column options on some\ncolumns, therefor columns should only be opened after passing this result\nthrough cf_options().", "repo": "girlbossceo/conduwuit", "path": "src/database/engine/db_opts.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/database/engine/db_opts.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "659ce0b43fea04be0894ee6574cd3fdfc2c5019e6a9cf24f9d1fa5a0b97c1a71"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update\n\nDocumentation:\nSynthesize any command line options with configuration file options.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn update(mut config: Figment, args: &Args) -> Result {\n\tif args.read_only {\n\t\tconfig = config.join((\"rocksdb_read_only\", true));\n\t}\n\n\tif args.maintenance || args.read_only {\n\t\tconfig = config.join((\"startup_netburst\", false));\n\t\tconfig = config.join((\"listening\", false));\n\t}\n\n\t#[cfg(feature = \"console\")]\n\t// Indicate the admin console should be spawned automatically if the\n\t// configuration file hasn't already.\n\tif args.console {\n\t\tconfig = config.join((\"admin_console_automatic\", true));\n\t}\n\n\t// Execute commands after any commands listed in configuration file\n\tconfig = config.adjoin((\"admin_execute\", &args.execute));\n\n\t// Update config with names of any functional-tests\n\tconfig = config.adjoin((\"test\", &args.test));\n\n\t// All other individual overrides can go last in case we have options which\n\t// set multiple conf items at once and the user still needs granular overrides.\n\tfor option in &args.option {\n\t\tlet (key, val) = option\n\t\t\t.split_once('=')\n\t\t\t.ok_or_else(|| err!(\"Missing '=' in -O/--option: {option:?}\"))?;\n\n\t\tif key.is_empty() {\n\t\t\treturn Err!(\"Missing key= in -O/--option: {option:?}\");\n\t\t}\n\n\t\tif val.is_empty() {\n\t\t\treturn Err!(\"Missing =val in -O/--option: {option:?}\");\n\t\t}\n\n\t\t// The value has to pass for what would appear as a line in the TOML file.\n\t\tlet val = toml::from_str::(option)?;\n\t\tlet FigmentValue::Dict(_, val) = val else {\n\t\t\tpanic!(\"Unexpected Figment Value: {val:#?}\");\n\t\t};\n\n\t\t// Figment::merge() overrides existing\n\t\tconfig = config.merge((key, val[key].clone()));\n\t}\n\n\tOk(config)\n}\n```"}], "func_name": "update", "docstring": "Synthesize any command line options with configuration file options.", "repo": "girlbossceo/conduwuit", "path": "src/main/clap.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/main/clap.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d47ad3dd1ee5990d9a5b5d9633716103835c6f94229274a4ccccea146b5a927a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_worker\n\nDocumentation:\nStart the worker in a task for the service.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn start_worker(\n\t\t&self,\n\t\tworkers: &mut WorkersLocked<'_>,\n\t\tservice: &Arc,\n\t) -> Result<()> {\n\t\tif !self.server.running() {\n\t\t\treturn Err!(\n\t\t\t\t\"Service {:?} worker not starting during server shutdown.\",\n\t\t\t\tservice.name()\n\t\t\t);\n\t\t}\n\n\t\tdebug!(\"Service {:?} worker starting...\", service.name());\n\t\tworkers.spawn_on(worker(service.clone()), self.server.runtime());\n\n\t\tOk(())\n\t}\n```"}], "func_name": "start_worker", "docstring": "Start the worker in a task for the service.", "repo": "girlbossceo/conduwuit", "path": "src/service/manager.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/manager.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b4666f68abbc9516c88ab3df89a89693721fcbe8135d71f38fbe2bbff5f51f9b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReference a Service by name. Returns None if the Service does not exist, but\npanics if incorrectly cast.\n\n# Panics\nIncorrect type is not a silent failure (None) as the type never has a reason\nto be incorrect.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn get(map: &Map, name: &str) -> Option>\nwhere\n\tT: Any + Send + Sync + Sized,\n{\n\tmap.read()\n\t\t.expect(\"locked for reading\")\n\t\t.get(name)\n\t\t.map(|(_, s)| {\n\t\t\ts.upgrade().map(|s| {\n\t\t\t\ts.downcast::()\n\t\t\t\t\t.expect(\"Service must be correctly downcast.\")\n\t\t\t})\n\t\t})?\n}\n```"}], "func_name": "get", "docstring": "Reference a Service by name. Returns None if the Service does not exist, but\npanics if incorrectly cast.\n\n# Panics\nIncorrect type is not a silent failure (None) as the type never has a reason\nto be incorrect.", "repo": "girlbossceo/conduwuit", "path": "src/service/service.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/service.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "753d6c509320dfb07a49dafddfde9ab01bd93469b723a9f3e2bee58bfcde8094"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_get\n\nDocumentation:\nReference a Service by name. Returns Err if the Service does not exist or\nwas incorrectly cast.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn try_get(map: &Map, name: &str) -> Result>\nwhere\n\tT: Any + Send + Sync + Sized,\n{\n\tmap.read()\n\t\t.expect(\"locked for reading\")\n\t\t.get(name)\n\t\t.map_or_else(\n\t\t\t|| Err!(\"Service {name:?} does not exist or has not been built yet.\"),\n\t\t\t|(_, s)| {\n\t\t\t\ts.upgrade().map_or_else(\n\t\t\t\t\t|| Err!(\"Service {name:?} no longer exists.\"),\n\t\t\t\t\t|s| {\n\t\t\t\t\t\ts.downcast::()\n\t\t\t\t\t\t\t.map_err(|_| err!(\"Service {name:?} must be correctly downcast.\"))\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t},\n\t\t)\n}\n```"}], "func_name": "try_get", "docstring": "Reference a Service by name. Returns Err if the Service does not exist or\nwas incorrectly cast.", "repo": "girlbossceo/conduwuit", "path": "src/service/service.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/service.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b288259ca957b142eb9fb97487f4c8f31757b9c2e6585327bb98cf202ce6a1c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: services\n\nDocumentation:\nIterate from snapshot of the services map\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn services(&self) -> impl Stream> + Send {\n\t\tself.service\n\t\t\t.read()\n\t\t\t.expect(\"locked for reading\")\n\t\t\t.values()\n\t\t\t.filter_map(|val| val.0.upgrade())\n\t\t\t.collect::>()\n\t\t\t.into_iter()\n\t\t\t.stream()\n\t}\n```"}], "func_name": "services", "docstring": "Iterate from snapshot of the services map", "repo": "girlbossceo/conduwuit", "path": "src/service/services.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/services.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a668e74549d2be9dbe754ba8e360374e53f5be26f173ceb72cd6865819ef5b96"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_err\n\nDocumentation:\nStandalone/static markdown printer for errors.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn print_err(markdown: &str) {\n\tlet output = configure_output_err(MadSkin::default_dark());\n\toutput.print_text(markdown);\n}\n```"}], "func_name": "print_err", "docstring": "Standalone/static markdown printer for errors.", "repo": "girlbossceo/conduwuit", "path": "src/service/admin/console.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/admin/console.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb29a73485ad2b5c7babde0c875ae58fae0eb3452915849f59c43f65f1ceced0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_admin_room\n\nDocumentation:\nCreate the admin room.\n\nUsers in this room are considered admins by conduwuit, and the room can be\nused to issue admin commands by talking to the server user inside it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn create_admin_room(services: &Services) -> Result {\n\tlet room_id = RoomId::new(services.globals.server_name());\n\tlet room_version = &services.config.default_room_version;\n\n\tlet _short_id = services\n\t\t.rooms\n\t\t.short\n\t\t.get_or_create_shortroomid(&room_id)\n\t\t.await;\n\n\tlet state_lock = services.rooms.state.mutex.lock(&room_id).await;\n\n\t// Create a user for the server\n\tlet server_user = services.globals.server_user.as_ref();\n\tservices.users.create(server_user, None)?;\n\n\tlet create_content = {\n\t\tuse RoomVersionId::*;\n\t\tmatch room_version {\n\t\t\t| V1 | V2 | V3 | V4 | V5 | V6 | V7 | V8 | V9 | V10 =>\n\t\t\t\tRoomCreateEventContent::new_v1(server_user.into()),\n\t\t\t| _ => RoomCreateEventContent::new_v11(),\n\t\t}\n\t};\n\n\t// 1. The room create event\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(String::new(), &RoomCreateEventContent {\n\t\t\t\tfederate: true,\n\t\t\t\tpredecessor: None,\n\t\t\t\troom_version: room_version.clone(),\n\t\t\t\t..create_content\n\t\t\t}),\n\t\t\tserver_user,\n\t\t\t&room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\t// 2. Make server user/bot join\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(\n\t\t\t\tString::from(server_user),\n\t\t\t\t&RoomMemberEventContent::new(MembershipState::Join),\n\t\t\t),\n\t\t\tserver_user,\n\t\t\t&room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\t// 3. Power levels\n\tlet users = BTreeMap::from_iter([(server_user.into(), 69420.into())]);\n\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(String::new(), &RoomPowerLevelsEventContent {\n\t\t\t\tusers,\n\t\t\t\t..Default::default()\n\t\t\t}),\n\t\t\tserver_user,\n\t\t\t&room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\t// 4.1 Join Rules\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(String::new(), &RoomJoinRulesEventContent::new(JoinRule::Invite)),\n\t\t\tserver_user,\n\t\t\t&room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\t// 4.2 History Visibility\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(\n\t\t\t\tString::new(),\n\t\t\t\t&RoomHistoryVisibilityEventContent::new(HistoryVisibility::Shared),\n\t\t\t),\n\t\t\tserver_user,\n\t\t\t&room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\t// 4.3 Guest Access\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(\n\t\t\t\tString::new(),\n\t\t\t\t&RoomGuestAccessEventContent::new(GuestAccess::Forbidden),\n\t\t\t),\n\t\t\tserver_user,\n\t\t\t&room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\t// 5. Events implied by name and topic\n\tlet room_name = format!(\"{} Admin Room\", services.config.server_name);\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(String::new(), &RoomNameEventContent::new(room_name)),\n\t\t\tserver_user,\n\t\t\t&room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(String::new(), &RoomTopicEventContent {\n\t\t\t\ttopic: format!(\"Manage {} | Run commands prefixed with `!admin` | Run `!admin -h` for help | Documentation: https://conduwuit.puppyirl.gay/\", services.config.server_name),\n\t\t\t}),\n\t\t\tserver_user,\n\t\t\t&room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\t// 6. Room alias\n\tlet alias = &services.globals.admin_alias;\n\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(String::new(), &RoomCanonicalAliasEventContent {\n\t\t\t\talias: Some(alias.clone()),\n\t\t\t\talt_aliases: Vec::new(),\n\t\t\t}),\n\t\t\tserver_user,\n\t\t\t&room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\tservices\n\t\t.rooms\n\t\t.alias\n\t\t.set_alias(alias, &room_id, server_user)?;\n\n\t// 7. (ad-hoc) Disable room URL previews for everyone by default\n\tservices\n\t\t.rooms\n\t\t.timeline\n\t\t.build_and_append_pdu(\n\t\t\tPduBuilder::state(String::new(), &RoomPreviewUrlsEventContent { disabled: true }),\n\t\t\tserver_user,\n\t\t\t&room_id,\n\t\t\t&state_lock,\n\t\t)\n\t\t.await?;\n\n\tOk(())\n}\n```"}], "func_name": "create_admin_room", "docstring": "Create the admin room.\n\nUsers in this room are considered admins by conduwuit, and the room can be\nused to issue admin commands by talking to the server user inside it.", "repo": "girlbossceo/conduwuit", "path": "src/service/admin/create.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/admin/create.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7da71bfc56b1967652f86db2055398ff141640e517394c2e0ddb37e9dff1159a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_text\n\nDocumentation:\nSends markdown message (not an m.notice for notification reasons) to the\nadmin room as the admin user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn send_text(&self, body: &str) {\n\t\tself.send_message(RoomMessageEventContent::text_markdown(body))\n\t\t\t.await\n\t\t\t.ok();\n\t}\n```"}], "func_name": "send_text", "docstring": "Sends markdown message (not an m.notice for notification reasons) to the\nadmin room as the admin user.", "repo": "girlbossceo/conduwuit", "path": "src/service/admin/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/admin/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad0a8b38af55bade08a066d185b8c4bc06ae339b0f55bc754df33416f68b4343"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_message\n\nDocumentation:\nSends a message to the admin room as the admin user (see send_text() for\nconvenience).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn send_message(&self, message_content: RoomMessageEventContent) -> Result<()> {\n\t\tlet user_id = &self.services.globals.server_user;\n\t\tlet room_id = self.get_admin_room().await?;\n\t\tself.respond_to_room(message_content, &room_id, user_id)\n\t\t\t.boxed()\n\t\t\t.await\n\t}\n```"}], "func_name": "send_message", "docstring": "Sends a message to the admin room as the admin user (see send_text() for\nconvenience).", "repo": "girlbossceo/conduwuit", "path": "src/service/admin/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/admin/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6274b017940f53f81ff473d9dd59253784d9cb782d905d4a24d6b0028618727d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: command\n\nDocumentation:\nPosts a command to the command processor queue and returns. Processing\nwill take place on the service worker's task asynchronously. Errors if\nthe queue is full.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn command(&self, command: String, reply_id: Option) -> Result<()> {\n\t\tself.channel\n\t\t\t.0\n\t\t\t.send(CommandInput { command, reply_id })\n\t\t\t.map_err(|e| err!(\"Failed to enqueue admin command: {e:?}\"))\n\t}\n```"}], "func_name": "command", "docstring": "Posts a command to the command processor queue and returns. Processing\nwill take place on the service worker's task asynchronously. Errors if\nthe queue is full.", "repo": "girlbossceo/conduwuit", "path": "src/service/admin/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/admin/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cccb5707b15cf85d8bb5e553fafb8584d2221034552d8a220958e025aaec7608"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: command_in_place\n\nDocumentation:\nDispatches a comamnd to the processor on the current task and waits for\ncompletion.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn command_in_place(\n\t\t&self,\n\t\tcommand: String,\n\t\treply_id: Option,\n\t) -> ProcessorResult {\n\t\tself.process_command(CommandInput { command, reply_id })\n\t\t\t.await\n\t}\n```"}], "func_name": "command_in_place", "docstring": "Dispatches a comamnd to the processor on the current task and waits for\ncompletion.", "repo": "girlbossceo/conduwuit", "path": "src/service/admin/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/admin/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e27ce4b0ac656d84613d84fee2d6c41940c927e8aa96465c8d287f8fe150d3d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: complete_command\n\nDocumentation:\nInvokes the tab-completer to complete the command. When unavailable,\nNone is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn complete_command(&self, command: &str) -> Option {\n\t\tself.complete\n\t\t\t.read()\n\t\t\t.expect(\"locked for reading\")\n\t\t\t.map(|complete| complete(command))\n\t}\n```"}], "func_name": "complete_command", "docstring": "Invokes the tab-completer to complete the command. When unavailable,\nNone is returned.", "repo": "girlbossceo/conduwuit", "path": "src/service/admin/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/admin/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "66f64bf5f4e7074d3591e918a7a89721ce1d0bf508c2418a700991f2955aec13"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: user_is_admin\n\nDocumentation:\nChecks whether a given user is an admin of this server\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn user_is_admin(&self, user_id: &UserId) -> bool {\n\t\tlet Ok(admin_room) = self.get_admin_room().await else {\n\t\t\treturn false;\n\t\t};\n\n\t\tself.services\n\t\t\t.state_cache\n\t\t\t.is_joined(user_id, &admin_room)\n\t\t\t.await\n\t}\n```"}], "func_name": "user_is_admin", "docstring": "Checks whether a given user is an admin of this server", "repo": "girlbossceo/conduwuit", "path": "src/service/admin/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/admin/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f2e918e0f160708c9b085fac8415dd33d3e3ddc7ccf2d255170ac36e6e45fe5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_admin_room\n\nDocumentation:\nGets the room ID of the admin room\n\nErrors are propagated from the database, and will have None if there is\nno admin room\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_admin_room(&self) -> Result {\n\t\tlet room_id = self\n\t\t\t.services\n\t\t\t.alias\n\t\t\t.resolve_local_alias(&self.services.globals.admin_alias)\n\t\t\t.await?;\n\n\t\tself.services\n\t\t\t.state_cache\n\t\t\t.is_joined(&self.services.globals.server_user, &room_id)\n\t\t\t.await\n\t\t\t.then_some(room_id)\n\t\t\t.ok_or_else(|| err!(Request(NotFound(\"Admin user not joined to admin room\"))))\n\t}\n```"}], "func_name": "get_admin_room", "docstring": "Gets the room ID of the admin room\n\nErrors are propagated from the database, and will have None if there is\nno admin room", "repo": "girlbossceo/conduwuit", "path": "src/service/admin/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/admin/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be2ae031950e9018ae27f4a16b83d92bec2b943f49ac9812a48a8efc43d63626"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_services\n\nDocumentation:\nSets the self-reference to crate::Services which will provide context to\nthe admin commands.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn set_services(&self, services: Option<&Arc>) {\n\t\tlet receiver = &mut *self.services.services.write().expect(\"locked for writing\");\n\t\tlet weak = services.map(Arc::downgrade);\n\t\t*receiver = weak;\n\t}\n```"}], "func_name": "set_services", "docstring": "Sets the self-reference to crate::Services which will provide context to\nthe admin commands.", "repo": "girlbossceo/conduwuit", "path": "src/service/admin/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/admin/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a382f39b8394f9e1064d4fb96703db1398939edc9e71a59c83b0d2ce137b704"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: register_appservice\n\nDocumentation:\nRegisters an appservice and returns the ID to the caller\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn register_appservice(\n\t\t&self,\n\t\tregistration: &Registration,\n\t\tappservice_config_body: &str,\n\t) -> Result {\n\t\t//TODO: Check for collisions between exclusive appservice namespaces\n\t\tself.registration_info\n\t\t\t.write()\n\t\t\t.await\n\t\t\t.insert(registration.id.clone(), registration.clone().try_into()?);\n\n\t\tself.db\n\t\t\t.id_appserviceregistrations\n\t\t\t.insert(®istration.id, appservice_config_body);\n\n\t\tOk(())\n\t}\n```"}], "func_name": "register_appservice", "docstring": "Registers an appservice and returns the ID to the caller", "repo": "girlbossceo/conduwuit", "path": "src/service/appservice/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/appservice/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e4c49aa7e08fc1715400c1aa94923d9dcc45c9330ebccd9a2f23ccad73e1c86f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unregister_appservice\n\nDocumentation:\nRemove an appservice registration\n\n# Arguments\n\n* `service_name` - the registration ID of the appservice\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn unregister_appservice(&self, appservice_id: &str) -> Result<()> {\n\t\t// removes the appservice registration info\n\t\tself.registration_info\n\t\t\t.write()\n\t\t\t.await\n\t\t\t.remove(appservice_id)\n\t\t\t.ok_or_else(|| err!(\"Appservice not found\"))?;\n\n\t\t// remove the appservice from the database\n\t\tself.db.id_appserviceregistrations.del(appservice_id);\n\n\t\t// deletes all active requests for the appservice if there are any so we stop\n\t\t// sending to the URL\n\t\tself.services\n\t\t\t.sending\n\t\t\t.cleanup_events(Some(appservice_id), None, None)\n\t\t\t.await\n\t}\n```"}], "func_name": "unregister_appservice", "docstring": "Remove an appservice registration\n\n# Arguments\n\n* `service_name` - the registration ID of the appservice", "repo": "girlbossceo/conduwuit", "path": "src/service/appservice/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/appservice/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b98e6fde864585b87a9ecfe3c75204adc1e5824d63519cd756fc6b23b30f1ff5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_exclusive_user_id\n\nDocumentation:\nChecks if a given user id matches any exclusive appservice regex\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn is_exclusive_user_id(&self, user_id: &UserId) -> bool {\n\t\tself.read()\n\t\t\t.await\n\t\t\t.values()\n\t\t\t.any(|info| info.is_exclusive_user_match(user_id))\n\t}\n```"}], "func_name": "is_exclusive_user_id", "docstring": "Checks if a given user id matches any exclusive appservice regex", "repo": "girlbossceo/conduwuit", "path": "src/service/appservice/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/appservice/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "11fcf6f2fccdf16a2f81819d8d7e6bac7a0ad95083bcb946132d464e9307076a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_exclusive_alias\n\nDocumentation:\nChecks if a given room alias matches any exclusive appservice regex\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn is_exclusive_alias(&self, alias: &RoomAliasId) -> bool {\n\t\tself.read()\n\t\t\t.await\n\t\t\t.values()\n\t\t\t.any(|info| info.aliases.is_exclusive_match(alias.as_str()))\n\t}\n```"}], "func_name": "is_exclusive_alias", "docstring": "Checks if a given room alias matches any exclusive appservice regex", "repo": "girlbossceo/conduwuit", "path": "src/service/appservice/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/appservice/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "abdeeda9f23da09da13dfa4be25355cb705eea42195ec3ca0c46c3199f1ce70e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_emergency_access\n\nDocumentation:\nSets the emergency password and push rules for the server user account\nin case emergency password is set\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn set_emergency_access(&self) -> Result {\n\t\tlet server_user = &self.services.globals.server_user;\n\n\t\tself.services\n\t\t\t.users\n\t\t\t.set_password(server_user, self.services.config.emergency_password.as_deref())?;\n\n\t\tlet (ruleset, pwd_set) = match self.services.config.emergency_password {\n\t\t\t| Some(_) => (Ruleset::server_default(server_user), true),\n\t\t\t| None => (Ruleset::new(), false),\n\t\t};\n\n\t\tself.services\n\t\t\t.account_data\n\t\t\t.update(\n\t\t\t\tNone,\n\t\t\t\tserver_user,\n\t\t\t\tGlobalAccountDataEventType::PushRules.to_string().into(),\n\t\t\t\t&serde_json::to_value(&GlobalAccountDataEvent {\n\t\t\t\t\tcontent: PushRulesEventContent { global: ruleset },\n\t\t\t\t})\n\t\t\t\t.expect(\"to json value always works\"),\n\t\t\t)\n\t\t\t.await?;\n\n\t\tif pwd_set {\n\t\t\twarn!(\n\t\t\t\t\"The server account emergency password is set! Please unset it as soon as you \\\n\t\t\t\t finish admin account recovery! You will be logged out of the server service \\\n\t\t\t\t account when you finish.\"\n\t\t\t);\n\t\t\tOk(())\n\t\t} else {\n\t\t\t// logs out any users still in the server service account and removes sessions\n\t\t\tself.services.users.deactivate_account(server_user).await\n\t\t}\n\t}\n```"}], "func_name": "set_emergency_access", "docstring": "Sets the emergency password and push rules for the server user account\nin case emergency password is set", "repo": "girlbossceo/conduwuit", "path": "src/service/emergency/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/emergency/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00f9d744362f3aa306a29f80959f9a25282a62402cb84595a5cb9bf375251687"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: search_mxc_metadata_prefix\n\nDocumentation:\nSearches for all files with the given MXC\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn search_mxc_metadata_prefix(&self, mxc: &Mxc<'_>) -> Result>> {\n\t\tdebug!(\"MXC URI: {mxc}\");\n\n\t\tlet prefix = (mxc, Interfix);\n\t\tlet keys: Vec> = self\n\t\t\t.mediaid_file\n\t\t\t.keys_prefix_raw(&prefix)\n\t\t\t.ignore_err()\n\t\t\t.map(<[u8]>::to_vec)\n\t\t\t.collect()\n\t\t\t.await;\n\n\t\tif keys.is_empty() {\n\t\t\treturn Err!(Database(\"Failed to find any keys in database for `{mxc}`\",));\n\t\t}\n\n\t\tdebug!(\"Got the following keys: {keys:?}\");\n\n\t\tOk(keys)\n\t}\n```"}], "func_name": "search_mxc_metadata_prefix", "docstring": "Searches for all files with the given MXC", "repo": "girlbossceo/conduwuit", "path": "src/service/media/data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/media/data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6312ce888b75cfa36940956295f72bad5d7fa3ba1a9e703561b981ab31a12344"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_all_user_mxcs\n\nDocumentation:\nGets all the MXCs associated with a user\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn get_all_user_mxcs(&self, user_id: &UserId) -> Vec {\n\t\tself.mediaid_user\n\t\t\t.stream()\n\t\t\t.ignore_err()\n\t\t\t.ready_filter_map(|(key, user): (&str, &UserId)| {\n\t\t\t\t(user == user_id).then(|| key.into())\n\t\t\t})\n\t\t\t.collect()\n\t\t\t.await\n\t}\n```"}], "func_name": "get_all_user_mxcs", "docstring": "Gets all the MXCs associated with a user", "repo": "girlbossceo/conduwuit", "path": "src/service/media/data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/media/data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "df48acdb523fbf8627e146f2d47f559658e63a0bebf469bce9bb1cef76239496"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_all_media_keys\n\nDocumentation:\nGets all the media keys in our database (this includes all the metadata\nassociated with it such as width, height, content-type, etc)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_all_media_keys(&self) -> Vec> {\n\t\tself.mediaid_file\n\t\t\t.raw_keys()\n\t\t\t.ignore_err()\n\t\t\t.map(<[u8]>::to_vec)\n\t\t\t.collect()\n\t\t\t.await\n\t}\n```"}], "func_name": "get_all_media_keys", "docstring": "Gets all the media keys in our database (this includes all the metadata\nassociated with it such as width, height, content-type, etc)", "repo": "girlbossceo/conduwuit", "path": "src/service/media/data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/media/data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "68100b23cca64dfd3f0dedf086221130ca88f86dbd48fdfbbab08cdca203eb3b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: migrate_sha256_media\n\nDocumentation:\nMigrates a media directory from legacy base64 file names to sha2 file names.\nAll errors are fatal. Upon success the database is keyed to not perform this\nagain.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn migrate_sha256_media(services: &Services) -> Result<()> {\n\tlet db = &services.db;\n\tlet config = &services.server.config;\n\n\twarn!(\"Migrating legacy base64 file names to sha256 file names\");\n\tlet mediaid_file = &db[\"mediaid_file\"];\n\n\t// Move old media files to new names\n\tlet mut changes = Vec::<(PathBuf, PathBuf)>::new();\n\tmediaid_file\n\t\t.raw_keys()\n\t\t.ignore_err()\n\t\t.ready_for_each(|key| {\n\t\t\tlet old = services.media.get_media_file_b64(key);\n\t\t\tlet new = services.media.get_media_file_sha256(key);\n\t\t\tdebug!(?key, ?old, ?new, num = changes.len(), \"change\");\n\t\t\tchanges.push((old, new));\n\t\t})\n\t\t.await;\n\n\t// move the file to the new location\n\tfor (old_path, path) in changes {\n\t\tif old_path.exists() {\n\t\t\ttokio::fs::rename(&old_path, &path).await?;\n\t\t\tif config.media_compat_file_link {\n\t\t\t\ttokio::fs::symlink(&path, &old_path).await?;\n\t\t\t}\n\t\t}\n\t}\n\n\tdb[\"global\"].insert(b\"feat_sha256_media\", []);\n\tinfo!(\"Finished applying sha256_media\");\n\tOk(())\n}\n```"}], "func_name": "migrate_sha256_media", "docstring": "Migrates a media directory from legacy base64 file names to sha2 file names.\nAll errors are fatal. Upon success the database is keyed to not perform this\nagain.", "repo": "girlbossceo/conduwuit", "path": "src/service/media/migrations.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/media/migrations.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09ebe74dd4e485362a42dff3ee52f075f009b75eab4aff2b2271bfb8fef5f0a2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: checkup_sha256_media\n\nDocumentation:\nCheck is run on startup for prior-migrated media directories. This handles:\n- Going back and forth to non-sha256 legacy binaries (e.g. upstream).\n- Deletion of artifacts in the media directory which will then fall out of\nsync with the database.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn checkup_sha256_media(services: &Services) -> Result<()> {\n\tuse crate::media::encode_key;\n\n\tdebug!(\"Checking integrity of media directory\");\n\tlet db = &services.db;\n\tlet media = &services.media;\n\tlet config = &services.server.config;\n\tlet mediaid_file = &db[\"mediaid_file\"];\n\tlet mediaid_user = &db[\"mediaid_user\"];\n\tlet dbs = (mediaid_file, mediaid_user);\n\tlet timer = Instant::now();\n\n\tlet dir = media.get_media_dir();\n\tlet files: HashSet = fs::read_dir(dir)?\n\t\t.filter_map(|ent| ent.map_or(None, |ent| Some(ent.path().into_os_string())))\n\t\t.collect();\n\n\tfor key in media.db.get_all_media_keys().await {\n\t\tlet new_path = media.get_media_file_sha256(&key).into_os_string();\n\t\tlet old_path = media.get_media_file_b64(&key).into_os_string();\n\t\tif let Err(e) = handle_media_check(&dbs, config, &files, &key, &new_path, &old_path).await\n\t\t{\n\t\t\terror!(\n\t\t\t\tmedia_id = ?encode_key(&key), ?new_path, ?old_path,\n\t\t\t\t\"Failed to resolve media check failure: {e}\"\n\t\t\t);\n\t\t}\n\t}\n\n\tdebug_info!(\n\t\telapsed = ?timer.elapsed(),\n\t\t\"Finished checking media directory\"\n\t);\n\n\tOk(())\n}\n```"}], "func_name": "checkup_sha256_media", "docstring": "Check is run on startup for prior-migrated media directories. This handles:\n- Going back and forth to non-sha256 legacy binaries (e.g. upstream).\n- Deletion of artifacts in the media directory which will then fall out of\nsync with the database.", "repo": "girlbossceo/conduwuit", "path": "src/service/media/migrations.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/media/migrations.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8ac2848b90db56053df0d3ca1513b62e6bfa9deafa45e8b8116aaf0b77d0a2c9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete\n\nDocumentation:\nDeletes a file in the database and from the media directory via an MXC\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn delete(&self, mxc: &Mxc<'_>) -> Result<()> {\n\t\tmatch self.db.search_mxc_metadata_prefix(mxc).await {\n\t\t\t| Ok(keys) => {\n\t\t\t\tfor key in keys {\n\t\t\t\t\ttrace!(?mxc, \"MXC Key: {key:?}\");\n\t\t\t\t\tdebug_info!(?mxc, \"Deleting from filesystem\");\n\n\t\t\t\t\tif let Err(e) = self.remove_media_file(&key).await {\n\t\t\t\t\t\tdebug_error!(?mxc, \"Failed to remove media file: {e}\");\n\t\t\t\t\t}\n\n\t\t\t\t\tdebug_info!(?mxc, \"Deleting from database\");\n\t\t\t\t\tself.db.delete_file_mxc(mxc).await;\n\t\t\t\t}\n\n\t\t\t\tOk(())\n\t\t\t},\n\t\t\t| _ => {\n\t\t\t\tErr!(Database(error!(\n\t\t\t\t\t\"Failed to find any media keys for MXC {mxc} in our database.\"\n\t\t\t\t)))\n\t\t\t},\n\t\t}\n\t}\n```"}], "func_name": "delete", "docstring": "Deletes a file in the database and from the media directory via an MXC", "repo": "girlbossceo/conduwuit", "path": "src/service/media/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/media/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "15835c4803a464091b8a758690a7da17dbac4eee3a6b68022dbd48a332dff538"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_from_user\n\nDocumentation:\nDeletes all media by the specified user\n\ncurrently, this is only practical for local users\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn delete_from_user(&self, user: &UserId) -> Result {\n\t\tlet mxcs = self.db.get_all_user_mxcs(user).await;\n\t\tlet mut deletion_count: usize = 0;\n\n\t\tfor mxc in mxcs {\n\t\t\tlet Ok(mxc) = mxc.as_str().try_into().inspect_err(|e| {\n\t\t\t\tdebug_error!(?mxc, \"Failed to parse MXC URI from database: {e}\");\n\t\t\t}) else {\n\t\t\t\tcontinue;\n\t\t\t};\n\n\t\t\tdebug_info!(%deletion_count, \"Deleting MXC {mxc} by user {user} from database and filesystem\");\n\t\t\tmatch self.delete(&mxc).await {\n\t\t\t\t| Ok(()) => {\n\t\t\t\t\tdeletion_count = deletion_count.saturating_add(1);\n\t\t\t\t},\n\t\t\t\t| Err(e) => {\n\t\t\t\t\tdebug_error!(%deletion_count, \"Failed to delete {mxc} from user {user}, ignoring error: {e}\");\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\tOk(deletion_count)\n\t}\n```"}], "func_name": "delete_from_user", "docstring": "Deletes all media by the specified user\n\ncurrently, this is only practical for local users", "repo": "girlbossceo/conduwuit", "path": "src/service/media/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/media/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7957d38406588e2bea1b6ff3bab41a4e4666a6eed149b442bc00be33f2ae10df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_all_mxcs\n\nDocumentation:\nGets all the MXC URIs in our media database\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_all_mxcs(&self) -> Result> {\n\t\tlet all_keys = self.db.get_all_media_keys().await;\n\n\t\tlet mut mxcs = Vec::with_capacity(all_keys.len());\n\n\t\tfor key in all_keys {\n\t\t\ttrace!(\"Full MXC key from database: {key:?}\");\n\n\t\t\tlet mut parts = key.split(|&b| b == 0xFF);\n\t\t\tlet mxc = parts\n\t\t\t\t.next()\n\t\t\t\t.map(|bytes| {\n\t\t\t\t\tutils::string_from_bytes(bytes).map_err(|e| {\n\t\t\t\t\t\terr!(Database(error!(\n\t\t\t\t\t\t\t\"Failed to parse MXC unicode bytes from our database: {e}\"\n\t\t\t\t\t\t)))\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t\t.transpose()?;\n\n\t\t\tlet Some(mxc_s) = mxc else {\n\t\t\t\tdebug_warn!(\n\t\t\t\t\t?mxc,\n\t\t\t\t\t\"Parsed MXC URL unicode bytes from database but is still invalid\"\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t};\n\n\t\t\ttrace!(\"Parsed MXC key to URL: {mxc_s}\");\n\t\t\tlet mxc = OwnedMxcUri::from(mxc_s);\n\n\t\t\tif mxc.is_valid() {\n\t\t\t\tmxcs.push(mxc);\n\t\t\t} else {\n\t\t\t\tdebug_warn!(\"{mxc:?} from database was found to not be valid\");\n\t\t\t}\n\t\t}\n\n\t\tOk(mxcs)\n\t}\n```"}], "func_name": "get_all_mxcs", "docstring": "Gets all the MXC URIs in our media database", "repo": "girlbossceo/conduwuit", "path": "src/service/media/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/media/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "55ea8c3dadcb2c98bacf78774ff5a2bb843667333b8918129f0601441bbdd32f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_all_remote_media_at_after_time\n\nDocumentation:\nDeletes all remote only media files in the given at or after\ntime/duration. Returns a usize with the amount of media files deleted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn delete_all_remote_media_at_after_time(\n\t\t&self,\n\t\ttime: SystemTime,\n\t\tbefore: bool,\n\t\tafter: bool,\n\t\tyes_i_want_to_delete_local_media: bool,\n\t) -> Result {\n\t\tlet all_keys = self.db.get_all_media_keys().await;\n\t\tlet mut remote_mxcs = Vec::with_capacity(all_keys.len());\n\n\t\tfor key in all_keys {\n\t\t\ttrace!(\"Full MXC key from database: {key:?}\");\n\t\t\tlet mut parts = key.split(|&b| b == 0xFF);\n\t\t\tlet mxc = parts\n\t\t\t\t.next()\n\t\t\t\t.map(|bytes| {\n\t\t\t\t\tutils::string_from_bytes(bytes).map_err(|e| {\n\t\t\t\t\t\terr!(Database(error!(\n\t\t\t\t\t\t\t\"Failed to parse MXC unicode bytes from our database: {e}\"\n\t\t\t\t\t\t)))\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t\t.transpose()?;\n\n\t\t\tlet Some(mxc_s) = mxc else {\n\t\t\t\tdebug_warn!(\n\t\t\t\t\t?mxc,\n\t\t\t\t\t\"Parsed MXC URL unicode bytes from database but is still invalid\"\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t};\n\n\t\t\ttrace!(\"Parsed MXC key to URL: {mxc_s}\");\n\t\t\tlet mxc = OwnedMxcUri::from(mxc_s);\n\t\t\tif (mxc.server_name() == Ok(self.services.globals.server_name())\n\t\t\t\t&& !yes_i_want_to_delete_local_media)\n\t\t\t\t|| !mxc.is_valid()\n\t\t\t{\n\t\t\t\tdebug!(\"Ignoring local or broken media MXC: {mxc}\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tlet path = self.get_media_file(&key);\n\n\t\t\tlet file_metadata = match fs::metadata(path.clone()).await {\n\t\t\t\t| Ok(file_metadata) => file_metadata,\n\t\t\t\t| Err(e) => {\n\t\t\t\t\terror!(\n\t\t\t\t\t\t\"Failed to obtain file metadata for MXC {mxc} at file path \\\n\t\t\t\t\t\t \\\"{path:?}\\\", skipping: {e}\"\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t},\n\t\t\t};\n\n\t\t\ttrace!(%mxc, ?path, \"File metadata: {file_metadata:?}\");\n\n\t\t\tlet file_created_at = match file_metadata.created() {\n\t\t\t\t| Ok(value) => value,\n\t\t\t\t| Err(err) if err.kind() == std::io::ErrorKind::Unsupported => {\n\t\t\t\t\tdebug!(\"btime is unsupported, using mtime instead\");\n\t\t\t\t\tfile_metadata.modified()?\n\t\t\t\t},\n\t\t\t\t| Err(err) => {\n\t\t\t\t\terror!(\"Could not delete MXC {mxc} at path {path:?}: {err:?}. Skipping...\");\n\t\t\t\t\tcontinue;\n\t\t\t\t},\n\t\t\t};\n\n\t\t\tdebug!(\"File created at: {file_created_at:?}\");\n\n\t\t\tif file_created_at >= time && before {\n\t\t\t\tdebug!(\n\t\t\t\t\t\"File is within (before) user duration, pushing to list of file paths and \\\n\t\t\t\t\t keys to delete.\"\n\t\t\t\t);\n\t\t\t\tremote_mxcs.push(mxc.to_string());\n\t\t\t} else if file_created_at <= time && after {\n\t\t\t\tdebug!(\n\t\t\t\t\t\"File is not within (after) user duration, pushing to list of file paths \\\n\t\t\t\t\t and keys to delete.\"\n\t\t\t\t);\n\t\t\t\tremote_mxcs.push(mxc.to_string());\n\t\t\t}\n\t\t}\n\n\t\tif remote_mxcs.is_empty() {\n\t\t\treturn Err!(Database(\"Did not found any eligible MXCs to delete.\"));\n\t\t}\n\n\t\tdebug_info!(\"Deleting media now in the past {time:?}\");\n\n\t\tlet mut deletion_count: usize = 0;\n\n\t\tfor mxc in remote_mxcs {\n\t\t\tlet Ok(mxc) = mxc.as_str().try_into() else {\n\t\t\t\tdebug_warn!(\"Invalid MXC in database, skipping\");\n\t\t\t\tcontinue;\n\t\t\t};\n\n\t\t\tdebug_info!(\"Deleting MXC {mxc} from database and filesystem\");\n\n\t\t\tmatch self.delete(&mxc).await {\n\t\t\t\t| Ok(()) => {\n\t\t\t\t\tdeletion_count = deletion_count.saturating_add(1);\n\t\t\t\t},\n\t\t\t\t| Err(e) => {\n\t\t\t\t\twarn!(\"Failed to delete {mxc}, ignoring error and skipping: {e}\");\n\t\t\t\t\tcontinue;\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\n\t\tOk(deletion_count)\n\t}\n```"}], "func_name": "delete_all_remote_media_at_after_time", "docstring": "Deletes all remote only media files in the given at or after\ntime/duration. Returns a usize with the amount of media files deleted.", "repo": "girlbossceo/conduwuit", "path": "src/service/media/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/media/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e901307d94aaf2b9aaf1622a2fe87337d7f8269f9525cce9d14b9a71bc5e566c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_ruma\n\nDocumentation:\nInstantiate a Dim from Ruma integers with optional method.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_ruma(width: UInt, height: UInt, method: Option) -> Result {\n\t\tlet width = width\n\t\t\t.try_into()\n\t\t\t.map_err(|e| err!(Request(InvalidParam(\"Width is invalid: {e:?}\"))))?;\n\t\tlet height = height\n\t\t\t.try_into()\n\t\t\t.map_err(|e| err!(Request(InvalidParam(\"Height is invalid: {e:?}\"))))?;\n\n\t\tOk(Self::new(width, height, method))\n\t}\n```"}], "func_name": "from_ruma", "docstring": "Instantiate a Dim from Ruma integers with optional method.", "repo": "girlbossceo/conduwuit", "path": "src/service/media/thumbnail.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/media/thumbnail.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e7f69352d284511cbdb84d0b0c046717fba43c571934168e2564fe6e7456a1bf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ping_presence\n\nDocumentation:\nPings the presence of the given user in the given room, setting the\nspecified state.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn ping_presence(&self, user_id: &UserId, new_state: &PresenceState) -> Result<()> {\n\t\tconst REFRESH_TIMEOUT: u64 = 60 * 1000;\n\n\t\tlet last_presence = self.db.get_presence(user_id).await;\n\t\tlet state_changed = match last_presence {\n\t\t\t| Err(_) => true,\n\t\t\t| Ok((_, ref presence)) => presence.content.presence != *new_state,\n\t\t};\n\n\t\tlet last_last_active_ago = match last_presence {\n\t\t\t| Err(_) => 0_u64,\n\t\t\t| Ok((_, ref presence)) =>\n\t\t\t\tpresence.content.last_active_ago.unwrap_or_default().into(),\n\t\t};\n\n\t\tif !state_changed && last_last_active_ago < REFRESH_TIMEOUT {\n\t\t\treturn Ok(());\n\t\t}\n\n\t\tlet status_msg = match last_presence {\n\t\t\t| Ok((_, ref presence)) => presence.content.status_msg.clone(),\n\t\t\t| Err(_) => Some(String::new()),\n\t\t};\n\n\t\tlet last_active_ago = UInt::new(0);\n\t\tlet currently_active = *new_state == PresenceState::Online;\n\t\tself.set_presence(user_id, new_state, Some(currently_active), last_active_ago, status_msg)\n\t\t\t.await\n\t}\n```"}], "func_name": "ping_presence", "docstring": "Pings the presence of the given user in the given room, setting the\nspecified state.", "repo": "girlbossceo/conduwuit", "path": "src/service/presence/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/presence/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0350286940b255d38fe8c0150bab990de210eec53258a46913c97acf75555ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_presence\n\nDocumentation:\nAdds a presence event which will be saved until a new event replaces it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn set_presence(\n\t\t&self,\n\t\tuser_id: &UserId,\n\t\tstate: &PresenceState,\n\t\tcurrently_active: Option,\n\t\tlast_active_ago: Option,\n\t\tstatus_msg: Option,\n\t) -> Result<()> {\n\t\tlet presence_state = match state.as_str() {\n\t\t\t| \"\" => &PresenceState::Offline, // default an empty string to 'offline'\n\t\t\t| &_ => state,\n\t\t};\n\n\t\tself.db\n\t\t\t.set_presence(user_id, presence_state, currently_active, last_active_ago, status_msg)\n\t\t\t.await?;\n\n\t\tif (self.timeout_remote_users || self.services.globals.user_is_local(user_id))\n\t\t\t&& user_id != self.services.globals.server_user\n\t\t{\n\t\t\tlet timeout = match presence_state {\n\t\t\t\t| PresenceState::Online => self.services.server.config.presence_idle_timeout_s,\n\t\t\t\t| _ => self.services.server.config.presence_offline_timeout_s,\n\t\t\t};\n\n\t\t\tself.timer_channel\n\t\t\t\t.0\n\t\t\t\t.send((user_id.to_owned(), Duration::from_secs(timeout)))\n\t\t\t\t.map_err(|e| {\n\t\t\t\t\terror!(\"Failed to add presence timer: {}\", e);\n\t\t\t\t\tError::bad_database(\"Failed to add presence timer\")\n\t\t\t\t})?;\n\t\t}\n\n\t\tOk(())\n\t}\n```"}], "func_name": "set_presence", "docstring": "Adds a presence event which will be saved until a new event replaces it.", "repo": "girlbossceo/conduwuit", "path": "src/service/presence/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/presence/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e18789fa1204cee03645ae5fd7dabb8582ef64438b07313d2062c98c024a2e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: presence_since\n\nDocumentation:\nReturns the most recent presence updates that happened after the event\nwith id `since`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn presence_since(\n\t\t&self,\n\t\tsince: u64,\n\t) -> impl Stream + Send + '_ {\n\t\tself.db.presence_since(since)\n\t}\n```"}], "func_name": "presence_since", "docstring": "Returns the most recent presence updates that happened after the event\nwith id `since`.", "repo": "girlbossceo/conduwuit", "path": "src/service/presence/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/presence/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ba27be3efdeae39115a14aaa13e431d0acdc285df8a2453c8928e9f20bd93db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: private_read_get\n\nDocumentation:\nGets the latest private read receipt from the user in the room\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn private_read_get(\n\t\t&self,\n\t\troom_id: &RoomId,\n\t\tuser_id: &UserId,\n\t) -> Result> {\n\t\tlet pdu_count = self.private_read_get_count(room_id, user_id).map_err(|e| {\n\t\t\terr!(Database(warn!(\"No private read receipt was set in {room_id}: {e}\")))\n\t\t});\n\t\tlet shortroomid = self.services.short.get_shortroomid(room_id).map_err(|e| {\n\t\t\terr!(Database(warn!(\"Short room ID does not exist in database for {room_id}: {e}\")))\n\t\t});\n\t\tlet (pdu_count, shortroomid) = try_join!(pdu_count, shortroomid)?;\n\n\t\tlet shorteventid = PduCount::Normal(pdu_count);\n\t\tlet pdu_id: RawPduId = PduId { shortroomid, shorteventid }.into();\n\n\t\tlet pdu = self.services.timeline.get_pdu_from_id(&pdu_id).await?;\n\n\t\tlet event_id: OwnedEventId = pdu.event_id;\n\t\tlet user_id: OwnedUserId = user_id.to_owned();\n\t\tlet content: BTreeMap = BTreeMap::from_iter([(\n\t\t\tevent_id,\n\t\t\tBTreeMap::from_iter([(\n\t\t\t\truma::events::receipt::ReceiptType::ReadPrivate,\n\t\t\t\tBTreeMap::from_iter([(user_id, ruma::events::receipt::Receipt {\n\t\t\t\t\tts: None, // TODO: start storing the timestamp so we can return one\n\t\t\t\t\tthread: ruma::events::receipt::ReceiptThread::Unthreaded,\n\t\t\t\t})]),\n\t\t\t)]),\n\t\t)]);\n\t\tlet receipt_event_content = ReceiptEventContent(content);\n\t\tlet receipt_sync_event = SyncEphemeralRoomEvent { content: receipt_event_content };\n\n\t\tlet event = serde_json::value::to_raw_value(&receipt_sync_event)\n\t\t\t.expect(\"receipt created manually\");\n\n\t\tOk(Raw::from_json(event))\n\t}\n```"}], "func_name": "private_read_get", "docstring": "Gets the latest private read receipt from the user in the room", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/read_receipt/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/read_receipt/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "326e6eeeedf752eb1d5352ab1664cb61ed73964c4bad25f6fa0c3f5c06fd5fc2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tokenize\n\nDocumentation:\nSplits a string into tokens used as keys in the search inverted index\n\nThis may be used to tokenize both message bodies (for indexing) or search\nqueries (for querying).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn tokenize(body: &str) -> impl Iterator + Send + '_ {\n\tbody.split_terminator(|c: char| !c.is_alphanumeric())\n\t\t.filter(|s| !s.is_empty())\n\t\t.filter(|word| word.len() <= WORD_MAX_LEN)\n\t\t.map(str::to_lowercase)\n}\n```"}], "func_name": "tokenize", "docstring": "Splits a string into tokens used as keys in the search inverted index\n\nThis may be used to tokenize both message bodies (for indexing) or search\nqueries (for querying).", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/search/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/search/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1013cb23c1dc860f36e67e73c046450b624543c36af8cd11a79d42a20592f1a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_parent_children_via\n\nDocumentation:\nReturns the children of a SpaceHierarchyParentSummary, making use of the\nchildren_state field\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_parent_children_via(\n\tparent: &SpaceHierarchyParentSummary,\n\tsuggested_only: bool,\n) -> impl DoubleEndedIterator + use<>)>\n+ Send\n+ '_ {\n\tparent\n\t\t.children_state\n\t\t.iter()\n\t\t.map(Raw::deserialize)\n\t\t.filter_map(Result::ok)\n\t\t.filter_map(move |ce| {\n\t\t\t(!suggested_only || ce.content.suggested)\n\t\t\t\t.then_some((ce.state_key, ce.content.via.into_iter()))\n\t\t})\n}\n```"}], "func_name": "get_parent_children_via", "docstring": "Returns the children of a SpaceHierarchyParentSummary, making use of the\nchildren_state field", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/spaces/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/spaces/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e4b913112cd9dc5bbfc7d2cef612e5a26ba79bbefcd74771f5afe4727ce54ce7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: force_state\n\nDocumentation:\nSet the room to the given statehash and update caches.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn force_state(\n\t\t&self,\n\t\troom_id: &RoomId,\n\t\tshortstatehash: u64,\n\t\tstatediffnew: Arc,\n\t\t_statediffremoved: Arc,\n\t\tstate_lock: &RoomMutexGuard,\n\t) -> Result {\n\t\tlet event_ids = statediffnew\n\t\t\t.iter()\n\t\t\t.stream()\n\t\t\t.map(|&new| parse_compressed_state_event(new).1)\n\t\t\t.then(|shorteventid| {\n\t\t\t\tself.services\n\t\t\t\t\t.short\n\t\t\t\t\t.get_eventid_from_short::>(shorteventid)\n\t\t\t})\n\t\t\t.ignore_err();\n\n\t\tpin_mut!(event_ids);\n\t\twhile let Some(event_id) = event_ids.next().await {\n\t\t\tlet Ok(pdu) = self.services.timeline.get_pdu(&event_id).await else {\n\t\t\t\tcontinue;\n\t\t\t};\n\n\t\t\tmatch pdu.kind {\n\t\t\t\t| TimelineEventType::RoomMember => {\n\t\t\t\t\tlet Some(user_id) = pdu.state_key.as_ref().map(UserId::parse).flat_ok()\n\t\t\t\t\telse {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t};\n\n\t\t\t\t\tlet Ok(membership_event) = pdu.get_content::() else {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t};\n\n\t\t\t\t\tself.services\n\t\t\t\t\t\t.state_cache\n\t\t\t\t\t\t.update_membership(\n\t\t\t\t\t\t\troom_id,\n\t\t\t\t\t\t\tuser_id,\n\t\t\t\t\t\t\tmembership_event,\n\t\t\t\t\t\t\t&pdu.sender,\n\t\t\t\t\t\t\tNone,\n\t\t\t\t\t\t\tNone,\n\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.await?;\n\t\t\t\t},\n\t\t\t\t| TimelineEventType::SpaceChild => {\n\t\t\t\t\tself.services\n\t\t\t\t\t\t.spaces\n\t\t\t\t\t\t.roomid_spacehierarchy_cache\n\t\t\t\t\t\t.lock()\n\t\t\t\t\t\t.await\n\t\t\t\t\t\t.remove(&pdu.room_id);\n\t\t\t\t},\n\t\t\t\t| _ => continue,\n\t\t\t}\n\t\t}\n\n\t\tself.services.state_cache.update_joined_count(room_id).await;\n\n\t\tself.set_room_state(room_id, shortstatehash, state_lock);\n\n\t\tOk(())\n\t}\n```"}], "func_name": "force_state", "docstring": "Set the room to the given statehash and update caches.", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/state/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/state/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48f624f1c51cd8fb24f83cdb2bc0978e77c5317f43d8d027ddafe94212ed37df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_world_readable\n\nDocumentation:\nChecks if guests are able to view room content without joining\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn is_world_readable(&self, room_id: &RoomId) -> bool {\n\t\tself.room_state_get_content(room_id, &StateEventType::RoomHistoryVisibility, \"\")\n\t\t\t.await\n\t\t\t.map(|c: RoomHistoryVisibilityEventContent| {\n\t\t\t\tc.history_visibility == HistoryVisibility::WorldReadable\n\t\t\t})\n\t\t\t.unwrap_or(false)\n\t}\n```"}], "func_name": "is_world_readable", "docstring": "Checks if guests are able to view room content without joining", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/state_accessor/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/state_accessor/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2bd025f02649225cfbf4f489efa2faf6803d80ea0fdfef9a4e9ff7fe55ce594e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: guest_can_join\n\nDocumentation:\nChecks if guests are able to join a given room\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn guest_can_join(&self, room_id: &RoomId) -> bool {\n\t\tself.room_state_get_content(room_id, &StateEventType::RoomGuestAccess, \"\")\n\t\t\t.await\n\t\t\t.map(|c: RoomGuestAccessEventContent| c.guest_access == GuestAccess::CanJoin)\n\t\t\t.unwrap_or(false)\n\t}\n```"}], "func_name": "guest_can_join", "docstring": "Checks if guests are able to join a given room", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/state_accessor/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/state_accessor/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "db0f56a6fd2c1c2074286bd668f4e2674f475ea555b0ad5ebc401a81dea7153d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_canonical_alias\n\nDocumentation:\nGets the primary alias from canonical alias event\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_canonical_alias(&self, room_id: &RoomId) -> Result {\n\t\tself.room_state_get_content(room_id, &StateEventType::RoomCanonicalAlias, \"\")\n\t\t\t.await\n\t\t\t.and_then(|c: RoomCanonicalAliasEventContent| {\n\t\t\t\tc.alias\n\t\t\t\t\t.ok_or_else(|| err!(Request(NotFound(\"No alias found in event content.\"))))\n\t\t\t})\n\t}\n```"}], "func_name": "get_canonical_alias", "docstring": "Gets the primary alias from canonical alias event", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/state_accessor/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/state_accessor/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b8a413f0c3d1d590ff4af26f1862b50028026ee020a517e3a47d7ff4bdbb847"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_join_rules\n\nDocumentation:\nReturns the join rules for a given room (`JoinRule` type). Will default\nto Invite if doesnt exist or invalid\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_join_rules(&self, room_id: &RoomId) -> JoinRule {\n\t\tself.room_state_get_content(room_id, &StateEventType::RoomJoinRules, \"\")\n\t\t\t.await\n\t\t\t.map_or(JoinRule::Invite, |c: RoomJoinRulesEventContent| c.join_rule)\n\t}\n```"}], "func_name": "get_join_rules", "docstring": "Returns the join rules for a given room (`JoinRule` type). Will default\nto Invite if doesnt exist or invalid", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/state_accessor/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/state_accessor/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9f901298f48d600b2a1b22273495df215d4368ed681ef0692a953be2ae726562"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_room_encryption\n\nDocumentation:\nGets the room's encryption algorithm if `m.room.encryption` state event\nis found\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_room_encryption(\n\t\t&self,\n\t\troom_id: &RoomId,\n\t) -> Result {\n\t\tself.room_state_get_content(room_id, &StateEventType::RoomEncryption, \"\")\n\t\t\t.await\n\t\t\t.map(|content: RoomEncryptionEventContent| content.algorithm)\n\t}\n```"}], "func_name": "get_room_encryption", "docstring": "Gets the room's encryption algorithm if `m.room.encryption` state event\nis found", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/state_accessor/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/state_accessor/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0899b10531eb648860208bbb3736f22dcb70144a69f06d3ce43c09a9001665e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: local_users_in_room\n\nDocumentation:\nReturns an iterator of all our local users in the room, even if they're\ndeactivated/guests\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn local_users_in_room<'a>(\n\t\t&'a self,\n\t\troom_id: &'a RoomId,\n\t) -> impl Stream + Send + 'a {\n\t\tself.room_members(room_id)\n\t\t\t.ready_filter(|user| self.services.globals.user_is_local(user))\n\t}\n```"}], "func_name": "local_users_in_room", "docstring": "Returns an iterator of all our local users in the room, even if they're\ndeactivated/guests", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/state_cache/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/state_cache/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7a9bd23b94ef533b0bb3bc07f022eeaa08011b4176e58d5a19baf71ade392a76"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: save_state_from_diff\n\nDocumentation:\nCreates a new shortstatehash that often is just a diff to an already\nexisting shortstatehash and therefore very efficient.\n\nThere are multiple layers of diffs. The bottom layer 0 always contains\nthe full state. Layer 1 contains diffs to states of layer 0, layer 2\ndiffs to layer 1 and so on. If layer n > 0 grows too big, it will be\ncombined with layer n-1 to create a new diff on layer n-1 that's\nbased on layer n-2. If that layer is also too big, it will recursively\nfix above layers too.\n\n* `shortstatehash` - Shortstatehash of this state\n* `statediffnew` - Added to base. Each vec is shortstatekey+shorteventid\n* `statediffremoved` - Removed from base. Each vec is\nshortstatekey+shorteventid\n* `diff_to_sibling` - Approximately how much the diff grows each time\nfor this layer\n* `parent_states` - A stack with info on shortstatehash, full state,\nadded diff and removed diff for each parent layer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn save_state_from_diff(\n\t\t&self,\n\t\tshortstatehash: ShortStateHash,\n\t\tstatediffnew: Arc,\n\t\tstatediffremoved: Arc,\n\t\tdiff_to_sibling: usize,\n\t\tmut parent_states: ParentStatesVec,\n\t) -> Result {\n\t\tlet statediffnew_len = statediffnew.len();\n\t\tlet statediffremoved_len = statediffremoved.len();\n\t\tlet diffsum = checked!(statediffnew_len + statediffremoved_len)?;\n\n\t\tif parent_states.len() > 3 {\n\t\t\t// Number of layers\n\t\t\t// To many layers, we have to go deeper\n\t\t\tlet parent = parent_states.pop().expect(\"parent must have a state\");\n\n\t\t\tlet mut parent_new = (*parent.added).clone();\n\t\t\tlet mut parent_removed = (*parent.removed).clone();\n\n\t\t\tfor removed in statediffremoved.iter() {\n\t\t\t\tif !parent_new.remove(removed) {\n\t\t\t\t\t// It was not added in the parent and we removed it\n\t\t\t\t\tparent_removed.insert(*removed);\n\t\t\t\t}\n\t\t\t\t// Else it was added in the parent and we removed it again. We\n\t\t\t\t// can forget this change\n\t\t\t}\n\n\t\t\tfor new in statediffnew.iter() {\n\t\t\t\tif !parent_removed.remove(new) {\n\t\t\t\t\t// It was not touched in the parent and we added it\n\t\t\t\t\tparent_new.insert(*new);\n\t\t\t\t}\n\t\t\t\t// Else it was removed in the parent and we added it again. We\n\t\t\t\t// can forget this change\n\t\t\t}\n\n\t\t\tself.save_state_from_diff(\n\t\t\t\tshortstatehash,\n\t\t\t\tArc::new(parent_new),\n\t\t\t\tArc::new(parent_removed),\n\t\t\t\tdiffsum,\n\t\t\t\tparent_states,\n\t\t\t)?;\n\n\t\t\treturn Ok(());\n\t\t}\n\n\t\tif parent_states.is_empty() {\n\t\t\t// There is no parent layer, create a new state\n\t\t\tself.save_statediff(shortstatehash, &StateDiff {\n\t\t\t\tparent: None,\n\t\t\t\tadded: statediffnew,\n\t\t\t\tremoved: statediffremoved,\n\t\t\t});\n\n\t\t\treturn Ok(());\n\t\t}\n\n\t\t// Else we have two options.\n\t\t// 1. We add the current diff on top of the parent layer.\n\t\t// 2. We replace a layer above\n\n\t\tlet parent = parent_states.pop().expect(\"parent must have a state\");\n\t\tlet parent_added_len = parent.added.len();\n\t\tlet parent_removed_len = parent.removed.len();\n\t\tlet parent_diff = checked!(parent_added_len + parent_removed_len)?;\n\n\t\tif checked!(diffsum * diffsum)? >= checked!(2 * diff_to_sibling * parent_diff)? {\n\t\t\t// Diff too big, we replace above layer(s)\n\t\t\tlet mut parent_new = (*parent.added).clone();\n\t\t\tlet mut parent_removed = (*parent.removed).clone();\n\n\t\t\tfor removed in statediffremoved.iter() {\n\t\t\t\tif !parent_new.remove(removed) {\n\t\t\t\t\t// It was not added in the parent and we removed it\n\t\t\t\t\tparent_removed.insert(*removed);\n\t\t\t\t}\n\t\t\t\t// Else it was added in the parent and we removed it again. We\n\t\t\t\t// can forget this change\n\t\t\t}\n\n\t\t\tfor new in statediffnew.iter() {\n\t\t\t\tif !parent_removed.remove(new) {\n\t\t\t\t\t// It was not touched in the parent and we added it\n\t\t\t\t\tparent_new.insert(*new);\n\t\t\t\t}\n\t\t\t\t// Else it was removed in the parent and we added it again. We\n\t\t\t\t// can forget this change\n\t\t\t}\n\n\t\t\tself.save_state_from_diff(\n\t\t\t\tshortstatehash,\n\t\t\t\tArc::new(parent_new),\n\t\t\t\tArc::new(parent_removed),\n\t\t\t\tdiffsum,\n\t\t\t\tparent_states,\n\t\t\t)?;\n\t\t} else {\n\t\t\t// Diff small enough, we add diff as layer on top of parent\n\t\t\tself.save_statediff(shortstatehash, &StateDiff {\n\t\t\t\tparent: Some(parent.shortstatehash),\n\t\t\t\tadded: statediffnew,\n\t\t\t\tremoved: statediffremoved,\n\t\t\t});\n\t\t}\n\n\t\tOk(())\n\t}\n```"}], "func_name": "save_state_from_diff", "docstring": "Creates a new shortstatehash that often is just a diff to an already\nexisting shortstatehash and therefore very efficient.\n\nThere are multiple layers of diffs. The bottom layer 0 always contains\nthe full state. Layer 1 contains diffs to states of layer 0, layer 2\ndiffs to layer 1 and so on. If layer n > 0 grows too big, it will be\ncombined with layer n-1 to create a new diff on layer n-1 that's\nbased on layer n-2. If that layer is also too big, it will recursively\nfix above layers too.\n\n* `shortstatehash` - Shortstatehash of this state\n* `statediffnew` - Added to base. Each vec is shortstatekey+shorteventid\n* `statediffremoved` - Removed from base. Each vec is\nshortstatekey+shorteventid\n* `diff_to_sibling` - Approximately how much the diff grows each time\nfor this layer\n* `parent_states` - A stack with info on shortstatehash, full state,\nadded diff and removed diff for each parent layer", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/state_compressor/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/state_compressor/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48a65c54a05f2efec745cfcc1eb49a47b8c8e82ed4066f868ed61b84e4534bde"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_pdu_count\n\nDocumentation:\nReturns the `count` of this pdu's id.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn get_pdu_count(&self, event_id: &EventId) -> Result {\n\t\tself.get_pdu_id(event_id)\n\t\t\t.await\n\t\t\t.map(|pdu_id| pdu_id.pdu_count())\n\t}\n```"}], "func_name": "get_pdu_count", "docstring": "Returns the `count` of this pdu's id.", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/timeline/data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/timeline/data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4fc5784d51dc1a020ed17c1452ac3165640d6df4100062c4810bd5ce2e398522"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_non_outlier_pdu\n\nDocumentation:\nReturns the pdu directly from `eventid_pduid` only.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn get_non_outlier_pdu(&self, event_id: &EventId) -> Result {\n\t\tlet pduid = self.get_pdu_id(event_id).await?;\n\n\t\tself.pduid_pdu.get(&pduid).await.deserialized()\n\t}\n```"}], "func_name": "get_non_outlier_pdu", "docstring": "Returns the pdu directly from `eventid_pduid` only.", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/timeline/data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/timeline/data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f4bacfdabfae380a3c0886182b633c4668dc48f4ec0f24997ccbc4da5c6ab0b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: non_outlier_pdu_exists\n\nDocumentation:\nLike get_non_outlier_pdu(), but without the expense of fetching and\nparsing the PduEvent\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn non_outlier_pdu_exists(&self, event_id: &EventId) -> Result {\n\t\tlet pduid = self.get_pdu_id(event_id).await?;\n\n\t\tself.pduid_pdu.exists(&pduid).await\n\t}\n```"}], "func_name": "non_outlier_pdu_exists", "docstring": "Like get_non_outlier_pdu(), but without the expense of fetching and\nparsing the PduEvent", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/timeline/data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/timeline/data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "db071f832bcd7cdedc60032b4811a59a69c83e2a9f309cc188bbb26f04df4e38"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_pdu\n\nDocumentation:\nReturns the pdu.\n\nChecks the `eventid_outlierpdu` Tree if not found in the timeline.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn get_pdu(&self, event_id: &EventId) -> Result {\n\t\tlet accepted = self.get_non_outlier_pdu(event_id).boxed();\n\t\tlet outlier = self\n\t\t\t.eventid_outlierpdu\n\t\t\t.get(event_id)\n\t\t\t.map(Deserialized::deserialized)\n\t\t\t.boxed();\n\n\t\tselect_ok([accepted, outlier]).await.map(at!(0))\n\t}\n```"}], "func_name": "get_pdu", "docstring": "Returns the pdu.\n\nChecks the `eventid_outlierpdu` Tree if not found in the timeline.", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/timeline/data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/timeline/data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b32c6487b7d0f8fcc0e398df40343bd2f16524e305f97bdae03fce8fe097db87"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pdu_exists\n\nDocumentation:\nLike get_pdu(), but without the expense of fetching and parsing the data\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn pdu_exists(&self, event_id: &EventId) -> Result {\n\t\tlet non_outlier = self.non_outlier_pdu_exists(event_id).boxed();\n\t\tlet outlier = self.outlier_pdu_exists(event_id).boxed();\n\n\t\tselect_ok([non_outlier, outlier]).await.map(at!(0))\n\t}\n```"}], "func_name": "pdu_exists", "docstring": "Like get_pdu(), but without the expense of fetching and parsing the data", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/timeline/data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/timeline/data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f9355b689a10d6df25d279f0bcc95d21110b421978e4bf45e8599502cfc3dfb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_pdu_json_from_id\n\nDocumentation:\nReturns the pdu as a `BTreeMap`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn get_pdu_json_from_id(\n\t\t&self,\n\t\tpdu_id: &RawPduId,\n\t) -> Result {\n\t\tself.pduid_pdu.get(pdu_id).await.deserialized()\n\t}\n```"}], "func_name": "get_pdu_json_from_id", "docstring": "Returns the pdu as a `BTreeMap`.", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/timeline/data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/timeline/data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "391a64d4a9a03d95c427d8b021eaca89c36d629a782b50ac3f392fe66efb7d17"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: replace_pdu\n\nDocumentation:\nRemoves a pdu and creates a new one with the same id.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn replace_pdu(\n\t\t&self,\n\t\tpdu_id: &RawPduId,\n\t\tpdu_json: &CanonicalJsonObject,\n\t\t_pdu: &PduEvent,\n\t) -> Result {\n\t\tif self.pduid_pdu.get(pdu_id).await.is_not_found() {\n\t\t\treturn Err!(Request(NotFound(\"PDU does not exist.\")));\n\t\t}\n\n\t\tself.pduid_pdu.raw_put(pdu_id, Json(pdu_json));\n\n\t\tOk(())\n\t}\n```"}], "func_name": "replace_pdu", "docstring": "Removes a pdu and creates a new one with the same id.", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/timeline/data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/timeline/data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d58c90d5d5cab77db0c3ba762b9abf15762be358c1a59f12a73ea894d348a54b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pdus_rev\n\nDocumentation:\nReturns an iterator over all events and their tokens in a room that\nhappened before the event with id `until` in reverse-chronological\norder.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn pdus_rev<'a>(\n\t\t&'a self,\n\t\tuser_id: Option<&'a UserId>,\n\t\troom_id: &'a RoomId,\n\t\tuntil: PduCount,\n\t) -> impl Stream> + Send + 'a {\n\t\tself.count_to_id(room_id, until, Direction::Backward)\n\t\t\t.map_ok(move |current| {\n\t\t\t\tlet prefix = current.shortroomid();\n\t\t\t\tself.pduid_pdu\n\t\t\t\t\t.rev_raw_stream_from(¤t)\n\t\t\t\t\t.ready_try_take_while(move |(key, _)| Ok(key.starts_with(&prefix)))\n\t\t\t\t\t.ready_and_then(move |item| Self::each_pdu(item, user_id))\n\t\t\t})\n\t\t\t.try_flatten_stream()\n\t}\n```"}], "func_name": "pdus_rev", "docstring": "Returns an iterator over all events and their tokens in a room that\nhappened before the event with id `until` in reverse-chronological\norder.", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/timeline/data.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/timeline/data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82e965c36d66fcfd8dbb534f5a2d9333e545f63a44e57dc1ff1a817bff2506d8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pdu_exists\n\nDocumentation:\nChecks if pdu exists\n\nChecks the `eventid_outlierpdu` Tree if not found in the timeline.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pdu_exists<'a>(\n\t\t&'a self,\n\t\tevent_id: &'a EventId,\n\t) -> impl Future + Send + 'a {\n\t\tself.db.pdu_exists(event_id).is_ok()\n\t}\n```"}], "func_name": "pdu_exists", "docstring": "Checks if pdu exists\n\nChecks the `eventid_outlierpdu` Tree if not found in the timeline.", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/timeline/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/timeline/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1dd6a9ab6dae92ddb52e5f615457d007bcba54d5861ec57efd739f3d810acb3d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: typing_add\n\nDocumentation:\nSets a user as typing until the timeout timestamp is reached or\nroomtyping_remove is called.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn typing_add(\n\t\t&self,\n\t\tuser_id: &UserId,\n\t\troom_id: &RoomId,\n\t\ttimeout: u64,\n\t) -> Result<()> {\n\t\tdebug_info!(\"typing started {user_id:?} in {room_id:?} timeout:{timeout:?}\");\n\t\t// update clients\n\t\tself.typing\n\t\t\t.write()\n\t\t\t.await\n\t\t\t.entry(room_id.to_owned())\n\t\t\t.or_default()\n\t\t\t.insert(user_id.to_owned(), timeout);\n\n\t\tself.last_typing_update\n\t\t\t.write()\n\t\t\t.await\n\t\t\t.insert(room_id.to_owned(), self.services.globals.next_count()?);\n\n\t\tif self.typing_update_sender.send(room_id.to_owned()).is_err() {\n\t\t\ttrace!(\"receiver found what it was looking for and is no longer interested\");\n\t\t}\n\n\t\t// update federation\n\t\tif self.services.globals.user_is_local(user_id) {\n\t\t\tself.federation_send(room_id, user_id, true).await?;\n\t\t}\n\n\t\tOk(())\n\t}\n```"}], "func_name": "typing_add", "docstring": "Sets a user as typing until the timeout timestamp is reached or\nroomtyping_remove is called.", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/typing/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/typing/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cffd450bddf050339a6812ce8f85d596407c3da3268ed2d3ab0ca00ec1487951"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: typing_remove\n\nDocumentation:\nRemoves a user from typing before the timeout is reached.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn typing_remove(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {\n\t\tdebug_info!(\"typing stopped {user_id:?} in {room_id:?}\");\n\t\t// update clients\n\t\tself.typing\n\t\t\t.write()\n\t\t\t.await\n\t\t\t.entry(room_id.to_owned())\n\t\t\t.or_default()\n\t\t\t.remove(user_id);\n\n\t\tself.last_typing_update\n\t\t\t.write()\n\t\t\t.await\n\t\t\t.insert(room_id.to_owned(), self.services.globals.next_count()?);\n\n\t\tif self.typing_update_sender.send(room_id.to_owned()).is_err() {\n\t\t\ttrace!(\"receiver found what it was looking for and is no longer interested\");\n\t\t}\n\n\t\t// update federation\n\t\tif self.services.globals.user_is_local(user_id) {\n\t\t\tself.federation_send(room_id, user_id, false).await?;\n\t\t}\n\n\t\tOk(())\n\t}\n```"}], "func_name": "typing_remove", "docstring": "Removes a user from typing before the timeout is reached.", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/typing/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/typing/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82ba08fc2d2779762fe9fae5e2e7e789c241d9a8b7531c8769e3a4b5be3de783"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: typings_maintain\n\nDocumentation:\nMakes sure that typing events with old timestamps get removed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn typings_maintain(&self, room_id: &RoomId) -> Result<()> {\n\t\tlet current_timestamp = utils::millis_since_unix_epoch();\n\t\tlet mut removable = Vec::new();\n\n\t\t{\n\t\t\tlet typing = self.typing.read().await;\n\t\t\tlet Some(room) = typing.get(room_id) else {\n\t\t\t\treturn Ok(());\n\t\t\t};\n\n\t\t\tfor (user, timeout) in room {\n\t\t\t\tif *timeout < current_timestamp {\n\t\t\t\t\tremovable.push(user.clone());\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tif !removable.is_empty() {\n\t\t\tlet typing = &mut self.typing.write().await;\n\t\t\tlet room = typing.entry(room_id.to_owned()).or_default();\n\t\t\tfor user in &removable {\n\t\t\t\tdebug_info!(\"typing timeout {user:?} in {room_id:?}\");\n\t\t\t\troom.remove(user);\n\t\t\t}\n\n\t\t\t// update clients\n\t\t\tself.last_typing_update\n\t\t\t\t.write()\n\t\t\t\t.await\n\t\t\t\t.insert(room_id.to_owned(), self.services.globals.next_count()?);\n\n\t\t\tif self.typing_update_sender.send(room_id.to_owned()).is_err() {\n\t\t\t\ttrace!(\"receiver found what it was looking for and is no longer interested\");\n\t\t\t}\n\n\t\t\t// update federation\n\t\t\tfor user in &removable {\n\t\t\t\tif self.services.globals.user_is_local(user) {\n\t\t\t\t\tself.federation_send(room_id, user, false).await?;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tOk(())\n\t}\n```"}], "func_name": "typings_maintain", "docstring": "Makes sure that typing events with old timestamps get removed.", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/typing/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/typing/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9eee84b833cb0bc89ef66dfad9190b4a20f6c3abe4542190fa45ac930a2de676"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: last_typing_update\n\nDocumentation:\nReturns the count of the last typing update in this room.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn last_typing_update(&self, room_id: &RoomId) -> Result {\n\t\tself.typings_maintain(room_id).await?;\n\t\tOk(self\n\t\t\t.last_typing_update\n\t\t\t.read()\n\t\t\t.await\n\t\t\t.get(room_id)\n\t\t\t.copied()\n\t\t\t.unwrap_or(0))\n\t}\n```"}], "func_name": "last_typing_update", "docstring": "Returns the count of the last typing update in this room.", "repo": "girlbossceo/conduwuit", "path": "src/service/rooms/typing/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/rooms/typing/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9698ff9ce6404448003b570c31fd957109867a29ee7ce3700beab5e99a3f60e7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_request\n\nDocumentation:\nSends a request to an appservice\n\nOnly returns Ok(None) if there is no url specified in the appservice\nregistration file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn send_request(\n\tclient: &Client,\n\tregistration: Registration,\n\trequest: T,\n) -> Result>\nwhere\n\tT: OutgoingRequest + Debug + Send,\n{\n\tconst VERSIONS: [MatrixVersion; 1] = [MatrixVersion::V1_7];\n\n\tlet Some(dest) = registration.url else {\n\t\treturn Ok(None);\n\t};\n\n\tif dest == *\"null\" || dest.is_empty() {\n\t\treturn Ok(None);\n\t}\n\n\ttrace!(\"Appservice URL \\\"{dest}\\\", Appservice ID: {}\", registration.id);\n\n\tlet hs_token = registration.hs_token.as_str();\n\tlet mut http_request = request\n\t\t.try_into_http_request::(\n\t\t\t&dest,\n\t\t\tSendAccessToken::IfRequired(hs_token),\n\t\t\t&VERSIONS,\n\t\t)\n\t\t.map_err(|e| {\n\t\t\terr!(BadServerResponse(\n\t\t\t\twarn!(appservice = %registration.id, \"Failed to find destination {dest}: {e:?}\")\n\t\t\t))\n\t\t})?\n\t\t.map(BytesMut::freeze);\n\n\tlet mut parts = http_request.uri().clone().into_parts();\n\tlet old_path_and_query = parts.path_and_query.unwrap().as_str().to_owned();\n\tlet symbol = if old_path_and_query.contains('?') { \"&\" } else { \"?\" };\n\n\tparts.path_and_query = Some(\n\t\t(old_path_and_query + symbol + \"access_token=\" + hs_token)\n\t\t\t.parse()\n\t\t\t.unwrap(),\n\t);\n\t*http_request.uri_mut() = parts.try_into().expect(\"our manipulation is always valid\");\n\n\tlet reqwest_request = reqwest::Request::try_from(http_request)?;\n\n\tlet mut response = client.execute(reqwest_request).await.map_err(|e| {\n\t\twarn!(\"Could not send request to appservice \\\"{}\\\" at {dest}: {e:?}\", registration.id);\n\t\te\n\t})?;\n\n\t// reqwest::Response -> http::Response conversion\n\tlet status = response.status();\n\tlet mut http_response_builder = http::Response::builder()\n\t\t.status(status)\n\t\t.version(response.version());\n\tmem::swap(\n\t\tresponse.headers_mut(),\n\t\thttp_response_builder\n\t\t\t.headers_mut()\n\t\t\t.expect(\"http::response::Builder is usable\"),\n\t);\n\n\tlet body = response.bytes().await?; // TODO: handle timeout\n\n\tif !status.is_success() {\n\t\tdebug_error!(\"Appservice response bytes: {:?}\", utils::string_from_bytes(&body));\n\t\treturn Err!(BadServerResponse(warn!(\n\t\t\t\"Appservice \\\"{}\\\" returned unsuccessful HTTP response {status} at {dest}\",\n\t\t\tregistration.id\n\t\t)));\n\t}\n\n\tlet response = T::IncomingResponse::try_from_http_response(\n\t\thttp_response_builder\n\t\t\t.body(body)\n\t\t\t.expect(\"reqwest body is valid http body\"),\n\t);\n\n\tresponse.map(Some).map_err(|e| {\n\t\terr!(BadServerResponse(warn!(\n\t\t\t\"Appservice \\\"{}\\\" returned invalid/malformed response bytes {dest}: {e}\",\n\t\t\tregistration.id\n\t\t)))\n\t})\n}\n```"}], "func_name": "send_request", "docstring": "Sends a request to an appservice\n\nOnly returns Ok(None) if there is no url specified in the appservice\nregistration file", "repo": "girlbossceo/conduwuit", "path": "src/service/sending/appservice.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/sending/appservice.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "85e2cf03de0d4aaea3464bcc90df0924070cf39dfa9bc201bd097e4399462507"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_appservice_request\n\nDocumentation:\nSends a request to an appservice\n\nOnly returns None if there is no url specified in the appservice\nregistration file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn send_appservice_request(\n\t\t&self,\n\t\tregistration: Registration,\n\t\trequest: T,\n\t) -> Result>\n\twhere\n\t\tT: OutgoingRequest + Debug + Send,\n\t{\n\t\tlet client = &self.services.client.appservice;\n\t\tappservice::send_request(client, registration, request).await\n\t}\n```"}], "func_name": "send_appservice_request", "docstring": "Sends a request to an appservice\n\nOnly returns None if there is no url specified in the appservice\nregistration file", "repo": "girlbossceo/conduwuit", "path": "src/service/sending/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/sending/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "572fad62e02470d52dbb706d004e444d9280810113a5d8bc0ec83eaa2f70a9ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: convert_to_outgoing_federation_event\n\nDocumentation:\nThis does not return a full `Pdu` it is only to satisfy ruma's types.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn convert_to_outgoing_federation_event(\n\t\t&self,\n\t\tmut pdu_json: CanonicalJsonObject,\n\t) -> Box {\n\t\tif let Some(unsigned) = pdu_json\n\t\t\t.get_mut(\"unsigned\")\n\t\t\t.and_then(|val| val.as_object_mut())\n\t\t{\n\t\t\tunsigned.remove(\"transaction_id\");\n\t\t}\n\n\t\t// room v3 and above removed the \"event_id\" field from remote PDU format\n\t\tif let Some(room_id) = pdu_json\n\t\t\t.get(\"room_id\")\n\t\t\t.and_then(|val| RoomId::parse(val.as_str()?).ok())\n\t\t{\n\t\t\tmatch self.services.state.get_room_version(room_id).await {\n\t\t\t\t| Ok(room_version_id) => match room_version_id {\n\t\t\t\t\t| RoomVersionId::V1 | RoomVersionId::V2 => {},\n\t\t\t\t\t| _ => _ = pdu_json.remove(\"event_id\"),\n\t\t\t\t},\n\t\t\t\t| Err(_) => _ = pdu_json.remove(\"event_id\"),\n\t\t\t}\n\t\t} else {\n\t\t\tpdu_json.remove(\"event_id\");\n\t\t}\n\n\t\t// TODO: another option would be to convert it to a canonical string to validate\n\t\t// size and return a Result>\n\t\t// serde_json::from_str::>(\n\t\t// ruma::serde::to_canonical_json_string(pdu_json).expect(\"CanonicalJson is\n\t\t// valid serde_json::Value\"), )\n\t\t// .expect(\"Raw::from_value always works\")\n\n\t\tto_raw_value(&pdu_json).expect(\"CanonicalJson is valid serde_json::Value\")\n\t}\n```"}], "func_name": "convert_to_outgoing_federation_event", "docstring": "This does not return a full `Pdu` it is only to satisfy ruma's types.", "repo": "girlbossceo/conduwuit", "path": "src/service/sending/sender.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/sending/sender.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f54faaef213e4c925b38408708e11e9604aa99904bbc1f4cf16a8c828f972001"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_or_sticky\n\nDocumentation:\nload params from cache if body doesn't contain it, as long as it's allowed\nin some cases we may need to allow an empty list as an actual value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn list_or_sticky(target: &mut Vec, cached: &Vec) {\n\tif target.is_empty() {\n\t\ttarget.clone_from(cached);\n\t}\n}\n```"}], "func_name": "list_or_sticky", "docstring": "load params from cache if body doesn't contain it, as long as it's allowed\nin some cases we may need to allow an empty list as an actual value", "repo": "girlbossceo/conduwuit", "path": "src/service/sync/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/sync/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "15425be3ad82529c0c89c3e04f9f5bdc8c44efce510e6f6eb8b3d2cdc9dc957f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: user_is_ignored\n\nDocumentation:\nReturns true/false based on whether the recipient/receiving user has\nblocked the sender\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn user_is_ignored(&self, sender_user: &UserId, recipient_user: &UserId) -> bool {\n\t\tself.services\n\t\t\t.account_data\n\t\t\t.get_global(recipient_user, GlobalAccountDataEventType::IgnoredUserList)\n\t\t\t.await\n\t\t\t.is_ok_and(|ignored: IgnoredUserListEvent| {\n\t\t\t\tignored\n\t\t\t\t\t.content\n\t\t\t\t\t.ignored_users\n\t\t\t\t\t.keys()\n\t\t\t\t\t.any(|blocked_user| blocked_user == sender_user)\n\t\t\t})\n\t}\n```"}], "func_name": "user_is_ignored", "docstring": "Returns true/false based on whether the recipient/receiving user has\nblocked the sender", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "568ac60ac2b81ea40ebd7b9f432fda2310dd7f894cec4022e75a9995d92d4994"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_active_local\n\nDocumentation:\nCheck if account is active, infallible\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn is_active_local(&self, user_id: &UserId) -> bool {\n\t\tself.services.globals.user_is_local(user_id) && self.is_active(user_id).await\n\t}\n```"}], "func_name": "is_active_local", "docstring": "Check if account is active, infallible", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3889f7e8de3719a339f27add80acc2e8f62b81dbbeb0cd7f95ed61d0bc5c2319"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_local_users\n\nDocumentation:\nReturns a list of local users as list of usernames.\n\nA user account is considered `local` if the length of it's password is\ngreater then zero.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_local_users(&self) -> impl Stream + Send + '_ {\n\t\tself.db\n\t\t\t.userid_password\n\t\t\t.stream()\n\t\t\t.ignore_err()\n\t\t\t.ready_filter_map(|(u, p): (&UserId, &[u8])| (!p.is_empty()).then_some(u))\n\t}\n```"}], "func_name": "list_local_users", "docstring": "Returns a list of local users as list of usernames.\n\nA user account is considered `local` if the length of it's password is\ngreater then zero.", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f0ac5147da064f75cff0f3af7f1d395be743117665e4d9a9e30260f542d81bc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_password\n\nDocumentation:\nHash and set the user's password to the Argon2 hash\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_password(&self, user_id: &UserId, password: Option<&str>) -> Result<()> {\n\t\tpassword\n\t\t\t.map(utils::hash::password)\n\t\t\t.transpose()\n\t\t\t.map_err(|e| {\n\t\t\t\terr!(Request(InvalidParam(\"Password does not meet the requirements: {e}\")))\n\t\t\t})?\n\t\t\t.map_or_else(\n\t\t\t\t|| self.db.userid_password.insert(user_id, b\"\"),\n\t\t\t\t|hash| self.db.userid_password.insert(user_id, hash),\n\t\t\t);\n\n\t\tOk(())\n\t}\n```"}], "func_name": "set_password", "docstring": "Hash and set the user's password to the Argon2 hash", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "39a4c83a065102d7231fd71064a05324cd269cc848489d84d8834295542e5379"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_displayname\n\nDocumentation:\nSets a new displayname or removes it if displayname is None. You still\nneed to nofify all rooms of this change.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_displayname(&self, user_id: &UserId, displayname: Option) {\n\t\tif let Some(displayname) = displayname {\n\t\t\tself.db.userid_displayname.insert(user_id, displayname);\n\t\t} else {\n\t\t\tself.db.userid_displayname.remove(user_id);\n\t\t}\n\t}\n```"}], "func_name": "set_displayname", "docstring": "Sets a new displayname or removes it if displayname is None. You still\nneed to nofify all rooms of this change.", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "136a1f5d49162d6ba201c24bf5f41fea531300d3344b311bd6db59475d815848"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_avatar_url\n\nDocumentation:\nSets a new avatar_url or removes it if avatar_url is None.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_avatar_url(&self, user_id: &UserId, avatar_url: Option) {\n\t\tmatch avatar_url {\n\t\t\t| Some(avatar_url) => {\n\t\t\t\tself.db.userid_avatarurl.insert(user_id, &avatar_url);\n\t\t\t},\n\t\t\t| _ => {\n\t\t\t\tself.db.userid_avatarurl.remove(user_id);\n\t\t\t},\n\t\t}\n\t}\n```"}], "func_name": "set_avatar_url", "docstring": "Sets a new avatar_url or removes it if avatar_url is None.", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5e1f91967fc95a269b592d7f8ce421b95f53919ebc10e1abbb18ab115eafd42f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: all_device_ids\n\nDocumentation:\nReturns an iterator over all device ids of this user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn all_device_ids<'a>(\n\t\t&'a self,\n\t\tuser_id: &'a UserId,\n\t) -> impl Stream + Send + 'a {\n\t\tlet prefix = (user_id, Interfix);\n\t\tself.db\n\t\t\t.userdeviceid_metadata\n\t\t\t.keys_prefix(&prefix)\n\t\t\t.ignore_err()\n\t\t\t.map(|(_, device_id): (Ignore, &DeviceId)| device_id)\n\t}\n```"}], "func_name": "all_device_ids", "docstring": "Returns an iterator over all device ids of this user.", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "67510afbdc852d509cd008eb39f063f77d5fe38128e3f9cff4f0153420b032ea"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_token\n\nDocumentation:\nReplaces the access token of one device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn set_token(\n\t\t&self,\n\t\tuser_id: &UserId,\n\t\tdevice_id: &DeviceId,\n\t\ttoken: &str,\n\t) -> Result<()> {\n\t\tlet key = (user_id, device_id);\n\t\tif self.db.userdeviceid_metadata.qry(&key).await.is_err() {\n\t\t\treturn Err!(Database(error!(\n\t\t\t\t?user_id,\n\t\t\t\t?device_id,\n\t\t\t\t\"User does not exist or device has no metadata.\"\n\t\t\t)));\n\t\t}\n\n\t\t// Remove old token\n\t\tif let Ok(old_token) = self.db.userdeviceid_token.qry(&key).await {\n\t\t\tself.db.token_userdeviceid.remove(&old_token);\n\t\t\t// It will be removed from userdeviceid_token by the insert later\n\t\t}\n\n\t\t// Assign token to user device combination\n\t\tself.db.userdeviceid_token.put_raw(key, token);\n\t\tself.db.token_userdeviceid.raw_put(token, key);\n\n\t\tOk(())\n\t}\n```"}], "func_name": "set_token", "docstring": "Replaces the access token of one device.", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a214ccdb52ea729887c817d01eac4f71de176eb61872b9cad7d1c0a320e415d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_filter\n\nDocumentation:\nCreates a new sync filter. Returns the filter id.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_filter(&self, user_id: &UserId, filter: &FilterDefinition) -> String {\n\t\tlet filter_id = utils::random_string(4);\n\n\t\tlet key = (user_id, &filter_id);\n\t\tself.db.userfilterid_filter.put(key, Json(filter));\n\n\t\tfilter_id\n\t}\n```"}], "func_name": "create_filter", "docstring": "Creates a new sync filter. Returns the filter id.", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba2b385c3a26e9f9fde9d1384e13690855dd23aaeb81b8c332a88fc225e0a290"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_openid_token\n\nDocumentation:\nCreates an OpenID token, which can be used to prove that a user has\naccess to an account (primarily for integrations)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_openid_token(&self, user_id: &UserId, token: &str) -> Result {\n\t\tuse std::num::Saturating as Sat;\n\n\t\tlet expires_in = self.services.server.config.openid_token_ttl;\n\t\tlet expires_at = Sat(utils::millis_since_unix_epoch()) + Sat(expires_in) * Sat(1000);\n\n\t\tlet mut value = expires_at.0.to_be_bytes().to_vec();\n\t\tvalue.extend_from_slice(user_id.as_bytes());\n\n\t\tself.db\n\t\t\t.openidtoken_expiresatuserid\n\t\t\t.insert(token.as_bytes(), value.as_slice());\n\n\t\tOk(expires_in)\n\t}\n```"}], "func_name": "create_openid_token", "docstring": "Creates an OpenID token, which can be used to prove that a user has\naccess to an account (primarily for integrations)", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c09142636ef91be81bd8f8f534ad1af4fee018448d2dd3b8b325feed543a29ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: find_from_openid_token\n\nDocumentation:\nFind out which user an OpenID access token belongs to.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn find_from_openid_token(&self, token: &str) -> Result {\n\t\tlet Ok(value) = self.db.openidtoken_expiresatuserid.get(token).await else {\n\t\t\treturn Err!(Request(Unauthorized(\"OpenID token is unrecognised\")));\n\t\t};\n\n\t\tlet (expires_at_bytes, user_bytes) = value.split_at(0_u64.to_be_bytes().len());\n\t\tlet expires_at =\n\t\t\tu64::from_be_bytes(expires_at_bytes.try_into().map_err(|e| {\n\t\t\t\terr!(Database(\"expires_at in openid_userid is invalid u64. {e}\"))\n\t\t\t})?);\n\n\t\tif expires_at < utils::millis_since_unix_epoch() {\n\t\t\tdebug_warn!(\"OpenID token is expired, removing\");\n\t\t\tself.db.openidtoken_expiresatuserid.remove(token.as_bytes());\n\n\t\t\treturn Err!(Request(Unauthorized(\"OpenID token is expired\")));\n\t\t}\n\n\t\tlet user_string = utils::string_from_bytes(user_bytes)\n\t\t\t.map_err(|e| err!(Database(\"User ID in openid_userid is invalid unicode. {e}\")))?;\n\n\t\tOwnedUserId::try_from(user_string)\n\t\t\t.map_err(|e| err!(Database(\"User ID in openid_userid is invalid. {e}\")))\n\t}\n```"}], "func_name": "find_from_openid_token", "docstring": "Find out which user an OpenID access token belongs to.", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c535b8b883eafb275776767b9664a4daad1daa35b49a8cc6434b613c3e40b661"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_login_token\n\nDocumentation:\nCreates a short-lived login token, which can be used to log in using the\n`m.login.token` mechanism.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_login_token(&self, user_id: &UserId, token: &str) -> u64 {\n\t\tuse std::num::Saturating as Sat;\n\n\t\tlet expires_in = self.services.server.config.login_token_ttl;\n\t\tlet expires_at = Sat(utils::millis_since_unix_epoch()) + Sat(expires_in);\n\n\t\tlet value = (expires_at.0, user_id);\n\t\tself.db.logintoken_expiresatuserid.raw_put(token, value);\n\n\t\texpires_in\n\t}\n```"}], "func_name": "create_login_token", "docstring": "Creates a short-lived login token, which can be used to log in using the\n`m.login.token` mechanism.", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "868fc37ca668c06ebf28da096b3f8593dabc173e5ca7356cc11018d1da07e23e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: find_from_login_token\n\nDocumentation:\nFind out which user a login token belongs to.\nRemoves the token to prevent double-use attacks.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn find_from_login_token(&self, token: &str) -> Result {\n\t\tlet Ok(value) = self.db.logintoken_expiresatuserid.get(token).await else {\n\t\t\treturn Err!(Request(Forbidden(\"Login token is unrecognised\")));\n\t\t};\n\t\tlet (expires_at, user_id): (u64, OwnedUserId) = value.deserialized()?;\n\n\t\tif expires_at < utils::millis_since_unix_epoch() {\n\t\t\ttrace!(?user_id, ?token, \"Removing expired login token\");\n\n\t\t\tself.db.logintoken_expiresatuserid.remove(token);\n\n\t\t\treturn Err!(Request(Forbidden(\"Login token is expired\")));\n\t\t}\n\n\t\tself.db.logintoken_expiresatuserid.remove(token);\n\n\t\tOk(user_id)\n\t}\n```"}], "func_name": "find_from_login_token", "docstring": "Find out which user a login token belongs to.\nRemoves the token to prevent double-use attacks.", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d6bfb8baf7d359da0071d660ac040a743b78f4da6980664def3437fdcb063ce"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: all_profile_keys\n\nDocumentation:\nGets all the user's profile keys and values in an iterator\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn all_profile_keys<'a>(\n\t\t&'a self,\n\t\tuser_id: &'a UserId,\n\t) -> impl Stream + 'a + Send {\n\t\ttype KeyVal = ((Ignore, String), serde_json::Value);\n\n\t\tlet prefix = (user_id, Interfix);\n\t\tself.db\n\t\t\t.useridprofilekey_value\n\t\t\t.stream_prefix(&prefix)\n\t\t\t.ignore_err()\n\t\t\t.map(|((_, key), val): KeyVal| (key, val))\n\t}\n```"}], "func_name": "all_profile_keys", "docstring": "Gets all the user's profile keys and values in an iterator", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51a70cf763e55fc48acae395b0a95f2d8e62f10d6ec861adcd793ee40fc4cf9d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_profile_key\n\nDocumentation:\nSets a new profile key value, removes the key if value is None\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_profile_key(\n\t\t&self,\n\t\tuser_id: &UserId,\n\t\tprofile_key: &str,\n\t\tprofile_key_value: Option,\n\t) {\n\t\t// TODO: insert to the stable MSC4175 key when it's stable\n\t\tlet key = (user_id, profile_key);\n\n\t\tif let Some(value) = profile_key_value {\n\t\t\tself.db.useridprofilekey_value.put(key, Json(value));\n\t\t} else {\n\t\t\tself.db.useridprofilekey_value.del(key);\n\t\t}\n\t}\n```"}], "func_name": "set_profile_key", "docstring": "Sets a new profile key value, removes the key if value is None", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1bee26afacc4c42616d7b0e884ab4f4c6885f991b5dcb8324891f2415069a181"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_timezone\n\nDocumentation:\nSets a new timezone or removes it if timezone is None.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_timezone(&self, user_id: &UserId, timezone: Option) {\n\t\t// TODO: insert to the stable MSC4175 key when it's stable\n\t\tlet key = (user_id, \"us.cloke.msc4175.tz\");\n\n\t\tif let Some(timezone) = timezone {\n\t\t\tself.db.useridprofilekey_value.put_raw(key, &timezone);\n\t\t} else {\n\t\t\tself.db.useridprofilekey_value.del(key);\n\t\t}\n\t}\n```"}], "func_name": "set_timezone", "docstring": "Sets a new timezone or removes it if timezone is None.", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d44544273c508b12f2cf8483d570dcb46647732d6831e39ca6ce5077a3a19fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clean_signatures\n\nDocumentation:\nEnsure that a user only sees signatures from themselves and the target user\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn clean_signatures(\n\tmut cross_signing_key: serde_json::Value,\n\tsender_user: Option<&UserId>,\n\tuser_id: &UserId,\n\tallowed_signatures: &F,\n) -> Result\nwhere\n\tF: Fn(&UserId) -> bool + Send + Sync,\n{\n\tif let Some(signatures) = cross_signing_key\n\t\t.get_mut(\"signatures\")\n\t\t.and_then(|v| v.as_object_mut())\n\t{\n\t\t// Don't allocate for the full size of the current signatures, but require\n\t\t// at most one resize if nothing is dropped\n\t\tlet new_capacity = signatures.len() / 2;\n\t\tfor (user, signature) in\n\t\t\tmem::replace(signatures, serde_json::Map::with_capacity(new_capacity))\n\t\t{\n\t\t\tlet sid = <&UserId>::try_from(user.as_str())\n\t\t\t\t.map_err(|_| Error::bad_database(\"Invalid user ID in database.\"))?;\n\t\t\tif sender_user == Some(user_id) || sid == user_id || allowed_signatures(sid) {\n\t\t\t\tsignatures.insert(user, signature);\n\t\t\t}\n\t\t}\n\t}\n\n\tOk(cross_signing_key)\n}\n```"}], "func_name": "clean_signatures", "docstring": "Ensure that a user only sees signatures from themselves and the target user", "repo": "girlbossceo/conduwuit", "path": "src/service/users/mod.rs", "url": "https://github.com/girlbossceo/conduwuit/blob/master/src/service/users/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3da05e58a79135671d359c095728fa9ea33f119fb78dff51d919e8e3da4f5f24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: gen_connection_check_apt_fallback\n\nDocumentation:\nNo other command is available, so fallback to apt, though doesn't check connection without name resolving.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn gen_connection_check_apt_fallback(uri: &str) -> (&'static str, String) {\n if ('0'..='9').contains(&uri.chars().last().unwrap()) {\n // this is an ip address\n (\"command -v apt\", \"true\".to_owned())\n } else {\n (\"command -v apt\", \"sudo apt update\".to_owned())\n }\n}\n```"}], "func_name": "gen_connection_check_apt_fallback", "docstring": "No other command is available, so fallback to apt, though doesn't check connection without name resolving.", "repo": "nullpo-head/wsl-distrod", "path": "distrod/distrod/tests/integration_test.rs", "url": "https://github.com/nullpo-head/wsl-distrod/blob/master/distrod/distrod/tests/integration_test.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "041fad39d656a8494c37717e51fa838a941d44ac83c8a2c9ea21a840c4c6075f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: gen_connection_check_zypper_fallback\n\nDocumentation:\nNo other command is available, so fallback to zypper, though doesn't check connection without name resolving.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn gen_connection_check_zypper_fallback(uri: &str) -> (&'static str, String) {\n if ('0'..='9').contains(&uri.chars().last().unwrap()) {\n // this is an ip address\n (\"command -v zypper\", \"true\".to_owned())\n } else {\n (\"command -v zypper\", \"sudo zypper refresh\".to_owned())\n }\n}\n```"}], "func_name": "gen_connection_check_zypper_fallback", "docstring": "No other command is available, so fallback to zypper, though doesn't check connection without name resolving.", "repo": "nullpo-head/wsl-distrod", "path": "distrod/distrod/tests/integration_test.rs", "url": "https://github.com/nullpo-head/wsl-distrod/blob/master/distrod/distrod/tests/integration_test.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b928f4bd97bdcbfb0ad3ecb48755acdd8a45de0dacc659ac5174fc89378b6bc6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delay_init_launch\n\nDocumentation:\nOn some distros, starting Systemd during WSL's /init being initialized on Windows startup\nmakes /init crash. So launch Systemd after some delay.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn delay_init_launch() {\n let delay_sec_str = match std::env::var(DISTROD_EXEC_DELAY_ENV_NAME) {\n Ok(delay_sec_str) => delay_sec_str,\n _ => return,\n };\n let delay_sec: u32 = match delay_sec_str.parse() {\n Ok(delay_sec) => delay_sec,\n Err(e) => {\n log::warn!(\n \"[BUG] Invalid {} was given: {:?}. {:?}\",\n DISTROD_EXEC_DELAY_ENV_NAME,\n delay_sec_str,\n e\n );\n return;\n }\n };\n\n log::debug!(\n \"Delaying launching init by {}sec. {:?}\",\n delay_sec,\n std::time::Instant::now()\n );\n std::thread::sleep(std::time::Duration::from_secs(delay_sec as u64));\n\n strip_wslenv_for_distod_exec_delay();\n log::debug!(\"delay finished {:?}\", std::time::Instant::now());\n}\n```"}], "func_name": "delay_init_launch", "docstring": "On some distros, starting Systemd during WSL's /init being initialized on Windows startup\nmakes /init crash. So launch Systemd after some delay.", "repo": "nullpo-head/wsl-distrod", "path": "distrod/distrod-exec/src/main.rs", "url": "https://github.com/nullpo-head/wsl-distrod/blob/master/distrod/distrod-exec/src/main.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "58690803b0a8841aca5e3a9373927ee811eb074ac25c86c34f183d4c5b234b43"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_init_pre_exec\n\nDocumentation:\n# Safety\nSee the notes and safety of https://doc.rust-lang.org/std/os/unix/process/trait.CommandExt.html#tymethod.pre_exec\nIn addition, note that registered pre_exec closures will run after the rootfs is set up including tmpfs such as /run.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub unsafe fn with_init_pre_exec(&mut self, f: F) -> &mut Self\n where\n F: FnMut() -> Result<()> + Send + Sync + 'static,\n {\n self.pre_exec_closures.push(Box::new(f));\n self\n }\n```"}], "func_name": "with_init_pre_exec", "docstring": "# Safety\nSee the notes and safety of https://doc.rust-lang.org/std/os/unix/process/trait.CommandExt.html#tymethod.pre_exec\nIn addition, note that registered pre_exec closures will run after the rootfs is set up including tmpfs such as /run.", "repo": "nullpo-head/wsl-distrod", "path": "distrod/libs/src/container.rs", "url": "https://github.com/nullpo-head/wsl-distrod/blob/master/distrod/libs/src/container.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "99530490526ac88f78d2e1bd77505c54489a5d65e62dd41fd2fb5e122a964029"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sanity_check_wsl_env\n\nDocumentation:\nMake sure that the values of WSL_INTEROP, WSLENV, and WSL_DISTRO_NAME are harmless values that can be\nwritten to /etc/environment and passed to Systemd via /proc/cmdline. These values may be polluted\nbecause distrod-exec can be launched by any user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn sanity_check_wsl_env(key: &OsStr, value: &OsStr) -> bool {\n if key == OsStr::new(\"WSL_INTEROP\") {\n sanity_check_wsl_interop(value)\n } else {\n sanity_check_general_wsl_envs(value)\n }\n}\n```"}], "func_name": "sanity_check_wsl_env", "docstring": "Make sure that the values of WSL_INTEROP, WSLENV, and WSL_DISTRO_NAME are harmless values that can be\nwritten to /etc/environment and passed to Systemd via /proc/cmdline. These values may be polluted\nbecause distrod-exec can be launched by any user.", "repo": "nullpo-head/wsl-distrod", "path": "distrod/libs/src/distro.rs", "url": "https://github.com/nullpo-head/wsl-distrod/blob/master/distrod/libs/src/distro.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f471e681037652ca24c3626afa0a3a4357b839f958173e190307d44e129807c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bench_file\n\nDocumentation:\nThis benchmarks decoding via a call to `Reader::next_frame`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn bench_file(g: &mut BenchmarkGroup, data: Vec, name: String) {\n if data.len() > 1_000_000 {\n g.sample_size(10);\n }\n\n let mut reader = create_reader(data.as_slice());\n let mut image = vec![0; reader.output_buffer_size()];\n let info = reader.next_frame(&mut image).unwrap();\n\n g.throughput(Throughput::Bytes(info.buffer_size() as u64));\n g.bench_with_input(name, &data, |b, data| {\n b.iter(|| {\n let mut reader = create_reader(data.as_slice());\n reader.next_frame(&mut image).unwrap();\n })\n });\n}\n```"}], "func_name": "bench_file", "docstring": "This benchmarks decoding via a call to `Reader::next_frame`.", "repo": "image-rs/image-png", "path": "benches/decoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/benches/decoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "84e120afaebaf977f8008883da9a87c2e096dc8856f76a814ea65f877b76a90f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bench_read_row\n\nDocumentation:\nThis benchmarks decoding via a sequence of `Reader::read_row` calls.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn bench_read_row(g: &mut BenchmarkGroup, data: Vec, name: &str) {\n let reader = create_reader(data.as_slice());\n let mut image = vec![0; reader.output_buffer_size()];\n let bytes_per_row = reader.output_line_size(reader.info().width);\n g.throughput(Throughput::Bytes(image.len() as u64));\n g.bench_with_input(name, &data, |b, data| {\n b.iter(|| {\n let mut reader = create_reader(data.as_slice());\n\n for output_row in image.chunks_exact_mut(bytes_per_row) {\n reader.read_row(output_row).unwrap().unwrap();\n }\n })\n });\n}\n```"}], "func_name": "bench_read_row", "docstring": "This benchmarks decoding via a sequence of `Reader::read_row` calls.", "repo": "image-rs/image-png", "path": "benches/decoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/benches/decoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a6dbc06b3d37bd1df77649ce74430dfb2790f927f085755415df4589d8ddcedd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: assert_all_results_are_consistent\n\nDocumentation:\nVerifies that either 1) all items in the iterator are `Ok(_)` or 2) all items in the\niterator are `Err(_)`. Passes through unmodified iterator items.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn assert_all_results_are_consistent(self) -> impl Iterator\n where\n Self: Iterator>,\n {\n // Eagerly collect all the items - this makes sure we check consistency of *all* results,\n // even if a downstream iterator combinator consumes items lazily and never \"pumps\" some\n // items via `next`. (`iter.take(2)` is one example of such lazy consumer;\n // `iter_of_results.collect::, _>>()` is another.)\n let all_results = self.collect::>();\n\n let any_err = all_results.iter().any(|res| res.is_err());\n let any_ok = all_results.iter().any(|res| res.is_ok());\n if any_err && any_ok {\n // Replacing `Self::Item` with an \"ok\" string, because we want to support items\n // that do not implement `Debug`.\n let printable_results = all_results.iter().map(|res| res.as_ref().map(|_| \"ok\"));\n for (i, res) in printable_results.enumerate() {\n eprintln!(\"Result #{i}: {res:?}\");\n }\n panic!(\"Inconsistent results - some are Ok(_) and some are Err(_)\");\n }\n\n all_results.into_iter()\n }\n```"}], "func_name": "assert_all_results_are_consistent", "docstring": "Verifies that either 1) all items in the iterator are `Ok(_)` or 2) all items in the\niterator are `Err(_)`. Passes through unmodified iterator items.", "repo": "image-rs/image-png", "path": "fuzz/fuzz_targets/buf_independent.rs", "url": "https://github.com/image-rs/image-png/blob/master/fuzz/fuzz_targets/buf_independent.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69630b21bc107d40332a4866b7a378403a4a06671c3862eb894b4be26e3c699e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: assert_all_items_are_equal\n\nDocumentation:\nVerifies that all items in the iterator are the same (according to their `Eq`\nimplementation). Returns one of the items.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn assert_all_items_are_equal(self) -> Self::Item\n where\n Self::Item: Debug + Eq,\n {\n self.assert_all_items_are_same(|lhs, rhs| assert_eq!(lhs, rhs))\n }\n```"}], "func_name": "assert_all_items_are_equal", "docstring": "Verifies that all items in the iterator are the same (according to their `Eq`\nimplementation). Returns one of the items.", "repo": "image-rs/image-png", "path": "fuzz/fuzz_targets/buf_independent.rs", "url": "https://github.com/image-rs/image-png/blob/master/fuzz/fuzz_targets/buf_independent.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9f47881b844e7ceff3c373dcc2be243ce7a4269c462fbbb9d74485b9a401f653"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: assert_all_items_are_same\n\nDocumentation:\nVerifies that all items in the iterator are the same (according to the `assert_same`\nfunction. Returns one of the items.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn assert_all_items_are_same(self, mut assert_same: F) -> ::Item\n where\n F: for<'a, 'b> FnMut(&'a Self::Item, &'b Self::Item),\n {\n self.enumerate()\n .reduce(|(i, lhs), (j, rhs)| {\n let panic = {\n let mut assert_same = std::panic::AssertUnwindSafe(&mut assert_same);\n let lhs = std::panic::AssertUnwindSafe(&lhs);\n let rhs = std::panic::AssertUnwindSafe(&rhs);\n std::panic::catch_unwind(move || assert_same(*lhs, *rhs))\n };\n match panic {\n Ok(_) => (),\n Err(panic) => {\n eprintln!(\"Difference found when comparing item #{i} and #{j}.\");\n std::panic::resume_unwind(panic);\n }\n }\n (\n j, lhs, /* Arbitrary - could just as well return `rhs` */\n )\n })\n .map(|(_index, item)| item)\n .expect(\"Expecting a non-empty iterator\")\n }\n```"}], "func_name": "assert_all_items_are_same", "docstring": "Verifies that all items in the iterator are the same (according to the `assert_same`\nfunction. Returns one of the items.", "repo": "image-rs/image-png", "path": "fuzz/fuzz_targets/buf_independent.rs", "url": "https://github.com/image-rs/image-png/blob/master/fuzz/fuzz_targets/buf_independent.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "132d423b983ad231402b85b41e53d0e53b8134c55bca48d593ea733b73ee4763"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: filter_from_u8\n\nDocumentation:\nFilter::from() doesn't cover the Filter::Adaptive variant, so we roll our own\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn filter_from_u8(input: u8) -> Filter {\n match input {\n 0 => Filter::NoFilter,\n 1 => Filter::Sub,\n 2 => Filter::Up,\n 3 => Filter::Avg,\n 4 => Filter::Paeth,\n _ => Filter::Adaptive,\n }\n}\n```"}], "func_name": "filter_from_u8", "docstring": "Filter::from() doesn't cover the Filter::Adaptive variant, so we roll our own", "repo": "image-rs/image-png", "path": "fuzz/fuzz_targets/roundtrip.rs", "url": "https://github.com/image-rs/image-png/blob/master/fuzz/fuzz_targets/roundtrip.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b4e4049a41b7e082ea48bf1b0bd4f425710e40a25934d1c7d1283ccb2d3cc088"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `Adam7Info`. May panic if the arguments are out of range (e.g. if `pass` is\n0 or greater than 8).\n\n* `pass` corresponds to a pass of the\n[the Adam7 algorithm](https://en.wikipedia.org/wiki/Adam7_algorithm)\n* `line` is the number of a line within a pass (starting with 0). For example,\nin an image of height 8, `line` can be beteween `0..4` in the 7th `pass`\n(those 4 interlaced rows correspond to 2nd, 4th, 6th, and 8th row of the full image).\n* `width` describes how many pixels are in an interlaced row. For example,\nin the 7th `pass`, the `width` is be the same as full image width, but in\nin the 1st `pass`, the `width` is be 1/8th of the image width (rounded up as\nnecessary).\n\nNote that in typical usage, `Adam7Info`s are returned by [Reader.next_interlaced_row]\nand there is no need to create them by calling `Adam7Info::new`. `Adam7Info::new` is\nnevertheless exposed as a public API, because it helps to provide self-contained example\nusage of [expand_interlaced_row](crate::expand_interlaced_row).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(pass: u8, line: u32, width: u32) -> Self {\n assert!(1 <= pass && pass <= 7);\n assert!(width > 0);\n Self { pass, line, width }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `Adam7Info`. May panic if the arguments are out of range (e.g. if `pass` is\n0 or greater than 8).\n\n* `pass` corresponds to a pass of the\n[the Adam7 algorithm](https://en.wikipedia.org/wiki/Adam7_algorithm)\n* `line` is the number of a line within a pass (starting with 0). For example,\nin an image of height 8, `line` can be beteween `0..4` in the 7th `pass`\n(those 4 interlaced rows correspond to 2nd, 4th, 6th, and 8th row of the full image).\n* `width` describes how many pixels are in an interlaced row. For example,\nin the 7th `pass`, the `width` is be the same as full image width, but in\nin the 1st `pass`, the `width` is be 1/8th of the image width (rounded up as\nnecessary).\n\nNote that in typical usage, `Adam7Info`s are returned by [Reader.next_interlaced_row]\nand there is no need to create them by calling `Adam7Info::new`. `Adam7Info::new` is\nnevertheless exposed as a public API, because it helps to provide self-contained example\nusage of [expand_interlaced_row](crate::expand_interlaced_row).", "repo": "image-rs/image-png", "path": "src/adam7.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/adam7.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d4c73ebed9039482d8db62013829388f7f2b27d42d1a0d3d6709687d369f15ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init_pass\n\nDocumentation:\nCalculates the bounds of the current pass\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn init_pass(&mut self) {\n let w = f64::from(self.width);\n let h = f64::from(self.height);\n let (line_width, lines) = match self.current_pass {\n 1 => (w / 8.0, h / 8.0),\n 2 => ((w - 4.0) / 8.0, h / 8.0),\n 3 => (w / 4.0, (h - 4.0) / 8.0),\n 4 => ((w - 2.0) / 4.0, h / 4.0),\n 5 => (w / 2.0, (h - 2.0) / 4.0),\n 6 => ((w - 1.0) / 2.0, h / 2.0),\n 7 => (w, (h - 1.0) / 2.0),\n _ => unreachable!(),\n };\n self.line_width = line_width.ceil() as u32;\n self.lines = lines.ceil() as u32;\n self.line = 0;\n }\n```"}], "func_name": "init_pass", "docstring": "Calculates the bounds of the current pass", "repo": "image-rs/image-png", "path": "src/adam7.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/adam7.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "24ba299d534a3fb6db4773b0cfaf3a0822b8ea156a85bf0511ca498dfbf065e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expand_adam7_bits\n\nDocumentation:\nGiven `row_stride`, interlace `info`, and bits-per-pixel, produce an iterator of bit positions\nof pixels to copy from the input scanline to the image buffer. The positions are expressed as\nbit offsets from position (0,0) in the frame that is currently being decoded.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn expand_adam7_bits(\n row_stride_in_bytes: usize,\n info: &Adam7Info,\n bits_pp: usize,\n) -> impl Iterator {\n let line_no = info.line as usize;\n let pass = info.pass;\n let interlaced_width = info.width as usize;\n\n let (line_mul, line_off, samp_mul, samp_off) = match pass {\n 1 => (8, 0, 8, 0),\n 2 => (8, 0, 8, 4),\n 3 => (8, 4, 4, 0),\n 4 => (4, 0, 4, 2),\n 5 => (4, 2, 2, 0),\n 6 => (2, 0, 2, 1),\n 7 => (2, 1, 1, 0),\n _ => {\n // `Adam7Info.pass` is a non-`pub`lic field. `InterlaceInfo` is expected\n // to maintain an invariant that `pass` is valid.\n panic!(\"Invalid `Adam7Info.pass`\");\n }\n };\n\n // the equivalent line number in progressive scan\n let prog_line = line_mul * line_no + line_off;\n let line_start = prog_line * row_stride_in_bytes * 8;\n\n (0..interlaced_width)\n .map(move |i| i * samp_mul + samp_off)\n .map(move |i| i * bits_pp)\n .map(move |bits_offset| bits_offset + line_start)\n}\n```"}], "func_name": "expand_adam7_bits", "docstring": "Given `row_stride`, interlace `info`, and bits-per-pixel, produce an iterator of bit positions\nof pixels to copy from the input scanline to the image buffer. The positions are expressed as\nbit offsets from position (0,0) in the frame that is currently being decoded.", "repo": "image-rs/image-png", "path": "src/adam7.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/adam7.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "628ca7452e0b5cab0ef5a082d79c0ac3e158458fd03e15c9e059deff100209b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expand_pass\n\nDocumentation:\nCopies pixels from `interlaced_row` into the right location in `img`.\n\nFirst bytes of `img` should belong to the top-left corner of the currently decoded frame.\n\n`img_row_stride` specifies an offset in bytes between subsequent rows of `img`.\nThis can be the width of the current frame being decoded, but this is not required - a bigger\nstride may be useful if the frame being decoded is a sub-region of `img`.\n\n`interlaced_row` and `interlace_info` typically come from\n[crate::decoder::Reader::next_interlaced_row], but this is not required. In particular, before\ncalling `expand_interlaced_row` one may need to expand the decoded row, so that its format and\n`bits_per_pixel` matches that of `img`. Note that in initial Adam7 passes the `interlaced_row`\nmay contain less pixels that the width of the frame being decoded (e.g. it contains only 1/8th\nof pixels in the initial pass).\n\nExample:\n\n```\nuse png::{expand_interlaced_row, Adam7Info};\nlet info = Adam7Info::new(5, 0, 4); // 1st line of 5th pass has 4 pixels.\nlet mut img = vec![0; 8 * 8];\nlet row = vec![1, 2, 3, 4];\nexpand_interlaced_row(&mut img, 8, &row, &info, 8);\nassert_eq!(&img, &[\n0, 0, 0, 0, 0, 0, 0, 0,\n0, 0, 0, 0, 0, 0, 0, 0,\n1, 0, 2, 0, 3, 0, 4, 0, // <= this is where the 1st line of 5s appears\n0, 0, 0, 0, 0, 0, 0, 0, // in the schematic drawing of the passes at\n0, 0, 0, 0, 0, 0, 0, 0, // https://en.wikipedia.org/wiki/Adam7_algorithm\n0, 0, 0, 0, 0, 0, 0, 0,\n0, 0, 0, 0, 0, 0, 0, 0,\n0, 0, 0, 0, 0, 0, 0, 0,\n]);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expand_pass(\n img: &mut [u8],\n img_row_stride: usize,\n interlaced_row: &[u8],\n interlace_info: &Adam7Info,\n bits_per_pixel: u8,\n) {\n let bits_pp = bits_per_pixel as usize;\n\n let bit_indices = expand_adam7_bits(img_row_stride, interlace_info, bits_pp);\n\n if bits_pp < 8 {\n for (pos, px) in bit_indices.zip(subbyte_pixels(interlaced_row, bits_pp)) {\n let rem = 8 - pos % 8 - bits_pp;\n img[pos / 8] |= px << rem as u8;\n }\n } else {\n let bytes_pp = bits_pp / 8;\n\n for (bitpos, px) in bit_indices.zip(interlaced_row.chunks(bytes_pp)) {\n for (offset, val) in px.iter().enumerate() {\n img[bitpos / 8 + offset] = *val;\n }\n }\n }\n}\n```"}], "func_name": "expand_pass", "docstring": "Copies pixels from `interlaced_row` into the right location in `img`.\n\nFirst bytes of `img` should belong to the top-left corner of the currently decoded frame.\n\n`img_row_stride` specifies an offset in bytes between subsequent rows of `img`.\nThis can be the width of the current frame being decoded, but this is not required - a bigger\nstride may be useful if the frame being decoded is a sub-region of `img`.\n\n`interlaced_row` and `interlace_info` typically come from\n[crate::decoder::Reader::next_interlaced_row], but this is not required. In particular, before\ncalling `expand_interlaced_row` one may need to expand the decoded row, so that its format and\n`bits_per_pixel` matches that of `img`. Note that in initial Adam7 passes the `interlaced_row`\nmay contain less pixels that the width of the frame being decoded (e.g. it contains only 1/8th\nof pixels in the initial pass).\n\nExample:\n\n```\nuse png::{expand_interlaced_row, Adam7Info};\nlet info = Adam7Info::new(5, 0, 4); // 1st line of 5th pass has 4 pixels.\nlet mut img = vec![0; 8 * 8];\nlet row = vec![1, 2, 3, 4];\nexpand_interlaced_row(&mut img, 8, &row, &info, 8);\nassert_eq!(&img, &[\n0, 0, 0, 0, 0, 0, 0, 0,\n0, 0, 0, 0, 0, 0, 0, 0,\n1, 0, 2, 0, 3, 0, 4, 0, // <= this is where the 1st line of 5s appears\n0, 0, 0, 0, 0, 0, 0, 0, // in the schematic drawing of the passes at\n0, 0, 0, 0, 0, 0, 0, 0, // https://en.wikipedia.org/wiki/Adam7_algorithm\n0, 0, 0, 0, 0, 0, 0, 0,\n0, 0, 0, 0, 0, 0, 0, 0,\n0, 0, 0, 0, 0, 0, 0, 0,\n]);\n```", "repo": "image-rs/image-png", "path": "src/adam7.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/adam7.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ac0793eac7ee73f441fa71dbf49a8a2016fca1a02cd99fb9459ca6b786c20f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unfilter\n\nDocumentation:\nRe-exporting `unfilter` to make it easier to benchmark, despite some items being only\n`pub(crate)`: `fn unfilter`, `enum BytesPerPixel`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unfilter(filter: Filter, tbpp: u8, previous: &[u8], current: &mut [u8]) {\n let filter = RowFilter::from_method(filter).unwrap(); // RowFilter type is private\n let tbpp = BytesPerPixel::from_usize(tbpp as usize);\n crate::filter::unfilter(filter, tbpp, previous, current)\n}\n```"}], "func_name": "unfilter", "docstring": "Re-exporting `unfilter` to make it easier to benchmark, despite some items being only\n`pub(crate)`: `fn unfilter`, `enum BytesPerPixel`.", "repo": "image-rs/image-png", "path": "src/benchable_apis.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/benchable_apis.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fb8bde83db93a228d4e54de79f0a90a27a4ef72d38d8d99b7e5d3d7bc98289e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_critical\n\nDocumentation:\nReturns true if the chunk is critical.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_critical(ChunkType(type_): ChunkType) -> bool {\n type_[0] & 32 == 0\n}\n```"}], "func_name": "is_critical", "docstring": "Returns true if the chunk is critical.", "repo": "image-rs/image-png", "path": "src/chunk.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/chunk.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d03e14fa3148f62c57649ac70a61a2a5e35e3836feb17dbbab62710c38045016"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_private\n\nDocumentation:\nReturns true if the chunk is private.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_private(ChunkType(type_): ChunkType) -> bool {\n type_[1] & 32 != 0\n}\n```"}], "func_name": "is_private", "docstring": "Returns true if the chunk is private.", "repo": "image-rs/image-png", "path": "src/chunk.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/chunk.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18fd55499b57840d7648f1022ed386f928750fe5e04135fc2fdaed2e7c8f418c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reserved_set\n\nDocumentation:\nChecks whether the reserved bit of the chunk name is set.\nIf it is set the chunk name is invalid.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reserved_set(ChunkType(type_): ChunkType) -> bool {\n type_[2] & 32 != 0\n}\n```"}], "func_name": "reserved_set", "docstring": "Checks whether the reserved bit of the chunk name is set.\nIf it is set the chunk name is invalid.", "repo": "image-rs/image-png", "path": "src/chunk.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/chunk.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f044a3dba902084782acc39754554ea514156811eebb2878574b1447a3aa8144"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: safe_to_copy\n\nDocumentation:\nReturns true if the chunk is safe to copy if unknown.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn safe_to_copy(ChunkType(type_): ChunkType) -> bool {\n type_[3] & 32 != 0\n}\n```"}], "func_name": "safe_to_copy", "docstring": "Returns true if the chunk is safe to copy if unknown.", "repo": "image-rs/image-png", "path": "src/chunk.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/chunk.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "840b5a12c58d651f56bd5b64183b4a8e935e24ff2f21edef471086e647bbb394"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_u8\n\nDocumentation:\nu8 -> Self. Temporary solution until Rust provides a canonical one.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_u8(n: u8) -> Option {\n match n {\n 0 => Some(ColorType::Grayscale),\n 2 => Some(ColorType::Rgb),\n 3 => Some(ColorType::Indexed),\n 4 => Some(ColorType::GrayscaleAlpha),\n 6 => Some(ColorType::Rgba),\n _ => None,\n }\n }\n```"}], "func_name": "from_u8", "docstring": "u8 -> Self. Temporary solution until Rust provides a canonical one.", "repo": "image-rs/image-png", "path": "src/common.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/common.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d7a30ee22f4e76fd9673f4a122bda3b0b56a683df1e56db9ed2d66df8523f639"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: in_range\n\nDocumentation:\nGets whether the value is within the clamped range of this type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn in_range(value: f32) -> bool {\n value >= 0.0 && (value * Self::SCALING).floor() <= u32::MAX as f32\n }\n```"}], "func_name": "in_range", "docstring": "Gets whether the value is within the clamped range of this type.", "repo": "image-rs/image-png", "path": "src/common.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/common.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54eef21a6b0503e9332e4e6606e961e3ff64783232801e1080ffd020b162cbbe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_size\n\nDocumentation:\nA utility constructor for a default info with width and height.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_size(width: u32, height: u32) -> Self {\n Info {\n width,\n height,\n ..Default::default()\n }\n }\n```"}], "func_name": "with_size", "docstring": "A utility constructor for a default info with width and height.", "repo": "image-rs/image-png", "path": "src/common.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/common.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2548b28eb9f47b00b8c140652b7d3404eb5ea85f01060d0d99c5b80e52db971c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: size\n\nDocumentation:\nSize of the image, width then height.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn size(&self) -> (u32, u32) {\n (self.width, self.height)\n }\n```"}], "func_name": "size", "docstring": "Size of the image, width then height.", "repo": "image-rs/image-png", "path": "src/common.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/common.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb1b1251faf2367a837512867c90045dc7659824ed2866f6e588c17e3d39521a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_animated\n\nDocumentation:\nReturns true if the image is an APNG image.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_animated(&self) -> bool {\n self.frame_control.is_some() && self.animation_control.is_some()\n }\n```"}], "func_name": "is_animated", "docstring": "Returns true if the image is an APNG image.", "repo": "image-rs/image-png", "path": "src/common.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/common.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7762b90360504cd8467efeee2755bed1e4a294c5d05d0fad38b3ba7bfedde315"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bytes_per_pixel\n\nDocumentation:\nReturns the number of bytes per pixel.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bytes_per_pixel(&self) -> usize {\n // If adjusting this for expansion or other transformation passes, remember to keep the old\n // implementation for bpp_in_prediction, which is internal to the png specification.\n self.color_type.bytes_per_pixel(self.bit_depth)\n }\n```"}], "func_name": "bytes_per_pixel", "docstring": "Returns the number of bytes per pixel.", "repo": "image-rs/image-png", "path": "src/common.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/common.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc22b92ba9ec6ef78db8a87b229f0a508183bfe9127789bd1dcd198a15aeed6c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: raw_bytes\n\nDocumentation:\nReturns the number of bytes needed for one deinterlaced image.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn raw_bytes(&self) -> usize {\n self.height as usize * self.raw_row_length()\n }\n```"}], "func_name": "raw_bytes", "docstring": "Returns the number of bytes needed for one deinterlaced image.", "repo": "image-rs/image-png", "path": "src/common.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/common.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b521f735fffc8ea5415cbc6d37fefd89abd8c63364772f64070d3b7c1acfb68b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: raw_row_length_from_width\n\nDocumentation:\nReturns the number of bytes needed for one deinterlaced row of width `width`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn raw_row_length_from_width(&self, width: u32) -> usize {\n self.color_type\n .raw_row_length_from_width(self.bit_depth, width)\n }\n```"}], "func_name": "raw_row_length_from_width", "docstring": "Returns the number of bytes needed for one deinterlaced row of width `width`.", "repo": "image-rs/image-png", "path": "src/common.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/common.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c2e4179639cec7470cbc62fde8d02366d4d5ceef52d1e8e7b282ae9c2cce7b1c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_source_srgb\n\nDocumentation:\nMark the image data as conforming to the SRGB color space with the specified rendering intent.\n\nAny ICC profiles will be ignored.\n\nSource gamma and chromaticities will be written only if they're set to fallback\nvalues specified in [11.3.2.5](https://www.w3.org/TR/png-3/#sRGB-gAMA-cHRM).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn set_source_srgb(&mut self, rendering_intent: SrgbRenderingIntent) {\n self.srgb = Some(rendering_intent);\n self.icc_profile = None;\n }\n```"}], "func_name": "set_source_srgb", "docstring": "Mark the image data as conforming to the SRGB color space with the specified rendering intent.\n\nAny ICC profiles will be ignored.\n\nSource gamma and chromaticities will be written only if they're set to fallback\nvalues specified in [11.3.2.5](https://www.w3.org/TR/png-3/#sRGB-gAMA-cHRM).", "repo": "image-rs/image-png", "path": "src/common.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/common.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "08373d2ceb1bc447218a0d4e2c5557c54e55e9b4875e8e97b8617d6fe54114c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_animated\n\nDocumentation:\nSpecify that the image is animated.\n\n`num_frames` controls how many frames the animation has, while\n`num_plays` controls how many times the animation should be\nrepeated until it stops, if it's zero then it will repeat\ninfinitely.\n\nWhen this method is returns successfully then the images written will be encoded as fdAT\nchunks, except for the first image that is still encoded as `IDAT`. You can control if the\nfirst frame should be treated as an animation frame with [`Encoder::set_sep_def_img()`].\n\nThis method returns an error if `num_frames` is 0.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_animated(&mut self, num_frames: u32, num_plays: u32) -> Result<()> {\n if num_frames == 0 {\n return Err(EncodingError::Format(FormatErrorKind::ZeroFrames.into()));\n }\n\n let actl = AnimationControl {\n num_frames,\n num_plays,\n };\n\n let fctl = FrameControl {\n sequence_number: 0,\n width: self.info.width,\n height: self.info.height,\n ..Default::default()\n };\n\n self.info.animation_control = Some(actl);\n self.info.frame_control = Some(fctl);\n Ok(())\n }\n```"}], "func_name": "set_animated", "docstring": "Specify that the image is animated.\n\n`num_frames` controls how many frames the animation has, while\n`num_plays` controls how many times the animation should be\nrepeated until it stops, if it's zero then it will repeat\ninfinitely.\n\nWhen this method is returns successfully then the images written will be encoded as fdAT\nchunks, except for the first image that is still encoded as `IDAT`. You can control if the\nfirst frame should be treated as an animation frame with [`Encoder::set_sep_def_img()`].\n\nThis method returns an error if `num_frames` is 0.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6c642e3371319ed835982399ed107c7fec45fd0ed4f9e10b5af8672cef9cbbc7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_palette\n\nDocumentation:\nSets the raw byte contents of the PLTE chunk. This method accepts\nboth borrowed and owned byte data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_palette>>(&mut self, palette: T) {\n self.info.palette = Some(palette.into());\n }\n```"}], "func_name": "set_palette", "docstring": "Sets the raw byte contents of the PLTE chunk. This method accepts\nboth borrowed and owned byte data.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "121806d9b172d9b7d5c223d36db5d646759154eb74c5c0f315edef47e0016783"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_trns\n\nDocumentation:\nSets the raw byte contents of the tRNS chunk. This method accepts\nboth borrowed and owned byte data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_trns>>(&mut self, trns: T) {\n self.info.trns = Some(trns.into());\n }\n```"}], "func_name": "set_trns", "docstring": "Sets the raw byte contents of the tRNS chunk. This method accepts\nboth borrowed and owned byte data.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c76fcb7ad7db7f6a7f65a1e61ac5c4aa5a8209293bb7ae43763284bd86f298d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_source_gamma\n\nDocumentation:\nSet the display gamma of the source system on which the image was generated or last edited.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_source_gamma(&mut self, source_gamma: ScaledFloat) {\n self.info.source_gamma = Some(source_gamma);\n }\n```"}], "func_name": "set_source_gamma", "docstring": "Set the display gamma of the source system on which the image was generated or last edited.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1be0156c0e986c2519b7f74538a8ade6ffa2488512611a235bb2b53db9a3aa6b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_source_chromaticities\n\nDocumentation:\nSet the chromaticities for the source system's display channels (red, green, blue) and the whitepoint\nof the source system on which the image was generated or last edited.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_source_chromaticities(\n &mut self,\n source_chromaticities: super::SourceChromaticities,\n ) {\n self.info.source_chromaticities = Some(source_chromaticities);\n }\n```"}], "func_name": "set_source_chromaticities", "docstring": "Set the chromaticities for the source system's display channels (red, green, blue) and the whitepoint\nof the source system on which the image was generated or last edited.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "638caf9507c6e6dd6c10f00d45e083b4558e8087fc4dbba1f8c7bc234abd7c3f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_header\n\nDocumentation:\nStart encoding by writing the header data.\n\nThe remaining data can be supplied by methods on the returned [`Writer`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_header(self) -> Result> {\n Writer::new(self.w, PartialInfo::new(&self.info), self.options).init(&self.info)\n }\n```"}], "func_name": "write_header", "docstring": "Start encoding by writing the header data.\n\nThe remaining data can be supplied by methods on the returned [`Writer`].", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "def898e44f4b0b023b263e6f2efe64281dddb3ef05ab7e691903841d649b98fd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_depth\n\nDocumentation:\nSet the indicated depth of the image data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_depth(&mut self, depth: BitDepth) {\n self.info.bit_depth = depth;\n }\n```"}], "func_name": "set_depth", "docstring": "Set the indicated depth of the image data.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb23ee6e03a9513b4a132f8fd574c8b843d0b6d13a43339e6f983efafeb35653"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_compression\n\nDocumentation:\nSet compression parameters, see [Compression] for the available options.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_compression(&mut self, compression: Compression) {\n self.set_deflate_compression(DeflateCompression::from_simple(compression));\n self.set_filter(Filter::from_simple(compression));\n }\n```"}], "func_name": "set_compression", "docstring": "Set compression parameters, see [Compression] for the available options.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f3ff3fe68abc3b8ac266a7d58256f283c94d70dd49f7a0f4873342ca97bb26e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_deflate_compression\n\nDocumentation:\nProvides in-depth customization of DEFLATE compression options.\n\nFor a simpler selection of compression options see [Self::set_compression].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_deflate_compression(&mut self, compression: DeflateCompression) {\n self.options.compression = compression;\n }\n```"}], "func_name": "set_deflate_compression", "docstring": "Provides in-depth customization of DEFLATE compression options.\n\nFor a simpler selection of compression options see [Self::set_compression].", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a50d3cfd9a83dd52999dfd295d943c85f953e6612d7539e64e60eca96a59d79"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_filter\n\nDocumentation:\nSet the used filter type.\n\nThe default filter is [`Filter::Adaptive`] which automatically selects the best filter\nfor each row of the image.\n\nYou should only change this if you are after very fast compression,\nand either don't care about compression ratio or know exactly what works best for your images.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_filter(&mut self, filter: Filter) {\n self.options.filter = filter;\n }\n```"}], "func_name": "set_filter", "docstring": "Set the used filter type.\n\nThe default filter is [`Filter::Adaptive`] which automatically selects the best filter\nfor each row of the image.\n\nYou should only change this if you are after very fast compression,\nand either don't care about compression ratio or know exactly what works best for your images.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b8d9700934443b3db78a6d6931cab0527128e00b15c45c307a8a8b91b2719656"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_frame_delay\n\nDocumentation:\nSet the fraction of time every frame is going to be displayed, in seconds.\n\n*Note that this parameter can be set for each individual frame after\n[`Encoder::write_header`] is called. (see [`Writer::set_frame_delay`])*\n\nIf the denominator is 0, it is to be treated as if it were 100\n(that is, the numerator then specifies 1/100ths of a second).\nIf the value of the numerator is 0 the decoder should render the next frame\nas quickly as possible, though viewers may impose a reasonable lower bound.\n\nThe default value is 0 for both the numerator and denominator.\n\nThis method will return an error if the image is not animated.\n(see [`set_animated`])\n\n[`write_header`]: Self::write_header\n[`set_animated`]: Self::set_animated\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_frame_delay(&mut self, numerator: u16, denominator: u16) -> Result<()> {\n if let Some(ref mut fctl) = self.info.frame_control {\n fctl.delay_den = denominator;\n fctl.delay_num = numerator;\n Ok(())\n } else {\n Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))\n }\n }\n```"}], "func_name": "set_frame_delay", "docstring": "Set the fraction of time every frame is going to be displayed, in seconds.\n\n*Note that this parameter can be set for each individual frame after\n[`Encoder::write_header`] is called. (see [`Writer::set_frame_delay`])*\n\nIf the denominator is 0, it is to be treated as if it were 100\n(that is, the numerator then specifies 1/100ths of a second).\nIf the value of the numerator is 0 the decoder should render the next frame\nas quickly as possible, though viewers may impose a reasonable lower bound.\n\nThe default value is 0 for both the numerator and denominator.\n\nThis method will return an error if the image is not animated.\n(see [`set_animated`])\n\n[`write_header`]: Self::write_header\n[`set_animated`]: Self::set_animated", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f2cb0238aa6f54a24cde441c95d1739a3009768c3319edf44ff93f9072e60d30"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_blend_op\n\nDocumentation:\nSet the blend operation for every frame.\n\nThe blend operation specifies whether the frame is to be alpha blended\ninto the current output buffer content, or whether it should completely\nreplace its region in the output buffer.\n\n*Note that this parameter can be set for each individual frame after\n[`write_header`] is called. (see [`Writer::set_blend_op`])*\n\nSee the [`BlendOp`] documentation for the possible values and their effects.\n\n*Note that for the first frame the two blend modes are functionally\nequivalent due to the clearing of the output buffer at the beginning\nof each play.*\n\nThe default value is [`BlendOp::Source`].\n\nThis method will return an error if the image is not animated.\n(see [`set_animated`])\n\n[`write_header`]: Self::write_header\n[`set_animated`]: Self::set_animated\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_blend_op(&mut self, op: BlendOp) -> Result<()> {\n if let Some(ref mut fctl) = self.info.frame_control {\n fctl.blend_op = op;\n Ok(())\n } else {\n Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))\n }\n }\n```"}], "func_name": "set_blend_op", "docstring": "Set the blend operation for every frame.\n\nThe blend operation specifies whether the frame is to be alpha blended\ninto the current output buffer content, or whether it should completely\nreplace its region in the output buffer.\n\n*Note that this parameter can be set for each individual frame after\n[`write_header`] is called. (see [`Writer::set_blend_op`])*\n\nSee the [`BlendOp`] documentation for the possible values and their effects.\n\n*Note that for the first frame the two blend modes are functionally\nequivalent due to the clearing of the output buffer at the beginning\nof each play.*\n\nThe default value is [`BlendOp::Source`].\n\nThis method will return an error if the image is not animated.\n(see [`set_animated`])\n\n[`write_header`]: Self::write_header\n[`set_animated`]: Self::set_animated", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e253c045f48bc23448a96fcdb83fb6a22d33d317c20bbb469e8f329cdd7ca6a2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_dispose_op\n\nDocumentation:\nSet the dispose operation for every frame.\n\nThe dispose operation specifies how the output buffer should be changed\nat the end of the delay (before rendering the next frame)\n\n*Note that this parameter can be set for each individual frame after\n[`write_header`] is called (see [`Writer::set_dispose_op`])*\n\nSee the [`DisposeOp`] documentation for the possible values and their effects.\n\n*Note that if the first frame uses [`DisposeOp::Previous`]\nit will be treated as [`DisposeOp::Background`].*\n\nThe default value is [`DisposeOp::None`].\n\nThis method will return an error if the image is not animated.\n(see [`set_animated`])\n\n[`set_animated`]: Self::set_animated\n[`write_header`]: Self::write_header\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_dispose_op(&mut self, op: DisposeOp) -> Result<()> {\n if let Some(ref mut fctl) = self.info.frame_control {\n fctl.dispose_op = op;\n Ok(())\n } else {\n Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))\n }\n }\n```"}], "func_name": "set_dispose_op", "docstring": "Set the dispose operation for every frame.\n\nThe dispose operation specifies how the output buffer should be changed\nat the end of the delay (before rendering the next frame)\n\n*Note that this parameter can be set for each individual frame after\n[`write_header`] is called (see [`Writer::set_dispose_op`])*\n\nSee the [`DisposeOp`] documentation for the possible values and their effects.\n\n*Note that if the first frame uses [`DisposeOp::Previous`]\nit will be treated as [`DisposeOp::Background`].*\n\nThe default value is [`DisposeOp::None`].\n\nThis method will return an error if the image is not animated.\n(see [`set_animated`])\n\n[`set_animated`]: Self::set_animated\n[`write_header`]: Self::write_header", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "68fb641ebe98d36f377da7ec1c9a16cae30c871fab74e0a95ba2269831ee6576"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_text_chunk\n\nDocumentation:\nConvenience function to add tEXt chunks to [`Info`] struct\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_text_chunk(&mut self, keyword: String, text: String) -> Result<()> {\n let text_chunk = TEXtChunk::new(keyword, text);\n self.info.uncompressed_latin1_text.push(text_chunk);\n Ok(())\n }\n```"}], "func_name": "add_text_chunk", "docstring": "Convenience function to add tEXt chunks to [`Info`] struct", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c06c73425e3c06be7620c77fb058a9a8abbee18d814e9458dcda753340dd2ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_ztxt_chunk\n\nDocumentation:\nConvenience function to add zTXt chunks to [`Info`] struct\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_ztxt_chunk(&mut self, keyword: String, text: String) -> Result<()> {\n let text_chunk = ZTXtChunk::new(keyword, text);\n self.info.compressed_latin1_text.push(text_chunk);\n Ok(())\n }\n```"}], "func_name": "add_ztxt_chunk", "docstring": "Convenience function to add zTXt chunks to [`Info`] struct", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f9286f47f2f132d4f2180d195d24609ce9819c133cc308084b2dbb026e569a9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_itxt_chunk\n\nDocumentation:\nConvenience function to add iTXt chunks to [`Info`] struct\n\nThis function only sets the `keyword` and `text` field of the iTXt chunk.\nTo set the other fields, create a [`ITXtChunk`] directly, and then encode it to the output stream.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_itxt_chunk(&mut self, keyword: String, text: String) -> Result<()> {\n let text_chunk = ITXtChunk::new(keyword, text);\n self.info.utf8_text.push(text_chunk);\n Ok(())\n }\n```"}], "func_name": "add_itxt_chunk", "docstring": "Convenience function to add iTXt chunks to [`Info`] struct\n\nThis function only sets the `keyword` and `text` field of the iTXt chunk.\nTo set the other fields, create a [`ITXtChunk`] directly, and then encode it to the output stream.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51dd8a28dee17ed073abcb40b36b8c389aad422085e71b1f95e8f57191767351"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: validate_sequence\n\nDocumentation:\nValidate the written image sequence.\n\nWhen validation is turned on (it's turned off by default) then attempts to write more than\none `IDAT` image or images beyond the number of frames indicated in the animation control\nchunk will fail and return an error result instead. Attempts to [finish][finish] the image\nwith missing frames will also return an error.\n\n[finish]: StreamWriter::finish\n\n(It's possible to circumvent these checks by writing raw chunks instead.)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn validate_sequence(&mut self, validate: bool) {\n self.options.validate_sequence = validate;\n }\n```"}], "func_name": "validate_sequence", "docstring": "Validate the written image sequence.\n\nWhen validation is turned on (it's turned off by default) then attempts to write more than\none `IDAT` image or images beyond the number of frames indicated in the animation control\nchunk will fail and return an error result instead. Attempts to [finish][finish] the image\nwith missing frames will also return an error.\n\n[finish]: StreamWriter::finish\n\n(It's possible to circumvent these checks by writing raw chunks instead.)", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2086f246526f854945b31db83f4bfad11ec962c820d830ce0aa6f3147c3c78aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode_header\n\nDocumentation:\nEncode PNG signature, IHDR, and then chunks that were added to the `Info`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn encode_header(&mut self, info: &Info<'_>) -> Result<()> {\n self.w.write_all(&[137, 80, 78, 71, 13, 10, 26, 10])?; // PNG signature\n\n // Encode the IHDR chunk\n let mut data = [0; 13];\n data[..4].copy_from_slice(&info.width.to_be_bytes());\n data[4..8].copy_from_slice(&info.height.to_be_bytes());\n data[8] = info.bit_depth as u8;\n data[9] = info.color_type as u8;\n data[12] = info.interlaced as u8;\n self.write_chunk(chunk::IHDR, &data)?;\n\n // Encode the pHYs chunk\n if let Some(pd) = info.pixel_dims {\n let mut phys_data = [0; 9];\n phys_data[0..4].copy_from_slice(&pd.xppu.to_be_bytes());\n phys_data[4..8].copy_from_slice(&pd.yppu.to_be_bytes());\n match pd.unit {\n Unit::Meter => phys_data[8] = 1,\n Unit::Unspecified => phys_data[8] = 0,\n }\n self.write_chunk(chunk::pHYs, &phys_data)?;\n }\n\n // If specified, the sRGB information overrides the source gamma and chromaticities.\n if let Some(srgb) = &info.srgb {\n srgb.encode(&mut self.w)?;\n\n // gAMA and cHRM are optional, for backwards compatibility\n let srgb_gamma = crate::srgb::substitute_gamma();\n if Some(srgb_gamma) == info.source_gamma {\n srgb_gamma.encode_gama(&mut self.w)?\n }\n let srgb_chromaticities = crate::srgb::substitute_chromaticities();\n if Some(srgb_chromaticities) == info.source_chromaticities {\n srgb_chromaticities.encode(&mut self.w)?;\n }\n } else {\n if let Some(gma) = info.source_gamma {\n gma.encode_gama(&mut self.w)?\n }\n if let Some(chrms) = info.source_chromaticities {\n chrms.encode(&mut self.w)?;\n }\n if let Some(iccp) = &info.icc_profile {\n self.write_iccp_chunk(\"_\", iccp)?\n }\n }\n\n if let Some(exif) = &info.exif_metadata {\n self.write_chunk(chunk::eXIf, exif)?;\n }\n\n if let Some(actl) = info.animation_control {\n actl.encode(&mut self.w)?;\n }\n\n // The position of the PLTE chunk is important, it must come before the tRNS chunk and after\n // many of the other metadata chunks.\n if let Some(p) = &info.palette {\n self.write_chunk(chunk::PLTE, p)?;\n };\n\n if let Some(t) = &info.trns {\n self.write_chunk(chunk::tRNS, t)?;\n }\n\n for text_chunk in &info.uncompressed_latin1_text {\n self.write_text_chunk(text_chunk)?;\n }\n\n for text_chunk in &info.compressed_latin1_text {\n self.write_text_chunk(text_chunk)?;\n }\n\n for text_chunk in &info.utf8_text {\n self.write_text_chunk(text_chunk)?;\n }\n\n Ok(())\n }\n```"}], "func_name": "encode_header", "docstring": "Encode PNG signature, IHDR, and then chunks that were added to the `Info`", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "43418dc9e613486e2614abc3947a3516b5e32100b4ae3034ec522225c5b72122"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_chunk\n\nDocumentation:\nWrite a raw chunk of PNG data.\n\nThis function calculates the required CRC sum so this should not be included in the input\n`data`, otherwise the data is not filtered in any way. This function returns an error if\nthe length of `data` can't be parsed as a `u32` though the length of the chunk data should\nnot exceed `i32::MAX` or 2,147,483,647.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_chunk(&mut self, name: ChunkType, data: &[u8]) -> Result<()> {\n use std::convert::TryFrom;\n\n if u32::try_from(data.len()).map_or(true, |length| length > i32::MAX as u32) {\n let kind = FormatErrorKind::WrittenTooMuch(data.len() - i32::MAX as usize);\n return Err(EncodingError::Format(kind.into()));\n }\n\n write_chunk(&mut self.w, name, data)\n }\n```"}], "func_name": "write_chunk", "docstring": "Write a raw chunk of PNG data.\n\nThis function calculates the required CRC sum so this should not be included in the input\n`data`, otherwise the data is not filtered in any way. This function returns an error if\nthe length of `data` can't be parsed as a `u32` though the length of the chunk data should\nnot exceed `i32::MAX` or 2,147,483,647.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf2443d6dd9bba2c3d0263ac8820637bde29eb16972ccb4b3faf6cef7c8011c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: validate_new_image\n\nDocumentation:\nCheck if we should allow writing another image.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn validate_new_image(&self) -> Result<()> {\n if !self.options.validate_sequence {\n return Ok(());\n }\n\n match self.info.animation_control {\n None => {\n if self.images_written == 0 {\n Ok(())\n } else {\n Err(EncodingError::Format(FormatErrorKind::EndReached.into()))\n }\n }\n Some(_) => {\n if self.info.frame_control.is_some() {\n Ok(())\n } else {\n Err(EncodingError::Format(FormatErrorKind::EndReached.into()))\n }\n }\n }\n }\n```"}], "func_name": "validate_new_image", "docstring": "Check if we should allow writing another image.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d2261150d1e35459f7dcaf3e1ed8aa5d8672536dd794c17885efb9f58e10742e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_frame_dimension\n\nDocumentation:\nSet the frame dimension to occupy all the image, starting from\nthe current position.\n\nTo reset the frame to the full image size [`reset_frame_position`]\nshould be called first.\n\nThis method will return an error if the image is not animated.\n\n[`reset_frame_position`]: Writer::reset_frame_position\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reset_frame_dimension(&mut self) -> Result<()> {\n if let Some(ref mut fctl) = self.info.frame_control {\n fctl.width = self.info.width - fctl.x_offset;\n fctl.height = self.info.height - fctl.y_offset;\n Ok(())\n } else {\n Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))\n }\n }\n```"}], "func_name": "reset_frame_dimension", "docstring": "Set the frame dimension to occupy all the image, starting from\nthe current position.\n\nTo reset the frame to the full image size [`reset_frame_position`]\nshould be called first.\n\nThis method will return an error if the image is not animated.\n\n[`reset_frame_position`]: Writer::reset_frame_position", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba62e2c66a99b1c685de5f95ebee4921ffa32d3672fb06b651ad1ae4de20201e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_frame_position\n\nDocumentation:\nSet the frame position to (0, 0).\n\nEquivalent to calling [`set_frame_position(0, 0)`].\n\nThis method will return an error if the image is not animated.\n\n[`set_frame_position(0, 0)`]: Writer::set_frame_position\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reset_frame_position(&mut self) -> Result<()> {\n if let Some(ref mut fctl) = self.info.frame_control {\n fctl.x_offset = 0;\n fctl.y_offset = 0;\n Ok(())\n } else {\n Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))\n }\n }\n```"}], "func_name": "reset_frame_position", "docstring": "Set the frame position to (0, 0).\n\nEquivalent to calling [`set_frame_position(0, 0)`].\n\nThis method will return an error if the image is not animated.\n\n[`set_frame_position(0, 0)`]: Writer::set_frame_position", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "32b319ffbe5832953dfd50ea81e7d7d4c8bd4b59d2a32392076df9efa59bdbed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stream_writer_with_size\n\nDocumentation:\nCreate a stream writer with custom buffer size.\n\nSee [`stream_writer`].\n\n[`stream_writer`]: Self::stream_writer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stream_writer_with_size(&mut self, size: usize) -> Result> {\n StreamWriter::new(ChunkOutput::Borrowed(self), size)\n }\n```"}], "func_name": "stream_writer_with_size", "docstring": "Create a stream writer with custom buffer size.\n\nSee [`stream_writer`].\n\n[`stream_writer`]: Self::stream_writer", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7fdaf60100dabb92b7aa4101e55a914141261258c1c6fa40a526809a353bc5fc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_stream_writer_with_size\n\nDocumentation:\nTurn this into a stream writer with custom buffer size.\n\nSee [`into_stream_writer`].\n\n[`into_stream_writer`]: Self::into_stream_writer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_stream_writer_with_size(self, size: usize) -> Result> {\n StreamWriter::new(ChunkOutput::Owned(self), size)\n }\n```"}], "func_name": "into_stream_writer_with_size", "docstring": "Turn this into a stream writer with custom buffer size.\n\nSee [`into_stream_writer`].\n\n[`into_stream_writer`]: Self::into_stream_writer", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b8be151445a4dfc80e95db44ad6ecad98e6351f479bf461c48d66a62a9f31d7f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish\n\nDocumentation:\nConsume the stream writer with validation.\n\nUnlike a simple drop this ensures that the final chunk was written correctly. When other\nvalidation options (chunk sequencing) had been turned on in the configuration then it will\nalso do a check on their correctness _before_ writing the final chunk.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn finish(mut self) -> Result<()> {\n self.validate_sequence_done()?;\n self.write_iend()?;\n self.w.flush()?;\n\n // Explicitly drop `self` just for clarity.\n drop(self);\n Ok(())\n }\n```"}], "func_name": "finish", "docstring": "Consume the stream writer with validation.\n\nUnlike a simple drop this ensures that the final chunk was written correctly. When other\nvalidation options (chunk sequencing) had been turned on in the configuration then it will\nalso do a check on their correctness _before_ writing the final chunk.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b4157dc34431e45ef5dcb9aeec6d0393e7c66461d909d5d04c303510ac605fb9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next_frame_info\n\nDocumentation:\nReturns the size of each scanline for the next frame\npaired with the size of the whole frame\n\nThis is used by the `StreamWriter` to know when the scanline ends\nso it can filter compress it and also to know when to start\nthe next one\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn next_frame_info(&self) -> (usize, usize) {\n let wrt = self.writer.deref();\n\n let width: usize;\n let height: usize;\n if let Some(fctl) = wrt.info.frame_control {\n width = fctl.width as usize;\n height = fctl.height as usize;\n } else {\n width = wrt.info.width as usize;\n height = wrt.info.height as usize;\n }\n\n let in_len = wrt.info.raw_row_length_from_width(width as u32) - 1;\n let data_size = in_len * height;\n\n (in_len, data_size)\n }\n```"}], "func_name": "next_frame_info", "docstring": "Returns the size of each scanline for the next frame\npaired with the size of the whole frame\n\nThis is used by the `StreamWriter` to know when the scanline ends\nso it can filter compress it and also to know when to start\nthe next one", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c553e325f27596e71a9a810f5147598ba32d36f1a4d5a23f1ef6e728757504a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_header\n\nDocumentation:\nNOTE: this bypasses the internal buffer so the flush method should be called before this\nin the case there is some data left in the buffer when this is called, it will panic\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_header(&mut self) -> Result<()> {\n assert_eq!(self.index, 0, \"Called when not flushed\");\n let wrt = self.writer.deref_mut();\n\n self.curr_chunk = if wrt.images_written == 0 {\n chunk::IDAT\n } else {\n chunk::fdAT\n };\n\n match wrt.info.frame_control {\n Some(_) if wrt.should_skip_frame_control_on_default_image() => {}\n Some(ref mut fctl) => {\n fctl.encode(&mut wrt.w)?;\n fctl.sequence_number += 1;\n }\n _ => {}\n }\n\n Ok(())\n }\n```"}], "func_name": "write_header", "docstring": "NOTE: this bypasses the internal buffer so the flush method should be called before this\nin the case there is some data left in the buffer when this is called, it will panic", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "24040b2d2383e5e4a86d17779ddbc6018025676d274707b0af54bfae9744f3aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_fctl\n\nDocumentation:\nSet the [`FrameControl`] for the following frame\n\nIt will ignore the `sequence_number` of the parameter\nas it is updated internally.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_fctl(&mut self, f: FrameControl) {\n if let Some(ref mut fctl) = self.writer.info.frame_control {\n // Ignore the sequence number\n *fctl = FrameControl {\n sequence_number: fctl.sequence_number,\n ..f\n };\n } else {\n panic!(\"This function must be called on an animated PNG\")\n }\n }\n```"}], "func_name": "set_fctl", "docstring": "Set the [`FrameControl`] for the following frame\n\nIt will ignore the `sequence_number` of the parameter\nas it is updated internally.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be7836c164b9c38e47f2c72ec43e0b74aa32e8266971d3c9f098032473428a45"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: take\n\nDocumentation:\nLike `Option::take` this returns the `Wrapper` contained\nin `self` and replaces it with `Wrapper::None`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn take(&mut self) -> Wrapper<'a, W> {\n let mut swap = Wrapper::None;\n mem::swap(self, &mut swap);\n swap\n }\n```"}], "func_name": "take", "docstring": "Like `Option::take` this returns the `Wrapper` contained\nin `self` and replaces it with `Wrapper::None`", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9d5d87f8752c24321cbcfa42bd5997ca1b39cb9ed6df8c0dcd2288f7d477c046"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_frame_delay\n\nDocumentation:\nSet the fraction of time the following frames are going to be displayed,\nin seconds\n\nIf the denominator is 0, it is to be treated as if it were 100\n(that is, the numerator then specifies 1/100ths of a second).\nIf the value of the numerator is 0 the decoder should render the next frame\nas quickly as possible, though viewers may impose a reasonable lower bound.\n\nThis method will return an error if the image is not animated.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_frame_delay(&mut self, numerator: u16, denominator: u16) -> Result<()> {\n if let Some(ref mut fctl) = self.fctl {\n fctl.delay_den = denominator;\n fctl.delay_num = numerator;\n Ok(())\n } else {\n Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))\n }\n }\n```"}], "func_name": "set_frame_delay", "docstring": "Set the fraction of time the following frames are going to be displayed,\nin seconds\n\nIf the denominator is 0, it is to be treated as if it were 100\n(that is, the numerator then specifies 1/100ths of a second).\nIf the value of the numerator is 0 the decoder should render the next frame\nas quickly as possible, though viewers may impose a reasonable lower bound.\n\nThis method will return an error if the image is not animated.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "87279683c8023b6d225b45517ffd04c507a73f145c97b8ed4e3b87f6c087de95"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_frame_dimension\n\nDocumentation:\nSet the dimension of the following frames.\n\nThis function will return an error when:\n- The image is not an animated;\n\n- The selected dimension, considering also the current frame position,\ngoes outside the image boundaries;\n\n- One or both the width and height are 0;\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_frame_dimension(&mut self, width: u32, height: u32) -> Result<()> {\n if let Some(ref mut fctl) = self.fctl {\n if Some(width) > self.width.checked_sub(fctl.x_offset)\n || Some(height) > self.height.checked_sub(fctl.y_offset)\n {\n return Err(EncodingError::Format(FormatErrorKind::OutOfBounds.into()));\n } else if width == 0 {\n return Err(EncodingError::Format(FormatErrorKind::ZeroWidth.into()));\n } else if height == 0 {\n return Err(EncodingError::Format(FormatErrorKind::ZeroHeight.into()));\n }\n fctl.width = width;\n fctl.height = height;\n Ok(())\n } else {\n Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))\n }\n }\n```"}], "func_name": "set_frame_dimension", "docstring": "Set the dimension of the following frames.\n\nThis function will return an error when:\n- The image is not an animated;\n\n- The selected dimension, considering also the current frame position,\ngoes outside the image boundaries;\n\n- One or both the width and height are 0;", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e41b051d5c395248393c73f5593a93da7e76d6ba1a29ec567345797feb530ebd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_frame_position\n\nDocumentation:\nSet the position of the following frames.\n\nAn error will be returned if:\n- The image is not animated;\n\n- The selected position, considering also the current frame dimension,\ngoes outside the image boundaries;\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_frame_position(&mut self, x: u32, y: u32) -> Result<()> {\n if let Some(ref mut fctl) = self.fctl {\n if Some(x) > self.width.checked_sub(fctl.width)\n || Some(y) > self.height.checked_sub(fctl.height)\n {\n return Err(EncodingError::Format(FormatErrorKind::OutOfBounds.into()));\n }\n fctl.x_offset = x;\n fctl.y_offset = y;\n Ok(())\n } else {\n Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))\n }\n }\n```"}], "func_name": "set_frame_position", "docstring": "Set the position of the following frames.\n\nAn error will be returned if:\n- The image is not animated;\n\n- The selected position, considering also the current frame dimension,\ngoes outside the image boundaries;", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "051513c301b1dcdb24288126eec993045bf3507079ce9b4ef695da2bcfdba159"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_blend_op\n\nDocumentation:\nSet the blend operation for the following frames.\n\nThe blend operation specifies whether the frame is to be alpha blended\ninto the current output buffer content, or whether it should completely\nreplace its region in the output buffer.\n\nSee the [`BlendOp`] documentation for the possible values and their effects.\n\n*Note that for the first frame the two blend modes are functionally\nequivalent due to the clearing of the output buffer at the beginning\nof each play.*\n\nThis method will return an error if the image is not animated.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_blend_op(&mut self, op: BlendOp) -> Result<()> {\n if let Some(ref mut fctl) = self.fctl {\n fctl.blend_op = op;\n Ok(())\n } else {\n Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))\n }\n }\n```"}], "func_name": "set_blend_op", "docstring": "Set the blend operation for the following frames.\n\nThe blend operation specifies whether the frame is to be alpha blended\ninto the current output buffer content, or whether it should completely\nreplace its region in the output buffer.\n\nSee the [`BlendOp`] documentation for the possible values and their effects.\n\n*Note that for the first frame the two blend modes are functionally\nequivalent due to the clearing of the output buffer at the beginning\nof each play.*\n\nThis method will return an error if the image is not animated.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8513bf2a4607a32c27c1addb0b1e1d2e2c1ccdbf46ace8008e81b259fd2b92d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_dispose_op\n\nDocumentation:\nSet the dispose operation for the following frames.\n\nThe dispose operation specifies how the output buffer should be changed\nat the end of the delay (before rendering the next frame)\n\nSee the [`DisposeOp`] documentation for the possible values and their effects.\n\n*Note that if the first frame uses [`DisposeOp::Previous`]\nit will be treated as [`DisposeOp::Background`].*\n\nThis method will return an error if the image is not animated.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_dispose_op(&mut self, op: DisposeOp) -> Result<()> {\n if let Some(ref mut fctl) = self.fctl {\n fctl.dispose_op = op;\n Ok(())\n } else {\n Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))\n }\n }\n```"}], "func_name": "set_dispose_op", "docstring": "Set the dispose operation for the following frames.\n\nThe dispose operation specifies how the output buffer should be changed\nat the end of the delay (before rendering the next frame)\n\nSee the [`DisposeOp`] documentation for the possible values and their effects.\n\n*Note that if the first frame uses [`DisposeOp::Previous`]\nit will be treated as [`DisposeOp::Background`].*\n\nThis method will return an error if the image is not animated.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "83630a2003f0d5c9063517b09b5d1d6b45b626dee4aff9aafba5115879a976bf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish_mut\n\nDocumentation:\nInternal helper that can be called both from `fn finish(mut self)`\nand from `fn drop(&mut self)`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn finish_mut(&mut self) -> Result<()> {\n if self.to_write > 0 {\n let err = FormatErrorKind::MissingData(self.to_write).into();\n return Err(EncodingError::Format(err));\n }\n\n self.flush()?;\n match self.writer.take() {\n Wrapper::Chunk(wrt) => {\n wrt.writer.validate_sequence_done()?;\n }\n Wrapper::FDeflate(wrt) => {\n wrt.finish()?;\n }\n Wrapper::Flate2(wrt) => {\n wrt.finish()?;\n }\n Wrapper::None => unreachable!(),\n Wrapper::Unrecoverable => {\n let err = FormatErrorKind::Unrecoverable.into();\n return Err(EncodingError::Format(err));\n }\n }\n\n Ok(())\n }\n```"}], "func_name": "finish_mut", "docstring": "Internal helper that can be called both from `fn finish(mut self)`\nand from `fn drop(&mut self)`.", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca525491e59e23379bd8074aaa35550428c7034297f72d4f386c829aafdd7d3d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_frame\n\nDocumentation:\nFlushes the buffered chunk, checks if it was the last frame,\nwrites the next frame header and gets the next frame scanline size\nand image size.\nNOTE: This method must only be called when the writer is the variant Chunk(_)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new_frame(&mut self) -> Result<()> {\n let wrt = match &mut self.writer {\n Wrapper::Chunk(wrt) => wrt,\n Wrapper::Unrecoverable => {\n let err = FormatErrorKind::Unrecoverable.into();\n return Err(EncodingError::Format(err));\n }\n Wrapper::Flate2(_) | Wrapper::FDeflate(_) => {\n unreachable!(\"never called on a half-finished frame\")\n }\n Wrapper::None => unreachable!(),\n };\n wrt.flush()?;\n wrt.writer.validate_new_image()?;\n\n if let Some(fctl) = self.fctl {\n wrt.set_fctl(fctl);\n }\n let (scansize, size) = wrt.next_frame_info();\n self.line_len = scansize;\n self.to_write = size;\n\n wrt.write_header()?;\n wrt.writer.increment_images_written();\n\n // now it can be taken because the next statements cannot cause any errors\n match self.writer.take() {\n Wrapper::Chunk(wrt) => match Wrapper::from_level(wrt, self.compression) {\n Ok(writer) => self.writer = writer,\n Err(err) => {\n self.writer = Wrapper::Unrecoverable;\n return Err(err.into());\n }\n },\n _ => unreachable!(),\n };\n\n Ok(())\n }\n```"}], "func_name": "new_frame", "docstring": "Flushes the buffered chunk, checks if it was the last frame,\nwrites the next frame header and gets the next frame scanline size\nand image size.\nNOTE: This method must only be called when the writer is the variant Chunk(_)", "repo": "image-rs/image-png", "path": "src/encoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/encoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f32b5d6bdf71a353a0f20fd8e8733d474ebe2fee240fcd26d6bfe2d24c6a7295"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: substitute_gamma\n\nDocumentation:\nGet the gamma that should be substituted for images conforming to the sRGB color space.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn substitute_gamma() -> ScaledFloat {\n // Value taken from https://www.w3.org/TR/2003/REC-PNG-20031110/#11sRGB\n ScaledFloat::from_scaled(45455)\n}\n```"}], "func_name": "substitute_gamma", "docstring": "Get the gamma that should be substituted for images conforming to the sRGB color space.", "repo": "image-rs/image-png", "path": "src/srgb.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/srgb.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "903a5c8f080088f587a46e9da3d09fb06e96e215594b8e52d3ca997077b51eee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: substitute_chromaticities\n\nDocumentation:\nGet the chromaticities that should be substituted for images conforming to the sRGB color space.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn substitute_chromaticities() -> SourceChromaticities {\n // Values taken from https://www.w3.org/TR/2003/REC-PNG-20031110/#11sRGB\n SourceChromaticities {\n white: (\n ScaledFloat::from_scaled(31270),\n ScaledFloat::from_scaled(32900),\n ),\n red: (\n ScaledFloat::from_scaled(64000),\n ScaledFloat::from_scaled(33000),\n ),\n green: (\n ScaledFloat::from_scaled(30000),\n ScaledFloat::from_scaled(60000),\n ),\n blue: (\n ScaledFloat::from_scaled(15000),\n ScaledFloat::from_scaled(6000),\n ),\n }\n}\n```"}], "func_name": "substitute_chromaticities", "docstring": "Get the chromaticities that should be substituted for images conforming to the sRGB color space.", "repo": "image-rs/image-png", "path": "src/srgb.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/srgb.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17af62d45e7a2e726f680144da10dd857e81b56964663642186a2984585e4c24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_noncompressed_png\n\nDocumentation:\nGenerates a store-only, non-compressed image:\n\n* `00` compression mode (i.e.`BTYPE` = `00` = no compression) is used\n* No filter is applied to the image rows\n\nCurrently the image always has the following properties:\n\n* Single `IDAT` chunk\n* Zlib chunks of maximum possible size\n* 8-bit RGBA\n\nThese images are somewhat artificial, but may be useful for benchmarking performance of parts\noutside of `fdeflate` crate and/or the `unfilter` function (e.g. these images were originally\nused to evaluate changes to minimize copying of image pixels between various buffers - see\n[this\ndiscussion](https://github.com/image-rs/image-png/discussions/416#discussioncomment-7436871)\nfor more details).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_noncompressed_png(w: &mut impl Write, size: u32, idat_bytes: usize) {\n write_png_sig(w);\n write_rgba8_ihdr_with_width(w, size);\n write_rgba8_idats(w, size, idat_bytes);\n write_iend(w);\n}\n```"}], "func_name": "write_noncompressed_png", "docstring": "Generates a store-only, non-compressed image:\n\n* `00` compression mode (i.e.`BTYPE` = `00` = no compression) is used\n* No filter is applied to the image rows\n\nCurrently the image always has the following properties:\n\n* Single `IDAT` chunk\n* Zlib chunks of maximum possible size\n* 8-bit RGBA\n\nThese images are somewhat artificial, but may be useful for benchmarking performance of parts\noutside of `fdeflate` crate and/or the `unfilter` function (e.g. these images were originally\nused to evaluate changes to minimize copying of image pixels between various buffers - see\n[this\ndiscussion](https://github.com/image-rs/image-png/discussions/416#discussioncomment-7436871)\nfor more details).", "repo": "image-rs/image-png", "path": "src/test_utils.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "696050fbd67c7580a301dd78d8003a8774f75229f19eed417431753126f6f8dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_png_sig\n\nDocumentation:\nWrites PNG signature.\nSee http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html#PNG-file-signature\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_png_sig(w: &mut impl Write) {\n const SIG: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10];\n w.write_all(&SIG).unwrap();\n}\n```"}], "func_name": "write_png_sig", "docstring": "Writes PNG signature.\nSee http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html#PNG-file-signature", "repo": "image-rs/image-png", "path": "src/test_utils.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "689ad30bb57eb15e116c3f9ac19b6c8696bc6748b0abe83a766d8a8133872311"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_rgba8_ihdr_with_width\n\nDocumentation:\nWrites an IHDR chunk that indicates a non-interlaced RGBA8 that uses the same height and\n`width`. See http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.IHDR\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_rgba8_ihdr_with_width(w: &mut impl Write, width: u32) {\n let mut data = Vec::new();\n data.write_u32::(width).unwrap();\n data.write_u32::(width).unwrap(); // height\n data.write_u8(8).unwrap(); // bit depth = always 8-bits per channel\n data.write_u8(6).unwrap(); // color type = color + alpha\n data.write_u8(0).unwrap(); // compression method (0 is the only allowed value)\n data.write_u8(0).unwrap(); // filter method (0 is the only allowed value)\n data.write_u8(0).unwrap(); // interlace method = no interlacing\n write_chunk(w, b\"IHDR\", &data);\n}\n```"}], "func_name": "write_rgba8_ihdr_with_width", "docstring": "Writes an IHDR chunk that indicates a non-interlaced RGBA8 that uses the same height and\n`width`. See http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.IHDR", "repo": "image-rs/image-png", "path": "src/test_utils.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2fa9c5d68772fa96d6aa92db6be5fcf5a0801ccb77ba7b43a48305dfc5fcf426"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_rgba8_with_width_and_height\n\nDocumentation:\nGenerates RGBA8 `width` x `height` image and wraps it in a store-only zlib container.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate_rgba8_with_width_and_height(width: u32, height: u32) -> Vec {\n // Generate arbitrary test pixels.\n let image_pixels = {\n let mut row = Vec::new();\n row.write_u8(0).unwrap(); // filter = no filter\n\n let row_pixels = (0..width).flat_map(|i| {\n let color: u8 = (i * 255 / width) as u8;\n let alpha: u8 = 0xff;\n [color, 255 - color, color / 2, alpha]\n });\n row.extend(row_pixels);\n\n std::iter::repeat(row)\n .take(height as usize)\n .flatten()\n .collect::>()\n };\n\n let mut zlib_data = Vec::new();\n let mut store_only_compressor =\n fdeflate::StoredOnlyCompressor::new(std::io::Cursor::new(&mut zlib_data)).unwrap();\n store_only_compressor.write_data(&image_pixels).unwrap();\n store_only_compressor.finish().unwrap();\n\n zlib_data\n}\n```"}], "func_name": "generate_rgba8_with_width_and_height", "docstring": "Generates RGBA8 `width` x `height` image and wraps it in a store-only zlib container.", "repo": "image-rs/image-png", "path": "src/test_utils.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "87be16b9f08db342316a2170f396c48068f611a1db92f53ead453c09470c44b8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_iend\n\nDocumentation:\nWrites an IEND chunk.\nSee http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.IEND\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_iend(w: &mut impl Write) {\n write_chunk(w, b\"IEND\", &[]);\n}\n```"}], "func_name": "write_iend", "docstring": "Writes an IEND chunk.\nSee http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.IEND", "repo": "image-rs/image-png", "path": "src/test_utils.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eed799f4443620fd418c8480a9b553f3a67ff79954c11a4e342a44fd87490182"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: buffer_size\n\nDocumentation:\nReturns the size needed to hold a decoded frame\nIf the output buffer was larger then bytes after this count should be ignored. They may\nstill have been changed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn buffer_size(&self) -> usize {\n self.line_size * self.height as usize\n }\n```"}], "func_name": "buffer_size", "docstring": "Returns the size needed to hold a decoded frame\nIf the output buffer was larger then bytes after this count should be ignored. They may\nstill have been changed.", "repo": "image-rs/image-png", "path": "src/decoder/mod.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b1f0a35bcddb1f22cb186346778c17c80c8d2c054feacf43313c4f71e35760b2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_with_options\n\nDocumentation:\nCreate a new decoder configuration with custom `DecodeOptions`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_with_options(r: R, decode_options: DecodeOptions) -> Decoder {\n let mut read_decoder = ReadDecoder::with_options(r, decode_options);\n read_decoder.set_limits(Limits::default());\n\n Decoder {\n read_decoder,\n transform: Transformations::IDENTITY,\n }\n }\n```"}], "func_name": "new_with_options", "docstring": "Create a new decoder configuration with custom `DecodeOptions`.", "repo": "image-rs/image-png", "path": "src/decoder/mod.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "56a321a6a193119c6eeed3182b95d3c0ace522b97f63a45fbd53c3027d66aa42"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decode_next\n\nDocumentation:\nReturns the next decoded chunk. If the chunk is an ImageData chunk, its contents are written\ninto image_data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn decode_next(\n &mut self,\n image_data: Option<&mut UnfilterBuf<'_>>,\n ) -> Result {\n let (consumed, result) = {\n let buf = self.reader.fill_buf()?;\n if buf.is_empty() {\n return Err(DecodingError::IoError(ErrorKind::UnexpectedEof.into()));\n }\n self.decoder.update(buf, image_data)?\n };\n self.reader.consume(consumed);\n Ok(result)\n }\n```"}], "func_name": "decode_next", "docstring": "Returns the next decoded chunk. If the chunk is an ImageData chunk, its contents are written\ninto image_data.", "repo": "image-rs/image-png", "path": "src/decoder/read_decoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/read_decoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d17492897b505e6dedde009c2aced0e361bbdafae05284751445d7a9393ca7d6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_header_info\n\nDocumentation:\nReads until the end of `IHDR` chunk.\n\nPrerequisite: None (idempotent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_header_info(&mut self) -> Result<&Info<'static>, DecodingError> {\n while self.info().is_none() {\n if let Decoded::ImageEnd = self.decode_next_without_image_data()? {\n unreachable!()\n }\n }\n Ok(self.info().unwrap())\n }\n```"}], "func_name": "read_header_info", "docstring": "Reads until the end of `IHDR` chunk.\n\nPrerequisite: None (idempotent).", "repo": "image-rs/image-png", "path": "src/decoder/read_decoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/read_decoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d39bee2db5c58e916fa3b76e860a0cf5ad7477b5c8c94ba08cc3c6a04863c1dd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_until_image_data\n\nDocumentation:\nReads until the start of the next `IDAT` or `fdAT` chunk.\n\nPrerequisite: **Not** within `IDAT` / `fdAT` chunk sequence.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_until_image_data(&mut self) -> Result<(), DecodingError> {\n loop {\n match self.decode_next_without_image_data()? {\n Decoded::ChunkBegin(_, chunk::IDAT) | Decoded::ChunkBegin(_, chunk::fdAT) => break,\n Decoded::ImageEnd => {\n return Err(DecodingError::Format(\n FormatErrorInner::MissingImageData.into(),\n ))\n }\n // Ignore all other chunk events. Any other chunk may be between IDAT chunks, fdAT\n // chunks and their control chunks.\n _ => {}\n }\n }\n Ok(())\n }\n```"}], "func_name": "read_until_image_data", "docstring": "Reads until the start of the next `IDAT` or `fdAT` chunk.\n\nPrerequisite: **Not** within `IDAT` / `fdAT` chunk sequence.", "repo": "image-rs/image-png", "path": "src/decoder/read_decoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/read_decoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c77bbc4d1839e6d4d371b5ee78fe96e09f7b3af3c81a3f487ee8ddca049a4e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decode_image_data\n\nDocumentation:\nReads `image_data` and reports whether there may be additional data afterwards (i.e. if it\nis okay to call `decode_image_data` and/or `finish_decoding_image_data` again)..\n\nPrerequisite: Input is currently positioned within `IDAT` / `fdAT` chunk sequence.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn decode_image_data(\n &mut self,\n image_data: Option<&mut UnfilterBuf<'_>>,\n ) -> Result {\n match self.decode_next(image_data)? {\n Decoded::ImageData => Ok(ImageDataCompletionStatus::ExpectingMoreData),\n Decoded::ImageDataFlushed => Ok(ImageDataCompletionStatus::Done),\n // Ignore other events that may happen within an `IDAT` / `fdAT` chunks sequence.\n Decoded::Nothing\n | Decoded::ChunkComplete(_, _)\n | Decoded::ChunkBegin(_, _)\n | Decoded::PartialChunk(_) => Ok(ImageDataCompletionStatus::ExpectingMoreData),\n // Other kinds of events shouldn't happen, unless we have been (incorrectly) called\n // when outside of a sequence of `IDAT` / `fdAT` chunks.\n unexpected => unreachable!(\"{:?}\", unexpected),\n }\n }\n```"}], "func_name": "decode_image_data", "docstring": "Reads `image_data` and reports whether there may be additional data afterwards (i.e. if it\nis okay to call `decode_image_data` and/or `finish_decoding_image_data` again)..\n\nPrerequisite: Input is currently positioned within `IDAT` / `fdAT` chunk sequence.", "repo": "image-rs/image-png", "path": "src/decoder/read_decoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/read_decoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e489ceaa81fb9bc76ec3aadfb8ff57f534e90358c582964f2481114cbacdd2ac"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish_decoding_image_data\n\nDocumentation:\nConsumes and discards the rest of an `IDAT` / `fdAT` chunk sequence.\n\nPrerequisite: Input is currently positioned within `IDAT` / `fdAT` chunk sequence.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn finish_decoding_image_data(&mut self) -> Result<(), DecodingError> {\n loop {\n if let ImageDataCompletionStatus::Done = self.decode_image_data(None)? {\n return Ok(());\n }\n }\n }\n```"}], "func_name": "finish_decoding_image_data", "docstring": "Consumes and discards the rest of an `IDAT` / `fdAT` chunk sequence.\n\nPrerequisite: Input is currently positioned within `IDAT` / `fdAT` chunk sequence.", "repo": "image-rs/image-png", "path": "src/decoder/read_decoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/read_decoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e8b98d3832b9790117b4b5fa24fe386afff021afeaa103f78c5f7ff2d62eeb58"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_until_end_of_input\n\nDocumentation:\nReads until the `IEND` chunk.\n\nPrerequisite: `IEND` chunk hasn't been reached yet.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_until_end_of_input(&mut self) -> Result<(), DecodingError> {\n while !matches!(\n self.decode_next_and_discard_image_data()?,\n Decoded::ImageEnd\n ) {}\n Ok(())\n }\n```"}], "func_name": "read_until_end_of_input", "docstring": "Reads until the `IEND` chunk.\n\nPrerequisite: `IEND` chunk hasn't been reached yet.", "repo": "image-rs/image-png", "path": "src/decoder/read_decoder.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/read_decoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fce33bb7faad8cbdabd89b3b65b23f12284e20a9cf29326a39c662a529727bf2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_ignore_adler32\n\nDocumentation:\nWhen set, the decoder will not compute and verify the Adler-32 checksum.\n\nDefaults to `true`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_ignore_adler32(&mut self, ignore_adler32: bool) {\n self.ignore_adler32 = ignore_adler32;\n }\n```"}], "func_name": "set_ignore_adler32", "docstring": "When set, the decoder will not compute and verify the Adler-32 checksum.\n\nDefaults to `true`.", "repo": "image-rs/image-png", "path": "src/decoder/stream.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d40ace0c6bffd85be9d4220e9b0acdfd978108116d2c1f28e47df3fa7adb05f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_ignore_crc\n\nDocumentation:\nWhen set, the decoder will not compute and verify the CRC code.\n\nDefaults to `false`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_ignore_crc(&mut self, ignore_crc: bool) {\n self.ignore_crc = ignore_crc;\n }\n```"}], "func_name": "set_ignore_crc", "docstring": "When set, the decoder will not compute and verify the CRC code.\n\nDefaults to `false`.", "repo": "image-rs/image-png", "path": "src/decoder/stream.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "249cc1603745045c8a408a63ad88416cb169acef960f253fd9c5828447c79096"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_ignore_checksums\n\nDocumentation:\nFlag to ignore computing and verifying the Adler-32 checksum and CRC\ncode.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_ignore_checksums(&mut self, ignore_checksums: bool) {\n self.ignore_adler32 = ignore_checksums;\n self.ignore_crc = ignore_checksums;\n }\n```"}], "func_name": "set_ignore_checksums", "docstring": "Flag to ignore computing and verifying the Adler-32 checksum and CRC\ncode.", "repo": "image-rs/image-png", "path": "src/decoder/stream.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "058666b7255084ae624346687fb949db49891cd01c13df2a340beded44bc427f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_ignore_text_chunk\n\nDocumentation:\nIgnore text chunks while decoding.\n\nDefaults to `false`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_ignore_text_chunk(&mut self, ignore_text_chunk: bool) {\n self.ignore_text_chunk = ignore_text_chunk;\n }\n```"}], "func_name": "set_ignore_text_chunk", "docstring": "Ignore text chunks while decoding.\n\nDefaults to `false`.", "repo": "image-rs/image-png", "path": "src/decoder/stream.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "edab3f637f1c088ad491746e78657d05d1a258ec1c9c5a7ec6c7632dc7bcb174"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_ignore_iccp_chunk\n\nDocumentation:\nIgnore ICCP chunks while decoding.\n\nDefaults to `false`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_ignore_iccp_chunk(&mut self, ignore_iccp_chunk: bool) {\n self.ignore_iccp_chunk = ignore_iccp_chunk;\n }\n```"}], "func_name": "set_ignore_iccp_chunk", "docstring": "Ignore ICCP chunks while decoding.\n\nDefaults to `false`.", "repo": "image-rs/image-png", "path": "src/decoder/stream.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "859ce6766f978ff38eb0bc3b628dea38f01da830ae3b7bf659bcf9269f392a04"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_skip_ancillary_crc_failures\n\nDocumentation:\nIgnore ancillary chunks if CRC fails\n\nDefaults to `true`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_skip_ancillary_crc_failures(&mut self, skip_ancillary_crc_failures: bool) {\n self.skip_ancillary_crc_failures = skip_ancillary_crc_failures;\n }\n```"}], "func_name": "set_skip_ancillary_crc_failures", "docstring": "Ignore ancillary chunks if CRC fails\n\nDefaults to `true`", "repo": "image-rs/image-png", "path": "src/decoder/stream.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3e0e0971ca029ac437c462f4cdd54def438fc07ef180c3283efd53ea1319c33c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update\n\nDocumentation:\nLow level StreamingDecoder interface.\n\nAllows to stream partial data to the encoder. Returns a tuple containing the bytes that have\nbeen consumed from the input buffer and the current decoding result. If the decoded chunk\nwas an image data chunk, it also appends the read data to `image_data`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn update(\n &mut self,\n mut buf: &[u8],\n mut image_data: Option<&mut UnfilterBuf<'_>>,\n ) -> Result<(usize, Decoded), DecodingError> {\n if self.state.is_none() {\n return Err(DecodingError::Parameter(\n ParameterErrorKind::PolledAfterFatalError.into(),\n ));\n }\n\n let len = buf.len();\n while !buf.is_empty() {\n let image_data = image_data.as_deref_mut();\n\n match self.next_state(buf, image_data) {\n Ok((bytes, Decoded::Nothing)) => buf = &buf[bytes..],\n Ok((bytes, result)) => {\n buf = &buf[bytes..];\n return Ok((len - buf.len(), result));\n }\n Err(err) => {\n debug_assert!(self.state.is_none());\n return Err(err);\n }\n }\n }\n Ok((len - buf.len(), Decoded::Nothing))\n }\n```"}], "func_name": "update", "docstring": "Low level StreamingDecoder interface.\n\nAllows to stream partial data to the encoder. Returns a tuple containing the bytes that have\nbeen consumed from the input buffer and the current decoding result. If the decoded chunk\nwas an image data chunk, it also appends the read data to `image_data`.", "repo": "image-rs/image-png", "path": "src/decoder/stream.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6c3f23d76d9b278bcdd064c2e96a0c5c9049222c4d2ff4d57b63601e87e2fbcb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_fdat_prefix\n\nDocumentation:\nWrites PNG signature and chunks that can precede an fdAT chunk that is expected\nto have\n- `sequence_number` set to 0\n- image data with rgba8 pixels in a `width` by `width` image\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_fdat_prefix(w: &mut impl Write, num_frames: u32, width: u32) {\n write_png_sig(w);\n write_rgba8_ihdr_with_width(w, width);\n write_actl(\n w,\n &crate::AnimationControl {\n num_frames,\n num_plays: 0,\n },\n );\n\n let mut fctl = crate::FrameControl {\n width,\n height: width,\n ..Default::default()\n };\n write_fctl(w, &fctl);\n write_rgba8_idats(w, width, 0x7fffffff);\n\n fctl.sequence_number += 1;\n write_fctl(w, &fctl);\n }\n```"}], "func_name": "write_fdat_prefix", "docstring": "Writes PNG signature and chunks that can precede an fdAT chunk that is expected\nto have\n- `sequence_number` set to 0\n- image data with rgba8 pixels in a `width` by `width` image", "repo": "image-rs/image-png", "path": "src/decoder/stream.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "edead54ae72dcffd1ab09a9822cf3f5935f7bf913fe1bd60b7b252f057eb8284"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_reader_of_ihdr_idat\n\nDocumentation:\nCreates a ready-to-test [`Reader`] which decodes a PNG that contains:\nIHDR, IDAT, IEND.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn create_reader_of_ihdr_idat() -> Reader>> {\n let mut png = Vec::new();\n write_noncompressed_png(&mut png, /* width = */ 16, /* idat_size = */ 1024);\n Decoder::new(Cursor::new(png)).read_info().unwrap()\n }\n```"}], "func_name": "create_reader_of_ihdr_idat", "docstring": "Creates a ready-to-test [`Reader`] which decodes a PNG that contains:\nIHDR, IDAT, IEND.", "repo": "image-rs/image-png", "path": "src/decoder/stream.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f81bb1fc3b6b52d96bf2f412b172d138dade67e09a5c0e7af4de99fd3aab24a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_reader_of_ihdr_actl_fctl_idat_fctl_fdat\n\nDocumentation:\nCreates a ready-to-test [`Reader`] which decodes an animated PNG that contains:\nIHDR, acTL, fcTL, IDAT, fcTL, fdAT, IEND. (i.e. IDAT is part of the animation)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn create_reader_of_ihdr_actl_fctl_idat_fctl_fdat() -> Reader>> {\n let width = 16;\n let mut fctl = crate::FrameControl {\n width,\n height: width,\n ..Default::default()\n };\n\n let mut png = Vec::new();\n write_png_sig(&mut png);\n write_rgba8_ihdr_with_width(&mut png, width);\n write_actl(\n &mut png,\n &crate::AnimationControl {\n num_frames: 2,\n num_plays: 0,\n },\n );\n fctl.sequence_number = 0;\n write_fctl(&mut png, &fctl);\n // Using `fctl.height + 1` means that the `IDAT` will have \"left-over\" data after\n // processing. This helps to verify that `Reader.read_until_image_data` discards the\n // left-over data when resetting `UnfilteredRowsBuffer`.\n let idat_data = generate_rgba8_with_width_and_height(fctl.width, fctl.height + 1);\n write_chunk(&mut png, b\"IDAT\", &idat_data);\n\n let fdat_width = 10;\n fctl.sequence_number = 1;\n // Using different width in `IDAT` and `fDAT` frames helps to catch problems that\n // may arise when `Reader.read_until_image_data` doesn't properly reset\n // `UnfilteredRowsBuffer`.\n fctl.width = fdat_width;\n write_fctl(&mut png, &fctl);\n let fdat_data = generate_rgba8_with_width_and_height(fctl.width, fctl.height);\n write_fdat(&mut png, 2, &fdat_data);\n write_iend(&mut png);\n\n Decoder::new(Cursor::new(png)).read_info().unwrap()\n }\n```"}], "func_name": "create_reader_of_ihdr_actl_fctl_idat_fctl_fdat", "docstring": "Creates a ready-to-test [`Reader`] which decodes an animated PNG that contains:\nIHDR, acTL, fcTL, IDAT, fcTL, fdAT, IEND. (i.e. IDAT is part of the animation)", "repo": "image-rs/image-png", "path": "src/decoder/stream.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c79b7c69b2ea80d9e5bdf66c929b28faf9b18b4663c6be2e0f9372719645bc06"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_reader_of_ihdr_actl_idat_fctl_fdat_fctl_fdat\n\nDocumentation:\nCreates a ready-to-test [`Reader`] which decodes an animated PNG that contains: IHDR, acTL,\nIDAT, fcTL, fdAT, fcTL, fdAT, IEND. (i.e. IDAT is *not* part of the animation)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn create_reader_of_ihdr_actl_idat_fctl_fdat_fctl_fdat() -> Reader>> {\n let width = 16;\n let frame_data = generate_rgba8_with_width_and_height(width, width);\n let mut fctl = crate::FrameControl {\n width,\n height: width,\n ..Default::default()\n };\n\n let mut png = Vec::new();\n write_png_sig(&mut png);\n write_rgba8_ihdr_with_width(&mut png, width);\n write_actl(\n &mut png,\n &crate::AnimationControl {\n num_frames: 2,\n num_plays: 0,\n },\n );\n write_chunk(&mut png, b\"IDAT\", &frame_data);\n fctl.sequence_number = 0;\n write_fctl(&mut png, &fctl);\n write_fdat(&mut png, 1, &frame_data);\n fctl.sequence_number = 2;\n write_fctl(&mut png, &fctl);\n write_fdat(&mut png, 3, &frame_data);\n write_iend(&mut png);\n\n Decoder::new(Cursor::new(png)).read_info().unwrap()\n }\n```"}], "func_name": "create_reader_of_ihdr_actl_idat_fctl_fdat_fctl_fdat", "docstring": "Creates a ready-to-test [`Reader`] which decodes an animated PNG that contains: IHDR, acTL,\nIDAT, fcTL, fdAT, fcTL, fdAT, IEND. (i.e. IDAT is *not* part of the animation)", "repo": "image-rs/image-png", "path": "src/decoder/stream.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3598db4544a90428510f56ce204a36141464f77b3971e2f4179ed2d14cf16065"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_transform_fn\n\nDocumentation:\nReturns a transformation function that should be applied to image rows based\non 1) decoded image metadata (`info`) and 2) the transformations requested\nby the crate client (`transform`).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_transform_fn(\n info: &Info,\n transform: Transformations,\n) -> Result {\n let color_type = info.color_type;\n let bit_depth = info.bit_depth as u8;\n let trns = info.trns.is_some() || transform.contains(Transformations::ALPHA);\n let expand =\n transform.contains(Transformations::EXPAND) || transform.contains(Transformations::ALPHA);\n let strip16 = bit_depth == 16 && transform.contains(Transformations::STRIP_16);\n match color_type {\n ColorType::Indexed if expand => {\n if info.palette.is_none() {\n Err(DecodingError::Format(\n FormatErrorInner::PaletteRequired.into(),\n ))\n } else if let BitDepth::Sixteen = info.bit_depth {\n // This should have been caught earlier but let's check again. Can't hurt.\n Err(DecodingError::Format(\n FormatErrorInner::InvalidColorBitDepth {\n color_type: ColorType::Indexed,\n bit_depth: BitDepth::Sixteen,\n }\n .into(),\n ))\n } else {\n Ok(if trns {\n palette::create_expansion_into_rgba8(info)\n } else {\n palette::create_expansion_into_rgb8(info)\n })\n }\n }\n ColorType::Grayscale | ColorType::GrayscaleAlpha if bit_depth < 8 && expand => {\n Ok(Box::new(if trns {\n expand_gray_u8_with_trns\n } else {\n expand_gray_u8\n }))\n }\n ColorType::Grayscale | ColorType::Rgb if expand && trns => {\n Ok(Box::new(if bit_depth == 8 {\n expand_trns_line\n } else if strip16 {\n expand_trns_and_strip_line16\n } else {\n assert_eq!(bit_depth, 16);\n expand_trns_line16\n }))\n }\n ColorType::Grayscale | ColorType::GrayscaleAlpha | ColorType::Rgb | ColorType::Rgba\n if strip16 =>\n {\n Ok(Box::new(transform_row_strip16))\n }\n _ => Ok(Box::new(copy_row)),\n }\n}\n```"}], "func_name": "create_transform_fn", "docstring": "Returns a transformation function that should be applied to image rows based\non 1) decoded image metadata (`info`) and 2) the transformations requested\nby the crate client (`transform`).", "repo": "image-rs/image-png", "path": "src/decoder/transform.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/transform.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "115de55d2a3a66512b6250f6fc1e791f7311f9767dbba89985fc800cbd3787a9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: debug_assert_invariants\n\nDocumentation:\nAsserts in debug builds that all the invariants hold. No-op in release\nbuilds. Intended to be called after creating or mutating `self` to\nensure that the final state preserves the invariants.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn debug_assert_invariants(&self) {\n debug_assert!(self.prev_start <= self.current_start);\n debug_assert!(self.current_start <= self.available);\n debug_assert!(self.available <= self.filled);\n debug_assert!(self.filled <= self.data_stream.len());\n }\n```"}], "func_name": "debug_assert_invariants", "docstring": "Asserts in debug builds that all the invariants hold. No-op in release\nbuilds. Intended to be called after creating or mutating `self` to\nensure that the final state preserves the invariants.", "repo": "image-rs/image-png", "path": "src/decoder/unfiltering_buffer.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/unfiltering_buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "07cbb214a3a6b82164b9da5407be4da74364ef517080c55b7bf19186dde907ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a buffer tuned for filtering rows of the image type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(info: &Info<'_>) -> Self {\n // We don't need all of `info` here so if that becomes a structural problem then these\n // derived constants can be extracted into a parameter struct. For instance they may be\n // adjusted according to platform hardware such as cache sizes.\n let data_stream_capacity = {\n let max_data = info\n .checked_raw_row_length()\n // In the current state this is really dependent on IDAT sizes and the compression\n // settings. We aim to avoid overallocation here, but that occurs in part due to\n // the algorithm for draining the buffer, which at the time of writing is at each\n // individual IDAT chunk boundary. So this is set for a quadratic image roughly\n // fitting into a single 4k chunk at compression.. A very arbitrary choice made\n // from (probably overfitting) a benchmark of that image size. With a different\n // algorithm we may come to different buffer uses and have to re-evaluate.\n .and_then(|v| v.checked_mul(info.height.min(128) as usize))\n // In the worst case this is additional room for use of unmasked SIMD moves. But\n // the other idea here is that the allocator generally aligns the buffer.\n .and_then(|v| checked_next_multiple_of(v, 256))\n .unwrap_or(usize::MAX);\n // We do not want to pre-allocate too much in case of a faulty image (no DOS by\n // pretending to be very very large) and also we want to avoid allocating more data\n // than we need for the image itself.\n max_data.min(128 * 1024)\n };\n\n let shift_back_limit = {\n // Prefer shifting by powers of two and only after having done some number of\n // lines that then become free at the end of the buffer.\n let rowlen_pot = info\n .checked_raw_row_length()\n // Ensure some number of rows are actually present before shifting back, i.e. next\n // time around we want to be able to decode them without reallocating the buffer.\n .and_then(|v| v.checked_mul(4))\n // And also, we should be able to use aligned memcopy on the whole thing. Well at\n // least that is the idea but the parameter is just benchmarking. Higher numbers\n // did not result in performance gains but lowers also, so this is fickle. Maybe\n // our shift back behavior can not be tuned very well.\n .and_then(|v| checked_next_multiple_of(v, 64))\n .unwrap_or(isize::MAX as usize);\n // But never shift back before we have a number of pages freed.\n rowlen_pot.max(128 * 1024)\n };\n\n let result = Self {\n data_stream: Vec::with_capacity(data_stream_capacity),\n prev_start: 0,\n current_start: 0,\n filled: 0,\n available: 0,\n shift_back_limit,\n };\n\n result.debug_assert_invariants();\n result\n }\n```"}], "func_name": "new", "docstring": "Create a buffer tuned for filtering rows of the image type.", "repo": "image-rs/image-png", "path": "src/decoder/unfiltering_buffer.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/unfiltering_buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5e6b3979579f419220be2aad90f071c4a2e3ac7946dc78d488a91005df036ff8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_prev_row\n\nDocumentation:\nCalled to indicate that there is no previous row (e.g. when the current\nrow is the first scanline of a given Adam7 pass).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reset_prev_row(&mut self) {\n self.prev_start = self.current_start;\n self.debug_assert_invariants();\n }\n```"}], "func_name": "reset_prev_row", "docstring": "Called to indicate that there is no previous row (e.g. when the current\nrow is the first scanline of a given Adam7 pass).", "repo": "image-rs/image-png", "path": "src/decoder/unfiltering_buffer.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/unfiltering_buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "13235297271f6df02af23858ed7ea20d8a5e075f90928f45ffc4d4bc77e78700"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: curr_row_len\n\nDocumentation:\nReturns how many bytes of the current row are present in the buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn curr_row_len(&self) -> usize {\n self.available - self.current_start\n }\n```"}], "func_name": "curr_row_len", "docstring": "Returns how many bytes of the current row are present in the buffer.", "repo": "image-rs/image-png", "path": "src/decoder/unfiltering_buffer.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/unfiltering_buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "777f2a0b6901c1406462d51e948dbe178f7ad0cc2cbd00d2f71590107da9768a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_unfilled_buffer\n\nDocumentation:\nReturns a `&mut Vec` suitable for passing to\n`ReadDecoder.decode_image_data` or `StreamingDecoder.update`.\n\nInvariants of `self` depend on the assumption that the caller will only\nappend new bytes to the returned vector (which is indeed the behavior of\n`ReadDecoder` and `StreamingDecoder`). TODO: Consider protecting the\ninvariants by returning an append-only view of the vector\n(`FnMut(&[u8])`??? or maybe `std::io::Write`???).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_unfilled_buffer(&mut self) -> UnfilterBuf<'_> {\n if self.prev_start >= self.shift_back_limit\n // Avoid the shift back if the buffer is still very empty. Consider how we got here: a\n // previous decompression filled the buffer, then we unfiltered, we're now refilling\n // the buffer again. The condition implies, the previous decompression filled at most\n // half the buffer. Likely the same will happen again so the following decompression\n // attempt will not yet be limited by the buffer length.\n && self.filled >= self.data_stream.len() / 2\n {\n // We have to relocate the data to the start of the buffer. Benchmarking suggests that\n // the codegen for an unbounded range is better / different than the one for a bounded\n // range. We prefer the former if the data overhead is not too high. `16` was\n // determined experimentally and might be system (memory) dependent. There's also the\n // question if we could be a little smarter and avoid crossing page boundaries when\n // that is not required. Alas, microbenchmarking TBD.\n if let Some(16..) = self.data_stream.len().checked_sub(self.filled) {\n self.data_stream\n .copy_within(self.prev_start..self.filled, 0);\n } else {\n self.data_stream.copy_within(self.prev_start.., 0);\n }\n\n // The data kept its relative position to `filled` which now lands exactly at\n // the distance between prev_start and filled.\n self.current_start -= self.prev_start;\n self.available -= self.prev_start;\n self.filled -= self.prev_start;\n self.prev_start = 0;\n }\n\n if self.filled + Self::GROWTH_BYTES > self.data_stream.len() {\n self.data_stream.resize(self.filled + Self::GROWTH_BYTES, 0);\n }\n\n UnfilterBuf {\n buffer: &mut self.data_stream,\n filled: &mut self.filled,\n available: &mut self.available,\n }\n }\n```"}], "func_name": "as_unfilled_buffer", "docstring": "Returns a `&mut Vec` suitable for passing to\n`ReadDecoder.decode_image_data` or `StreamingDecoder.update`.\n\nInvariants of `self` depend on the assumption that the caller will only\nappend new bytes to the returned vector (which is indeed the behavior of\n`ReadDecoder` and `StreamingDecoder`). TODO: Consider protecting the\ninvariants by returning an append-only view of the vector\n(`FnMut(&[u8])`??? or maybe `std::io::Write`???).", "repo": "image-rs/image-png", "path": "src/decoder/unfiltering_buffer.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/unfiltering_buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d8855b11e8c380461920ccbedd1718f1d206c11482a41cbf26ada4a1a59e16d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unfilter_curr_row\n\nDocumentation:\nRuns `unfilter` on the current row, and then shifts rows so that the current row becomes the previous row.\n\nWill panic if `self.curr_row_len() < rowlen`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unfilter_curr_row(\n &mut self,\n rowlen: usize,\n bpp: BytesPerPixel,\n ) -> Result<(), DecodingError> {\n debug_assert!(rowlen >= 2); // 1 byte for `FilterType` and at least 1 byte of pixel data.\n\n let (prev, row) = self.data_stream.split_at_mut(self.current_start);\n let prev: &[u8] = &prev[self.prev_start..];\n\n debug_assert!(prev.is_empty() || prev.len() == (rowlen - 1));\n\n // Get the filter type.\n let filter = RowFilter::from_u8(row[0]).ok_or(DecodingError::Format(\n FormatErrorInner::UnknownFilterMethod(row[0]).into(),\n ))?;\n let row = &mut row[1..rowlen];\n\n unfilter(filter, bpp, prev, row);\n\n self.prev_start = self.current_start + 1;\n self.current_start += rowlen;\n\n self.debug_assert_invariants();\n\n Ok(())\n }\n```"}], "func_name": "unfilter_curr_row", "docstring": "Runs `unfilter` on the current row, and then shifts rows so that the current row becomes the previous row.\n\nWill panic if `self.curr_row_len() < rowlen`.", "repo": "image-rs/image-png", "path": "src/decoder/unfiltering_buffer.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/unfiltering_buffer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5307613f3e7e64c4a1a9f5ede98e10cc8b3c07809a69f5dc0140a653f5b84ffe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_ignore_adler32\n\nDocumentation:\nSet the `ignore_adler32` flag and return `true` if the flag was\nsuccessfully set.\n\nThe default is `true`.\n\nThis flag cannot be modified after decompression has started until the\n[ZlibStream] is reset.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn set_ignore_adler32(&mut self, flag: bool) -> bool {\n if !self.started {\n self.ignore_adler32 = flag;\n true\n } else {\n false\n }\n }\n```"}], "func_name": "set_ignore_adler32", "docstring": "Set the `ignore_adler32` flag and return `true` if the flag was\nsuccessfully set.\n\nThe default is `true`.\n\nThis flag cannot be modified after decompression has started until the\n[ZlibStream] is reset.", "repo": "image-rs/image-png", "path": "src/decoder/zlib.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/zlib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "89f4f4c8d1c11eb4976f60ffb5f8812f4518867a7a200ce5aa78caaeb8599f5c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decompress\n\nDocumentation:\nFill the decoded buffer as far as possible from `data`.\nOn success returns the number of consumed input bytes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn decompress(\n &mut self,\n data: &[u8],\n image_data: &mut UnfilterBuf<'_>,\n ) -> Result {\n // There may be more data past the adler32 checksum at the end of the deflate stream. We\n // match libpng's default behavior and ignore any trailing data. In the future we may want\n // to add a flag to control this behavior.\n if self.state.is_done() {\n return Ok(data.len());\n }\n\n if !self.started && self.ignore_adler32 {\n self.state.ignore_adler32();\n }\n\n let (buffer, filled) = image_data.borrow_mut();\n let output_limit = (filled + UnfilteringBuffer::GROWTH_BYTES).min(buffer.len());\n let (in_consumed, out_consumed) = self\n .state\n .read(data, &mut buffer[..output_limit], filled, false)\n .map_err(|err| {\n DecodingError::Format(FormatErrorInner::CorruptFlateStream { err }.into())\n })?;\n\n self.started = true;\n let filled = filled + out_consumed;\n image_data.filled(filled);\n\n if self.state.is_done() {\n image_data.commit(filled);\n } else {\n // See [`Self::LOOKBACK_SIZE`].\n image_data.commit(filled.saturating_sub(Self::LOOKBACK_SIZE));\n }\n\n Ok(in_consumed)\n }\n```"}], "func_name": "decompress", "docstring": "Fill the decoded buffer as far as possible from `data`.\nOn success returns the number of consumed input bytes.", "repo": "image-rs/image-png", "path": "src/decoder/zlib.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/zlib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6a92ec48490b4781e00d7e42f7b75452a24eb1630156e263e680c91e5d8d0afb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish_compressed_chunks\n\nDocumentation:\nCalled after all consecutive IDAT chunks were handled.\n\nThe compressed stream can be split on arbitrary byte boundaries. This enables some cleanup\nwithin the decompressor and flushing additional data which may have been kept back in case\nmore data were passed to it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn finish_compressed_chunks(\n &mut self,\n image_data: &mut UnfilterBuf<'_>,\n ) -> Result<(), DecodingError> {\n if !self.started {\n return Ok(());\n }\n\n if self.state.is_done() {\n // We can end up here only after the [`decompress`] call above has detected the state\n // to be done, too. In this case the filled and committed amount of data are already\n // equal to each other. So neither of them needs to be touched in any way.\n return Ok(());\n }\n\n let (_, mut filled) = image_data.borrow_mut();\n while !self.state.is_done() {\n let (buffer, _) = image_data.borrow_mut();\n let (_in_consumed, out_consumed) =\n self.state.read(&[], buffer, filled, true).map_err(|err| {\n DecodingError::Format(FormatErrorInner::CorruptFlateStream { err }.into())\n })?;\n\n filled += out_consumed;\n\n if !self.state.is_done() {\n image_data.flush_allocate();\n }\n }\n\n image_data.filled(filled);\n image_data.commit(filled);\n\n Ok(())\n }\n```"}], "func_name": "finish_compressed_chunks", "docstring": "Called after all consecutive IDAT chunks were handled.\n\nThe compressed stream can be split on arbitrary byte boundaries. This enables some cleanup\nwithin the decompressor and flushing additional data which may have been kept back in case\nmore data were passed to it.", "repo": "image-rs/image-png", "path": "src/decoder/zlib.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/zlib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "02a0ff126b895acfef079c452e479707b032627e84c4a8c268472a630338c31b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_buf\n\nDocumentation:\nUse this region to decompress new filtered rowline data.\n\nPass the wrapped buffer to\n[`StreamingDecoder::update`][`super::stream::StreamingDecoder::update`] to fill it with\ndata and update the region indices.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_buf<'data>(&'data mut self, buffer: &'data mut Vec) -> UnfilterBuf<'data> {\n UnfilterBuf {\n buffer,\n filled: &mut self.filled,\n available: &mut self.available,\n }\n }\n```"}], "func_name": "as_buf", "docstring": "Use this region to decompress new filtered rowline data.\n\nPass the wrapped buffer to\n[`StreamingDecoder::update`][`super::stream::StreamingDecoder::update`] to fill it with\ndata and update the region indices.", "repo": "image-rs/image-png", "path": "src/decoder/zlib.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/zlib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "71814fbef996f7c5adeee3233b59a6efc788c7ab85efc10b0190893ed0aa85c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: oracle_expand_paletted_into_rgb8\n\nDocumentation:\nOld, non-memoized version of the code is used as a test oracle.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn oracle_expand_paletted_into_rgb8(row: &[u8], buffer: &mut [u8], info: &Info) {\n let palette = info.palette.as_deref().expect(\"Caller should verify\");\n let black = [0, 0, 0];\n\n super::unpack_bits(row, buffer, 3, info.bit_depth as u8, |i, chunk| {\n let rgb = palette\n .get(3 * i as usize..3 * i as usize + 3)\n .unwrap_or(&black);\n chunk[0] = rgb[0];\n chunk[1] = rgb[1];\n chunk[2] = rgb[2];\n })\n }\n```"}], "func_name": "oracle_expand_paletted_into_rgb8", "docstring": "Old, non-memoized version of the code is used as a test oracle.", "repo": "image-rs/image-png", "path": "src/decoder/transform/palette.rs", "url": "https://github.com/image-rs/image-png/blob/master/src/decoder/transform/palette.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0fcbe847aaa41b4bf5675a4a22c0d562d8cc5ed9911569047192e3833c4bf73e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: skip_all_escape_code\n\nDocumentation:\nReturns the number of bytes of escape code that start the slice.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn skip_all_escape_code(buf: &[u8]) -> usize {\n // Skip one sequence\n fn skip_escape_code(buf: &[u8]) -> Option {\n if 2 <= buf.len() && &buf[..2] == b\"\\x1b[\" {\n // \"\\x1b[\" + sequence body + \"m\" => 3 additional bytes\n Some(index_of(&buf[2..], b'm')? + 3)\n } else {\n None\n }\n }\n let mut buf = buf;\n let mut sum = 0;\n while let Some(nbytes) = skip_escape_code(buf) {\n buf = &buf[nbytes..];\n sum += nbytes\n }\n sum\n}\n```"}], "func_name": "skip_all_escape_code", "docstring": "Returns the number of bytes of escape code that start the slice.", "repo": "mookid/diffr", "path": "src/main.rs", "url": "https://github.com/mookid/diffr/blob/master/src/main.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a342c2a3e751c5a581d649cad4c176d7634f5c7d0d533b62ef36eb3df029d0fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: first_after_escape\n\nDocumentation:\nReturns the first byte of the slice, after skipping the escape\ncode bytes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn first_after_escape(buf: &[u8]) -> Option {\n let nbytes = skip_all_escape_code(buf);\n buf.iter().skip(nbytes).cloned().next()\n}\n```"}], "func_name": "first_after_escape", "docstring": "Returns the first byte of the slice, after skipping the escape\ncode bytes.", "repo": "mookid/diffr", "path": "src/main.rs", "url": "https://github.com/mookid/diffr/blob/master/src/main.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "73468be7f4f44087663b73a45c6c2eb225a64757fc83ab02ebd80c08c045104f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: index_of\n\nDocumentation:\nScan the slice looking for the given byte, returning the index of\nits first appearance.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn index_of(buf: &[u8], target: u8) -> Option {\n let mut it = buf.iter().enumerate();\n loop {\n match it.next() {\n Some((index, c)) => {\n if *c == target {\n return Some(index);\n }\n }\n None => return None,\n }\n }\n}\n```"}], "func_name": "index_of", "docstring": "Scan the slice looking for the given byte, returning the index of\nits first appearance.", "repo": "mookid/diffr", "path": "src/main.rs", "url": "https://github.com/mookid/diffr/blob/master/src/main.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8febb9b2d54001df20ffc6d13a481fc2dc72cba41d1db9858653141215b5f454"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: skip_token\n\nDocumentation:\nComputes the number of bytes until either the next escape code, or\nthe end of buf.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn skip_token(buf: &[u8]) -> usize {\n match buf.len() {\n 0 => 0,\n len => {\n for i in 0..buf.len() - 1 {\n if &buf[i..i + 2] == b\"\\x1b[\" {\n return i;\n }\n }\n len\n }\n }\n}\n```"}], "func_name": "skip_token", "docstring": "Computes the number of bytes until either the next escape code, or\nthe end of buf.", "repo": "mookid/diffr", "path": "src/main.rs", "url": "https://github.com/mookid/diffr/blob/master/src/main.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "424aa82a4f86348c7857a0eb6085a11f38d7e761779b58377bd93d8972ef45ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shared_segments\n\nDocumentation:\nThe shared segments between both inputs of `optimize_partition`.\nThe `seq` argument is the longest of the two inputs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn shared_segments<'a>(\n &'a self,\n seq: &'a Tokenization,\n ) -> impl Iterator + 'a {\n SharedSegments::new(self, seq)\n }\n```"}], "func_name": "shared_segments", "docstring": "The shared segments between both inputs of `optimize_partition`.\nThe `seq` argument is the longest of the two inputs.", "repo": "mookid/diffr", "path": "src/diffr_lib/best_projection.rs", "url": "https://github.com/mookid/diffr/blob/master/src/diffr_lib/best_projection.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1d61a63c46ec4c893615af35af7f866166b4fbd1cef3180e1cb53563a3a19185"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: optimize_partition\n\nDocumentation:\nMinimize the number of elements when partitioning `seq` according to `lcs`.\n`lcs` is a subsequence of `seq`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn optimize_partition(seq: &Tokenization, lcs: &Tokenization) -> NormalizationResult {\n let context = Context::new(seq, lcs);\n let root = Coord {\n next_lcs: 0,\n next_seq: 0,\n };\n let target = Coord {\n next_lcs: lcs.nb_tokens(),\n next_seq: seq.nb_tokens(),\n };\n let mut frontier = vec![root];\n let mut new_frontier = vec![];\n let mut prev = HashMap::new();\n let mut found_seq = None;\n while !frontier.is_empty() && found_seq.is_none() {\n new_frontier.clear();\n for &coord in frontier.iter() {\n if coord.next_lcs == target.next_lcs {\n found_seq = Some(coord.next_seq);\n if coord.next_seq == target.next_seq {\n break;\n } else {\n // TODO do something more clever here\n continue;\n }\n }\n let start_lcs = coord.next_lcs;\n let lcs_len = lcs.nb_tokens() - start_lcs;\n let mut last_enqueued_snake_len = 0;\n for start_seq in\n context.get_indexes(lcs.nth_token(to_isize(coord.next_lcs)), coord.next_seq)\n {\n if start_seq + lcs_len > seq.nb_tokens() {\n break;\n }\n let snake_len = 1 + snake_len(seq, lcs, start_lcs + 1, start_seq + 1);\n let next_coord = Coord {\n next_lcs: start_lcs + snake_len,\n next_seq: start_seq + snake_len,\n };\n if last_enqueued_snake_len < snake_len || next_coord == target {\n if next_coord.next_lcs == target.next_lcs\n && (next_coord.next_seq == target.next_seq || found_seq.is_none())\n {\n found_seq = Some(next_coord.next_seq);\n }\n match prev.entry(next_coord) {\n Occupied(_) => continue,\n Vacant(e) => e.insert(coord),\n };\n new_frontier.push(next_coord);\n last_enqueued_snake_len = snake_len;\n }\n }\n }\n std::mem::swap(&mut frontier, &mut new_frontier)\n }\n\n let target = found_seq.map(|next_seq| Coord {\n next_lcs: lcs.nb_tokens(),\n next_seq,\n });\n let mut path = vec![];\n let mut starts_with_shared = false;\n let mut coord = target.as_ref();\n let mut seq = seq.nb_tokens();\n let mut lcs = lcs.nb_tokens();\n while let Some(&coord_content) = coord {\n let next_seq = coord_content.next_seq;\n let next_lcs = coord_content.next_lcs;\n let snake_len = lcs - next_lcs;\n push_if_not_last(&mut path, to_isize(seq - snake_len));\n starts_with_shared = !push_if_not_last(&mut path, to_isize(next_seq));\n\n coord = prev.get(&coord_content);\n\n seq = next_seq;\n lcs = next_lcs;\n }\n path.reverse();\n NormalizationResult {\n path,\n starts_with_shared,\n }\n}\n```"}], "func_name": "optimize_partition", "docstring": "Minimize the number of elements when partitioning `seq` according to `lcs`.\n`lcs` is a subsequence of `seq`.", "repo": "mookid/diffr", "path": "src/diffr_lib/best_projection.rs", "url": "https://github.com/mookid/diffr/blob/master/src/diffr_lib/best_projection.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "76da50752aff76541ff32526c586f8b7acd7f5bfb1bbc89b1bf777aa56a9fce6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: split_at\n\nDocumentation:\nSplit `self` in two tokenizations:\n* the first one from the start to `lo`;\n* the second one from `hi` to the end.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn split_at(&self, lo: isize, hi: isize) -> (Self, Self) {\n let start = self.start_index;\n let end = self.one_past_end_index;\n assert!(start <= lo);\n assert!(lo <= hi);\n assert!(hi <= end);\n (\n TokenizationRange {\n one_past_end_index: lo,\n ..*self\n },\n TokenizationRange {\n start_index: hi,\n ..*self\n },\n )\n }\n```"}], "func_name": "split_at", "docstring": "Split `self` in two tokenizations:\n* the first one from the start to `lo`;\n* the second one from `hi` to the end.", "repo": "mookid/diffr", "path": "src/diffr_lib/mod.rs", "url": "https://github.com/mookid/diffr/blob/master/src/diffr_lib/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "21828dc48325702f052e9337c22f448829118ed57cddf398f8a40ba51f13cc0d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: diff\n\nDocumentation:\nCompute the longest common subsequence for `input` into `dst`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn diff(input: &DiffInput, v: &mut Vec, dst: &mut Vec) {\n dst.clear();\n enum Task<'a> {\n Diff(DiffInput<'a>),\n PushSnake(Snake),\n }\n use Task::*;\n\n let mut todo = vec![Diff(input.to_owned())];\n while let Some(task) = todo.pop() {\n match task {\n Diff(input) => {\n let n = to_isize(input.n());\n fn trivial_diff(tok: &TokenizationRange) -> bool {\n tok.one_past_end_index <= tok.start_index\n }\n\n if trivial_diff(&input.removed) || trivial_diff(&input.added) {\n continue;\n }\n\n let snake = diff_sequences_bidirectional_snake(&input, v);\n if let Some((snake @ Snake { x0, y0, len }, d)) = snake {\n if 1 < d {\n let (input1, input2) = input.split_at((x0, y0), (x0 + len, y0 + len));\n todo.push(Diff(input2));\n if len != 0 {\n todo.push(PushSnake(snake));\n }\n todo.push(Diff(input1));\n } else {\n let SplittingPoint { sp, dx, dy } = find_splitting_point(&input);\n let x0 = input.removed.start_index;\n let y0 = input.added.start_index;\n if sp != 0 {\n dst.push(Snake::default().from(x0, y0).len(sp));\n }\n let len = n - sp - dx;\n if len != 0 {\n dst.push(Snake::default().from(x0 + sp + dx, y0 + sp + dy).len(len));\n }\n }\n }\n }\n PushSnake(snake) => dst.push(snake),\n }\n }\n}\n```"}], "func_name": "diff", "docstring": "Compute the longest common subsequence for `input` into `dst`.", "repo": "mookid/diffr", "path": "src/diffr_lib/mod.rs", "url": "https://github.com/mookid/diffr/blob/master/src/diffr_lib/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18ef7b7053a1893879f6946c60a60e48516ddb0b2252f1cbab441cdc4aaf1302"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tokenize\n\nDocumentation:\nTokenize data from `src` from the position `ofs` into `tokens`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn tokenize(src: &[u8], ofs: usize, tokens: &mut Vec) {\n let mut push = |lo: usize, hi: usize| {\n if lo < hi {\n tokens.push((lo, hi))\n }\n };\n let mut kind = TokenKind::Other;\n let mut lo = ofs;\n #[allow(clippy::needless_range_loop)]\n for (grapheme_start, _, g) in src[ofs..].grapheme_indices() {\n let hi = grapheme_start + ofs;\n let oldkind = kind;\n kind = classify_grapheme(g);\n if kind != oldkind || oldkind == TokenKind::Other {\n push(lo, hi);\n lo = hi\n }\n }\n push(lo, src.len());\n}\n```"}], "func_name": "tokenize", "docstring": "Tokenize data from `src` from the position `ofs` into `tokens`.", "repo": "mookid/diffr", "path": "src/diffr_lib/mod.rs", "url": "https://github.com/mookid/diffr/blob/master/src/diffr_lib/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f819554f5e85263e97e7d0a71145ba7ada27309dd8771e87fc3d4eb64e7b468c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: main\n\nDocumentation:\nThis example demonstrates using dynamic audio channels. If you need a number of audio channels\nthat is not known at compile time, you can create and use dynamic channels based on string keys.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn main() {\n App::new()\n .add_plugins((DefaultPlugins, AudioPlugin))\n .add_systems(Startup, start_background_audio)\n .add_systems(Update, plop)\n .run();\n}\n```"}], "func_name": "main", "docstring": "This example demonstrates using dynamic audio channels. If you need a number of audio channels\nthat is not known at compile time, you can create and use dynamic channels based on string keys.", "repo": "NiklasEi/bevy_kira_audio", "path": "examples/dynamic_channels.rs", "url": "https://github.com/NiklasEi/bevy_kira_audio/blob/master/examples/dynamic_channels.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "797181d8fb3deb00ba17d9569c40dc116f835ae74d88bea44f52741ddd27b008"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: main\n\nDocumentation:\nThis example shows the different settings that can be applied when playing a sound.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn main() {\n App::new()\n .add_plugins((DefaultPlugins, AudioPlugin))\n .add_systems(Startup, play_audio)\n .run();\n}\n```"}], "func_name": "main", "docstring": "This example shows the different settings that can be applied when playing a sound.", "repo": "NiklasEi/bevy_kira_audio", "path": "examples/settings.rs", "url": "https://github.com/NiklasEi/bevy_kira_audio/blob/master/examples/settings.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8ab349cfe9a0cf45bb548019676cff0d243ad06f883b82a75e4b57522f5c3cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: play_audio\n\nDocumentation:\nSettings applied when playing a sound will overwrite the channel settings (like volume and panning)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn play_audio(asset_server: Res, audio: Res

(name: P) -> Result\n where\n P: AsRef + Display,\n {\n var_os(\"PATH\")\n .and_then(|paths| {\n split_paths(&paths)\n .filter_map(|dir| {\n let full_path = dir.join(&name);\n if full_path.is_file() {\n Some(full_path)\n } else {\n None\n }\n })\n .next()\n })\n .with_context(|| format!(\"Unable to find executable '{}' in $PATH\", name))\n }\n```"}], "func_name": "find_executable", "docstring": "Find an executable inside the current $PATH environment", "repo": "saschagrunert/kubernix", "path": "src/system.rs", "url": "https://github.com/saschagrunert/kubernix/blob/master/src/system.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "01414fd398f8f7a7dc993d6b6efb44ee07a796ff3893c1fdfcc55adbb49f53d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shell\n\nDocumentation:\nReturn the full path to the default system shell\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn shell() -> Result {\n let shell = var(\"SHELL\").unwrap_or_else(|_| \"sh\".into());\n Ok(format!(\n \"{}\",\n Self::find_executable(&shell)\n .with_context(|| format!(\"Unable to find system shell '{}'\", shell))?\n .display()\n ))\n }\n```"}], "func_name": "shell", "docstring": "Return the full path to the default system shell", "repo": "saschagrunert/kubernix", "path": "src/system.rs", "url": "https://github.com/saschagrunert/kubernix/blob/master/src/system.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc6c882eb00e3ef0f81fa9c5a3c8a898c90197239843fd3787071e390e85d76f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: modprobe\n\nDocumentation:\nLoad a single kernel module via 'modprobe'\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn modprobe(module: &str) -> Result<()> {\n debug!(\"Loading kernel module '{}'\", module);\n let output = Command::new(\"modprobe\").arg(module).output()?;\n if !output.status.success() {\n bail!(\n \"Unable to load '{}' kernel module: {}\",\n module,\n String::from_utf8(output.stderr)?,\n );\n }\n Ok(())\n }\n```"}], "func_name": "modprobe", "docstring": "Load a single kernel module via 'modprobe'", "repo": "saschagrunert/kubernix", "path": "src/system.rs", "url": "https://github.com/saschagrunert/kubernix/blob/master/src/system.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3966614e946cac2785c33027d89e37c12d7db29e446c7d827e7b6de13474d27d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sysctl_enable\n\nDocumentation:\nEnable a single sysctl by setting it to '1'\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn sysctl_enable(key: &str) -> Result<()> {\n debug!(\"Enabling sysctl '{}'\", key);\n let enable_arg = format!(\"{}=1\", key);\n let output = Command::new(\"sysctl\").arg(\"-w\").arg(&enable_arg).output()?;\n let stderr = String::from_utf8(output.stderr)?;\n if !stderr.is_empty() {\n bail!(\"Unable to set sysctl '{}': {}\", enable_arg, stderr);\n }\n Ok(())\n }\n```"}], "func_name": "sysctl_enable", "docstring": "Enable a single sysctl by setting it to '1'", "repo": "saschagrunert/kubernix", "path": "src/system.rs", "url": "https://github.com/saschagrunert/kubernix/blob/master/src/system.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2fd45d1baf9da83387242f6f720d35c747dacecc1643d6b8bbc4d1cf2b2fd24c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open_image\n\nDocumentation:\nOpen an image from disk and send it somewhere\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn open_image(\n img_location: &Path,\n message_sender: Option>,\n) -> Result> {\n let (sender, receiver): (Sender, Receiver) = channel();\n let img_location = (*img_location).to_owned();\n\n use file_format::FileFormat;\n\n let mut extension = img_location\n .extension()\n .unwrap_or_default()\n .to_str()\n .unwrap_or_default()\n .to_lowercase()\n // add aliased extensions here if the same formats have multiple extensions\n .replace(\"tiff\", \"tif\")\n .replace(\"jpeg\", \"jpg\")\n .replace(\"jpeg\", \"jpg\")\n .replace(\"ima\", \"dcm\")\n .replace(\"heic\", \"heif\")\n .replace(\"hif\", \"heic\");\n\n // These are detected incorrectly, for example svg is xml etc\n let unchecked_extensions = [\"svg\", \"kra\", \"tga\", \"dng\"];\n\n if let Ok(fmt) = FileFormat::from_file(&img_location) {\n debug!(\"Detected as {:?} {}\", fmt.name(), fmt.extension());\n if fmt\n .extension()\n .replace(\"tiff\", \"tif\")\n .replace(\"apng\", \"png\")\n != extension\n {\n if unchecked_extensions.contains(&extension.as_str()) {\n info!(\"Extension {extension} skipped check.\")\n } else {\n message_sender.map(|s| {\n s.send(Message::Warning(format!(\n \"Extension mismatch. This image is loaded as {}\",\n fmt.extension()\n )))\n });\n extension = fmt.extension().into()\n }\n }\n } else {\n error!(\"Can't determine image type\")\n }\n\n debug!(\"matching '{extension}'\");\n\n match extension.as_str() {\n \"dds\" => {\n let file = File::open(img_location)?;\n let mut reader = BufReader::new(file);\n let dds = DDS::decode(&mut reader).map_err(|e| anyhow!(\"{:?}\", e))?;\n if let Some(main_layer) = dds.layers.get(0) {\n let buf = main_layer.as_bytes();\n let buf =\n image::ImageBuffer::from_raw(dds.header.width, dds.header.height, buf.into())\n .context(\"Can't create DDS ImageBuffer with given res\")?;\n let d = DynamicImage::ImageRgba8(buf);\n _ = sender.send(Frame::new_still(d));\n return Ok(receiver);\n }\n }\n \"dcm\" | \"ima\" => {\n use dicom_pixeldata::PixelDecoder;\n let obj = dicom_object::open_file(img_location)?;\n let image = obj.decode_pixel_data()?;\n let dynamic_image = image.to_dynamic_image(0)?;\n _ = sender.send(Frame::new_still(dynamic_image));\n }\n \"ktx2\" => {\n // let file = File::open(img_location)?;\n let data = std::fs::read(img_location)?;\n\n let ktx = ktx2_loader::ktx2_buffer_to_image(\n data.as_bytes(),\n CompressedImageFormats::all(),\n true,\n )\n .map_err(|e| anyhow!(\"{:?}\", e))?;\n let d = ktx.try_into_dynamic().map_err(|e| anyhow!(\"{:?}\", e))?;\n _ = sender.send(Frame::new_still(d));\n return Ok(receiver);\n }\n #[cfg(feature = \"dav1d\")]\n \"avif\" | \"avifs\" => {\n use std::io::Read;\n let mut file = File::open(img_location)?;\n let mut buf = vec![];\n file.read_to_end(&mut buf)?;\n let i = libavif_image::read(buf.as_slice())?;\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n\n // col.add_still(i.to_rgba8());\n }\n #[cfg(feature = \"j2k\")]\n \"jp2\" => {\n let jp2_image = jpeg2k::Image::from_file(img_location)?;\n\n match jp2_image.get_pixels(Some(255))?.data {\n jpeg2k::ImagePixelData::L8(_) => bail!(\"jpeg2k L8 unsupported\"),\n jpeg2k::ImagePixelData::La8(_) => bail!(\"jpeg2k La8 unsupported\"),\n jpeg2k::ImagePixelData::Rgb8(data) => {\n let image_buffer =\n RgbImage::from_raw(jp2_image.width(), jp2_image.height(), data)\n .context(\"Can't decode jp2k buffer\")?;\n _ = sender.send(Frame::new_still(DynamicImage::ImageRgb8(image_buffer)));\n return Ok(receiver);\n }\n jpeg2k::ImagePixelData::Rgba8(data) => {\n let image_buffer =\n RgbaImage::from_raw(jp2_image.width(), jp2_image.height(), data)\n .context(\"Can't decode jp2k buffer\")?;\n let i = DynamicImage::ImageRgba8(image_buffer);\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n }\n jpeg2k::ImagePixelData::L16(_) => bail!(\"jpeg2k L16 unsupported\"),\n jpeg2k::ImagePixelData::La16(_) => bail!(\"jpeg2k La16 unsupported\"),\n jpeg2k::ImagePixelData::Rgb16(_) => bail!(\"jpeg2k Rgb16 unsupported\"),\n jpeg2k::ImagePixelData::Rgba16(_) => bail!(\"jpeg2k Rgba16 unsupported\"),\n }\n }\n #[cfg(feature = \"heif\")]\n \"heif\" | \"heic\" => {\n // Built on work in https://github.com/rsuu/rmg - thanks!\n use libheif_rs::{ColorSpace, HeifContext, LibHeif, RgbChroma};\n\n let lib_heif = LibHeif::new();\n let mut ctx = HeifContext::read_from_file(&img_location.to_string_lossy().to_string())?;\n if let Ok(num_threads) = std::thread::available_parallelism() {\n ctx.set_max_decoding_threads(num_threads.get() as u32);\n }\n let handle = ctx.primary_image_handle()?;\n let img = lib_heif.decode(&handle, ColorSpace::Rgb(RgbChroma::Rgba), None)?;\n let planes = img.planes();\n let interleaved = planes\n .interleaved\n .context(\"Can't create interleaved plane\")?;\n\n let data = interleaved.data;\n let width = interleaved.width;\n let height = interleaved.height;\n let stride = interleaved.stride;\n\n let mut res: Vec = Vec::new();\n for y in 0..height {\n let mut step = y as usize * stride;\n\n for _ in 0..width {\n res.extend_from_slice(&[\n data[step],\n data[step + 1],\n data[step + 2],\n data[step + 3],\n ]);\n step += 4;\n }\n }\n let buf = image::ImageBuffer::from_vec(width as u32, height as u32, res)\n .context(\"Can't create HEIC/HEIF ImageBuffer with given res\")?;\n let i = DynamicImage::ImageRgba8(buf);\n\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n }\n #[cfg(feature = \"avif_native\")]\n #[cfg(not(feature = \"dav1d\"))]\n \"avif\" => {\n let mut file = File::open(img_location)?;\n let avif = avif_decode::Decoder::from_reader(&mut file)?.to_image()?;\n match avif {\n avif_decode::Image::Rgb8(img) => {\n let mut img_buffer = vec![];\n let (buf, width, height) = img.into_contiguous_buf();\n for b in buf {\n img_buffer.push(b.r);\n img_buffer.push(b.g);\n img_buffer.push(b.b);\n img_buffer.push(255);\n }\n let buf = image::ImageBuffer::from_vec(width as u32, height as u32, img_buffer)\n .context(\"Can't create avif ImageBuffer with given res\")?;\n let i = DynamicImage::ImageRgba8(buf);\n\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n }\n avif_decode::Image::Rgba8(img) => {\n let mut img_buffer = vec![];\n let (buf, width, height) = img.into_contiguous_buf();\n for b in buf {\n img_buffer.push(b.r);\n img_buffer.push(b.g);\n img_buffer.push(b.b);\n img_buffer.push(b.a);\n }\n let buf = image::ImageBuffer::from_vec(width as u32, height as u32, img_buffer)\n .context(\"Can't create avif ImageBuffer with given res\")?;\n let i = DynamicImage::ImageRgba8(buf);\n\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n }\n avif_decode::Image::Rgb16(img) => {\n let mut img_buffer = vec![];\n let (buf, width, height) = img.into_contiguous_buf();\n for b in buf {\n img_buffer.push(u16_to_u8(b.r));\n img_buffer.push(u16_to_u8(b.g));\n img_buffer.push(u16_to_u8(b.b));\n img_buffer.push(255);\n }\n let buf = image::ImageBuffer::from_vec(width as u32, height as u32, img_buffer)\n .context(\"Can't create avif ImageBuffer with given res\")?;\n let i = DynamicImage::ImageRgba8(buf);\n\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n }\n avif_decode::Image::Rgba16(_) => {\n anyhow::bail!(\"This avif is not yet supported (Rgba16).\")\n }\n avif_decode::Image::Gray8(_) => {\n anyhow::bail!(\"This avif is not yet supported (Gray8).\")\n }\n avif_decode::Image::Gray16(_) => {\n anyhow::bail!(\"This avif is not yet supported (Gray16).\")\n }\n }\n }\n \"svg\" => {\n // TODO: Should the svg be scaled? if so by what number?\n // This should be specified in a smarter way, maybe resolution * x?\n\n let render_scale = 2.;\n let mut opt = usvg::Options::default();\n\n let fontdb = opt.fontdb_mut();\n fontdb.load_system_fonts();\n fontdb.load_font_data(FONT.to_vec());\n fontdb.set_cursive_family(\"Inter\");\n fontdb.set_sans_serif_family(\"Inter\");\n fontdb.set_serif_family(\"Inter\");\n\n opt.font_family = \"Inter\".into();\n opt.font_size = 6.;\n\n let svg_data = std::fs::read(img_location)?;\n if let Ok(tree) = usvg::Tree::from_data(&svg_data, &opt) {\n let pixmap_size = tree\n .size()\n .to_int_size()\n .scale_by(render_scale)\n .context(\"Can't get SVG size\")?;\n\n if let Some(mut pixmap) =\n tiny_skia::Pixmap::new(pixmap_size.width(), pixmap_size.height())\n {\n let mut fontdb = usvg::fontdb::Database::new();\n fontdb.load_system_fonts();\n fontdb.load_font_data(FONT.to_vec());\n fontdb.set_cursive_family(\"Inter\");\n fontdb.set_sans_serif_family(\"Inter\");\n fontdb.set_serif_family(\"Inter\");\n\n let render_ts = tiny_skia::Transform::from_scale(render_scale, render_scale);\n resvg::render(&tree, render_ts, &mut pixmap.as_mut());\n let buf: RgbaImage = image::ImageBuffer::from_raw(\n pixmap_size.width(),\n pixmap_size.height(),\n pixmap.data().to_vec(),\n )\n .context(\"Can't create image buffer from SVG render\")?;\n let i = DynamicImage::ImageRgba8(buf);\n\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n }\n }\n }\n \"exr\" => {\n let reader = exrs::read()\n .no_deep_data()\n .largest_resolution_level()\n .rgba_channels(\n |resolution, _channels: &RgbaChannels| -> RgbaImage {\n image::ImageBuffer::new(\n resolution.width() as u32,\n resolution.height() as u32,\n )\n },\n // set each pixel in the png buffer from the exr file\n |png_pixels, position, (r, g, b, a): (f32, f32, f32, f32)| {\n png_pixels.put_pixel(\n position.x() as u32,\n position.y() as u32,\n // exr's tonemap:\n // image::Rgba([tone_map(r), tone_map(g), tone_map(b), (a * 255.0) as u8]),\n image::Rgba(tonemap_rgba([r, g, b, a])),\n );\n },\n )\n .first_valid_layer()\n .all_attributes();\n\n // an image that contains a single layer containing an png rgba buffer\n let maybe_image: Result<\n Image>>,\n exrs::Error,\n > = reader.from_file(&img_location);\n match maybe_image {\n Ok(image) => {\n let buf = image.layer_data.channel_data.pixels;\n let i = DynamicImage::ImageRgba8(buf);\n\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n }\n Err(e) => {\n let layer = exrs::read_first_flat_layer_from_file(&img_location)?;\n\n let size = layer.layer_data.size;\n for i in layer.layer_data.channel_data.list {\n let d = i.sample_data;\n match d {\n FlatSamples::F16(_) => bail!(\"F16 color mode not supported\"),\n FlatSamples::F32(f) => {\n let Some(gray_image) = GrayImage::from_raw(\n size.width() as u32,\n size.height() as u32,\n f.par_iter().map(|x| tonemap_f32(*x)).collect::>(),\n ) else {\n error!(\"Can't decode gray alpha buffer\");\n continue;\n };\n\n let d = DynamicImage::ImageLuma8(gray_image);\n _ = sender.send(Frame::new_still(d));\n return Ok(receiver);\n }\n FlatSamples::U32(_) => bail!(\"U32 color mode not supported\"),\n }\n }\n\n bail!(\"{} from {:?}\", e, img_location)\n }\n }\n }\n \"nef\" | \"cr2\" | \"dng\" | \"mos\" | \"erf\" | \"raf\" | \"arw\" | \"3fr\" | \"ari\" | \"srf\" | \"sr2\"\n | \"braw\" | \"r3d\" | \"nrw\" | \"raw\" => {\n debug!(\"Loading RAW\");\n let buf = load_raw(&img_location)?;\n let i = DynamicImage::ImageRgba8(buf);\n\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n }\n \"jxl\" => {\n std::thread::spawn(move || {\n if let Err(e) = load_jxl(&img_location, sender) {\n error!(\"{e}\");\n }\n });\n return Ok(receiver);\n }\n \"hdr\" => {\n let f = File::open(img_location)?;\n let reader = BufReader::new(f);\n let hdr_decoder = image::codecs::hdr::HdrDecoder::new(reader)?;\n let meta = hdr_decoder.metadata();\n\n #[cfg(feature = \"hdr\")]\n {\n let d = DynamicImage::from_decoder(hdr_decoder)?;\n _ = sender.send(Frame::new_still(d));\n return Ok(receiver);\n }\n\n #[cfg(not(feature = \"hdr\"))]\n {\n let hdr_img: Rgb32FImage = match DynamicImage::from_decoder(hdr_decoder)? {\n DynamicImage::ImageRgb32F(image) => image,\n _ => bail!(\"expected rgb32f image\"),\n };\n let buf = RgbaImage::from_fn(meta.width, meta.height, |x, y| {\n let pixel = hdr_img.get_pixel(x, y);\n image::Rgba(tonemap_rgb(pixel.0))\n });\n let i = DynamicImage::ImageRgba8(buf);\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n }\n }\n \"psd\" => {\n let contents = std::fs::read(img_location)?;\n let psd = Psd::from_bytes(&contents).map_err(|e| anyhow!(\"{:?}\", e))?;\n let buf = image::ImageBuffer::from_raw(psd.width(), psd.height(), psd.rgba())\n .context(\"Can't create imagebuffer from PSD\")?;\n let i = DynamicImage::ImageRgba8(buf);\n\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n }\n \"webp\" => {\n debug!(\"Loading WebP\");\n let contents = std::fs::read(&img_location)?;\n let decoder = image::codecs::webp::WebPDecoder::new(std::io::Cursor::new(&contents))?;\n if !decoder.has_animation() {\n //force this to webp\n let img = image::ImageReader::with_format(\n std::io::Cursor::new(contents),\n image::ImageFormat::WebP,\n )\n .decode()?;\n _ = sender.send(Frame::new_still(img));\n return Ok(receiver);\n }\n\n let buffer = std::fs::read(img_location)?;\n let mut decoder = Decoder::new(&buffer)?.into_iter();\n let mut last_timestamp = 0;\n\n loop {\n if let Some(frame) = decoder.next() {\n let buf = image::ImageBuffer::from_raw(\n frame.dimensions().0,\n frame.dimensions().1,\n frame.data().to_vec(),\n )\n .context(\"Can't create imagebuffer from webp\")?;\n let t = frame.timestamp();\n let delay = t - last_timestamp;\n debug!(\"time {t} {delay}\");\n last_timestamp = t;\n let i = DynamicImage::ImageRgba8(buf);\n let frame = Frame::new_animation(i, delay as u16);\n _ = sender.send(frame);\n } else {\n break;\n }\n }\n\n // TODO: Use thread for animation and return receiver immediately, but this needs error handling\n return Ok(receiver);\n }\n \"png\" | \"apng\" => {\n use zune_png::zune_core::bytestream::ZCursor;\n use zune_png::zune_core::options::EncoderOptions;\n use zune_png::PngDecoder;\n\n let contents = std::fs::read(&img_location)?;\n let mut decoder = PngDecoder::new(ZCursor::new(contents));\n decoder.set_options(\n DecoderOptions::new_fast()\n .set_max_height(128000)\n .set_max_width(128000),\n );\n\n //animation\n decoder.decode_headers()?;\n if decoder.is_animated() {\n info!(\"Image is animated\");\n decoder.decode_headers()?;\n\n let colorspace = decoder.colorspace().context(\"Can't get color space\")?;\n let depth = decoder.depth().context(\"Can't get decoder depth\")?;\n // get decoder information,we clone this because we need a standalone\n // info since we mutably modify decoder struct below\n let info = decoder.info().context(\"Can't get decoder info\")?.clone();\n // set up our background variable. Soon it will contain the data for the previous\n // frame, the first frame has no background hence why this is None\n let mut background: Option> = None;\n // the output, since we know that no frame will be bigger than the width and height, we can\n // set this up outside of the loop.\n let mut output = vec![\n 0;\n info.width\n * info.height\n * decoder\n .colorspace()\n .context(\"Can't get decoder color depth\")?\n .num_components()\n ];\n\n while decoder.more_frames() {\n // decode the header, in case we haven't processed a frame header\n decoder.decode_headers()?;\n // then decode the current frame information,\n // NB: Frame information is for current frame hence should be accessed before decoding the frame\n // as it will change on subsequent frames\n let frame = decoder.frame_info().context(\"Can't get frame info\")?;\n debug!(\"Frame: {:?}\", frame);\n\n // decode the raw pixels, even on smaller frames, we only allocate frame_info.width*frame_info.height\n let pix = decoder.decode_raw()?;\n // call post process\n zune_png::post_process_image(\n &info,\n colorspace,\n &frame,\n &pix,\n background.as_ref().map(|x| x.as_slice()),\n &mut output,\n None,\n )?;\n // create encoder parameters\n let encoder_opts =\n EncoderOptions::new(info.width, info.height, colorspace, depth);\n\n let mut out = vec![];\n _ = zune_png::PngEncoder::new(&output, encoder_opts).encode(&mut out);\n let img = image::load_from_memory(&out)?;\n\n let delay = frame.delay_num as f32 / frame.delay_denom as f32 * 1000.;\n\n _ = sender.send(Frame::new_animation(img, delay as u16));\n background = Some(output.clone());\n }\n return Ok(receiver);\n }\n\n debug!(\"Image is not animated\");\n match decoder.decode().map_err(|e| anyhow!(\"{:?}\", e))? {\n // 16 bpp data\n DecodingResult::U16(imgdata) => {\n //convert to 8bpp\n let imgdata_8bpp = imgdata\n .par_iter()\n .map(|x| *x as f32 / u16::MAX as f32)\n .map(|p| p.powf(2.2))\n .map(|p| tonemap_f32(p))\n // .map(|x| x as u8)\n .collect::>();\n\n let (width, height) =\n decoder.dimensions().context(\"Can't get png dimensions\")?;\n let colorspace = decoder.colorspace().context(\"Can't get colorspace\")?;\n\n if colorspace.is_grayscale() {\n let buf: GrayImage =\n image::ImageBuffer::from_raw(width as u32, height as u32, imgdata_8bpp)\n .context(\"Can't interpret image as grayscale\")?;\n let image_result = DynamicImage::ImageLuma8(buf);\n _ = sender.send(Frame::new_still(image_result));\n return Ok(receiver);\n }\n\n if colorspace.has_alpha() {\n let float_image =\n RgbaImage::from_raw(width as u32, height as u32, imgdata_8bpp)\n .context(\"Can't decode rgba buffer\")?;\n _ = sender.send(Frame::new_still(DynamicImage::ImageRgba8(float_image)));\n return Ok(receiver);\n } else {\n let float_image =\n RgbImage::from_raw(width as u32, height as u32, imgdata_8bpp)\n .context(\"Can't decode rgba buffer\")?;\n _ = sender.send(Frame::new_still(DynamicImage::ImageRgb8(float_image)));\n return Ok(receiver);\n }\n }\n // 8bpp\n DecodingResult::U8(value) => {\n let (width, height) =\n decoder.dimensions().context(\"Can't get png dimensions\")?;\n\n let colorspace = decoder.colorspace().context(\"Can't get colorspace\")?;\n if colorspace.is_grayscale() && !colorspace.has_alpha() {\n let buf: GrayImage =\n image::ImageBuffer::from_raw(width as u32, height as u32, value)\n .context(\"Can't interpret image as grayscale\")?;\n let image_result = DynamicImage::ImageLuma8(buf);\n _ = sender.send(Frame::new_still(image_result));\n return Ok(receiver);\n }\n\n if colorspace.is_grayscale() && colorspace.has_alpha() {\n let buf: GrayAlphaImage =\n image::ImageBuffer::from_raw(width as u32, height as u32, value)\n .context(\"Can't interpret image as grayscale\")?;\n let image_result = DynamicImage::ImageLumaA8(buf);\n _ = sender.send(Frame::new_still(image_result));\n return Ok(receiver);\n }\n\n if colorspace.has_alpha() && !colorspace.is_grayscale() {\n let buf: RgbaImage =\n image::ImageBuffer::from_raw(width as u32, height as u32, value)\n .context(\"Can't interpret image as rgba\")?;\n let i = DynamicImage::ImageRgba8(buf);\n\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n } else {\n let buf: RgbImage =\n image::ImageBuffer::from_raw(width as u32, height as u32, value)\n .context(\"Can't interpret image as rgb\")?;\n let image_result = DynamicImage::ImageRgb8(buf);\n _ = sender.send(Frame::new_still(image_result));\n return Ok(receiver);\n }\n }\n _ => {}\n }\n }\n \"gif\" => {\n let file = File::open(img_location)?;\n\n // Below is a workaround for partially corrupt gifs.\n let mut gif_opts = gif::DecodeOptions::new();\n gif_opts.set_color_output(gif::ColorOutput::Indexed);\n let mut decoder = gif_opts.read_info(file)?;\n let dim = (decoder.width() as u32, decoder.height() as u32);\n let mut screen = gif_dispose::Screen::new_decoder(&decoder);\n loop {\n if let Ok(i) = decoder.read_next_frame() {\n debug!(\"decoded frame\");\n if let Some(frame) = i {\n screen.blit_frame(&frame)?;\n let buf: Option = image::ImageBuffer::from_raw(\n dim.0,\n dim.1,\n screen.pixels_rgba().buf().as_bytes().to_vec(),\n );\n let buf = buf.context(\"Can't read gif frame\")?;\n let i = DynamicImage::ImageRgba8(buf);\n _ = sender.send(Frame::new_animation(i, frame.delay * 10));\n } else {\n break;\n }\n } else {\n break;\n }\n }\n debug!(\"Done decoding Gif!\");\n\n return Ok(receiver);\n\n // TODO: Re-enable if https://github.com/image-rs/image/issues/1818 is resolved\n\n // let gif_decoder = GifDecoder::new(file)?;\n // let frames = gif_decoder.into_frames().collect_frames()?;\n // for f in frames {\n // let delay = f.delay().numer_denom_ms().0 as u16;\n // col.add_anim_frame(f.into_buffer(), delay);\n // col.repeat = true;\n // }\n }\n #[cfg(feature = \"turbo\")]\n \"jpg\" | \"jpeg\" => {\n match load_jpeg_turbojpeg(&img_location) {\n Ok(i) => {\n _ = sender.send(Frame::new_still(i));\n }\n Err(e) => {\n error!(\n \"Could not load using turbojpeg: {e}. Trying to load with image library.\"\n );\n let img = image::open(img_location)?;\n _ = sender.send(Frame::new_still(img));\n }\n }\n return Ok(receiver);\n }\n \"kra\" => {\n let i = load_kra(&img_location)?;\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n }\n \"icns\" => {\n let file = BufReader::new(File::open(&img_location)?);\n let icon_family = icns::IconFamily::read(file)?;\n\n // loop over the largest icons, take the largest one and return\n for icon_type in [\n icns::IconType::RGBA32_512x512_2x,\n icns::IconType::RGBA32_512x512,\n icns::IconType::RGBA32_256x256,\n icns::IconType::RGBA32_128x128,\n ] {\n let mut target = vec![];\n let Ok(image) = icon_family.get_icon_with_type(icon_type) else {\n continue;\n };\n image.write_png(&mut target)?;\n let d = image::load_from_memory(&target).context(\"Load icns mem\")?;\n _ = sender.send(Frame::new_still(d));\n return Ok(receiver);\n }\n\n bail!(\"No valid icons in {}\", img_location.display());\n }\n \"tif\" | \"tiff\" => match load_tiff(&img_location) {\n Ok(buf) => {\n _ = sender.send(Frame::new_still(buf));\n return Ok(receiver);\n }\n Err(tiff_error) => match load_raw(&img_location) {\n Ok(buf) => {\n let i = DynamicImage::ImageRgba8(buf);\n\n info!(\"This image is a raw image with tiff format.\");\n _ = sender.send(Frame::new_still(i));\n return Ok(receiver);\n }\n Err(raw_error) => {\n bail!(\"Could not load tiff: {tiff_error}, tried as raw and still got error: {raw_error}\")\n }\n },\n },\n _ => {\n // All other supported image files are handled by using `image`\n debug!(\"Loading using generic image library\");\n let img = image::open(img_location)?;\n // col.add_still(img.to_rgba8());\n _ = sender.send(Frame::new_still(img));\n return Ok(receiver);\n }\n }\n\n Ok(receiver)\n}\n```"}], "func_name": "open_image", "docstring": "Open an image from disk and send it somewhere", "repo": "woelper/oculante", "path": "src/image_loader.rs", "url": "https://github.com/woelper/oculante/blob/master/src/image_loader.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bd08cd9dd35fded1441a1d3b42613a284c46ee2aed85d4d9cdc2346612854d3c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: find_first_image_in_directory\n\nDocumentation:\nFind first valid image from the directory\nAssumes the given path is a directory and not a file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn find_first_image_in_directory(folder_path: &Path) -> Result {\n if !folder_path.is_dir() {\n bail!(\"This is not a folder\");\n };\n get_image_filenames_for_directory(folder_path).map(|x| {\n x.first()\n .cloned()\n .context(\"Folder does not have any supported images in it\")\n })?\n}\n```"}], "func_name": "find_first_image_in_directory", "docstring": "Find first valid image from the directory\nAssumes the given path is a directory and not a file", "repo": "woelper/oculante", "path": "src/scrubber.rs", "url": "https://github.com/woelper/oculante/blob/master/src/scrubber.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1fa7ad618843d7ed60394425be4c8b59c61fb5c8792e718ead1adff74da1d0c3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_advanced\n\nDocumentation:\nThe main loading function of the player\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load_advanced(&mut self, img_location: &Path, forced_frame_source: Option) {\n debug!(\"Stopping player on load\");\n self.stop();\n let (stop_sender, stop_receiver): (Sender<()>, Receiver<()>) = mpsc::channel();\n self.stop_sender = stop_sender;\n\n if let Some(cached_image) = self.cache.get(img_location) {\n debug!(\"Cache hit for {}\", img_location.display());\n\n let frame = Frame::new_still(cached_image);\n if let Some(fs) = forced_frame_source {\n debug!(\"Frame source set to {fs}\");\n _ = self.image_sender.send(frame.transmute(fs));\n } else {\n _ = self.image_sender.send(frame);\n }\n return;\n }\n\n debug!(\"Image not in cache.\");\n\n send_image_threaded(\n img_location,\n self.image_sender.clone(),\n self.message_sender.clone(),\n stop_receiver,\n forced_frame_source,\n );\n\n if let Ok(meta) = std::fs::metadata(img_location) {\n if let Ok(modified) = meta.modified() {\n self.watcher.insert(img_location.into(), modified);\n }\n }\n }\n```"}], "func_name": "load_advanced", "docstring": "The main loading function of the player", "repo": "woelper/oculante", "path": "src/utils.rs", "url": "https://github.com/woelper/oculante/blob/master/src/utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "efe87f944e1aa1616ea1d04947cac8710fe57f1a653b77b30b93319c5b0b3d5d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_image\n\nDocumentation:\nReturn the image buffor of a `Frame`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_image(&self) -> Option {\n match self {\n Frame::AnimationStart(img)\n | Frame::Still(img)\n | Frame::EditResult(img)\n | Frame::CompareResult(img, _)\n | Frame::Animation(img, _)\n | Frame::ImageCollectionMember(img) => Some(img.clone()),\n _ => None,\n }\n }\n```"}], "func_name": "get_image", "docstring": "Return the image buffor of a `Frame`.", "repo": "woelper/oculante", "path": "src/utils.rs", "url": "https://github.com/woelper/oculante/blob/master/src/utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "703fb3c4201a0ebb7b94d6669d1f9fe1cd6089d9d507fdae860cbd20d8431b22"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_ext_compatible\n\nDocumentation:\nDetermine if an enxtension is compatible with oculante\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_ext_compatible(fname: &Path) -> bool {\n SUPPORTED_EXTENSIONS.contains(\n &fname\n .extension()\n .unwrap_or_default()\n .to_str()\n .unwrap_or_default()\n .to_lowercase()\n .as_str(),\n )\n}\n```"}], "func_name": "is_ext_compatible", "docstring": "Determine if an enxtension is compatible with oculante", "repo": "woelper/oculante", "path": "src/utils.rs", "url": "https://github.com/woelper/oculante/blob/master/src/utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54f3e44ffd311dcdce5e3727a462a5928e6add9484a2c1544addae86395d659e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: highlight_bleed\n\nDocumentation:\nMark pixels with no alpha but color info\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn highlight_bleed(img: &DynamicImage) -> DynamicImage {\n let mut updated_img = img.to_rgba8();\n updated_img.par_chunks_mut(4).for_each(|pixel| {\n if pixel[3] == 0 && (pixel[0] != 0 || pixel[1] != 0 || pixel[2] != 0) {\n pixel[1] = pixel[1].saturating_add(100);\n pixel[3] = 255;\n }\n });\n DynamicImage::ImageRgba8(updated_img)\n}\n```"}], "func_name": "highlight_bleed", "docstring": "Mark pixels with no alpha but color info", "repo": "woelper/oculante", "path": "src/utils.rs", "url": "https://github.com/woelper/oculante/blob/master/src/utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93affa45967a666df1d16965f3b67d3d0dfba21fb56f7c90500563568a9c6194"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fix_exif\n\nDocumentation:\nFix missing exif by re-applying exif to saved files\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fix_exif(p: &Path, exif: Option) -> Result<()> {\n use std::fs::{self, File};\n let input = fs::read(p)?;\n let mut dynimage = DynImage::from_bytes(input.into())?.context(\"Unsupported EXIF format\")?;\n dynimage.set_exif(exif);\n let output = File::create(p)?;\n dynimage.encoder().write_to(output)?;\n Ok(())\n}\n```"}], "func_name": "fix_exif", "docstring": "Fix missing exif by re-applying exif to saved files", "repo": "woelper/oculante", "path": "src/utils.rs", "url": "https://github.com/woelper/oculante/blob/master/src/utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d484ed3277f22c77881ce4e75034841a4ba26b97e224ead1cbb06e85e65ec9b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new image from raw binary data and the corresponding metadata.\n\n# Panics\nPanics if the length of the `data`, volume of the `size` and the size of the `format`\ndo not match.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n size: Extent3d,\n dimension: TextureDimension,\n data: Vec,\n format: TextureFormat,\n ) -> Self {\n debug_assert_eq!(\n size.volume() * format.pixel_size(),\n data.len(),\n \"Pixel data, size and format have to match\",\n );\n let mut image = Self {\n data,\n ..Default::default()\n };\n image.texture_descriptor.dimension = dimension;\n image.texture_descriptor.size = size;\n image.texture_descriptor.format = format;\n image\n }\n```"}], "func_name": "new", "docstring": "Creates a new image from raw binary data and the corresponding metadata.\n\n# Panics\nPanics if the length of the `data`, volume of the `size` and the size of the `format`\ndo not match.", "repo": "woelper/oculante", "path": "src/ktx2_loader/image.rs", "url": "https://github.com/woelper/oculante/blob/master/src/ktx2_loader/image.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "61e9453bde63f6f12f1a9235498a3544afb4f5bf92267e0c4b13d3c0469aad1b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_fill\n\nDocumentation:\nCreates a new image from raw binary data and the corresponding metadata, by filling\nthe image data with the `pixel` data repeated multiple times.\n\n# Panics\nPanics if the size of the `format` is not a multiple of the length of the `pixel` data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_fill(\n size: Extent3d,\n dimension: TextureDimension,\n pixel: &[u8],\n format: TextureFormat,\n ) -> Self {\n let mut value = Image::default();\n value.texture_descriptor.format = format;\n value.texture_descriptor.dimension = dimension;\n value.resize(size);\n\n debug_assert_eq!(\n pixel.len() % format.pixel_size(),\n 0,\n \"Must not have incomplete pixel data.\"\n );\n debug_assert!(\n pixel.len() <= value.data.len(),\n \"Fill data must fit within pixel buffer.\"\n );\n\n for current_pixel in value.data.chunks_exact_mut(pixel.len()) {\n current_pixel.copy_from_slice(pixel);\n }\n value\n }\n```"}], "func_name": "new_fill", "docstring": "Creates a new image from raw binary data and the corresponding metadata, by filling\nthe image data with the `pixel` data repeated multiple times.\n\n# Panics\nPanics if the size of the `format` is not a multiple of the length of the `pixel` data.", "repo": "woelper/oculante", "path": "src/ktx2_loader/image.rs", "url": "https://github.com/woelper/oculante/blob/master/src/ktx2_loader/image.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e88eadd1904d8fdd939c6bee3649f95c5f17c5912e18fac5add9101a182209e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resize\n\nDocumentation:\nResizes the image to the new size, by removing information or appending 0 to the `data`.\nDoes not properly resize the contents of the image, but only its internal `data` buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn resize(&mut self, size: Extent3d) {\n self.texture_descriptor.size = size;\n self.data.resize(\n size.volume() * self.texture_descriptor.format.pixel_size(),\n 0,\n );\n }\n```"}], "func_name": "resize", "docstring": "Resizes the image to the new size, by removing information or appending 0 to the `data`.\nDoes not properly resize the contents of the image, but only its internal `data` buffer.", "repo": "woelper/oculante", "path": "src/ktx2_loader/image.rs", "url": "https://github.com/woelper/oculante/blob/master/src/ktx2_loader/image.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0378ac2a107abda24d68a4b73b2cc501a485984688760296a55ca381dd0dab4a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_buffer\n\nDocumentation:\nLoad a bytes buffer in a [`Image`], according to type `image_type`, using the `image`\ncrate\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_buffer(\n buffer: &[u8],\n image_type: ImageType,\n #[allow(unused_variables)] supported_compressed_formats: CompressedImageFormats,\n is_srgb: bool,\n ) -> Result {\n let format = image_type.to_image_format()?;\n\n // Load the image in the expected format.\n // Some formats like PNG allow for R or RG textures too, so the texture\n // format needs to be determined. For RGB textures an alpha channel\n // needs to be added, so the image data needs to be converted in those\n // cases.\n\n let image = match format {\n ImageFormat::Basis => {\n basis_buffer_to_image(buffer, supported_compressed_formats, is_srgb)?\n }\n // #[cfg(feature = \"dds\")]\n // ImageFormat::Dds => dds_buffer_to_image(buffer, supported_compressed_formats, is_srgb)?,\n ImageFormat::Ktx2 => {\n ktx2_buffer_to_image(buffer, supported_compressed_formats, is_srgb)?\n }\n _ => {\n todo!()\n }\n };\n\n Ok(image)\n }\n```"}], "func_name": "from_buffer", "docstring": "Load a bytes buffer in a [`Image`], according to type `image_type`, using the `image`\ncrate", "repo": "woelper/oculante", "path": "src/ktx2_loader/image.rs", "url": "https://github.com/woelper/oculante/blob/master/src/ktx2_loader/image.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb16f6ece4e1d40daf3da4758062b6343400ecc56c0d485481df11b21848de3f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_compressed\n\nDocumentation:\nWhether the texture format is compressed or uncompressed\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_compressed(&self) -> bool {\n let format_description = self.texture_descriptor.format;\n format_description\n .required_features()\n .contains(wgpu::Features::TEXTURE_COMPRESSION_ASTC)\n || format_description\n .required_features()\n .contains(wgpu::Features::TEXTURE_COMPRESSION_BC)\n || format_description\n .required_features()\n .contains(wgpu::Features::TEXTURE_COMPRESSION_ETC2)\n }\n```"}], "func_name": "is_compressed", "docstring": "Whether the texture format is compressed or uncompressed", "repo": "woelper/oculante", "path": "src/ktx2_loader/image.rs", "url": "https://github.com/woelper/oculante/blob/master/src/ktx2_loader/image.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5ab5c0838cf61f675ce917805c722559c8e21e493a519864726d3fbff2b303fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_into_dynamic\n\nDocumentation:\nConverts a [`DynamicImage`] to an [`Image`].\nConvert a [`Image`] to a [`DynamicImage`]. Useful for editing image\ndata. Not all [`TextureFormat`] are covered, therefore it will return an\nerror if the format is unsupported. Supported formats are:\n- `TextureFormat::R8Unorm`\n- `TextureFormat::Rg8Unorm`\n- `TextureFormat::Rgba8UnormSrgb`\n- `TextureFormat::Bgra8UnormSrgb`\n\nTo convert [`Image`] to a different format see: [`Image::convert`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_into_dynamic(self) -> Result {\n debug!(\n \"Attemting to interpret format {:?}\",\n self.texture_descriptor.format\n );\n debug!(\"Mip levels: {:?}\", self.texture_descriptor.mip_level_count);\n debug!(\n \"Array Layers {:?}\",\n self.texture_descriptor.array_layer_count()\n );\n debug!(\"Size {:?}\", self.texture_descriptor.size);\n debug!(\"W x H {}x{}\", self.width(), self.height());\n match self.texture_descriptor.format {\n TextureFormat::R8Unorm => ImageBuffer::from_raw(self.width(), self.height(), self.data)\n .map(DynamicImage::ImageLuma8),\n TextureFormat::Rg8Unorm => {\n ImageBuffer::from_raw(self.width(), self.height(), self.data)\n .map(DynamicImage::ImageLumaA8)\n }\n TextureFormat::Rgba8UnormSrgb => {\n ImageBuffer::from_raw(self.width(), self.height(), self.data)\n .map(DynamicImage::ImageRgba8)\n }\n // This format is commonly used as the format for the swapchain texture\n // This conversion is added here to support screenshots\n TextureFormat::Bgra8UnormSrgb | TextureFormat::Bgra8Unorm => {\n ImageBuffer::from_raw(self.width(), self.height(), {\n let mut data = self.data;\n for bgra in data.chunks_exact_mut(4) {\n bgra.swap(0, 2);\n }\n data\n })\n .map(DynamicImage::ImageRgba8)\n }\n TextureFormat::Rgba16Float => {\n let d = self\n .data\n .chunks_exact(2)\n .map(|c| [f16::from_le_bytes(c[0..=1].try_into().unwrap()).to_f32()])\n .flatten()\n .collect::>();\n Rgba32FImage::from_vec(self.width() as u32, self.height() as u32, d)\n .map(|i| DynamicImage::ImageRgba8(DynamicImage::ImageRgba32F(i).to_rgba8()))\n }\n TextureFormat::Rgba32Float => {\n let d = self\n .data\n .chunks_exact(4)\n .map(|c| [f32::from_le_bytes(c[0..=3].try_into().unwrap())])\n .flatten()\n .map(|p| p.powf(2.2))\n .map(|p| (p.powf(1.0 / 2.2).max(0.0).min(1.0)))\n .collect::>();\n Rgba32FImage::from_vec(self.width() as u32, self.height() as u32, d)\n .map(|i| DynamicImage::ImageRgba8(DynamicImage::ImageRgba32F(i).to_rgba8()))\n }\n // Throw and error if conversion isn't supported\n texture_format => return Err(IntoDynamicImageError::UnsupportedFormat(texture_format)),\n }\n .ok_or(IntoDynamicImageError::UnknownConversionError(\n self.texture_descriptor.format,\n ))\n }\n```"}], "func_name": "try_into_dynamic", "docstring": "Converts a [`DynamicImage`] to an [`Image`].\nConvert a [`Image`] to a [`DynamicImage`]. Useful for editing image\ndata. Not all [`TextureFormat`] are covered, therefore it will return an\nerror if the format is unsupported. Supported formats are:\n- `TextureFormat::R8Unorm`\n- `TextureFormat::Rg8Unorm`\n- `TextureFormat::Rgba8UnormSrgb`\n- `TextureFormat::Bgra8UnormSrgb`\n\nTo convert [`Image`] to a different format see: [`Image::convert`].", "repo": "woelper/oculante", "path": "src/ktx2_loader/image_texture_conversion.rs", "url": "https://github.com/woelper/oculante/blob/master/src/ktx2_loader/image_texture_conversion.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "72f8c3f33e3b1bed642c4872a6145d4bb530b18fe6e6a171f0e0afcf5789ed80"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: label_i\n\nDocumentation:\nDraw a justified icon from a string containing an emoji\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn label_i(&mut self, text: impl Into) -> Response {\n let text: WidgetText = text.into();\n let text = text.text();\n\n let (icon, description) = parse_icon_plus_text(text);\n let icon = icon.unwrap_or_default();\n\n self.with_layout(egui::Layout::left_to_right(Align::Center), |ui| {\n ui.add(egui::Label::new(\n RichText::new(icon).color(ui.style().visuals.selection.bg_fill),\n ));\n ui.label(\n RichText::new(description).color(ui.style().visuals.noninteractive().text_color()),\n );\n })\n .response\n }\n```"}], "func_name": "label_i", "docstring": "Draw a justified icon from a string containing an emoji", "repo": "woelper/oculante", "path": "src/ui/mod.rs", "url": "https://github.com/woelper/oculante/blob/master/src/ui/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9ec4ffd82845b97c0f5457bd9082d672eee9ec4174b5fdc776885774806c74f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: styled_button\n\nDocumentation:\nDraw a justified icon from a string starting with an emoji\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn styled_button(&mut self, text: impl Into) -> Response {\n let text: WidgetText = text.into();\n let text = text.text();\n\n let (icon, description) = parse_icon_plus_text(text);\n let icon = icon.unwrap_or_default();\n\n let spacing = if icon.is_empty() { \"\" } else { \" \" };\n let r = self.add(\n egui::Button::new(format!(\"{spacing}{description}\"))\n .rounding(self.get_rounding(BUTTON_HEIGHT_LARGE))\n .min_size(vec2(140., BUTTON_HEIGHT_LARGE)),\n );\n\n let mut icon_pos = r.rect.left_center();\n icon_pos.x += 16.;\n\n self.painter().text(\n icon_pos,\n Align2::CENTER_CENTER,\n icon,\n FontId::proportional(16.),\n self.style().visuals.selection.bg_fill,\n );\n r\n }\n```"}], "func_name": "styled_button", "docstring": "Draw a justified icon from a string starting with an emoji", "repo": "woelper/oculante", "path": "src/ui/mod.rs", "url": "https://github.com/woelper/oculante/blob/master/src/ui/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8268d1bd53c4f079f91b3cf2e36ac488e8b901618644a463d74ea71f4dc96766"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: drag_area\n\nDocumentation:\nAn area that can be dragged by a user to move the window\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn drag_area(ui: &mut Ui, state: &mut OculanteState, app: &mut App) {\n #[cfg(not(any(target_os = \"netbsd\", target_os = \"freebsd\")))]\n if state.persistent_settings.borderless {\n let r = ui.interact(\n ui.available_rect_before_wrap(),\n Id::new(\"drag\"),\n Sense::click_and_drag(),\n );\n\n if r.dragged() {\n // improve responsiveness\n app.window().request_frame();\n let position = Mouse::get_mouse_position();\n match position {\n Mouse::Position { mut x, mut y } => {\n // translate mouse pos into real pixels\n let dpi = app.backend.window().dpi();\n x = (x as f64 * dpi) as i32;\n y = (y as f64 * dpi) as i32;\n\n let offset = match ui\n .ctx()\n .memory(|r| r.data.get_temp::<(i32, i32)>(\"offset\".into()))\n {\n Some(o) => o,\n None => {\n let window_pos = app.window().position();\n let offset = (window_pos.0 - x, window_pos.1 - y);\n ui.ctx()\n .memory_mut(|w| w.data.insert_temp(Id::new(\"offset\"), offset));\n offset\n }\n };\n app.window().set_position(x + offset.0, y + offset.1);\n }\n Mouse::Error => error!(\"Error getting mouse position\"),\n }\n }\n if r.drag_stopped() {\n ui.ctx()\n .memory_mut(|w| w.data.remove::<(i32, i32)>(\"offset\".into()))\n }\n }\n}\n```"}], "func_name": "drag_area", "docstring": "An area that can be dragged by a user to move the window", "repo": "woelper/oculante", "path": "src/ui/mod.rs", "url": "https://github.com/woelper/oculante/blob/master/src/ui/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f46e76c6b257ca2d2949c5179802e75bb6ee07d6cd6b8c86dca195577f192943"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: save_with_encoding\n\nDocumentation:\nSave an image to a path using encoding options and generate a thumbnail\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn save_with_encoding(\n image: &DynamicImage,\n path: &Path,\n image_info: &Option,\n encoders: &Vec,\n) -> anyhow::Result<()> {\n let encoding_options = FileEncoder::matching_variant(path, encoders);\n encoding_options.save(image, path)?;\n debug!(\"Saved to {}\", path.display());\n // Re-apply exif\n if let Some(info) = &image_info {\n debug!(\"Extended image info present\");\n // before doing anything, make sure we have raw exif data\n if info.raw_exif.is_some() {\n fix_exif(path, info.raw_exif.clone())?;\n } else {\n debug!(\"No raw exif\");\n }\n }\n thumbnails::generate(path)?;\n Ok(())\n}\n```"}], "func_name": "save_with_encoding", "docstring": "Save an image to a path using encoding options and generate a thumbnail", "repo": "woelper/oculante", "path": "src/ui/mod.rs", "url": "https://github.com/woelper/oculante/blob/master/src/ui/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "976ac7f725d434dc5aaf3048448b06492c592507542c2e43a4d786bcf729dbe1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_font_family\n\nDocumentation:\nAttempt to load a system font by any of the given `family_names`, returning the first match.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn load_font_family(family_names: &[&str]) -> Option> {\n let system_source = SystemSource::new();\n for &name in family_names {\n let font_handle = system_source\n .select_best_match(&[FamilyName::Title(name.to_string())], &Properties::new());\n match font_handle {\n Ok(h) => match &h {\n Handle::Memory { bytes, .. } => {\n info!(\"Loaded {name} from memory.\");\n return Some(bytes.to_vec());\n }\n Handle::Path { path, .. } => {\n info!(\"Loaded {name} from path: {:?}\", path);\n if let Ok(data) = read(path) {\n return Some(data);\n }\n }\n },\n Err(e) => debug!(\"Could not load {}: {:?}\", name, e),\n }\n }\n None\n}\n```"}], "func_name": "load_font_family", "docstring": "Attempt to load a system font by any of the given `family_names`, returning the first match.", "repo": "woelper/oculante", "path": "src/ui/theme.rs", "url": "https://github.com/woelper/oculante/blob/master/src/ui/theme.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48e91708dc0443ebcfe4775584d917485481074148fada3df9105560f9cdc0b8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: main\n\nDocumentation:\n# Attention when using `RUST_LOG`\n\nEvery function here supports our usual [`mod@tracing::instrument`] setup, with default\n`log_level = \"trace`, but if you dare run with `RUST_LOG=trace` you're going to have a bad time!\n\nThe logging is put in place so you can quickly change whatever function you need to\n`log_level = \"debug\"` (or whatever).\n\ntl;dr: do **NOT** use `RUST_LOG=trace`!\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn main() -> Result<(), DocsError> {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::fmt::layer()\n .with_span_events(FmtSpan::ACTIVE)\n .pretty(),\n )\n .with(tracing_subscriber::EnvFilter::from_default_env())\n .init();\n\n let MedschoolArgs {\n prepend,\n output,\n input,\n } = ::parse();\n\n let files = parse_files(input.unwrap_or_else(|| PathBuf::from(\"./src\")))?;\n let type_docs = parse_docs_into_set(files)?;\n let resolved = resolve_references(type_docs.clone());\n\n if let Some(produced) = resolved {\n let mut final_docs = produced.produce_docs();\n if let Some(header) = prepend {\n let header = fs::read_to_string(header)?;\n final_docs.insert_str(0, &(header + \"\\n\"));\n }\n let output = output.unwrap_or_else(|| PathBuf::from(\"./configuration.md\"));\n fs::write(output, final_docs)?;\n }\n Ok(())\n}\n```"}], "func_name": "main", "docstring": "# Attention when using `RUST_LOG`\n\nEvery function here supports our usual [`mod@tracing::instrument`] setup, with default\n`log_level = \"trace`, but if you dare run with `RUST_LOG=trace` you're going to have a bad time!\n\nThe logging is put in place so you can quickly change whatever function you need to\n`log_level = \"debug\"` (or whatever).\n\ntl;dr: do **NOT** use `RUST_LOG=trace`!", "repo": "metalbear-co/mirrord", "path": "medschool/src/main.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/medschool/src/main.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "705650cf4dbf55e337fee4956c89935c3e0355973ec4a90906da828e943a1166"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: produce_docs\n\nDocumentation:\nTurns the `root` [`PartialType`] documentation into one big `String`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn produce_docs(self) -> String {\n self.docs\n .into_iter()\n .chain(\n self.fields\n .into_iter()\n .flat_map(|field| field.docs.into_iter()),\n )\n .collect()\n }\n```"}], "func_name": "produce_docs", "docstring": "Turns the `root` [`PartialType`] documentation into one big `String`.", "repo": "metalbear-co/mirrord", "path": "medschool/src/types.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/medschool/src/types.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63cc3529d797111581c44e182036a4a16935d7d90fd9682c11c04180b4469650"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance.\n\nAll instances should be kept together in [`super::envs`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) const fn new(name: &'static str) -> Self {\n Self {\n name,\n value_type: PhantomData,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance.\n\nAll instances should be kept together in [`super::envs`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/env/src/checked_env.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/env/src/checked_env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "667ee3d1af0fb69fd65803d3866ee2977a3ed7a1ea2647ebd902eb3be813d390"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_from_env\n\nDocumentation:\nReads this variable's value from the process environment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_from_env(self) -> Result, V::FromReprError> {\n match std::env::var_os(self.name) {\n Some(repr) => {\n let value = V::from_repr(repr.as_bytes())?;\n Ok(Some(value))\n }\n None => Ok(None),\n }\n }\n```"}], "func_name": "try_from_env", "docstring": "Reads this variable's value from the process environment.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/env/src/checked_env.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/env/src/checked_env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2799fa0485c93d0ed1ac444934bac15c5ac80d12cc4cc9dc499f1e922fa28542"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_env_or_default\n\nDocumentation:\nConvenience method for getting this variable's value.\n\nReads this variable's value from the process environment.\nIf this variable is missing or its value is malformed, returns a [`Default`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_env_or_default(self) -> V {\n match self.try_from_env() {\n Ok(None) => Default::default(),\n Ok(Some(value)) => value,\n Err(error) => {\n let default_value = V::default();\n\n tracing::error!(\n ?error,\n ?default_value,\n ?self,\n \"Failed to read an environment variable, value is malformed. Using a default value.\",\n );\n\n default_value\n }\n }\n }\n```"}], "func_name": "from_env_or_default", "docstring": "Convenience method for getting this variable's value.\n\nReads this variable's value from the process environment.\nIf this variable is missing or its value is malformed, returns a [`Default`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/env/src/checked_env.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/env/src/checked_env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e66b8f95a02eae5f21673ffb8fb8913a45e6c24061128a79f2d8f346144a97f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_iptables\n\nDocumentation:\nwrapper around iptables::new that uses nft or legacy based on env\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_iptables() -> iptables::IPTables {\n if envs::NFTABLES.from_env_or_default() {\n iptables::new_with_cmd(\"/usr/sbin/iptables-nft\")\n } else {\n iptables::new_with_cmd(\"/usr/sbin/iptables-legacy\")\n }\n .expect(\"IPTables initialization may not fail!\")\n}\n```"}], "func_name": "new_iptables", "docstring": "wrapper around iptables::new that uses nft or legacy based on env", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/iptables/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/iptables/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dbd701822e9190666e96c083a5201445a010e72621a413a5c569aa602c12a59e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create\n\nDocumentation:\nCreate a new `chain` and mount it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create(ipt: Arc, chain: &str) -> IPTablesResult {\n let managed = IPTableChain::create(ipt, chain.to_string())?;\n\n Ok(Self { managed })\n }\n```"}], "func_name": "create", "docstring": "Create a new `chain` and mount it.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/iptables/src/mesh/exclusion.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/iptables/src/mesh/exclusion.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e9db178976795e5c33415d7b4d70310e8cf0762f6f5913c2dbeb2d0c414082e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load\n\nDocumentation:\nLoad existing `chain` and mount it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load(ipt: Arc, chain: &str) -> IPTablesResult {\n let managed = IPTableChain::load(ipt, chain.to_string())?;\n\n Ok(Self { managed })\n }\n```"}], "func_name": "load", "docstring": "Load existing `chain` and mount it.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/iptables/src/mesh/exclusion.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/iptables/src/mesh/exclusion.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6fccecb148dcc3e2d44b581ec10643f47789de19552725f48e5ececc45e78970"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance of this worker.\nTo run this worker, call [`Self::run`].\n\n# Note\n\n`pid` is used to find the correct path of `etc` directory.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new(\n pid: Option,\n request_rx: Receiver,\n support_ipv6: bool,\n ) -> Self {\n let etc_path = pid\n .map(|pid| {\n PathBuf::from(\"/proc\")\n .join(pid.to_string())\n .join(\"root/etc\")\n })\n .unwrap_or_else(|| PathBuf::from(\"/etc\"));\n\n let timeout = envs::DNS_TIMEOUT\n .try_from_env()\n .ok()\n .flatten()\n .map(u64::from)\n .map(Duration::from_secs);\n let attempts = envs::DNS_ATTEMPTS\n .try_from_env()\n .ok()\n .flatten()\n .map(|attempts| usize::try_from(attempts).unwrap_or(usize::MAX));\n\n Self {\n etc_path,\n request_rx,\n timeout,\n attempts,\n support_ipv6,\n tasks: Default::default(),\n response_txs: Default::default(),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance of this worker.\nTo run this worker, call [`Self::run`].\n\n# Note\n\n`pid` is used to find the correct path of `etc` directory.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/dns.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/dns.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8abd3f24e2500c1432f1c1ca0422f8b228b75d2cf846c79d4115279fc62c80e1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_request\n\nDocumentation:\nSchedules a new DNS request.\n\nResults of scheduled requests are available via [`Self::recv`] (order is preserved).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn make_request(\n &mut self,\n request: ClientGetAddrInfoRequest,\n ) -> AgentResult<()> {\n let (response_tx, response_rx) = oneshot::channel();\n\n let command = DnsCommand {\n request,\n response_tx,\n };\n if self.request_tx.send(command).await.is_err() {\n return Err(self.task_status.wait_assert_running().await);\n }\n\n self.responses.push_back(response_rx);\n\n Ok(())\n }\n```"}], "func_name": "make_request", "docstring": "Schedules a new DNS request.\n\nResults of scheduled requests are available via [`Self::recv`] (order is preserved).", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/dns.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/dns.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c3ced78b7a181e1f1b24ca59c168ab45212d66ae01d7bf8a4f9882414ca1b7fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nReturn [`Err`] if container runtime operations failed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn new(args: &Args) -> AgentResult {\n let tls_connector = args\n .operator_tls_cert_pem\n .clone()\n .map(AgentTlsConnector::new)\n .transpose()?;\n\n let mut env: HashMap = HashMap::new();\n\n let (ephemeral, container) = match &args.mode {\n cli::Mode::Targeted {\n container_id,\n container_runtime,\n ..\n } => {\n let container = get_container(container_id.clone(), container_runtime).await?;\n\n let container_handle = ContainerHandle::new(container).await?;\n\n env.extend(container_handle.raw_env().clone());\n\n (false, Some(container_handle))\n }\n cli::Mode::Ephemeral { .. } => {\n let container_handle = ContainerHandle::new(runtime::Container::Ephemeral(\n runtime::EphemeralContainer {\n container_id: envs::EPHEMERAL_TARGET_CONTAINER_ID\n .try_from_env()\n .ok()\n .flatten()\n .unwrap_or_default(),\n },\n ))\n .await?;\n\n env.extend(container_handle.raw_env().clone());\n\n // If we are in an ephemeral container, we use pid 1.\n (true, Some(container_handle))\n }\n cli::Mode::Targetless => (false, None),\n };\n\n let network_runtime = match container.as_ref().map(ContainerHandle::pid) {\n Some(pid) if ephemeral.not() => BgTaskRuntime::Remote(\n RemoteRuntime::new_in_namespace(pid, NamespaceType::Net).await?,\n ),\n None | Some(..) => BgTaskRuntime::Local,\n };\n\n let env_pid = match container.as_ref().map(ContainerHandle::pid) {\n Some(pid) => pid.to_string(),\n None => \"self\".to_string(),\n };\n let environ_path = PathBuf::from(\"/proc\").join(env_pid).join(\"environ\");\n match env::get_proc_environ(environ_path).await {\n Ok(environ) => env.extend(environ.into_iter()),\n Err(err) => {\n error!(\"Failed to get process environment variables: {err:?}\");\n }\n };\n\n Ok(State {\n next_client_id: Default::default(),\n container,\n env: Arc::new(env),\n ephemeral,\n tls_connector,\n network_runtime,\n })\n }\n```"}], "func_name": "new", "docstring": "Return [`Err`] if container runtime operations failed.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/entrypoint.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/entrypoint.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9edf58089cb6898e6b3656bbc610566fbfe8e695189528375d8594602a53b9e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: notify_client_about_dirty_iptables\n\nDocumentation:\nUpon first client connection, immediately sends [`DaemonMessage::Close`] to the client due to\nthe presence of dirty IP tables.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn notify_client_about_dirty_iptables(\n listener: TcpListener,\n communication_timeout: u16,\n tls_connector: Option,\n) -> AgentResult<()> {\n // WARNING: `wait_for_agent_startup` in `mirrord/kube/src/api/container.rs` expects a line\n // containing \"agent_ready\" to be printed. If you change this then mirrord fails to\n // initialize.\n println!(\"agent ready - version {}\", env!(\"CARGO_PKG_VERSION\"));\n\n // We wait for the first client until `communication_timeout` elapses.\n let first_connection = timeout(\n Duration::from_secs(communication_timeout.into()),\n listener.accept(),\n )\n .await;\n\n // Attempt to send [`DaemonMessage::Close`]. Otherwise, the agent will still fail (but\n // ungracefully).\n match first_connection {\n Ok(Ok((stream, ..))) => {\n let mut connection = ClientConnection::new(stream, 0, tls_connector).await?;\n connection\n .send(DaemonMessage::Close(\n \"Detected dirty iptables. Either some other mirrord agent is running \\\n or the previous agent failed to clean up before exit. \\\n If no other mirrord agent is targeting this pod, please delete the pod.\"\n .to_string(),\n ))\n .await?;\n }\n\n Ok(Err(error)) => {\n tracing::warn!(\n ?error,\n \"notify_client_about_dirty_iptables -> Failed to accept first connection\"\n );\n Err(error)?\n }\n\n Err(..) => {\n tracing::warn!(\n \"notify_client_about_dirty_iptables -> Failed to accept first connection: timeout\"\n );\n Err(AgentError::FirstConnectionTimeout)?\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "notify_client_about_dirty_iptables", "docstring": "Upon first client connection, immediately sends [`DaemonMessage::Close`] to the client due to\nthe presence of dirty IP tables.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/entrypoint.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/entrypoint.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fdd43a07d739c47587a684ca8b318407e36c420fdd7b88696e92d5f6f09c3a30"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_child_agent\n\nDocumentation:\nRuns the current binary as a child process,\nusing the exact same command line.\n\nWhen this future is aborted before completion, the child process is automatically killed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_child_agent() -> AgentResult<()> {\n let command_args = std::env::args().collect::>();\n let (command, args) = command_args\n .split_first()\n .expect(\"cannot spawn child agent: command missing from program arguments\");\n\n let mut child_agent = Command::new(command)\n .env(CHILD_PROCESS_ENV, \"true\")\n .args(args)\n .kill_on_drop(true)\n .spawn()?;\n\n let status = child_agent.wait().await?;\n if !status.success() {\n Err(AgentError::AgentFailed(status))\n } else {\n Ok(())\n }\n}\n```"}], "func_name": "run_child_agent", "docstring": "Runs the current binary as a child process,\nusing the exact same command line.\n\nWhen this future is aborted before completion, the child process is automatically killed.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/entrypoint.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/entrypoint.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c25506e7ae88cefdfb5940e8e6ce8f9f94865ae3ec78d44af5e75fb2acf5265"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_iptable_guard\n\nDocumentation:\nTargeted agent's parent process.\n\nSpawns the main agent routine in the child process and handles cleanup of iptables\nwhen the child process exits.\n\nCaptures SIGTERM signals sent by Kubernetes when the pod is being gracefully deleted.\nWhen a signal is captured, the child process is killed and the iptables are cleaned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn start_iptable_guard(args: Args) -> AgentResult<()> {\n debug!(\"start_iptable_guard -> Initializing iptable-guard.\");\n\n let state = State::new(&args).await?;\n let pid = state.container_pid();\n let with_mesh_exclusion = state.is_with_mesh_exclusion();\n\n let mut sigterm = tokio::signal::unix::signal(SignalKind::terminate())?;\n\n let result = tokio::select! {\n _ = sigterm.recv() => {\n debug!(\"start_iptable_guard -> SIGTERM received, killing agent process\");\n Ok(())\n }\n\n result = run_child_agent() => match result {\n Err(AgentError::AgentFailed(status)) if status.code() == Some(IPTABLES_DIRTY_EXIT_CODE as i32) => {\n // Err status `IPTABLES_DIRTY_EXIT_CODE` means dirty IP tables detected, skip cleanup\n tracing::warn!(\"dirty IP tables, cleanup skipped\");\n return result;\n }\n _ => result,\n },\n };\n\n let Some(pid) = pid else {\n return result;\n };\n\n let runtime = RemoteRuntime::new_in_namespace(pid, NamespaceType::Net).await?;\n runtime\n .spawn(clear_iptable_chain(args.ipv6, with_mesh_exclusion))\n .await\n .map_err(|error| AgentError::BackgroundTaskFailed {\n task: \"IPTablesCleaner\",\n error: Arc::new(error),\n })?\n .map_err(|error| AgentError::BackgroundTaskFailed {\n task: \"IPTablesCleaner\",\n error: Arc::new(error),\n })?;\n\n result\n}\n```"}], "func_name": "start_iptable_guard", "docstring": "Targeted agent's parent process.\n\nSpawns the main agent routine in the child process and handles cleanup of iptables\nwhen the child process exits.\n\nCaptures SIGTERM signals sent by Kubernetes when the pod is being gracefully deleted.\nWhen a signal is captured, the child process is killed and the iptables are cleaned.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/entrypoint.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/entrypoint.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e4b168df09a769bb032c23aaecceaa2cc645b6dcbfa562e98d124d4e177c9ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: main\n\nDocumentation:\nmirrord-agent entrypoint.\n\nInstalls a default [`CryptoProvider`](rustls::crypto::CryptoProvider) and initializes tracing.\n\n# Flow\n\nIf the agent is targetless, it goes straight to spawning background tasks and listening for\nclient connections.\n\nIf the agent has a target, the flow is a bit different.\nThis is because we might need to redirect incoming traffic.\n\nNote that the agent uses static IP tables chain names, and running multiple agents at the same\ntime will cause an error.\n\nThe agent spawns a child process with the exact same command line,\nand waits for a SIGTERM signal. When the signal is received or the child process fails,\nthe agent cleans the iptables (based on the previously set environment variables) before\nexiting.\n\nThe child process is the real agent, which spawns background tasks and listens for client\nconnections. The child process knowns is the real agent, because it has the environment\nvariables set.\n\nThis weird flow is a safety measure - should the real agent OOM (which means instant process\ntermination) or be killed with a signal, the parent will a chance to clean iptables. If we leave\nthe iptables dirty, the whole target pod is broken, probably forever.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn main() -> AgentResult<()> {\n rustls::crypto::CryptoProvider::install_default(rustls::crypto::aws_lc_rs::default_provider())\n .expect(\"Failed to install crypto provider\");\n\n if envs::JSON_LOG.from_env_or_default() {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::fmt::layer()\n .with_thread_ids(true)\n .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)\n .json(),\n )\n .with(tracing_subscriber::EnvFilter::from_default_env())\n .init();\n } else {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::fmt::layer()\n .with_thread_ids(true)\n .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)\n .pretty()\n .with_line_number(true),\n )\n .with(tracing_subscriber::EnvFilter::from_default_env())\n .init();\n }\n\n debug!(\n \"main -> Initializing mirrord-agent, version {}.\",\n env!(\"CARGO_PKG_VERSION\")\n );\n\n let args = cli::parse_args();\n let second_process = std::env::var(CHILD_PROCESS_ENV).is_ok();\n\n if args.mode.is_targetless() || second_process {\n start_agent(args).await\n } else {\n start_iptable_guard(args).await\n }\n}\n```"}], "func_name": "main", "docstring": "mirrord-agent entrypoint.\n\nInstalls a default [`CryptoProvider`](rustls::crypto::CryptoProvider) and initializes tracing.\n\n# Flow\n\nIf the agent is targetless, it goes straight to spawning background tasks and listening for\nclient connections.\n\nIf the agent has a target, the flow is a bit different.\nThis is because we might need to redirect incoming traffic.\n\nNote that the agent uses static IP tables chain names, and running multiple agents at the same\ntime will cause an error.\n\nThe agent spawns a child process with the exact same command line,\nand waits for a SIGTERM signal. When the signal is received or the child process fails,\nthe agent cleans the iptables (based on the previously set environment variables) before\nexiting.\n\nThe child process is the real agent, which spawns background tasks and listens for client\nconnections. The child process knowns is the real agent, because it has the environment\nvariables set.\n\nThis weird flow is a safety measure - should the real agent OOM (which means instant process\ntermination) or be killed with a signal, the parent will a chance to clean iptables. If we leave\nthe iptables dirty, the whole target pod is broken, probably forever.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/entrypoint.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/entrypoint.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e7e291090fd85d1340cfce8333b9154842207b1e47f6a14d1c26064761821c41"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_raw_env\n\nDocumentation:\nTranslate `ToIter>` of \"K=V\" to HashMap.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn parse_raw_env<'a, S: AsRef + 'a + ?Sized, T: IntoIterator>(\n raw: T,\n) -> HashMap {\n raw.into_iter()\n .map(|key_and_value| key_and_value.as_ref().splitn(2, '=').collect::>())\n // [[\"DB\", \"foo.db\"], [\"PORT\", \"99\"], [\"HOST\"], [\"PATH\", \"/fake\"]]\n .filter_map(\n |mut keys_and_values| match (keys_and_values.pop(), keys_and_values.pop()) {\n (Some(value), Some(key)) => Some((key.to_string(), value.to_string())),\n _ => None,\n },\n )\n // [(\"DB\", \"foo.db\")]\n .collect::>()\n}\n```"}], "func_name": "parse_raw_env", "docstring": "Translate `ToIter>` of \"K=V\" to HashMap.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/env.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "966e0e2637d1f5a28abd8dd0306ad8f122bd4e4a4737fa9f5a1081ae05864591"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_current_and_parent_entries\n\nDocumentation:\nGet an iterator that contains entries of the current and parent (if exists) directories,\nto chain with the iterator returned by [`std::fs::read_dir`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_current_and_parent_entries(current: &Path) -> VecDeque> {\n let mut entries = VecDeque::default();\n entries.push_back(Self::path_to_dir_entry_internal(\n current,\n 0,\n \".\".to_string(),\n ));\n if let Some(parent) = current.parent() {\n entries.push_back(Self::path_to_dir_entry_internal(\n parent,\n 1,\n \"..\".to_string(),\n ))\n }\n entries\n }\n```"}], "func_name": "get_current_and_parent_entries", "docstring": "Get an iterator that contains entries of the current and parent (if exists) directories,\nto chain with the iterator returned by [`std::fs::read_dir`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/file.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/file.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b78e93023ebb2fb06fe694c0c3b9f30505f28316abf64c7ecd96fd612c3481be"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_version\n\nDocumentation:\nIf the stream is known to be an HTTP connection,\nreturns its version.\n\nOtherwise, returns [`None`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_version(self) -> Option {\n match self {\n Self::Http(version) => Some(version),\n Self::Unknown => None,\n Self::NotHttp => None,\n }\n }\n```"}], "func_name": "into_version", "docstring": "If the stream is known to be an HTTP connection,\nreturns its version.\n\nOtherwise, returns [`None`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/http.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/http.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "16fc2e006c4007f2273d8393a4036ebfd0f7bd9dff29d6d3eb090a1acd67dcc9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_known\n\nDocumentation:\nReturns whether it's known whether the stream is an HTTP connection or not.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_known(&self) -> bool {\n match self {\n Self::Http(_) => true,\n Self::Unknown => false,\n Self::NotHttp => true,\n }\n }\n```"}], "func_name": "is_known", "docstring": "Returns whether it's known whether the stream is an HTTP connection or not.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/http.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/http.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3af914643eb2a2eff02efb64dbc8dd72b8ef04727bfe9d8d237a9cab61466e69"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: detect_http_version\n\nDocumentation:\nAttempts to detect HTTP version from the first bytes of a stream.\n\nKeeps reading data until the timeout elapses or we're certain whether the stream is an HTTP\nconnection or not.\n\n# Notes\n\n* The given `timeout` starts elapsing only after we complete the first read.\n* This function can read arbitrarily large amount of data from the stream. However,\n[`HttpVersion::detect`] should almost always be able to determine the stream type after\nreading no more than ~2kb (assuming **very** long request URI).\n* Consumed data is stored in [`RolledBackStream`]'s prefix, which will be dropped after the data\nis read again.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn detect_http_version(\n mut stream: IO,\n timeout: Duration,\n) -> io::Result<(RolledBackStream, Option)>\nwhere\n IO: AsyncRead + Unpin,\n{\n let mut buf = BytesMut::with_capacity(1024);\n let mut detected = DetectedHttpVersion::Unknown;\n let mut timeout_at: Option = None;\n\n while detected.is_known().not() {\n let timeout_fut = OptionFuture::from(timeout_at.map(tokio::time::sleep_until));\n\n let result = tokio::select! {\n Some(..) = timeout_fut => break,\n result = stream.read_buf(&mut buf) => result,\n };\n\n let read_size = result?;\n if read_size == 0 {\n break;\n }\n\n timeout_at = timeout_at.or_else(|| Some(Instant::now() + timeout));\n detected = HttpVersion::detect(buf.as_ref());\n }\n\n Ok((RolledBackStream::new(stream, buf), detected.into_version()))\n}\n```"}], "func_name": "detect_http_version", "docstring": "Attempts to detect HTTP version from the first bytes of a stream.\n\nKeeps reading data until the timeout elapses or we're certain whether the stream is an HTTP\nconnection or not.\n\n# Notes\n\n* The given `timeout` starts elapsing only after we complete the first read.\n* This function can read arbitrarily large amount of data from the stream. However,\n[`HttpVersion::detect`] should almost always be able to determine the stream type after\nreading no more than ~2kb (assuming **very** long request URI).\n* Consumed data is stored in [`RolledBackStream`]'s prefix, which will be dropped after the data\nis read again.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/http.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/http.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6af2f3089ed4a437e8e1e686b76c2ae7a7bbe759309e791201a3f6700faad664"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_iptables_redirector\n\nDocumentation:\nCreates a [`ComposedRedirector`] based on [`IpTablesRedirector`]s.\n\nFails when no inner redirector can be created.\n\n# Params\n\n* `flush_connections` - passed to inner redirectors.\n* `pod_ips` - passed to inner redirectors.\n* `support_ipv6` - if set, this function will attempt to create both an IPv4 and an IPv6\nredirector. Otherwise, it will only attempt to create an IPv4 redirector.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn create_iptables_redirector(\n flush_connections: bool,\n pod_ips: &[IpAddr],\n support_ipv6: bool,\n with_mesh_exclusion: Option,\n) -> io::Result> {\n let ipv4 = IpTablesRedirector::create(flush_connections, pod_ips, false, with_mesh_exclusion)\n .await\n .inspect_err(|error| {\n tracing::error!(\n %error,\n \"Failed to create an IPv4 traffic redirector\",\n )\n });\n\n let ipv6 = if support_ipv6 {\n IpTablesRedirector::create(flush_connections, pod_ips, true, with_mesh_exclusion)\n .await\n .inspect_err(|error| {\n tracing::error!(\n %error,\n \"Failed to create an IPv6 traffic redirector\",\n )\n })\n .into()\n } else {\n None\n };\n\n let redirectors = match (ipv4, ipv6) {\n (Ok(ipv4), ipv6) => {\n let mut redirectors = vec![ipv4];\n redirectors.extend(ipv6.transpose().ok().flatten());\n redirectors\n }\n (Err(error), None | Some(Err(..))) => return Err(error),\n (Err(..), Some(Ok(ipv6))) => vec![ipv6],\n };\n\n Ok(ComposedRedirector::new(redirectors))\n}\n```"}], "func_name": "create_iptables_redirector", "docstring": "Creates a [`ComposedRedirector`] based on [`IpTablesRedirector`]s.\n\nFails when no inner redirector can be created.\n\n# Params\n\n* `flush_connections` - passed to inner redirectors.\n* `pod_ips` - passed to inner redirectors.\n* `support_ipv6` - if set, this function will attempt to create both an IPv4 and an IPv6\nredirector. Otherwise, it will only attempt to create an IPv4 redirector.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "24b2507db7c131e878f73b02be727d02e5fa07b8e22406e802694a26c67934d7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new dummy redirector.\n\nReturns:\n1. the redirector,\n2. a [`watch::Receiver`] that can be used to inspect the redirector's state,\n3. an [`mpsc::Sender`] that can be used to send mocked [`Redirected`] connections\nthrough the redirector.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new() -> (\n Self,\n watch::Receiver,\n mpsc::Sender,\n ) {\n let (conn_tx, conn_rx) = mpsc::channel(8);\n let (state_tx, state_rx) = watch::channel(DummyRedirectorState::default());\n\n (\n Self {\n state: state_tx,\n conn_rx,\n },\n state_rx,\n conn_tx,\n )\n }\n```"}], "func_name": "new", "docstring": "Creates a new dummy redirector.\n\nReturns:\n1. the redirector,\n2. a [`watch::Receiver`] that can be used to inspect the redirector's state,\n3. an [`mpsc::Sender`] that can be used to send mocked [`Redirected`] connections\nthrough the redirector.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c1b25dff050a3ee821de23f94b642d6619f18ca070aa99b440ab5fccc8a2852b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a [`Registry`] to ... register our [`IntGauge`]s.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new() -> Self {\n use prometheus::Opts;\n\n let registry = Registry::new();\n\n let client_count = {\n let opts = Opts::new(\n \"mirrord_agent_client_count\",\n \"amount of connected clients to this mirrord-agent\",\n );\n IntGauge::with_opts(opts).expect(\"Valid at initialization!\")\n };\n\n let dns_request_count = {\n let opts = Opts::new(\n \"mirrord_agent_dns_request_count\",\n \"amount of in-progress dns requests in the mirrord-agent\",\n );\n IntGauge::with_opts(opts).expect(\"Valid at initialization!\")\n };\n\n let open_fd_count = {\n let opts = Opts::new(\n \"mirrord_agent_open_fd_count\",\n \"amount of open file descriptors in mirrord-agent file manager\",\n );\n IntGauge::with_opts(opts).expect(\"Valid at initialization!\")\n };\n\n let mirror_port_subscription = {\n let opts = Opts::new(\n \"mirrord_agent_mirror_port_subscription_count\",\n \"amount of mirror port subscriptions in mirror-agent\",\n );\n IntGauge::with_opts(opts).expect(\"Valid at initialization!\")\n };\n\n let mirror_connection_subscription = {\n let opts = Opts::new(\n \"mirrord_agent_mirror_connection_subscription_count\",\n \"amount of connections in mirror mode in mirrord-agent\",\n );\n IntGauge::with_opts(opts).expect(\"Valid at initialization!\")\n };\n\n let steal_filtered_port_subscription = {\n let opts = Opts::new(\n \"mirrord_agent_steal_filtered_port_subscription_count\",\n \"amount of filtered steal port subscriptions in mirrord-agent\",\n );\n IntGauge::with_opts(opts).expect(\"Valid at initialization!\")\n };\n\n let steal_unfiltered_port_subscription = {\n let opts = Opts::new(\n \"mirrord_agent_steal_unfiltered_port_subscription_count\",\n \"amount of unfiltered steal port subscriptions in mirrord-agent\",\n );\n IntGauge::with_opts(opts).expect(\"Valid at initialization!\")\n };\n\n let steal_filtered_connection_subscription = {\n let opts = Opts::new(\n \"mirrord_agent_steal_connection_subscription_count\",\n \"amount of filtered connections in steal mode in mirrord-agent\",\n );\n IntGauge::with_opts(opts).expect(\"Valid at initialization!\")\n };\n\n let steal_unfiltered_connection_subscription = {\n let opts = Opts::new(\n \"mirrord_agent_steal_unfiltered_connection_subscription_count\",\n \"amount of unfiltered connections in steal mode in mirrord-agent\",\n );\n IntGauge::with_opts(opts).expect(\"Valid at initialization!\")\n };\n\n let http_request_in_progress_count = {\n let opts = Opts::new(\n \"mirrord_agent_http_request_in_progress_count\",\n \"amount of in-progress http requests in the mirrord-agent\",\n );\n IntGauge::with_opts(opts).expect(\"Valid at initialization!\")\n };\n\n let tcp_outgoing_connection = {\n let opts = Opts::new(\n \"mirrord_agent_tcp_outgoing_connection_count\",\n \"amount of tcp outgoing connections in mirrord-agent\",\n );\n IntGauge::with_opts(opts).expect(\"Valid at initialization!\")\n };\n\n let udp_outgoing_connection = {\n let opts = Opts::new(\n \"mirrord_agent_udp_outgoing_connection_count\",\n \"amount of udp outgoing connections in mirrord-agent\",\n );\n IntGauge::with_opts(opts).expect(\"Valid at initialization!\")\n };\n\n registry\n .register(Box::new(client_count.clone()))\n .expect(\"Register must be valid at initialization!\");\n registry\n .register(Box::new(dns_request_count.clone()))\n .expect(\"Register must be valid at initialization!\");\n registry\n .register(Box::new(open_fd_count.clone()))\n .expect(\"Register must be valid at initialization!\");\n registry\n .register(Box::new(mirror_port_subscription.clone()))\n .expect(\"Register must be valid at initialization!\");\n registry\n .register(Box::new(mirror_connection_subscription.clone()))\n .expect(\"Register must be valid at initialization!\");\n registry\n .register(Box::new(steal_filtered_port_subscription.clone()))\n .expect(\"Register must be valid at initialization!\");\n registry\n .register(Box::new(steal_unfiltered_port_subscription.clone()))\n .expect(\"Register must be valid at initialization!\");\n registry\n .register(Box::new(steal_filtered_connection_subscription.clone()))\n .expect(\"Register must be valid at initialization!\");\n registry\n .register(Box::new(steal_unfiltered_connection_subscription.clone()))\n .expect(\"Register must be valid at initialization!\");\n registry\n .register(Box::new(http_request_in_progress_count.clone()))\n .expect(\"Register must be valid at initialization!\");\n registry\n .register(Box::new(tcp_outgoing_connection.clone()))\n .expect(\"Register must be valid at initialization!\");\n registry\n .register(Box::new(udp_outgoing_connection.clone()))\n .expect(\"Register must be valid at initialization!\");\n\n Self {\n registry,\n client_count,\n dns_request_count,\n open_fd_count,\n mirror_port_subscription,\n mirror_connection_subscription,\n steal_filtered_port_subscription,\n steal_unfiltered_port_subscription,\n steal_filtered_connection_subscription,\n steal_unfiltered_connection_subscription,\n http_request_in_progress_count,\n tcp_outgoing_connection,\n udp_outgoing_connection,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a [`Registry`] to ... register our [`IntGauge`]s.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/metrics.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/metrics.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dd283e0948b31b6465dcfbdc59dbcdee55735abef3f0950a296d5ca408122daf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: gather_metrics\n\nDocumentation:\nCalls [`IntGauge::set`] on every [`IntGauge`] of `Self`, setting it to the value of\nthe corresponding [`AtomicUsize`] global (the uppercase named version of the gauge).\n\nReturns the list of [`MetricFamily`] registered in our [`Metrics::registry`], ready to be\nencoded and sent to prometheus.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn gather_metrics(&self) -> Vec {\n let Self {\n registry,\n client_count,\n dns_request_count,\n open_fd_count,\n mirror_port_subscription,\n mirror_connection_subscription,\n steal_filtered_port_subscription,\n steal_unfiltered_port_subscription,\n steal_filtered_connection_subscription,\n steal_unfiltered_connection_subscription,\n http_request_in_progress_count,\n tcp_outgoing_connection,\n udp_outgoing_connection,\n } = self;\n\n client_count.set(CLIENT_COUNT.load_as_i64());\n dns_request_count.set(DNS_REQUEST_COUNT.load_as_i64());\n open_fd_count.set(OPEN_FD_COUNT.load_as_i64());\n mirror_port_subscription.set(MIRROR_PORT_SUBSCRIPTION.load_as_i64());\n mirror_connection_subscription.set(MIRROR_CONNECTION_SUBSCRIPTION.load_as_i64());\n steal_filtered_port_subscription.set(STEAL_FILTERED_PORT_SUBSCRIPTION.load_as_i64());\n steal_unfiltered_port_subscription.set(STEAL_UNFILTERED_PORT_SUBSCRIPTION.load_as_i64());\n steal_filtered_connection_subscription\n .set(STEAL_FILTERED_CONNECTION_SUBSCRIPTION.load_as_i64());\n steal_unfiltered_connection_subscription\n .set(STEAL_UNFILTERED_CONNECTION_SUBSCRIPTION.load_as_i64());\n http_request_in_progress_count.set(HTTP_REQUEST_IN_PROGRESS_COUNT.load_as_i64());\n tcp_outgoing_connection.set(TCP_OUTGOING_CONNECTION.load_as_i64());\n udp_outgoing_connection.set(UDP_OUTGOING_CONNECTION.load_as_i64());\n\n registry.gather()\n }\n```"}], "func_name": "gather_metrics", "docstring": "Calls [`IntGauge::set`] on every [`IntGauge`] of `Self`, setting it to the value of\nthe corresponding [`AtomicUsize`] global (the uppercase named version of the gauge).\n\nReturns the list of [`MetricFamily`] registered in our [`Metrics::registry`], ready to be\nencoded and sent to prometheus.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/metrics.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/metrics.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e587b94415e92410e7259120ad012d63c162d1e6f578f2012cc897da5e104832"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: path_for_target\n\nDocumentation:\nReturns a path to the namespace file for the given target process ID.\n\nThis path can be used with [`setns`] to enter the namespace.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn path_for_target(self, target_pid: u64) -> String {\n match self {\n NamespaceType::Net => format!(\"/proc/{target_pid}/ns/net\"),\n }\n }\n```"}], "func_name": "path_for_target", "docstring": "Returns a path to the namespace file for the given target process ID.\n\nThis path can be used with [`setns`] to enter the namespace.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/namespace.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/namespace.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "627e71f4f8f53982b1fa0f2f6c33a527f01fbaed2621a7cbb30dfc4cc4bd38c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nSpawns a new background task for handling the `outgoing` feature and creates a new instance\nof this struct to serve as an interface.\n\n# Params\n\n* `runtime` - tokio runtime to spawn the background task on.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new(runtime: &BgTaskRuntime) -> Self {\n let (layer_tx, layer_rx) = mpsc::channel(1000);\n let (daemon_tx, daemon_rx) = mpsc::channel(1000);\n\n let pid = runtime.target_pid();\n let task_status = runtime\n .spawn(TcpOutgoingTask::new(pid, layer_rx, daemon_tx).run())\n .into_status(\"TcpOutgoingTask\");\n\n Self {\n task_status,\n layer_tx,\n daemon_rx,\n }\n }\n```"}], "func_name": "new", "docstring": "Spawns a new background task for handling the `outgoing` feature and creates a new instance\nof this struct to serve as an interface.\n\n# Params\n\n* `runtime` - tokio runtime to spawn the background task on.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/outgoing.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/outgoing.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2977ee25fda5d41853025345a506e8cb805b8f61d9201b0824639066ea5c65f8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_container\n\nDocumentation:\nget a container object according to args.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_container(\n container_id: String,\n container_runtime: &str,\n) -> ContainerRuntimeResult {\n match container_runtime {\n \"docker\" => Ok(Container::Docker(\n DockerContainer::from_id(container_id).await?,\n )),\n \"containerd\" => Ok(Container::Containerd(ContainerdContainer { container_id })),\n \"cri-o\" => Ok(Container::CriO(CriOContainer::from_id(container_id))),\n other => Err(ContainerRuntimeError::unknown_runtime(other)),\n }\n}\n```"}], "func_name": "get_container", "docstring": "get a container object according to args.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/runtime.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/runtime.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d151c2aaf9bd85f3e02c71cf1e9324155b9eae02457033aa2427adb0112f9da4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect_and_find_container\n\nDocumentation:\nConnects to the given containerd socket\nand returns the client only if the given container\nexists.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn connect_and_find_container(\n container_id: String,\n sock_path: impl AsRef,\n) -> ContainerRuntimeResult {\n let channel = connect(sock_path).await?;\n let mut client = TasksClient::new(channel.clone());\n let request = GetRequest {\n container_id,\n ..Default::default()\n };\n let request = with_namespace!(request, DEFAULT_CONTAINERD_NAMESPACE);\n client\n .get(request)\n .await\n .map_err(ContainerRuntimeError::containerd)?;\n Ok(channel)\n}\n```"}], "func_name": "connect_and_find_container", "docstring": "Connects to the given containerd socket\nand returns the client only if the given container\nexists.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/runtime.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/runtime.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "99197b264b2a1e0c8fc70b736391c3f0793bf7862bf3026b5b66b41145403e1f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_channel\n\nDocumentation:\nGet the containerd channel for a given container id.\nThis is useful since we might have more than one\ncontainerd socket to use and we need to find the one\nthat manages our target container\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn get_channel(&self) -> ContainerRuntimeResult {\n for sock_path in CONTAINERD_SOCK_PATHS {\n if let Ok(channel) =\n connect_and_find_container(self.container_id.clone(), sock_path).await\n {\n return Ok(channel);\n }\n }\n Err(ContainerRuntimeError::containerd(\n r#\"Couldn't find containerd socket to use, please open a bug report\n providing information on how you installed k8s and if you know where\n the containerd socket is\"#,\n ))\n }\n```"}], "func_name": "get_channel", "docstring": "Get the containerd channel for a given container id.\nThis is useful since we might have more than one\ncontainerd socket to use and we need to find the one\nthat manages our target container", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/runtime.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/runtime.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f918b28a7fb8913aa8854ac7e3a1453b7e5210847988e63e7538a13165afa509"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: subscribe\n\nDocumentation:\nAdd a new subscription to a topic for a given client.\nReturns whether this resulted in adding a new topic to this mapping.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn subscribe(&mut self, client: C, topic: T) -> bool {\n match self.inner.entry(topic) {\n Entry::Occupied(mut e) => {\n e.get_mut().insert(client);\n false\n }\n Entry::Vacant(e) => {\n e.insert([client].into());\n true\n }\n }\n }\n```"}], "func_name": "subscribe", "docstring": "Add a new subscription to a topic for a given client.\nReturns whether this resulted in adding a new topic to this mapping.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/util.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a78bc3292ed8eb4ac34da81ab5f8ff42acd871293a2219e4069f7cbea1d870fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unsubscribe\n\nDocumentation:\nRemove a subscription of given client from the topic.\nTopic is removed if no subscribers left.\nReturn whether the topic was removed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unsubscribe(&mut self, client: C, topic: T) -> bool {\n match self.inner.entry(topic) {\n Entry::Occupied(mut e) => {\n e.get_mut().remove(&client);\n if e.get().is_empty() {\n e.remove();\n true\n } else {\n false\n }\n }\n Entry::Vacant(..) => false,\n }\n }\n```"}], "func_name": "unsubscribe", "docstring": "Remove a subscription of given client from the topic.\nTopic is removed if no subscribers left.\nReturn whether the topic was removed.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/util.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6c7c588ef2f3fda15a9c2034b1ddf3ad4a689d9fb64a2240aee0d838fb8e3241"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_client\n\nDocumentation:\nRemove all subscriptions of a client.\nTopics are removed if no subscribers left.\nReturns whether any topic was removed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn remove_client(&mut self, client: C) -> bool {\n let prev_length = self.inner.len();\n\n self.inner.retain(|_, client_set| {\n client_set.remove(&client);\n !client_set.is_empty()\n });\n\n self.inner.len() != prev_length\n }\n```"}], "func_name": "remove_client", "docstring": "Remove all subscriptions of a client.\nTopics are removed if no subscribers left.\nReturns whether any topic was removed.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/util.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7a91e2dd1acbf7f681b4da30d6e4b4dd2ab91c8524f42a9a2ff04265b529837a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nSpawns a new background task for handling the `vpn` feature and creates a new instance of\nthis struct to serve as an interface.\n\n# Params\n\n* `runtime` - tokio runtime to spawn the task on.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new(runtime: &BgTaskRuntime) -> Self {\n let (layer_tx, layer_rx) = mpsc::channel(1000);\n let (daemon_tx, daemon_rx) = mpsc::channel(1000);\n let pid = runtime.target_pid();\n\n let task_status = runtime\n .spawn(VpnTask::new(pid, layer_rx, daemon_tx).run())\n .into_status(\"VpnTask\");\n\n Self {\n task_status,\n layer_tx,\n daemon_rx,\n }\n }\n```"}], "func_name": "new", "docstring": "Spawns a new background task for handling the `vpn` feature and creates a new instance of\nthis struct to serve as an interface.\n\n# Params\n\n* `runtime` - tokio runtime to spawn the task on.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/vpn.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/vpn.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d63a56ac9c0b6ad63576e8fc5aebb4c992ba4fef946cd87a1bf7bcb8790ead61"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: layer_message\n\nDocumentation:\nSends the [`ClientVpn`] message to the background task.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn layer_message(&mut self, message: ClientVpn) -> AgentResult<()> {\n if self.layer_tx.send(message).await.is_ok() {\n Ok(())\n } else {\n Err(self.task_status.wait_assert_running().await)\n }\n }\n```"}], "func_name": "layer_message", "docstring": "Sends the [`ClientVpn`] message to the background task.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/vpn.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/vpn.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a09a729e792dd370389f47c1cf5b850f4f22bd7487fa80c2371d7e88069a0037"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: daemon_message\n\nDocumentation:\nReceives a [`ServerVpn`] message from the background task.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn daemon_message(&mut self) -> AgentResult {\n match self.daemon_rx.recv().await {\n Some(msg) => Ok(msg),\n None => Err(self.task_status.wait_assert_running().await),\n }\n }\n```"}], "func_name": "daemon_message", "docstring": "Receives a [`ServerVpn`] message from the background task.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/vpn.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/vpn.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "161bdddf397723742cb8119087e7929d8c65e97da958fde03d1492028cb75e56"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_traffic_redirector\n\nDocumentation:\nStarts a [`RedirectorTask`] on the given `runtime`.\n\nReturns the [`StealHandle`] that can be used to steal incoming traffic.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn start_traffic_redirector(\n runtime: &BgTaskRuntime,\n with_mesh_exclusion: Option,\n) -> AgentResult {\n let flush_connections = envs::STEALER_FLUSH_CONNECTIONS.from_env_or_default();\n let pod_ips = envs::POD_IPS.from_env_or_default();\n let support_ipv6 = envs::IPV6_SUPPORT.from_env_or_default();\n\n let (task, handle) = runtime\n .spawn(async move {\n incoming::create_iptables_redirector(\n flush_connections,\n &pod_ips,\n support_ipv6,\n with_mesh_exclusion,\n )\n .await\n .map(RedirectorTask::new)\n })\n .await\n .map_err(|error| AgentError::IPTablesSetupError(error.into()))?\n .map_err(|error| AgentError::IPTablesSetupError(error.into()))?;\n\n runtime.spawn(task.run());\n\n Ok(handle)\n}\n```"}], "func_name": "start_traffic_redirector", "docstring": "Starts a [`RedirectorTask`] on the given `runtime`.\n\nReturns the [`StealHandle`] that can be used to steal incoming traffic.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/entrypoint/setup.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/entrypoint/setup.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "663236f3a3d046f8a794caaa34722431796f35928e8ae3b54be84c3564709d77"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreated a new [`ComposedRedirector`] that will use the provided inner redirectors.\n\n# Panic\n\nPanics if the given redirectors vector is empty.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(redirectors: Vec) -> Self {\n assert!(\n redirectors.is_empty().not(),\n \"cannot create a ComposedRedirector with no inner redirectors\"\n );\n\n Self { redirectors }\n }\n```"}], "func_name": "new", "docstring": "Created a new [`ComposedRedirector`] that will use the provided inner redirectors.\n\n# Panic\n\nPanics if the given redirectors vector is empty.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming/composed.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming/composed.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9d85513c91e8850ef4c6ff6579e254b7865269dd9ebcd0ee1473a2433918813f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_redirection\n\nDocumentation:\nCalled in order on all inner redirectors.\n\nStops at the first error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn add_redirection(&mut self, from_port: u16) -> Result<(), Self::Error> {\n for redirector in &mut self.redirectors {\n redirector.add_redirection(from_port).await?;\n }\n\n Ok(())\n }\n```"}], "func_name": "add_redirection", "docstring": "Called in order on all inner redirectors.\n\nStops at the first error.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming/composed.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming/composed.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3615c2d794712d1e7171cc26445b4e10809b86606346ce91ca479144aa9eeba1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cleanup\n\nDocumentation:\nCalled in order on all inner redirectors.\n\nReturns the last encountered error.\nAll errors are logged.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn cleanup(&mut self) -> Result<(), Self::Error> {\n let mut result = Ok(());\n\n for redirector in &mut self.redirectors {\n if let Err(error) = redirector.cleanup().await {\n tracing::error!(\n %error,\n ?redirector,\n \"Failed to do cleanup on a port redirector\",\n );\n\n result = Err(error);\n }\n }\n\n result\n }\n```"}], "func_name": "cleanup", "docstring": "Called in order on all inner redirectors.\n\nReturns the last encountered error.\nAll errors are logged.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming/composed.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming/composed.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9eac6e789aaab8231e7e8a6a5d649d7c06462d72aeb827f8d703ff6844730c62"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next_connection\n\nDocumentation:\nConcurrently polls all inner redirectors for the next connection.\n\nReturns the first result.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn next_connection(&mut self) -> Result {\n self.redirectors\n .iter_mut()\n .map(R::next_connection)\n .collect::>()\n .next()\n .await\n .expect(\"ComposedRedirector cannot be created with no inner redirector\")\n }\n```"}], "func_name": "next_connection", "docstring": "Concurrently polls all inner redirectors for the next connection.\n\nReturns the first result.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming/composed.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming/composed.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "edc37e5e5af71d7c56f7074701d539f3716354bbb752ef5b2feb630dcc02b006"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: steal\n\nDocumentation:\nIssues a request to start stealing from the given port.\n\nIf this port is already stolen, does nothing.\n\nIf this method returns [`Ok`], it means that the port redirection\nwas done in the [`RedirectorTask`](super::RedirectorTask),\nand incoming connections are now being stolen.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn steal(&mut self, port: u16) -> Result<(), RedirectorTaskError> {\n if self.stolen_ports.contains_key(&port) {\n return Ok(());\n };\n\n let (receiver_tx, receiver_rx) = oneshot::channel();\n if self\n .message_tx\n .send(StealRequest { port, receiver_tx })\n .await\n .is_err()\n {\n return Err(self.task_error.get().await);\n }\n\n let Ok(rx) = receiver_rx.await else {\n return Err(self.task_error.get().await);\n };\n\n self.stolen_ports\n .insert(port, StreamNotifyClose::new(ReceiverStream::new(rx)));\n\n Ok(())\n }\n```"}], "func_name": "steal", "docstring": "Issues a request to start stealing from the given port.\n\nIf this port is already stolen, does nothing.\n\nIf this method returns [`Ok`], it means that the port redirection\nwas done in the [`RedirectorTask`](super::RedirectorTask),\nand incoming connections are now being stolen.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming/steal_handle.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming/steal_handle.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "32a4107a827b60c39be76656641749d5177e003ee685b5892a36568bec7647f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next\n\nDocumentation:\nReturns the next redirected connection.\n\nReturns nothing if no port is stolen.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn next(&mut self) -> Option> {\n match self.stolen_ports.next().await? {\n (.., Some(conn)) => Some(Ok(conn)),\n (.., None) => Some(Err(self.task_error.get().await)),\n }\n }\n```"}], "func_name": "next", "docstring": "Returns the next redirected connection.\n\nReturns nothing if no port is stolen.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming/steal_handle.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming/steal_handle.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "06e9b7ca1f3188047b22eb09d1c9a9871fdf1e729f384ae918c1ba58f95c6d04"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance of this task.\n\nThe task has to be run with [`Self::run`] to start redirecting connections.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(redirector: R) -> (Self, StealHandle) {\n let (error_tx, error_rx) = oneshot::channel();\n let (message_tx, message_rx) = mpsc::channel(16);\n\n let task = Self {\n redirector,\n error_tx,\n message_rx,\n dead_channels: Default::default(),\n steals: Default::default(),\n };\n\n let task_error = TaskError(error_rx.shared());\n let steal_handle = StealHandle::new(message_tx.clone(), task_error.clone());\n\n (task, steal_handle)\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance of this task.\n\nThe task has to be run with [`Self::run`] to start redirecting connections.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming/task.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming/task.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb1566a07772bb33b8a1e0bf5b3074a673a127a0341508adbb8a4c3296a906e1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_connection\n\nDocumentation:\nHandles a redirected connection coming from [`Self::redirector`].\n\nThis function does not do any cleanup if the steal channel is closed,\nas the cleanup is handled in [`Self::handle_dead_channel`].\n\n# Unstolen connections\n\nIf the connection is not stolen, this functions simply drops it.\nIt happens when our port redirector returns a connection\nto a port that is no longer stolen.\nWe consider this to be an unlikely race condition.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_connection(&mut self, conn: Redirected) {\n let redirected = RedirectedConnection {\n source: conn.source,\n destination: conn.destination,\n stream: conn.stream,\n };\n\n let Some(steal) = self.steals.get(&redirected.destination.port()) else {\n return;\n };\n\n let _ = steal.send(redirected).await;\n }\n```"}], "func_name": "handle_connection", "docstring": "Handles a redirected connection coming from [`Self::redirector`].\n\nThis function does not do any cleanup if the steal channel is closed,\nas the cleanup is handled in [`Self::handle_dead_channel`].\n\n# Unstolen connections\n\nIf the connection is not stolen, this functions simply drops it.\nIt happens when our port redirector returns a connection\nto a port that is no longer stolen.\nWe consider this to be an unlikely race condition.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming/task.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming/task.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8785a39598077d3dc610044b7f746bfcea3d1043beb7c6a8e959ec48750d25c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_message\n\nDocumentation:\nHandles a [`StealRequest`] coming from this task's [`StealHandle`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_message(&mut self, message: StealRequest) -> Result<(), R::Error> {\n let StealRequest { port, receiver_tx } = message;\n\n let entry = self.steals.entry(port);\n\n if matches!(&entry, Entry::Occupied(e) if e.get().is_closed().not()) {\n panic!(\"detected duplicate steal port subscription for port {port}, StealHandle should not allow this\")\n }\n\n let (conn_tx, conn_rx) = mpsc::channel(32);\n\n if matches!(entry, Entry::Vacant(..)) {\n self.redirector.add_redirection(port).await?;\n }\n\n entry.insert_entry(conn_tx.clone());\n self.dead_channels.push(\n async move {\n conn_tx.closed().await;\n port\n }\n .boxed(),\n );\n\n let _ = receiver_tx.send(conn_rx);\n\n Ok(())\n }\n```"}], "func_name": "handle_message", "docstring": "Handles a [`StealRequest`] coming from this task's [`StealHandle`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming/task.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming/task.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "222a4a00026e7b6ab7edbfed631799541142a11b31371dca39b939388db9ca25"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_dead_channel\n\nDocumentation:\nCalled when this task's [`StealHandle`] drops its [`StolenConnectionsRx`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_dead_channel(&mut self, port: u16) -> Result<(), R::Error> {\n let Entry::Occupied(e) = self.steals.entry(port) else {\n panic!(\"the stolen connections sender is only removed here\");\n };\n\n if e.get().is_closed().not() {\n // The handle started a new steal and this is a different channel.\n // `DeadChannelFut` for this one was spawned in `handle_message`.\n return Ok(());\n }\n\n e.remove();\n\n self.redirector.remove_redirection(port).await?;\n if self.steals.is_empty() {\n self.redirector.cleanup().await?;\n }\n\n Ok(())\n }\n```"}], "func_name": "handle_dead_channel", "docstring": "Called when this task's [`StealHandle`] drops its [`StolenConnectionsRx`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming/task.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming/task.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b6ccf6958ed0fb9fa62ceae952ceb3a4b89475d9cb13205caffdb5a4e8b85dc8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cleanup\n\nDocumentation:\nCalled the [`StealHandle`] is dropped and this is about to exit.\n\nCleans the redirections in [`Self::redirector`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn cleanup(&mut self) -> Result<(), R::Error> {\n for port in std::mem::take(&mut self.steals).into_keys() {\n self.redirector.remove_redirection(port).await?;\n }\n\n self.redirector.cleanup().await\n }\n```"}], "func_name": "cleanup", "docstring": "Called the [`StealHandle`] is dropped and this is about to exit.\n\nCleans the redirections in [`Self::redirector`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming/task.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming/task.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e07329bf28dbc88b38d16e3276d78ca6cd222211db9b92d6a816ecf79a1b15e1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRuns this task.\n\nThis should be called only in the target's network namespace.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run(mut self) -> Result<(), RedirectorTaskError> {\n let main_result = self.run_inner().await;\n let cleanup_result = self.redirector.cleanup().await;\n\n let result = main_result\n .and(cleanup_result)\n .map_err(|error| RedirectorTaskError::RedirectorError(error.into()));\n\n if let Err(e) = result.clone() {\n let _ = self.error_tx.send(e);\n }\n\n result\n }\n```"}], "func_name": "run", "docstring": "Runs this task.\n\nThis should be called only in the target's network namespace.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming/task.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming/task.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f92ff1ccbc6ca57775988d5510ac637d0681f2402ff846279f1ce681e360eed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nResolves when an error occurs in the [`RedirectorTask`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn get(&self) -> RedirectorTaskError {\n self.0\n .clone()\n .await\n .unwrap_or(RedirectorTaskError::Panicked)\n }\n```"}], "func_name": "get", "docstring": "Resolves when an error occurs in the [`RedirectorTask`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/incoming/task.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/incoming/task.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1e54000c8a4d0dbb02ab4b3e1bf5bbe0a5576b54c25e599bab90914b181437f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: local_addr\n\nDocumentation:\nGet the local address on this socket.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn local_addr(&self) -> io::Result {\n Ok(match self {\n SocketStream::Ip(tcp_stream) => SocketAddress::Ip(tcp_stream.local_addr()?),\n SocketStream::Unix(unix_stream) => {\n let local_address = unix_stream.local_addr()?;\n SocketAddress::Unix(if local_address.is_unnamed() {\n Unnamed\n } else {\n // Unwrap: we probably don't connect from a local abstract address.\n Pathname(local_address.as_pathname().unwrap().to_owned())\n })\n }\n })\n }\n```"}], "func_name": "local_addr", "docstring": "Get the local address on this socket.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/outgoing/socket_stream.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/outgoing/socket_stream.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fb95a2ffe95edda3a931900587ee638967f2a80b23b7d83cb319913bfcff25e3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nConnect to a given [`SocketAddress`], whether IP or unix.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn connect(addr: SocketAddress, pid: Option) -> RemoteResult {\n match addr {\n SocketAddress::Ip(addr) => Ok(Self::from(TcpStream::connect(addr).await?)),\n SocketAddress::Unix(Pathname(path)) => {\n // In order to connect to a unix socket on the target pod, instead of connecting to\n // /the/target/path we connect to /proc//root/the/target/path.\n let path = if let Some(pid) = pid {\n InTargetPathResolver::new(pid).resolve(&path)?\n } else {\n path\n };\n\n Ok(Self::from(UnixStream::connect(path).await?))\n }\n SocketAddress::Unix(Abstract(bytes)) => {\n // Tokio's UnixStream does not support connecting to an abstract address so we first\n // create an std UnixStream, then we convert it to a tokio UnixStream.\n Ok(Self::from(UnixStream::from_std(\n StdUnixStream::connect_addr(\n &::from_abstract_name(bytes)?,\n )?,\n )?))\n }\n SocketAddress::Unix(Unnamed) => {\n // Cannot connect to unnamed socket by address.\n Err(ResponseError::Remote(RemoteError::InvalidAddress(addr)))\n }\n }\n }\n```"}], "func_name": "connect", "docstring": "Connect to a given [`SocketAddress`], whether IP or unix.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/outgoing/socket_stream.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/outgoing/socket_stream.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "62f370ed0613cdb2f2e466a3f3e36a55f47d1f040c94162a5e9d0be218d3a649"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new instance of this struct and connect it to a\n[`TcpConnectionSniffer`](super::TcpConnectionSniffer) instance.\n* `client_id` - id of the client using this struct\n* `sniffer_sender` - channel used to send commands to the\n[`TcpConnectionSniffer`](super::TcpConnectionSniffer)\n* `task_status` - handle to the [`TcpConnectionSniffer`](super::TcpConnectionSniffer) exit\nstatus\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn new(\n client_id: ClientId,\n sniffer_sender: Sender,\n task_status: BgTaskStatus,\n ) -> AgentResult {\n let (sender, receiver) = mpsc::channel(Self::CONNECTION_CHANNEL_SIZE);\n\n let command = SnifferCommand {\n client_id,\n command: SnifferCommandInner::NewClient(sender),\n };\n if sniffer_sender.send(command).await.is_err() {\n return Err(task_status.wait_assert_running().await);\n }\n\n Ok(Self {\n client_id,\n sender: sniffer_sender,\n receiver,\n task_status,\n connections: Default::default(),\n connection_ids_iter: (0..=ConnectionId::MAX),\n subscriptions_in_progress: Default::default(),\n })\n }\n```"}], "func_name": "new", "docstring": "Create a new instance of this struct and connect it to a\n[`TcpConnectionSniffer`](super::TcpConnectionSniffer) instance.\n* `client_id` - id of the client using this struct\n* `sniffer_sender` - channel used to send commands to the\n[`TcpConnectionSniffer`](super::TcpConnectionSniffer)\n* `task_status` - handle to the [`TcpConnectionSniffer`](super::TcpConnectionSniffer) exit\nstatus", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/sniffer/api.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/sniffer/api.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2e44cbb66438aa7c1a8d0191d3c4946bc3ab7f00f92d30337ea5014b001e7f82"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_command\n\nDocumentation:\nSend the given command to the connected\n[`TcpConnectionSniffer`](super::TcpConnectionSniffer).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn send_command(&mut self, command: SnifferCommandInner) -> AgentResult<()> {\n let command = SnifferCommand {\n client_id: self.client_id,\n command,\n };\n\n if self.sender.send(command).await.is_ok() {\n Ok(())\n } else {\n Err(self.task_status.wait_assert_running().await)\n }\n }\n```"}], "func_name": "send_command", "docstring": "Send the given command to the connected\n[`TcpConnectionSniffer`](super::TcpConnectionSniffer).", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/sniffer/api.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/sniffer/api.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f651cade56c658c50669276543ca3a10a0814cb76e4e0c25503cb7951ede2b2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: recv\n\nDocumentation:\nReturn the next message from the connected\n[`TcpConnectionSniffer`](super::TcpConnectionSniffer).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn recv(&mut self) -> AgentResult<(DaemonTcp, Option)> {\n tokio::select! {\n conn = self.receiver.recv() => match conn {\n Some(conn) => {\n let id = self.connection_ids_iter.next().ok_or(AgentError::ExhaustedConnectionId)?;\n\n self.connections.insert(id, StreamNotifyClose::new(BroadcastStream::new(conn.data)));\n\n Ok((\n DaemonTcp::NewConnectionV1(NewTcpConnectionV1 {\n connection_id: id,\n remote_address: conn.session_id.source_addr.into(),\n local_address: conn.session_id.dest_addr.into(),\n source_port: conn.session_id.source_port,\n destination_port: conn.session_id.dest_port,\n }),\n None,\n ))\n },\n\n None => {\n Err(self.task_status.wait_assert_running().await)\n },\n },\n\n Some((connection_id, bytes)) = self.connections.next() => match bytes {\n Some(Ok(bytes)) => {\n Ok((\n DaemonTcp::Data(TcpData {\n connection_id,\n bytes,\n }),\n None,\n ))\n }\n\n Some(Err(BroadcastStreamRecvError::Lagged(missed_packets))) => {\n let log = LogMessage::error(format!(\n \"failed to process on time {missed_packets} packet(s) from mirrored connection {connection_id}, closing connection\"\n ));\n\n Ok((\n DaemonTcp::Close(TcpClose { connection_id }),\n Some(log),\n ))\n }\n\n None => {\n Ok((\n DaemonTcp::Close(TcpClose { connection_id }),\n None\n ))\n }\n },\n\n Some(result) = self.subscriptions_in_progress.next() => match result {\n Ok(port) => Ok((DaemonTcp::SubscribeResult(Ok(port)), None)),\n Err(..) => {\n Err(self.task_status.wait_assert_running().await)\n }\n }\n }\n }\n```"}], "func_name": "recv", "docstring": "Return the next message from the connected\n[`TcpConnectionSniffer`](super::TcpConnectionSniffer).", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/sniffer/api.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/sniffer/api.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1e40ef9eef02c6b2ea948c9b8cf2926fb44b30f0c02c4de9de9f9116f89ecc0d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_client_message\n\nDocumentation:\nTansforms a [`LayerTcp`] message into a [`SnifferCommand`] and passes it to the connected\n[`TcpConnectionSniffer`](super::TcpConnectionSniffer).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn handle_client_message(&mut self, message: LayerTcp) -> AgentResult<()> {\n match message {\n LayerTcp::PortSubscribe(port) => {\n let (tx, rx) = oneshot::channel();\n self.send_command(SnifferCommandInner::Subscribe(port, tx))\n .await?;\n self.subscriptions_in_progress.push(rx);\n Ok(())\n }\n\n LayerTcp::PortUnsubscribe(port) => {\n self.send_command(SnifferCommandInner::UnsubscribePort(port))\n .await?;\n Ok(())\n }\n\n LayerTcp::ConnectionUnsubscribe(connection_id) => {\n self.connections.remove(&connection_id);\n Ok(())\n }\n }\n }\n```"}], "func_name": "handle_client_message", "docstring": "Tansforms a [`LayerTcp`] message into a [`SnifferCommand`] and passes it to the connected\n[`TcpConnectionSniffer`](super::TcpConnectionSniffer).", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/sniffer/api.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/sniffer/api.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "de390c23063c32627b9a9902f59ec60f3fa6a41385c2a0f7663060f75392a97c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_filter\n\nDocumentation:\nFilter is ignored, we don't want to execute BPF programs in tests.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_filter(&mut self, _filter: SocketFilterProgram) -> io::Result<()> {\n self.times_filter_changed.fetch_add(1, Ordering::Relaxed);\n\n Ok(())\n }\n```"}], "func_name": "set_filter", "docstring": "Filter is ignored, we don't want to execute BPF programs in tests.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/sniffer/tcp_capture.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/sniffer/tcp_capture.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "feb170a15425f906c59d791bd8cb2e3c337784699037248477288e6ebf71b4b2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_command\n\nDocumentation:\nSend `command` to stealer, with the client id of the client that is using this API instance.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn send_command(&mut self, command: Command) -> AgentResult<()> {\n let command = StealerCommand {\n client_id: self.client_id,\n command,\n };\n\n if self.command_tx.send(command).await.is_ok() {\n Ok(())\n } else {\n Err(self.task_status.wait_assert_running().await)\n }\n }\n```"}], "func_name": "send_command", "docstring": "Send `command` to stealer, with the client id of the client that is using this API instance.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/api.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/api.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6c7b8a0904a3fa026296f6a3ea80f92977ab9c27848f7724807f26320471ef57"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connection_unsubscribe\n\nDocumentation:\nHandles the conversion of [`LayerTcpSteal::ConnectionUnsubscribe`], that is passed from the\nagent, to an internal stealer command [`Command::ConnectionUnsubscribe`].\n\nThe actual handling of this message is done in [`TcpConnectionStealer`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn connection_unsubscribe(\n &mut self,\n connection_id: ConnectionId,\n ) -> AgentResult<()> {\n self.send_command(Command::ConnectionUnsubscribe(connection_id))\n .await\n }\n```"}], "func_name": "connection_unsubscribe", "docstring": "Handles the conversion of [`LayerTcpSteal::ConnectionUnsubscribe`], that is passed from the\nagent, to an internal stealer command [`Command::ConnectionUnsubscribe`].\n\nThe actual handling of this message is done in [`TcpConnectionStealer`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/api.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/api.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "88f464af49d732d59beaef02bece0757ada68e23fd809da18e422283ca85555a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: http_response\n\nDocumentation:\nHandles the conversion of [`LayerTcpSteal::HttpResponse`], that is passed from the\nagent, to an internal stealer command [`Command::HttpResponse`].\n\nThe actual handling of this message is done in [`TcpConnectionStealer`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn http_response(\n &mut self,\n response: HttpResponseFallback,\n ) -> AgentResult<()> {\n self.send_command(Command::HttpResponse(response)).await\n }\n```"}], "func_name": "http_response", "docstring": "Handles the conversion of [`LayerTcpSteal::HttpResponse`], that is passed from the\nagent, to an internal stealer command [`Command::HttpResponse`].\n\nThe actual handling of this message is done in [`TcpConnectionStealer`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/api.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/api.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2e5ff93063ac7c005cba22abe236515c0e3d9fb0ddf39c1f8c020689e893238a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_request_in_bg\n\nDocumentation:\nAttempts to spawn a new [`tokio::task`] to transform the given [`MatchedHttpRequest`] into\n[`DaemonTcp::HttpRequest`], [`DaemonTcp::HttpRequestFramed`] or\n[`DaemonTcp::HttpRequestChunked`] and send it via cloned [`Client::tx`].\n\nInspects [`Client::protocol_version`] to pick between [`DaemonTcp`] variants and check for\nupgrade requests.\n\n# Why in the background?\n\nThis method spawns a [`tokio::task`] to read the [`Incoming`] body of the request without\nblocking the main [`TcpConnectionStealer`] loop.\n\n# Tracing\n\nThe spawned background task calls one of `send_` helper methods.\nThese can fail only when we encounter an error while reading request body, or when the\nclient disconnects. Both cases are quite normal, so don't log errors higher than on\n[`Level::DEBUG`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn send_request_in_bg(&self, request: MatchedHttpRequest) {\n let framed = self.protocol_version.matches(&HTTP_FRAMED_VERSION);\n let chunked = self.protocol_version.matches(&HTTP_CHUNKED_REQUEST_VERSION);\n let chunked_v2 = self\n .protocol_version\n .matches(&HTTP_CHUNKED_REQUEST_V2_VERSION);\n\n let tx = self.tx.clone();\n\n tracing::trace!(\n ?request,\n client_protocol_version = ?self.protocol_version,\n \"Sending stolen request to the client\",\n );\n\n tokio::spawn(async move {\n let _ = if chunked {\n Self::send_chunked(request, chunked_v2, tx).await\n } else if framed {\n Self::send_framed(request, tx).await\n } else {\n Self::send_legacy(request, tx).await\n };\n });\n }\n```"}], "func_name": "send_request_in_bg", "docstring": "Attempts to spawn a new [`tokio::task`] to transform the given [`MatchedHttpRequest`] into\n[`DaemonTcp::HttpRequest`], [`DaemonTcp::HttpRequestFramed`] or\n[`DaemonTcp::HttpRequestChunked`] and send it via cloned [`Client::tx`].\n\nInspects [`Client::protocol_version`] to pick between [`DaemonTcp`] variants and check for\nupgrade requests.\n\n# Why in the background?\n\nThis method spawns a [`tokio::task`] to read the [`Incoming`] body of the request without\nblocking the main [`TcpConnectionStealer`] loop.\n\n# Tracing\n\nThe spawned background task calls one of `send_` helper methods.\nThese can fail only when we encounter an error while reading request body, or when the\nclient disconnects. Both cases are quite normal, so don't log errors higher than on\n[`Level::DEBUG`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connection.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connection.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "38213ef774e94930cb56598e2365798551d37d863b1b6198ee67466d7e5add05"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nInitializes a new [`TcpConnectionStealer`], but doesn't start the actual work.\nYou need to call [`TcpConnectionStealer::start`] to do so.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new(\n command_rx: Receiver,\n steal_handle: StealHandle,\n tls_handler_store: Option,\n ) -> Self {\n Self {\n port_subscriptions: PortSubscriptions::new(steal_handle, 4),\n command_rx,\n clients: HashMap::with_capacity(8),\n clients_closed: Default::default(),\n connections: StolenConnections::new(8, tls_handler_store),\n }\n }\n```"}], "func_name": "new", "docstring": "Initializes a new [`TcpConnectionStealer`], but doesn't start the actual work.\nYou need to call [`TcpConnectionStealer::start`] to do so.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connection.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connection.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00030c64d4d7ce2bec310a7a79a96ea6836d339833860c19c1940a82f425247e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: close_client\n\nDocumentation:\nRemoves the client with `client_id` from our list of clients (layers), and also removes\ntheir subscriptions from [`Self::port_subscriptions`] and all their open\nconnections.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn close_client(&mut self, client_id: ClientId) {\n self.port_subscriptions.remove_all(client_id);\n\n let client = self.clients.remove(&client_id).expect(\"client not found\");\n\n for connection in client.subscribed_connections {\n self.connections\n .send(connection, ConnectionMessageIn::Unsubscribed { client_id })\n .await;\n }\n }\n```"}], "func_name": "close_client", "docstring": "Removes the client with `client_id` from our list of clients (layers), and also removes\ntheir subscriptions from [`Self::port_subscriptions`] and all their open\nconnections.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connection.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connection.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e38ae56886de2a0f1e1cac610318974e46b7ff6aea621a434d3cd0477e710c3b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: client_id\n\nDocumentation:\nReturns [`ClientId`] of the client that triggered this message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn client_id(&self) -> ClientId {\n match self {\n Self::Raw { client_id, .. } => *client_id,\n Self::Response { client_id, .. } => *client_id,\n Self::Unsubscribed { client_id } => *client_id,\n }\n }\n```"}], "func_name": "client_id", "docstring": "Returns [`ClientId`] of the client that triggered this message.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6cb25c3e41d3c185baea8e44ff8d37ce502d4703d988658c83b30bf40a67c26f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new empty set of [`StolenConnection`]s.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(capacity: usize, tls_handler_store: Option) -> Self {\n let (main_tx, main_rx) = mpsc::channel(Self::MAIN_CHANNEL_CAPACITY);\n\n Self {\n next_connection_id: 0,\n\n connection_txs: HashMap::with_capacity(capacity),\n tasks: Default::default(),\n\n main_tx,\n main_rx,\n\n tls_handler_store,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new empty set of [`StolenConnection`]s.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a505f136be131d1921ae67bed6f937a90ea63eea793e2293456c4da1b1eee61"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait\n\nDocumentation:\nWaits for an update from one of the connection tasks in this set.\n\n# Note\n\nIf this set is empty, this method blocks forever.\n\n# Cancel Safety\n\nThis method is cancel safe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn wait(&mut self) -> ConnectionMessageOut {\n loop {\n tokio::select! {\n Some(task_res) = self.tasks.join_next() => match task_res {\n Ok(connection_id) => {\n self.connection_txs.remove(&connection_id);\n },\n\n Err(error) => {\n tracing::error!(?error, \"Failed to join connection task\");\n },\n },\n\n message = self.main_rx.recv() => break message.expect(\"this channel is never closed\"),\n }\n }\n }\n```"}], "func_name": "wait", "docstring": "Waits for an update from one of the connection tasks in this set.\n\n# Note\n\nIf this set is empty, this method blocks forever.\n\n# Cancel Safety\n\nThis method is cancel safe.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9f390519d7e0ce5227dacf18cb0323bb18c0f91ad4b6041449fce786e6f50de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRuns this task until the connection is closed.\n\n# Note\n\nThis task is responsible for **always** sending [`ConnectionMessageOut::Closed`] to\ninterested stealer clients, even when an error has occurred.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run(mut self) -> Result<(), ConnectionTaskError> {\n let StolenConnection {\n connection,\n port_subscription,\n } = self.connection;\n\n let mut destination = connection.destination();\n let localhost = if destination.is_ipv6() {\n IpAddr::V6(Ipv6Addr::LOCALHOST)\n } else {\n IpAddr::V4(Ipv4Addr::LOCALHOST)\n };\n // If we use the original IP we would go through prerouting and hit a loop.\n // localhost should always work.\n destination.set_ip(localhost);\n\n let source = connection.source();\n\n let filters = match port_subscription {\n PortSubscription::Unfiltered(client_id) => {\n self.tx\n .send(ConnectionMessageOut::SubscribedTcp {\n client_id,\n connection: NewTcpConnectionV1 {\n connection_id: self.connection_id,\n remote_address: source.ip(),\n source_port: source.port(),\n destination_port: destination.port(),\n local_address: connection.local_addr()?.ip(),\n },\n })\n .await?;\n\n return UnfilteredStealTask::new(self.connection_id, client_id, connection)\n .run(self.tx, &mut self.rx)\n .await;\n }\n\n PortSubscription::Filtered(filters) => filters,\n };\n\n let tls_handler = match self.tls_handler_store {\n Some(store) => store.get(destination.port()).await?,\n None => None,\n };\n\n let Some(tls_handler) = tls_handler else {\n let (mut stream, http_version) =\n detect_http_version(connection, Self::HTTP_DETECTION_TIMEOUT).await?;\n\n let Some(http_version) = http_version else {\n tracing::trace!(\"No HTTP version detected, proxying the connection transparently\");\n\n let mut outgoing_io = TcpStream::connect(destination).await?;\n tokio::io::copy_bidirectional(&mut stream, &mut outgoing_io).await?;\n\n return Ok(());\n };\n\n tracing::trace!(?http_version, \"Detected HTTP version\");\n\n let task = FilteredStealTask::new(\n self.connection_id,\n filters,\n OriginalDestination::new(destination, None),\n source,\n http_version,\n stream,\n );\n\n return task.run(self.tx.clone(), &mut self.rx).await;\n };\n\n let mut tls_stream = tls_handler\n .acceptor()\n .accept(connection)\n .await\n .map(Box::new)?; // size of `TlsStream` exceeds 1kb, let's box it\n\n let http_version = match tls_stream.get_ref().1.alpn_protocol() {\n Some(tls::HTTP_2_ALPN_NAME) => {\n tracing::debug!(\n original_destination = %destination,\n \"Stolen TLS connection was upgraded to HTTP/2 with ALPN\"\n );\n\n HttpVersion::V2\n }\n Some(tls::HTTP_1_1_ALPN_NAME) => {\n tracing::debug!(\n original_destination = %destination,\n \"Stolen TLS connection was upgraded to HTTP/1.1 with ALPN\"\n );\n\n HttpVersion::V1\n }\n Some(tls::HTTP_1_0_ALPN_NAME) => {\n tracing::debug!(\n original_destination = %destination,\n \"Stolen TLS connection was upgraded to HTTP/1.0 with ALPN\"\n );\n\n HttpVersion::V1\n }\n Some(other) => {\n tracing::info!(\n protocol = %String::from_utf8_lossy(other),\n original_destination = %destination,\n \"Stolen TLS connection was upgraded with ALPN to a non-HTTP protocol. \\\n Proxying data to the original destination.\",\n );\n\n let outgoing_io = TcpStream::connect(destination).await?;\n let connector = tls_handler.connector(tls_stream.get_ref().1);\n let mut outgoing_io = connector\n .connect(destination.ip(), None, outgoing_io)\n .await?;\n\n tokio::io::copy_bidirectional(&mut tls_stream, &mut outgoing_io).await?;\n\n return Ok(());\n }\n None => {\n let (mut stream, http_version) =\n detect_http_version(tls_stream, Self::HTTP_DETECTION_TIMEOUT).await?;\n\n let Some(http_version) = http_version else {\n tracing::trace!(\n \"No HTTP version detected, proxying the connection transparently\"\n );\n\n let outgoing_io = TcpStream::connect(destination).await?;\n let connector = tls_handler.connector(stream.inner().get_ref().1);\n let mut outgoing_io = connector\n .connect(destination.ip(), None, outgoing_io)\n .await?;\n\n tokio::io::copy_bidirectional(&mut stream, &mut outgoing_io).await?;\n\n return Ok(());\n };\n\n let connector = tls_handler.connector(stream.inner().get_ref().1);\n let task = FilteredStealTask::new(\n self.connection_id,\n filters,\n OriginalDestination::new(destination, Some(connector)),\n source,\n http_version,\n stream,\n );\n\n return task.run(self.tx.clone(), &mut self.rx).await;\n }\n };\n\n let connector = tls_handler.connector(tls_stream.get_ref().1);\n let task = FilteredStealTask::new(\n self.connection_id,\n filters,\n OriginalDestination::new(destination, Some(connector)),\n source,\n http_version,\n tls_stream,\n );\n\n return task.run(self.tx.clone(), &mut self.rx).await;\n }\n```"}], "func_name": "run", "docstring": "Runs this task until the connection is closed.\n\n# Note\n\nThis task is responsible for **always** sending [`ConnectionMessageOut::Closed`] to\ninterested stealer clients, even when an error has occurred.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b8ba6f68c33a0900f502dbf055f03afc25f9914c4e14caf3dcab339b2ec39af9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate an empty instance of this struct.\n\n# Params\n\n* `handle` - will be used to enforce connection stealing according to the state of this set.\n* `initial_capacity` - initial capacity for the inner (port -> subscription) mapping.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(handle: StealHandle, initial_capacity: usize) -> Self {\n Self {\n handle,\n subscriptions: HashMap::with_capacity(initial_capacity),\n }\n }\n```"}], "func_name": "new", "docstring": "Create an empty instance of this struct.\n\n# Params\n\n* `handle` - will be used to enforce connection stealing according to the state of this set.\n* `initial_capacity` - initial capacity for the inner (port -> subscription) mapping.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "de71facd11d3ddf8883b91398238b0de00a3e6bb09317b5dfbcded61f39f7e5a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add\n\nDocumentation:\nTry adding a new subscription to this set.\n\n# Subscription clash rules\n\n* A single client may have only one subscription for the given port\n* A single port may have only one unfiltered subscription\n\n# Params\n\n* `client_id` - identifier of the client that issued the subscription\n* `port` - number of the port to steal from\n* `client_protocol_version` - version of client's [`mirrord_protocol`], [`None`] if the\nversion has not been negotiated yet\n* `filter` - optional [`HttpFilter`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn add(\n &mut self,\n client_id: ClientId,\n port: Port,\n client_protocol_version: ClientProtocolVersion,\n filter: Option,\n ) -> Result, RedirectorTaskError> {\n let filtered = filter.is_some();\n\n match self.subscriptions.entry(port) {\n Entry::Occupied(mut e) => {\n if e.get_mut()\n .try_extend(client_id, client_protocol_version, filter)\n .not()\n {\n return Ok(Err(ResponseError::PortAlreadyStolen(port)));\n }\n }\n\n Entry::Vacant(e) => {\n self.handle.steal(port).await?;\n\n e.insert(PortSubscription::new(\n client_id,\n client_protocol_version,\n filter,\n ));\n }\n };\n\n if filtered {\n STEAL_FILTERED_PORT_SUBSCRIPTION.fetch_add(1, Ordering::Relaxed);\n } else {\n STEAL_UNFILTERED_PORT_SUBSCRIPTION.fetch_add(1, Ordering::Relaxed);\n }\n\n Ok(Ok(port))\n }\n```"}], "func_name": "add", "docstring": "Try adding a new subscription to this set.\n\n# Subscription clash rules\n\n* A single client may have only one subscription for the given port\n* A single port may have only one unfiltered subscription\n\n# Params\n\n* `client_id` - identifier of the client that issued the subscription\n* `port` - number of the port to steal from\n* `client_protocol_version` - version of client's [`mirrord_protocol`], [`None`] if the\nversion has not been negotiated yet\n* `filter` - optional [`HttpFilter`]", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3e4901dd35c587857493dfb99067d6b0f45cb36e2263190120679b32f9394e04"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove\n\nDocumentation:\nRemove a subscription from this set, if it exists.\n\n# Params\n\n* `client_id` - identifier of the client that issued the subscription\n* `port` - number of the subscription port\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn remove(&mut self, client_id: ClientId, port: Port) {\n let Entry::Occupied(mut e) = self.subscriptions.entry(port) else {\n return;\n };\n\n match e.get_mut() {\n PortSubscription::Unfiltered(subscribed_client) if *subscribed_client == client_id => {\n e.remove();\n STEAL_UNFILTERED_PORT_SUBSCRIPTION\n .fetch_sub(1, std::sync::atomic::Ordering::Relaxed);\n\n self.handle.stop_steal(port);\n }\n PortSubscription::Unfiltered(..) => {}\n PortSubscription::Filtered(filters) => {\n if filters.remove(&client_id).is_some() {\n STEAL_FILTERED_PORT_SUBSCRIPTION\n .fetch_sub(1, std::sync::atomic::Ordering::Relaxed);\n }\n\n if filters.is_empty() {\n e.remove();\n self.handle.stop_steal(port);\n }\n }\n }\n }\n```"}], "func_name": "remove", "docstring": "Remove a subscription from this set, if it exists.\n\n# Params\n\n* `client_id` - identifier of the client that issued the subscription\n* `port` - number of the subscription port", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "698b7dfe832093de1ffa848ca5b92ae84f2507cea042bafa2252a3f7977f5e89"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_all\n\nDocumentation:\nRemove all client subscriptions from this set.\n\n# Params\n\n* `client_id` - identifier of the client that issued the subscriptions\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn remove_all(&mut self, client_id: ClientId) {\n self.subscriptions\n .retain(|port, subscription| match subscription {\n PortSubscription::Unfiltered(subscribed_client)\n if *subscribed_client == client_id =>\n {\n STEAL_UNFILTERED_PORT_SUBSCRIPTION\n .fetch_sub(1, std::sync::atomic::Ordering::Relaxed);\n\n self.handle.stop_steal(*port);\n\n false\n }\n PortSubscription::Unfiltered(..) => true,\n PortSubscription::Filtered(filters) => {\n if filters.remove(&client_id).is_some() {\n STEAL_FILTERED_PORT_SUBSCRIPTION\n .fetch_sub(1, std::sync::atomic::Ordering::Relaxed);\n }\n\n if filters.is_empty() {\n self.handle.stop_steal(*port);\n }\n\n filters.is_empty().not()\n }\n });\n }\n```"}], "func_name": "remove_all", "docstring": "Remove all client subscriptions from this set.\n\n# Params\n\n* `client_id` - identifier of the client that issued the subscriptions", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "23dd750b8de7cd607bbfd3e292fac1fe88499cbd8964e9537ccf8df61c716ed8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next_connection\n\nDocumentation:\nWait until there's a new redirected connection.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn next_connection(\n &mut self,\n ) -> Result<(RedirectedConnection, PortSubscription), RedirectorTaskError> {\n loop {\n let conn = self.handle.next().await.transpose()?;\n\n let Some(conn) = conn else {\n break std::future::pending().await;\n };\n\n if let Some(subscription) = self.subscriptions.get(&conn.destination().port()) {\n break Ok((conn, subscription.clone()));\n }\n }\n }\n```"}], "func_name": "next_connection", "docstring": "Wait until there's a new redirected connection.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d6885d30edc64f71f4dd380ca2a8860331ff501866e86180814c20cc50520b3d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new instance. Variant is picked based on the optional `filter`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(\n client_id: ClientId,\n client_protocol_version: ClientProtocolVersion,\n filter: Option,\n ) -> Self {\n match filter {\n Some(filter) => Self::Filtered(Arc::new(DashMap::from_iter([(\n client_id,\n (filter, client_protocol_version),\n )]))),\n None => Self::Unfiltered(client_id),\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new instance. Variant is picked based on the optional `filter`.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c6fee124933dc72d22f07cf1c15d8c5a58ddab2f62e5cad165fd3b461d7de5b8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_extend\n\nDocumentation:\nTry extending this subscription with a new subscription request.\nReturn whether extension was successful.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn try_extend(\n &mut self,\n client_id: ClientId,\n client_protocol_version: ClientProtocolVersion,\n filter: Option,\n ) -> bool {\n match (self, filter) {\n (_, None) => false,\n\n (Self::Unfiltered(..), _) => false,\n\n (Self::Filtered(filters), Some(filter)) => match filters.entry(client_id) {\n DashMapEntry::Occupied(..) => false,\n DashMapEntry::Vacant(e) => {\n e.insert((filter, client_protocol_version));\n true\n }\n },\n }\n }\n```"}], "func_name": "try_extend", "docstring": "Try extending this subscription with a new subscription request.\nReturn whether extension was successful.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5caf743b918669f3552c8fb092b4431f82fe7b133ecd6a6ab3fbf61b431e4ccf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_client\n\nDocumentation:\nReturn whether this subscription belongs (possibly partially) to the given client.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn has_client(&self, client_id: ClientId) -> bool {\n match self {\n Self::Filtered(filters) => filters.contains_key(&client_id),\n Self::Unfiltered(subscribed_client) => *subscribed_client == client_id,\n }\n }\n```"}], "func_name": "has_client", "docstring": "Return whether this subscription belongs (possibly partially) to the given client.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f71a99bb2cdf62ab4a885fc8a5f0d448337f713e0af6cfc7ecd6bfbbf00f9dd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bad_gateway\n\nDocumentation:\nProduces a new [`StatusCode::BAD_GATEWAY`] [`Response`] with the given [`Version`] and the\ngiven `error` in body.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn bad_gateway(version: Version, error: FilteringServiceError) -> Response {\n let error = Report::new(error).pretty(true);\n let body = format!(\"mirrord-agent: {error}\\n\");\n\n Response::builder()\n .status(StatusCode::BAD_GATEWAY)\n .version(version)\n .body(BoxBody::new(body.map_err(|_| unreachable!())))\n .expect(\"creating an empty response should not fail\")\n }\n```"}], "func_name": "bad_gateway", "docstring": "Produces a new [`StatusCode::BAD_GATEWAY`] [`Response`] with the given [`Version`] and the\ngiven `error` in body.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/filtered.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/filtered.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a86a8cfbe2c3846861ea401cf2636c6ac33dd63579190cc984e294fc8c08f1aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_protocol_switch\n\nDocumentation:\nChecks whether the given [`Response`] is [`StatusCode::SWITCHING_PROTOCOLS`].\nIf this is the case, spawns new [`tokio::task`] to await on the given [`OnUpgrade`].\nAssumes that the [`Response`] comes from the stealer client given as `from_client`\nand the given `on_upgrade` comes from the original [`Request`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn check_protocol_switch(\n &self,\n response: &Response,\n on_upgrade: OnUpgrade,\n from_client: ClientId,\n ) {\n if response.status() == StatusCode::SWITCHING_PROTOCOLS {\n let upgrade_tx = self.upgrade_tx.clone();\n\n task::spawn(async move {\n let Ok(upgraded) = on_upgrade.await.inspect_err(|error| {\n tracing::trace!(?error, client_id = from_client, \"HTTP upgrade failed\")\n }) else {\n return;\n };\n\n let res = upgrade_tx\n .send(UpgradedConnection {\n http_client_io: upgraded,\n http_server_io: UpgradedServerSide::MatchedClient(from_client),\n })\n .await;\n\n if res.is_err() {\n tracing::trace!(\n client_id = from_client,\n \"HTTP upgrade lost - channel closed\"\n );\n }\n });\n }\n }\n```"}], "func_name": "check_protocol_switch", "docstring": "Checks whether the given [`Response`] is [`StatusCode::SWITCHING_PROTOCOLS`].\nIf this is the case, spawns new [`tokio::task`] to await on the given [`OnUpgrade`].\nAssumes that the [`Response`] comes from the stealer client given as `from_client`\nand the given `on_upgrade` comes from the original [`Request`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/filtered.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/filtered.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ddf21b52b7f19f15d25a45e4fcb318cabb849a69b8f5ec083dddad4118d7e4ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_request\n\nDocumentation:\nExtracts [`OnUpgrade`] from the given [`Request`] and sends it to [`FilteredStealTask`].\nWaits on a dynamically created [`oneshot::channel`] for [`RequestHandling`] instruction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_request(\n &self,\n mut request: Request,\n ) -> Result, ConnectionTaskError> {\n let version = request.version();\n let on_upgrade = hyper::upgrade::on(&mut request);\n\n let (response_tx, response_rx) = oneshot::channel();\n self.requests_tx\n .send(ExtractedRequest {\n request,\n response_tx,\n })\n .await?;\n\n let response = match response_rx.await {\n Ok(RequestHandling::LetThrough { unchanged }) => {\n self.let_through(unchanged, on_upgrade).await\n }\n Ok(RequestHandling::RespondWith {\n response,\n for_client,\n }) => {\n self.check_protocol_switch(&response, on_upgrade, for_client)\n .await;\n response\n }\n Err(..) => Self::bad_gateway(version, FilteringServiceError::ClientResponse),\n };\n\n Ok(response)\n }\n```"}], "func_name": "handle_request", "docstring": "Extracts [`OnUpgrade`] from the given [`Request`] and sends it to [`FilteredStealTask`].\nWaits on a dynamically created [`oneshot::channel`] for [`RequestHandling`] instruction.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/filtered.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/filtered.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2d76bcb03771d26fbf71e52280a7537d4c25b4ab9c117779a1326f280a95ea92"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_after_http_ends\n\nDocumentation:\nRuns this task after the HTTP connection was closed or upgraded.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_after_http_ends(\n &mut self,\n mut queued_raw_data: HashMap>>,\n tx: Sender,\n rx: &mut Receiver,\n ) -> Result<(), ConnectionTaskError> {\n let (task_handle, _drop_guard) = self\n .hyper_conn_task\n .take()\n .expect(\"task handle is consumed only here\");\n\n let Some(upgraded) = task_handle\n .await\n .map_err(|_| ConnectionTaskError::HttpConnectionTaskPanicked)?\n else {\n return Ok(());\n };\n\n let parts = upgraded\n .http_client_io\n .downcast::>()\n .expect(\"IO type is known\");\n let mut http_client_io = parts.io.into_inner();\n let http_client_read_buf = parts.read_buf;\n\n match upgraded.http_server_io {\n // Connection was upgraded and some HTTP filter matched the upgrade request.\n UpgradedServerSide::MatchedClient(client_id) => {\n tracing::trace!(\n connection_id = self.connection_id,\n client_id,\n \"HTTP connection upgraded for client\",\n );\n\n for data in queued_raw_data.remove(&client_id).unwrap_or_default() {\n if data.is_empty() {\n http_client_io.shutdown().await?;\n } else {\n http_client_io.write_all(&data).await?;\n }\n }\n\n for (id, subscribed) in self.subscribed.iter_mut() {\n if *subscribed && *id != client_id {\n tx.send(ConnectionMessageOut::Closed {\n client_id: *id,\n connection_id: self.connection_id,\n })\n .await?;\n\n *subscribed = false;\n }\n }\n\n if self.subscribed.remove(&client_id) != Some(true) {\n return Ok(());\n }\n\n if !http_client_read_buf.is_empty() {\n tx.send(ConnectionMessageOut::Raw {\n client_id,\n connection_id: self.connection_id,\n data: http_client_read_buf.into(),\n })\n .await?;\n }\n\n UnfilteredStealTask {\n connection_id: self.connection_id,\n client_id,\n stream: http_client_io,\n }\n .run(tx, rx)\n .await\n }\n\n // Connection was upgraded and no HTTP filter matched the upgrade request.\n UpgradedServerSide::OriginalDestination(upgraded) => {\n tracing::trace!(\n connection_id = self.connection_id,\n \"HTTP connection upgraded for original destination\",\n );\n\n for (client_id, subscribed) in self.subscribed.iter_mut() {\n if *subscribed {\n tx.send(ConnectionMessageOut::Closed {\n connection_id: self.connection_id,\n client_id: *client_id,\n })\n .await?;\n\n *subscribed = false;\n }\n }\n\n let parts = upgraded\n .downcast::>()\n .expect(\"IO type is known\");\n let mut http_server_io = parts.io.into_inner();\n let http_server_read_buf = parts.read_buf;\n\n tokio::try_join!(\n async {\n if http_client_read_buf.is_empty() {\n return Ok(());\n }\n\n http_server_io.write_all(&http_client_read_buf).await\n },\n async {\n if http_server_read_buf.is_empty() {\n return Ok(());\n }\n\n http_client_io.write_all(&http_server_read_buf).await\n },\n )?;\n\n tokio::io::copy_bidirectional(&mut http_client_io, &mut http_server_io).await?;\n\n Ok(())\n }\n }\n }\n```"}], "func_name": "run_after_http_ends", "docstring": "Runs this task after the HTTP connection was closed or upgraded.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/filtered.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/filtered.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "384ad5f0bb1b181781b8893abdccc0bd631a3037fd536dff2a19bd3f2fd011fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRuns this task until the connection is closed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run(\n mut self,\n tx: Sender,\n rx: &mut Receiver,\n ) -> Result<(), ConnectionTaskError> {\n let res = self.run_until_http_ends(tx.clone(), rx).await;\n\n STEAL_UNFILTERED_CONNECTION_SUBSCRIPTION.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);\n self.metrics_updated = true;\n\n let res = match res {\n Ok(data) => self.run_after_http_ends(data, tx.clone(), rx).await,\n Err(e) => Err(e),\n };\n\n for (client_id, subscribed) in self.subscribed.iter() {\n if *subscribed {\n tx.send(ConnectionMessageOut::Closed {\n client_id: *client_id,\n connection_id: self.connection_id,\n })\n .await?;\n }\n }\n\n res\n }\n```"}], "func_name": "run", "docstring": "Runs this task until the connection is closed.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/filtered.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/filtered.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f8d53e94512c748745fe2d2865e3f41c1fa7f0c0267055630bd59bd3c192f1d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_request\n\nDocumentation:\nRequest handler of the original HTTP server.\nResponds with [`StatusCode::BAD_REQUEST`] to anything that is not a valid\n[`Self::TEST_PROTO`] upgrade request. Allows the connection to\n[`Self::TEST_PROTO`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_request(\n request: Request,\n ) -> hyper::Result> {\n let mut response = Response::new(Empty::new().map_err(|_| unreachable!()).boxed());\n *response.version_mut() = request.version();\n\n let contains_expected_upgrade = request\n .headers()\n .get(UPGRADE)\n .filter(|proto| *proto == Self::TEST_PROTO)\n .is_some()\n && request\n .headers()\n .get(CONNECTION)\n .filter(|value| *value == \"upgrade\")\n .is_some();\n\n if !contains_expected_upgrade {\n *response.status_mut() = StatusCode::BAD_REQUEST;\n return Ok(response);\n }\n\n task::spawn(async move {\n let upgraded = hyper::upgrade::on(request).await.unwrap();\n let parts = upgraded.downcast::>().unwrap();\n let mut stream = parts.io.into_inner();\n\n stream.write_all(b\"hello\").await.unwrap();\n if !parts.read_buf.is_empty() {\n stream.write_all(&parts.read_buf).await.unwrap();\n }\n stream.flush().await.unwrap();\n\n let mut buffer = BytesMut::with_capacity(4096);\n\n loop {\n stream.read_buf(&mut buffer).await.unwrap();\n if buffer.is_empty() {\n break;\n }\n stream.write_all(&buffer).await.unwrap();\n stream.flush().await.unwrap();\n buffer.clear();\n }\n });\n\n *response.status_mut() = StatusCode::SWITCHING_PROTOCOLS;\n response\n .headers_mut()\n .insert(UPGRADE, HeaderValue::from_static(Self::TEST_PROTO));\n response\n .headers_mut()\n .insert(CONNECTION, HeaderValue::from_static(\"upgrade\"));\n\n Ok(response)\n }\n```"}], "func_name": "handle_request", "docstring": "Request handler of the original HTTP server.\nResponds with [`StatusCode::BAD_REQUEST`] to anything that is not a valid\n[`Self::TEST_PROTO`] upgrade request. Allows the connection to\n[`Self::TEST_PROTO`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/filtered.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/filtered.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea6a6e6019100603199df9892eae3374dc3b509e9b4e9e1e785a382dd56041f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance of this struct.\nSpawns an HTTP server using [`Self::handle_request`], spawns [`FilteredStealTask`],\nprepares connections.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn new() -> Self {\n let mut tasks = JoinSet::new();\n\n let original_listener = TcpListener::bind(\"127.0.0.1:0\").await.unwrap();\n let original_address = original_listener.local_addr().unwrap();\n let original_server_token = CancellationToken::new();\n let token_clone = original_server_token.clone();\n\n let (server_stream, peer_address, client_stream) = {\n let stealing_listener = TcpListener::bind(\"127.0.0.1:0\").await.unwrap();\n let ((server_stream, peer_address), client_stream) = tokio::try_join!(\n stealing_listener.accept(),\n TcpStream::connect(stealing_listener.local_addr().unwrap()),\n )\n .unwrap();\n\n (server_stream, peer_address, client_stream)\n };\n\n tasks.spawn(async move {\n let mut tasks = JoinSet::new();\n\n loop {\n tokio::select! {\n accept = original_listener.accept() => {\n let (stream, _) = accept.unwrap();\n let conn = hyper::server::conn::http1::Builder::new()\n .serve_connection(TokioIo::new(stream), service_fn(Self::handle_request)).with_upgrades();\n\n tasks.spawn(async move {\n conn\n .await\n .unwrap();\n });\n },\n\n Some(res) = tasks.join_next() => res.unwrap(),\n\n _ = token_clone.cancelled() => break,\n }\n }\n\n tasks.shutdown().await;\n });\n\n let filters: Filters = Default::default();\n let filters_clone = filters.clone();\n\n let (in_tx, mut in_rx) = mpsc::channel(8);\n let (out_tx, out_rx) = mpsc::channel(8);\n\n tasks.spawn(async move {\n let task = FilteredStealTask::new(\n Self::CONNECTION_ID,\n filters_clone,\n OriginalDestination::new(original_address, None),\n peer_address,\n HttpVersion::V1,\n server_stream,\n );\n\n task.run(out_tx, &mut in_rx).await.unwrap();\n });\n\n let (request_sender, conn) = hyper::client::conn::http1::handshake::<_, DynamicBody>(\n TokioIo::new(client_stream),\n )\n .await\n .unwrap();\n\n tasks.spawn(async move {\n conn.with_upgrades().await.unwrap();\n });\n\n TestSetup {\n filters,\n original_address,\n request_sender,\n task_in_tx: in_tx,\n task_out_rx: out_rx,\n tasks,\n original_server_token,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance of this struct.\nSpawns an HTTP server using [`Self::handle_request`], spawns [`FilteredStealTask`],\nprepares connections.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/filtered.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/filtered.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b38cc4e7e52070bf698f0c9b11487965c2d81936cc38d4e979a0d9c44de45385"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prepare_request\n\nDocumentation:\nPrepares a new [`Request`] to be sent via [`Self::request_sender`].\n\n# Params\n\n1. `client_id` - If this is set to [`Some`] value, the request will contain a header\nsuch that the [`FilteredStealTask`] will steal the request for the client.\n2. `is_upgrade` - If `false`, an ordinary `GET` request will be produced. If `true`, a\n[`Self::TEST_PROTO`] upgrade request will be produced.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn prepare_request(\n &self,\n client_id: Option,\n is_upgrade: bool,\n ) -> Request {\n let mut builder = Request::builder().method(Method::GET).uri(if is_upgrade {\n \"testproto://www.some-server.com\"\n } else {\n \"http://www.some-server.com\"\n });\n\n if let Some(client_id) = client_id {\n builder = builder.header(\"x-client\", &client_id.to_string());\n self.filters.insert(\n client_id,\n (\n HttpFilter::Header(format!(\"x-client: {client_id}\").parse().unwrap()),\n \"1.19.0\".parse().unwrap(),\n ),\n );\n }\n\n if is_upgrade {\n builder = builder\n .header(UPGRADE, Self::TEST_PROTO)\n .header(CONNECTION, \"upgrade\");\n }\n\n builder\n .body(Empty::new().map_err(|_| unreachable!()).boxed())\n .unwrap()\n }\n```"}], "func_name": "prepare_request", "docstring": "Prepares a new [`Request`] to be sent via [`Self::request_sender`].\n\n# Params\n\n1. `client_id` - If this is set to [`Some`] value, the request will contain a header\nsuch that the [`FilteredStealTask`] will steal the request for the client.\n2. `is_upgrade` - If `false`, an ordinary `GET` request will be produced. If `true`, a\n[`Self::TEST_PROTO`] upgrade request will be produced.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/filtered.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/filtered.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea456cffaa2adcb6856ef9038ff6cc49fbf4c42bfb566a5ac4845502ef258a79"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prepare_request_for_multiple\n\nDocumentation:\nPrepares a new [`Request`] to be sent via [`Self::request_sender`]. Inserts the same\nheader filter for multiple clients.\n\n# Params\n\n1. `client_ids` - For each client_id, insert a header filter. The request will contain a\ncorresponding header such that the [`FilteredStealTask`] will steal it.\n2. `is_upgrade` - If `false`, an ordinary `GET` request will be produced. If `true`, a\n[`Self::TEST_PROTO`] upgrade request will be produced.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn prepare_request_for_multiple(\n &self,\n clients: &[ClientInfo],\n is_upgrade: bool,\n ) -> Request {\n for client in clients {\n let filter = (\n HttpFilter::Header(\"x-subscription: ABCD\".parse().unwrap()),\n client\n .version\n .map(|v| v.parse().unwrap())\n .unwrap_or_default(),\n );\n self.filters.insert(client.id, filter);\n }\n\n let mut builder = Request::builder()\n .method(Method::GET)\n .uri(if is_upgrade {\n \"testproto://www.some-server.com\"\n } else {\n \"http://www.some-server.com\"\n })\n .header(\"x-subscription\", \"ABCD\".to_string());\n\n if is_upgrade {\n builder = builder\n .header(UPGRADE, Self::TEST_PROTO)\n .header(CONNECTION, \"upgrade\");\n }\n\n builder\n .body(Empty::new().map_err(|_| unreachable!()).boxed())\n .unwrap()\n }\n```"}], "func_name": "prepare_request_for_multiple", "docstring": "Prepares a new [`Request`] to be sent via [`Self::request_sender`]. Inserts the same\nheader filter for multiple clients.\n\n# Params\n\n1. `client_ids` - For each client_id, insert a header filter. The request will contain a\ncorresponding header such that the [`FilteredStealTask`] will steal it.\n2. `is_upgrade` - If `false`, an ordinary `GET` request will be produced. If `true`, a\n[`Self::TEST_PROTO`] upgrade request will be produced.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/filtered.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/filtered.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81627d01ad2d1e42e29c8404daf9b221b8666f6ed13742eb3718968d75317c21"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shutdown\n\nDocumentation:\n1. Closes the stolen connection and the original HTTP server.\n2. Waits until [`FilteredStealTask`] finishes.\n3. Checks results of the background tasks.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn shutdown(mut self) -> Receiver {\n std::mem::drop(self.request_sender);\n self.task_in_tx.closed().await;\n self.original_server_token.cancel();\n\n while let Some(task_result) = self.tasks.join_next().await {\n task_result.unwrap();\n }\n\n self.task_out_rx\n }\n```"}], "func_name": "shutdown", "docstring": "1. Closes the stolen connection and the original HTTP server.\n2. Waits until [`FilteredStealTask`] finishes.\n3. Checks results of the background tasks.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/filtered.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/filtered.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "088f5efcd7e254b8604b711232a8675e8265d8de9f5c9d97b65c90fadd5eff6a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_request\n\nDocumentation:\nRequest handler for the original HTTPS server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_request(\n mut request: hyper::Request,\n ) -> hyper::Result> {\n while let Some(frame) = request.body_mut().frame().await {\n frame?;\n }\n\n let mut response = Response::new(Empty::new().map_err(|_| unreachable!()).boxed());\n *response.version_mut() = request.version();\n *response.status_mut() = StatusCode::OK;\n\n Ok(response)\n }\n```"}], "func_name": "handle_request", "docstring": "Request handler for the original HTTPS server.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/filtered.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/filtered.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ebaec15831066eb62cf29421717e6feea6f83a7096bf5d344412532ff744e693"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance.\n\n# Params\n\n* `address` - address of the HTTP server.\n* `connector` - optional TLS connector. If given, it means that the original HTTP connection\nwas wrapped in TLS. We should pass the requests with TLS as well.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(address: SocketAddr, connector: Option) -> Self {\n Self { address, connector }\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance.\n\n# Params\n\n* `address` - address of the HTTP server.\n* `connector` - optional TLS connector. If given, it means that the original HTTP connection\nwas wrapped in TLS. We should pass the requests with TLS as well.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/original_destination.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/original_destination.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d713db0dc012641f63fcdc08e79f0a82f71fd24e8f676942359130778940f2b7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nMakes a connection to the server.\n\nGiven [`Uri`] will be used in case we need a TLS connection and we don't have the original\nSNI (we need some server name to connect with TLS).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn connect(&self, request_uri: &Uri) -> Result {\n let stream = TcpStream::connect(self.address).await?;\n\n match self.connector.as_ref() {\n Some(connector) => {\n let stream = connector\n .connect(self.address.ip(), Some(request_uri), stream)\n .await?;\n Ok(MaybeTls::Tls(stream))\n }\n None => Ok(MaybeTls::NoTls(stream)),\n }\n }\n```"}], "func_name": "connect", "docstring": "Makes a connection to the server.\n\nGiven [`Uri`] will be used in case we need a TLS connection and we don't have the original\nSNI (we need some server name to connect with TLS).", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/original_destination.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/original_destination.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad0bf8ffea161ff3a217814988f008fb683db8fd7aad3ce0832107448ee69611"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRuns this task until the managed connection is closed.\n\n# Note\n\nDoes not send [`ConnectionMessageOut::SubscribedTcp`], assuming that this message has\nalready been sent to the client. This allows this code to be used for both unfiltered\nand upgraded connections.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run(\n mut self,\n tx: Sender,\n rx: &mut Receiver,\n ) -> Result<(), ConnectionTaskError> {\n let mut buf = BytesMut::with_capacity(64 * 1024);\n let mut reading_closed = false;\n\n loop {\n tokio::select! {\n read = self.stream.read_buf(&mut buf), if !reading_closed => match read {\n Ok(..) => {\n if buf.is_empty() {\n STEAL_UNFILTERED_CONNECTION_SUBSCRIPTION.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);\n\n tracing::trace!(\n client_id = self.client_id,\n connection_id = self.connection_id,\n \"Connection shutdown, sending 0-sized read to the client\",\n );\n\n reading_closed = true;\n }\n\n let message = ConnectionMessageOut::Raw {\n client_id: self.client_id,\n connection_id: self.connection_id,\n data: buf.to_vec(),\n };\n\n tx.send(message).await?;\n\n buf.clear();\n }\n\n Err(e) if e.kind() == ErrorKind::WouldBlock => {}\n\n Err(e) => {\n STEAL_UNFILTERED_CONNECTION_SUBSCRIPTION.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);\n\n tx.send(ConnectionMessageOut::Closed {\n client_id: self.client_id,\n connection_id: self.connection_id\n }).await?;\n\n break Err(e.into());\n }\n\n },\n\n message = rx.recv() => match message.ok_or(ConnectionTaskError::RecvError)? {\n message if message.client_id() != self.client_id => {\n tracing::error!(\n client_id = message.client_id(),\n expected_client_id = self.client_id,\n connection_id = self.connection_id,\n \"Received message from an unexpected client\",\n );\n }\n\n ConnectionMessageIn::Raw { data, .. } => {\n let res = if data.is_empty() {\n STEAL_UNFILTERED_CONNECTION_SUBSCRIPTION.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);\n\n tracing::trace!(\n client_id = self.client_id,\n connection_id = self.connection_id,\n \"Received a 0-sized write from the client, shutting down connection\",\n );\n\n self.stream.shutdown().await\n } else {\n self.stream.write_all(&data).await\n };\n\n if let Err(e) = res {\n STEAL_UNFILTERED_CONNECTION_SUBSCRIPTION.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);\n\n tx.send(ConnectionMessageOut::Closed {\n client_id: self.client_id,\n connection_id: self.connection_id\n }).await?;\n\n break Err(e.into());\n }\n },\n\n ConnectionMessageIn::Response { request_id, .. } => {\n tracing::trace!(\n connection_id = self.connection_id,\n request_id,\n \"Received an unexpected HTTP message\",\n );\n },\n\n ConnectionMessageIn::Unsubscribed { .. } => {\n STEAL_UNFILTERED_CONNECTION_SUBSCRIPTION.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);\n\n return Ok(());\n }\n }\n }\n }\n }\n```"}], "func_name": "run", "docstring": "Runs this task until the managed connection is closed.\n\n# Note\n\nDoes not send [`ConnectionMessageOut::SubscribedTcp`], assuming that this message has\nalready been sent to the client. This allows this code to be used for both unfiltered\nand upgraded connections.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/connections/unfiltered.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/connections/unfiltered.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e8179c42739e02d92c109493a6eca2eda2bbafd31641738024e0d82da8eaa0b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_last\n\nDocumentation:\nChecks `http_body::Body::is_end_stream`, returning `true` if this response is done.\n\nUsed by our metrics system to decrement the `HTTP_REQUEST_IN_PROGRESS_COUNT` counter\nwhen an streamed HTTP request has finished.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_last(&self) -> bool {\n match self {\n HttpResponseFallback::Framed(http_response) => {\n http_response.internal_response.body.is_end_stream()\n }\n HttpResponseFallback::Fallback(_) => true,\n HttpResponseFallback::Streamed(http_response) => {\n http_response.internal_response.body.is_end_stream()\n }\n }\n }\n```"}], "func_name": "is_last", "docstring": "Checks `http_body::Body::is_end_stream`, returning `true` if this response is done.\n\nUsed by our metrics system to decrement the `HTTP_REQUEST_IN_PROGRESS_COUNT` counter\nwhen an streamed HTTP request has finished.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/http/response_fallback.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/http/response_fallback.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7610cff35c0a82d688d02c88677eeaecb1e863c396fbc53aa8ecbfe256926fd5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connector\n\nDocumentation:\nReturns [`PassThroughTlsConnector`] that can be used on TCP connections with the original\ndestination server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connector(&self, original_connection: &ServerConnection) -> PassThroughTlsConnector {\n let server_name = original_connection\n .server_name()\n .and_then(|name| ServerName::try_from(name).ok()?.to_owned().into());\n let client_alpn = original_connection\n .alpn_protocol()\n .into_iter()\n .map(Vec::from)\n .collect::>();\n\n let mut client_config = self.client_config.as_ref().clone();\n client_config.alpn_protocols = client_alpn;\n\n PassThroughTlsConnector {\n client_config: Arc::new(client_config),\n server_name,\n }\n }\n```"}], "func_name": "connector", "docstring": "Returns [`PassThroughTlsConnector`] that can be used on TCP connections with the original\ndestination server.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/tls/handler.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/tls/handler.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cbdafdc169c2f44875fbfe4996bf829c96ebc97b2f94af21204c010139746169"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nMakes to make client TLS connection in the given stream.\n\n[`TlsConnector::connect`] requires a [`ServerName`].\nWe try to get it from following sources (in order of preference):\n1. SNI from the original connection source (if supplied)\n2. Request URI (if have a request)\n3. Original destination ip\n\nReturns the [`client::TlsStream`] boxed, as its size exceeds 1kb.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn connect(\n &self,\n server_ip: IpAddr,\n request_uri: Option<&Uri>,\n stream: IO,\n ) -> io::Result>>\n where\n IO: AsyncRead + AsyncWrite + Unpin,\n {\n let server_name = self\n .server_name\n .clone()\n .or_else(|| request_uri?.get_server_name()?.to_owned().into())\n .unwrap_or_else(|| ServerName::from(server_ip));\n\n let connector = TlsConnector::from(self.client_config.clone());\n\n connector\n .connect(server_name, stream)\n .await\n .inspect_err(|error| {\n tracing::warn!(\n %server_ip,\n ?request_uri,\n original_sni = ?self.server_name,\n alpn_protocol = ?self.client_config.alpn_protocols.first().map(|proto| String::from_utf8_lossy(proto)),\n %error,\n \"Failed to make a TLS connection to the original destination.\",\n );\n })\n .map(Box::new)\n }\n```"}], "func_name": "connect", "docstring": "Makes to make client TLS connection in the given stream.\n\n[`TlsConnector::connect`] requires a [`ServerName`].\nWe try to get it from following sources (in order of preference):\n1. SNI from the original connection source (if supplied)\n2. Request URI (if have a request)\n3. Original destination ip\n\nReturns the [`client::TlsStream`] boxed, as its size exceeds 1kb.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/steal/tls/handler.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/steal/tls/handler.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d1f5cda2e2a5d02e8eec82aa2232bff6a9b664f90f66d3e96a2a94699edd9c76"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_root_path\n\nDocumentation:\nConstructs a new resolver with the given root path.\n\nMakes it easy to test with [`tempfile::tempdir`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_root_path(root: PathBuf) -> Self {\n Self { root }\n }\n```"}], "func_name": "with_root_path", "docstring": "Constructs a new resolver with the given root path.\n\nMakes it easy to test with [`tempfile::tempdir`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/util/path_resolver.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/util/path_resolver.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "06653df6229740bbc25d644d8e1d1a0c119b415254640a3d06054c97ced66c78"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: replace\n\nDocumentation:\nReplaces the protocol version stored in this struct.\n\nShould be called when\n[`ClientMessage::SwitchProtocolVersion`](mirrord_protocol::ClientMessage::SwitchProtocolVersion)\nis received from the client.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn replace(&self, version: semver::Version) {\n *self.0.lock().unwrap() = version;\n }\n```"}], "func_name": "replace", "docstring": "Replaces the protocol version stored in this struct.\n\nShould be called when\n[`ClientMessage::SwitchProtocolVersion`](mirrord_protocol::ClientMessage::SwitchProtocolVersion)\nis received from the client.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/util/protocol_version.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/util/protocol_version.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b0a0876d454c308c511f6dee933ddb55157c605793d8c44a39a93868a7459a28"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_in_namespace\n\nDocumentation:\nCreates a new remote runtime.\n\nThis runtime's thread will enter the specified namespace of the target.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn new_in_namespace(\n target_pid: u64,\n namespace_type: NamespaceType,\n ) -> Result {\n let (future_tx, mut future_rx) = mpsc::channel(16);\n let (result_tx, result_rx) = oneshot::channel();\n let thread_name = format!(\"remote-{target_pid}-{namespace_type}-runtime-thread\");\n let thread_logic = move || {\n if let Err(error) = namespace::set_namespace(target_pid, namespace_type) {\n let _ = result_tx.send(Err(error.into()));\n return;\n }\n\n let rt_result = tokio::runtime::Builder::new_current_thread()\n .enable_all()\n .thread_name(format!(\n \"remote-{target_pid}-{namespace_type}-runtime-worker\"\n ))\n .build();\n let rt = match rt_result {\n Ok(rt) => rt,\n Err(error) => {\n let _ = result_tx.send(Err(RemoteRuntimeError::TokioRuntimeError(error)));\n return;\n }\n };\n\n if result_tx.send(Ok(())).is_err() {\n return;\n }\n\n rt.block_on(async move {\n while let Some(future) = future_rx.recv().await {\n tokio::spawn(future);\n }\n });\n };\n\n thread::Builder::new()\n .name(thread_name)\n .spawn(thread_logic)\n .map_err(RemoteRuntimeError::ThreadSpawnError)?;\n\n match result_rx.await {\n Ok(Ok(())) => Ok(Self {\n target_pid,\n future_tx,\n }),\n Ok(Err(error)) => Err(error),\n Err(..) => Err(RemoteRuntimeError::Panicked),\n }\n }\n```"}], "func_name": "new_in_namespace", "docstring": "Creates a new remote runtime.\n\nThis runtime's thread will enter the specified namespace of the target.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/util/remote_runtime.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/util/remote_runtime.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d8bfd3cb9004e8f4013ff13c33af78a0e1fb53b0c1d5526e4fbb7ecc61d4342"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn\n\nDocumentation:\nSpawns the given future on this remote runtime.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn spawn(&self, future: F) -> BgTask\n where\n F: 'static + Future + Send,\n F::Output: 'static + Send,\n {\n let (result_tx, result_rx) = oneshot::channel();\n\n let future = async move {\n let result = future.await;\n let _ = result_tx.send(result);\n }\n .boxed();\n\n let future_tx = self.future_tx.clone();\n tokio::spawn(async move {\n let _ = future_tx.send(future).await;\n });\n\n BgTask {\n future_result: result_rx,\n }\n }\n```"}], "func_name": "spawn", "docstring": "Spawns the given future on this remote runtime.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/util/remote_runtime.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/util/remote_runtime.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1bcfeaa49a2aba19fe1a18c73e48da7438d0d47355e36a408b0f32e0aaca3a99"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait\n\nDocumentation:\nWaits for the future to finish and returns its result.\n\nShould the future fail or panic, this function will return\n[`AgentError::BackgroundTaskFailed`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn wait(&self) -> Result<(), AgentError> {\n match self.result.clone().await {\n Ok(Ok(())) => Ok(()),\n Ok(Err(error)) => Err(AgentError::BackgroundTaskFailed {\n task: self.task_name,\n error,\n }),\n Err(..) => Err(AgentError::BackgroundTaskFailed {\n task: self.task_name,\n error: Arc::new(BgTaskPanicked) as Arc,\n }),\n }\n }\n```"}], "func_name": "wait", "docstring": "Waits for the future to finish and returns its result.\n\nShould the future fail or panic, this function will return\n[`AgentError::BackgroundTaskFailed`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/util/remote_runtime.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/util/remote_runtime.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b7dbe6b487b650aa6aa054352aedafc5fe489a47bac7b3d060f8f6e34efeda90"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait_assert_running\n\nDocumentation:\nWaits for the future to finish and returns its result.\n\nThis function always returns [`AgentError::BackgroundTaskFailed`]. Use it when the task is\nnot expected to finish yet.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn wait_assert_running(&self) -> AgentError {\n match self.result.clone().await {\n Ok(Ok(())) => AgentError::BackgroundTaskFailed {\n task: self.task_name,\n error: Box::::from(\"task finished unexpectedly\").into(),\n },\n Ok(Err(error)) => AgentError::BackgroundTaskFailed {\n task: self.task_name,\n error,\n },\n Err(..) => AgentError::BackgroundTaskFailed {\n task: self.task_name,\n error: Arc::new(BgTaskPanicked) as Arc,\n },\n }\n }\n```"}], "func_name": "wait_assert_running", "docstring": "Waits for the future to finish and returns its result.\n\nThis function always returns [`AgentError::BackgroundTaskFailed`]. Use it when the task is\nnot expected to finish yet.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/util/remote_runtime.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/util/remote_runtime.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c086d07d8358a0a8c047fc1b26038df487b15e454a1175e48e6a5f36c88b1787"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn\n\nDocumentation:\nSpawns the given future on this runtime.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn spawn(&self, future: F) -> BgTask\n where\n F: 'static + Future + Send,\n F::Output: 'static + Send,\n {\n match self {\n Self::Remote(remote_runtime) => remote_runtime.spawn(future),\n Self::Local => {\n let (result_tx, result_rx) = oneshot::channel();\n\n tokio::spawn(async move {\n let result = future.await;\n let _ = result_tx.send(result);\n });\n\n BgTask {\n future_result: result_rx,\n }\n }\n }\n }\n```"}], "func_name": "spawn", "docstring": "Spawns the given future on this runtime.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/util/remote_runtime.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/util/remote_runtime.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e8e3fe5c27fbffd2087608511dab6a438c5bd110170fefb6b654b44ac67042f1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: target_pid\n\nDocumentation:\nIf this is a remote runtime, returns the target's PID.\nOtherwise, returns [`None`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn target_pid(&self) -> Option {\n match self {\n Self::Remote(remote_runtime) => Some(remote_runtime.target_pid()),\n Self::Local => None,\n }\n }\n```"}], "func_name": "target_pid", "docstring": "If this is a remote runtime, returns the target's PID.\nOtherwise, returns [`None`].", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/util/remote_runtime.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/util/remote_runtime.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ef7f2b6869382380b77c2f5b8a860bcbf4ecc14eecb461c0c4393743be748b1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nPrepends the given stream with the `prefix`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(stream: IO, prefix: B) -> Self {\n Self {\n stream,\n prefix: prefix.has_remaining().then_some(prefix),\n }\n }\n```"}], "func_name": "new", "docstring": "Prepends the given stream with the `prefix`.", "repo": "metalbear-co/mirrord", "path": "mirrord/agent/src/util/rolledback_stream.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/agent/src/util/rolledback_stream.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ec2dc3f2867745da11671d8c6b012499907a705826f921d4a0d2637db77c3cda"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expiration_date\n\nDocumentation:\nExtracts the expiration date (`not_after`) out of the certificate as a nice\n`DateTime`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expiration_date(&self) -> DateTime {\n let validity = &self.0.as_ref().tbs_certificate.validity;\n\n match validity.not_after.clone() {\n x509_certificate::asn1time::Time::UtcTime(time) => *time,\n x509_certificate::asn1time::Time::GeneralTime(time) => From::from(time),\n }\n }\n```"}], "func_name": "expiration_date", "docstring": "Extracts the expiration date (`not_after`) out of the certificate as a nice\n`DateTime`.", "repo": "metalbear-co/mirrord", "path": "mirrord/auth/src/certificate.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/auth/src/certificate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d4c186681ed18b3312802f4b3a0ccfb4f93783340d9e79dc8370025a05b4c153"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_valid\n\nDocumentation:\nChecks if [`Certificate`] in this struct is valid in terms of expiration.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_valid(&self) -> bool {\n self.certificate\n .as_ref()\n .tbs_certificate\n .validity\n .is_date_valid(Utc::now())\n }\n```"}], "func_name": "is_valid", "docstring": "Checks if [`Certificate`] in this struct is valid in terms of expiration.", "repo": "metalbear-co/mirrord", "path": "mirrord/auth/src/credentials.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/auth/src/credentials.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8b0f69b280181a5967d7721669d94d6c9c7d03fc50697a1799dcd19177d323a9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init\n\nDocumentation:\nCreate a [`rfc2986::CertificationRequest`] and send it to the operator.\nIf the `key_pair` is not given, the request is signed with a randomly generated one.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn init(\n client: Client,\n common_name: &str,\n key_pair: Option,\n ) -> Result\n where\n R: Resource + Clone + Debug,\n R: for<'de> Deserialize<'de>,\n R::DynamicType: Default,\n {\n let key_pair = match key_pair {\n Some(key_pair) => key_pair,\n None => KeyPair::new_random()?,\n };\n\n let certificate_request = Self::certificate_request(common_name, &key_pair)?\n .encode_pem()\n .map_err(X509CertificateError::from)?;\n\n let api: Api = Api::all(client);\n\n let certificate: Certificate = api\n .create_subresource(\n \"certificate\",\n \"operator\",\n &PostParams::default(),\n certificate_request.into(),\n )\n .await?;\n\n Ok(Credentials {\n certificate,\n key_pair,\n })\n }\n```"}], "func_name": "init", "docstring": "Create a [`rfc2986::CertificationRequest`] and send it to the operator.\nIf the `key_pair` is not given, the request is signed with a randomly generated one.", "repo": "metalbear-co/mirrord", "path": "mirrord/auth/src/credentials.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/auth/src/credentials.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "20bb80239a9199157eaad97fca97970ed2727fa4d5dc77f6d2fe49ca1cfa37ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: refresh\n\nDocumentation:\nCreate [`rfc2986::CertificationRequest`] and send it to the operator.\nReturned certificate replaces the [`Certificate`] stored in this struct.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn refresh(\n &mut self,\n client: Client,\n common_name: &str,\n ) -> Result<(), CredentialStoreError>\n where\n R: Resource + Clone + Debug,\n R: for<'de> Deserialize<'de>,\n R::DynamicType: Default,\n {\n let certificate_request = Self::certificate_request(common_name, &self.key_pair)?\n .encode_pem()\n .map_err(X509CertificateError::from)?;\n\n let api: Api = Api::all(client);\n\n let certificate: Certificate = api\n .create_subresource(\n \"certificate\",\n \"operator\",\n &PostParams::default(),\n certificate_request.into(),\n )\n .await?;\n\n self.certificate = certificate;\n\n Ok(())\n }\n```"}], "func_name": "refresh", "docstring": "Create [`rfc2986::CertificationRequest`] and send it to the operator.\nReturned certificate replaces the [`Certificate`] stored in this struct.", "repo": "metalbear-co/mirrord", "path": "mirrord/auth/src/credentials.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/auth/src/credentials.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "08d849051512a3517eb7548f16d1fdf9694f8a83c0687e6a931504fcd64217d1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load\n\nDocumentation:\nLoad contents of store from file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn load(source: &mut R) -> Result {\n let mut buffer = Vec::new();\n source\n .read_to_end(&mut buffer)\n .await\n .map_err(CredentialStoreError::FileAccess)?;\n serde_yaml::from_slice(&buffer).map_err(From::from)\n }\n```"}], "func_name": "load", "docstring": "Load contents of store from file", "repo": "metalbear-co/mirrord", "path": "mirrord/auth/src/credential_store.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/auth/src/credential_store.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dfb2146a200f71e729c34d5329ef2f781ee5768bd015e497a759faaf2c17da8c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: save\n\nDocumentation:\nSave contents of store to file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn save(\n &self,\n writer: &mut W,\n ) -> Result<(), CredentialStoreError> {\n let buffer = serde_yaml::to_string(&self)?;\n writer\n .write_all(buffer.as_bytes())\n .await\n .map_err(CredentialStoreError::FileAccess)?;\n\n Ok(())\n }\n```"}], "func_name": "save", "docstring": "Save contents of store to file", "repo": "metalbear-co/mirrord", "path": "mirrord/auth/src/credential_store.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/auth/src/credential_store.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "15f1133bc596502eef8874f35cd785f9fdf5641798f2196fd75dd1a29f6169a2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: certificate_common_name\n\nDocumentation:\nGet hostname to be used as common name in a certification request.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn certificate_common_name() -> String {\n let mut hostname = fallible::hostname().unwrap_or_else(|_| \"localhost\".to_string());\n\n hostname.make_ascii_lowercase();\n hostname\n }\n```"}], "func_name": "certificate_common_name", "docstring": "Get hostname to be used as common name in a certification request.", "repo": "metalbear-co/mirrord", "path": "mirrord/auth/src/credential_store.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/auth/src/credential_store.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09963199fa86a4d87d6b5ac1fda8c6d4ccef88442f37e584b958a85a5eaeab18"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: access_credential\n\nDocumentation:\nTry and get/create a specific client certificate.\nThe exclusive file lock is already acquired.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn access_credential(\n &mut self,\n client: &Client,\n operator_fingerprint: String,\n operator_subscription_id: Option,\n callback: C,\n ) -> Result\n where\n R: Resource + Clone + Debug,\n R: for<'de> Deserialize<'de>,\n R::DynamicType: Default,\n C: FnOnce(&mut Credentials) -> V,\n {\n let mut store = CredentialStore::load(&mut self.store_file)\n .await\n .inspect_err(|error| tracing::warn!(%error, \"CredentialStore load failed\"))\n .unwrap_or_default();\n\n let value = callback(\n store\n .get_or_init::(client, operator_fingerprint, operator_subscription_id)\n .await?,\n );\n\n // Make sure the store_file's cursor is at the start of the file before sending it to save\n self.store_file\n .seek(SeekFrom::Start(0))\n .await\n .map_err(CredentialStoreError::FileAccess)?;\n self.store_file\n .set_len(0)\n .await\n .map_err(CredentialStoreError::FileAccess)?;\n\n store.save(&mut self.store_file).await?;\n\n Ok(value)\n }\n```"}], "func_name": "access_credential", "docstring": "Try and get/create a specific client certificate.\nThe exclusive file lock is already acquired.", "repo": "metalbear-co/mirrord", "path": "mirrord/auth/src/credential_store.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/auth/src/credential_store.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ecaf79059446697348a222731db6ac2c51c4d20abce6bd03893607d8614dcc70"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_client_certificate\n\nDocumentation:\nGet or create specific client certificate with an exclusive lock on the file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_client_certificate(\n &mut self,\n client: &Client,\n operator_fingerprint: String,\n operator_subscription_id: Option,\n ) -> Result\n where\n R: Resource + Clone + Debug,\n R: for<'de> Deserialize<'de>,\n R::DynamicType: Default,\n {\n self.store_file\n .lock_exclusive()\n .map_err(CredentialStoreError::Lockfile)?;\n\n let result = self\n .access_credential::(\n client,\n operator_fingerprint,\n operator_subscription_id,\n |credentials| credentials.as_ref().clone(),\n )\n .await;\n\n self.store_file\n .unlock()\n .map_err(CredentialStoreError::Lockfile)?;\n\n result\n }\n```"}], "func_name": "get_client_certificate", "docstring": "Get or create specific client certificate with an exclusive lock on the file.", "repo": "metalbear-co/mirrord", "path": "mirrord/auth/src/credential_store.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/auth/src/credential_store.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "45559b395b81f7157f4634a68d52ae5e39b859cb60ec724478ca54e66e3b9864"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: patch_buggy_der\n\nDocumentation:\nIf the given DER was produced by old version of `ring` crate, returns a patched valid\nversion that contains the same key pair. If not, returns [`None`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn patch_buggy_der(der: &[u8]) -> Option> {\n if der.len() != 85\n || der.get(..16).expect(\"length was checked\") != Self::BUGGED_PREFIX\n || der.get(16 + 32..16 + 32 + 5).expect(\"length was checked\") != Self::BUGGED_MIDDLE\n {\n return None;\n }\n\n let seed = der\n .get(Self::BUGGED_PREFIX.len()..Self::BUGGED_PREFIX.len() + 32)\n .expect(\"length was checked\");\n let public_key = der\n .get(Self::BUGGED_PREFIX.len() + 32 + Self::BUGGED_MIDDLE.len()..)\n .expect(\"length was checked\");\n\n [&Self::FIXED_PREFIX, seed, &Self::FIXED_MIDDLE, public_key]\n .concat()\n .into()\n }\n```"}], "func_name": "patch_buggy_der", "docstring": "If the given DER was produced by old version of `ring` crate, returns a patched valid\nversion that contains the same key pair. If not, returns [`None`].", "repo": "metalbear-co/mirrord", "path": "mirrord/auth/src/key_pair.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/auth/src/key_pair.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "399f390aec04ae2c7e386c59dac1065bfab02c72206303e027fcef2b426da090"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_random\n\nDocumentation:\nGenerates a new random [`KeyPair`].\nThe new [`KeyPair`] initially has valid format.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_random() -> Result {\n let key_pair = InMemorySigningKeyPair::generate_random(KeyAlgorithm::Ed25519)?;\n let der = key_pair.to_pkcs8_one_asymmetric_key_der();\n let pem_key = pem::Pem::new(\"PRIVATE KEY\", der.to_vec());\n let pem_document = pem::encode(&pem_key);\n\n Ok(Self {\n pem: pem_document,\n key_pair: key_pair.into(),\n der_bugged: false,\n })\n }\n```"}], "func_name": "new_random", "docstring": "Generates a new random [`KeyPair`].\nThe new [`KeyPair`] initially has valid format.", "repo": "metalbear-co/mirrord", "path": "mirrord/auth/src/key_pair.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/auth/src/key_pair.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ecd690e34f2f1df113838b63216d49baae029f9fae9ade6f976fd89a37e552d9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bug_der\n\nDocumentation:\nChanges format to the buggy one.\nOld `ring` and [`x509_certificate`] versions will accept it.\nNew `ring` and [`x509_certificate`] versions will reject it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bug_der(&mut self) {\n if self.der_bugged {\n return;\n }\n\n let pem_key = pem::parse(&self.pem).expect(\"PEM was verified when creating this KeyPair\");\n let der = pem_key.contents();\n let seed = der\n .get(Self::FIXED_PREFIX.len()..Self::FIXED_PREFIX.len() + 32)\n .expect(\"PEM was verified when creating this KeyPair\");\n let public_key = der\n .get(Self::FIXED_PREFIX.len() + 32 + Self::FIXED_MIDDLE.len()..)\n .expect(\"PEM was verified when creating this KeyPair\");\n\n let bugged_der = [&Self::BUGGED_PREFIX, seed, &Self::BUGGED_MIDDLE, public_key].concat();\n let pem_key = pem::Pem::new(\"PRIVATE KEY\", bugged_der);\n let pem_document = pem::encode(&pem_key);\n\n self.pem = pem_document;\n self.der_bugged = true;\n }\n```"}], "func_name": "bug_der", "docstring": "Changes format to the buggy one.\nOld `ring` and [`x509_certificate`] versions will accept it.\nNew `ring` and [`x509_certificate`] versions will reject it.", "repo": "metalbear-co/mirrord", "path": "mirrord/auth/src/key_pair.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/auth/src/key_pair.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4857fb590a1103dcf31b23fc76eab582a9116a2d59ae934529f5b40942e3ed0f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fix_der\n\nDocumentation:\nChanges format to the valid one.\nOld `ring` and [`x509_certificate`] versions will reject it.\nNew `ring` and [`x509_certificate`] versions will accept it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fix_der(&mut self) {\n if !self.der_bugged {\n return;\n }\n\n let der = self.key_pair.to_pkcs8_one_asymmetric_key_der();\n let pem_key = pem::Pem::new(\"PRIVATE KEY\", der.to_vec());\n let pem_document = pem::encode(&pem_key);\n\n self.pem = pem_document;\n self.der_bugged = false;\n }\n```"}], "func_name": "fix_der", "docstring": "Changes format to the valid one.\nOld `ring` and [`x509_certificate`] versions will reject it.\nNew `ring` and [`x509_certificate`] versions will accept it.", "repo": "metalbear-co/mirrord", "path": "mirrord/auth/src/key_pair.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/auth/src/key_pair.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "58381367a77b5afec28ae70289dbbc96f173e6aa7fac779d9b93171aeab759d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_env_vars\n\nDocumentation:\nReturns these parameters as an environment variables map.\n\nThe map can be used when resolving the config with [`LayerConfig::resolve`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_env_vars(&self) -> HashMap<&'static OsStr, Cow<'_, OsStr>> {\n let mut envs = self.agent.as_env_vars();\n\n envs.extend(\n self.target\n .as_env_vars()\n .into_iter()\n .map(|(key, value)| (key, Cow::Borrowed(value))),\n );\n\n if self.no_telemetry {\n envs.insert(\n \"MIRRORD_TELEMETRY\".as_ref(),\n Cow::Borrowed(\"false\".as_ref()),\n );\n }\n if let Some(skip_processes) = &self.skip_processes {\n envs.insert(\n \"MIRRORD_SKIP_PROCESSES\".as_ref(),\n Cow::Borrowed(skip_processes.as_ref()),\n );\n }\n if let Some(fs_mode) = self.fs_mode {\n envs.insert(\n \"MIRRORD_FILE_MODE\".as_ref(),\n Cow::Owned(OsString::from_vec(fs_mode.to_string().into_bytes())),\n );\n }\n if let Some(override_env_vars_exclude) = &self.override_env_vars_exclude {\n envs.insert(\n MIRRORD_OVERRIDE_ENV_VARS_EXCLUDE_ENV.as_ref(),\n Cow::Borrowed(override_env_vars_exclude.as_ref()),\n );\n }\n if let Some(override_env_vars_include) = &self.override_env_vars_include {\n envs.insert(\n MIRRORD_OVERRIDE_ENV_VARS_INCLUDE_ENV.as_ref(),\n Cow::Borrowed(override_env_vars_include.as_ref()),\n );\n }\n if self.no_remote_dns {\n envs.insert(\n \"MIRRORD_REMOTE_DNS\".as_ref(),\n Cow::Borrowed(\"false\".as_ref()),\n );\n }\n if let Some(accept_invalid_certificates) = self.accept_invalid_certificates {\n let value = if accept_invalid_certificates {\n tracing::warn!(\"Accepting invalid certificates\");\n \"true\"\n } else {\n \"false\"\n };\n\n envs.insert(\n \"MIRRORD_ACCEPT_INVALID_CERTIFICATES\".as_ref(),\n Cow::Borrowed(value.as_ref()),\n );\n }\n if self.tcp_steal {\n envs.insert(\n \"MIRRORD_AGENT_TCP_STEAL_TRAFFIC\".as_ref(),\n Cow::Borrowed(\"true\".as_ref()),\n );\n }\n if self.no_outgoing || self.no_tcp_outgoing {\n envs.insert(\n \"MIRRORD_TCP_OUTGOING\".as_ref(),\n Cow::Borrowed(\"false\".as_ref()),\n );\n }\n if self.no_outgoing || self.no_udp_outgoing {\n envs.insert(\n \"MIRRORD_UDP_OUTGOING\".as_ref(),\n Cow::Borrowed(\"false\".as_ref()),\n );\n }\n if let Some(context) = &self.context {\n envs.insert(\n \"MIRRORD_KUBE_CONTEXT\".as_ref(),\n Cow::Borrowed(context.as_ref()),\n );\n }\n if let Some(config_file) = &self.config_file {\n envs.insert(\n LayerConfig::FILE_PATH_ENV.as_ref(),\n Cow::Borrowed(config_file.as_ref()),\n );\n }\n if let Some(env_file) = &self.env_file {\n envs.insert(\n MIRRORD_OVERRIDE_ENV_FILE_ENV.as_ref(),\n Cow::Borrowed(env_file.as_ref()),\n );\n }\n\n envs\n }\n```"}], "func_name": "as_env_vars", "docstring": "Returns these parameters as an environment variables map.\n\nThe map can be used when resolving the config with [`LayerConfig::resolve`].", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/config.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/config.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "43899a6e4d14f109c8a7593ecd4f1f75d8b6758486fa6486843e01a419faba81"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: hex_id\n\nDocumentation:\nParses the operator session id from hex (without `0x` prefix) into `u64`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn hex_id(raw: &str) -> Result {\n u64::from_str_radix(raw, 16)\n .map_err(|fail| format!(\"Failed parsing hex session id value with {fail}!\"))\n}\n```"}], "func_name": "hex_id", "docstring": "Parses the operator session id from hex (without `0x` prefix) into `u64`.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/config.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/config.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d2e5e03d98822e60e10fb420101ff1fdb57837bf0b7b7f55c5f40207417ea70f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_parts\n\nDocumentation:\nUnpack exec command to inner components [`RuntimeArgs`] and [`ExecParams`]\n(need to parse [`RuntimeArgs`] here just to make clap happy with nested trailing_var_arg)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_parts(self) -> (RuntimeArgs, ExecParams) {\n let ContainerArgs { params, exec } = self;\n\n let runtime_args = RuntimeArgs::parse_from(\n std::iter::once(\"mirrord container exec --\".into()).chain(exec),\n );\n\n (runtime_args, *params)\n }\n```"}], "func_name": "into_parts", "docstring": "Unpack exec command to inner components [`RuntimeArgs`] and [`ExecParams`]\n(need to parse [`RuntimeArgs`] here just to make clap happy with nested trailing_var_arg)", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/config.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/config.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "10d906508654ff3788e389d190ee62962607143087c252e7bab14b5ef2437ef7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_mirrord_console_addr\n\nDocumentation:\nRetrieves the value of [`MIRRORD_CONSOLE_ADDR_ENV`].\n\nIf the variable is not present, returns [`None`].\n\n# Panic\n\nThis function panics when the variable value is not a non loopback [`SocketAddr`].\n\nWe require that the address is not a loopback,\nbecause it has to be accessible from the spawned docker containers.\n\nIt's ok to panic, because mirrord-console is our debugging tool.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_mirrord_console_addr() -> Option {\n let console_addr = std::env::var(MIRRORD_CONSOLE_ADDR_ENV).ok()?;\n\n let is_non_loopback = console_addr\n .parse::()\n .ok()\n .is_some_and(|addr| addr.ip().is_loopback().not());\n if is_non_loopback {\n Some(console_addr)\n } else {\n panic!(\"{MIRRORD_CONSOLE_ADDR_ENV} needs to be a non loopback address when used with containers: {console_addr}\")\n }\n}\n```"}], "func_name": "get_mirrord_console_addr", "docstring": "Retrieves the value of [`MIRRORD_CONSOLE_ADDR_ENV`].\n\nIf the variable is not present, returns [`None`].\n\n# Panic\n\nThis function panics when the variable value is not a non loopback [`SocketAddr`].\n\nWe require that the address is not a loopback,\nbecause it has to be accessible from the spawned docker containers.\n\nIt's ok to panic, because mirrord-console is our debugging tool.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/container.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/container.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "65b80aa7be0d3d68983f6d8ec20a6b2849084c3ac508be79facaf1001825c7e0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_config_and_analytics\n\nDocumentation:\nResolves the [`LayerConfig`] and creates [`AnalyticsReporter`] whilst reporting any warnings.\n\nUses [`ExecutionKind::Container`] to create the [`AnalyticsReporter`].\n\nUses the given `progress` to pass warnings from [`LayerConfig`] verification.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn create_config_and_analytics(\n progress: &mut P,\n mut cfg_context: ConfigContext,\n watch: drain::Watch,\n) -> CliResult<(LayerConfig, AnalyticsReporter)> {\n let mut config = LayerConfig::resolve(&mut cfg_context)?;\n crate::profile::apply_profile_if_configured(&mut config, progress).await?;\n\n // Initialize only error analytics, extproxy will be the full AnalyticsReporter.\n let analytics =\n AnalyticsReporter::only_error(config.telemetry, ExecutionKind::Container, watch);\n\n let result = config.verify(&mut cfg_context);\n for warning in cfg_context.into_warnings() {\n progress.warning(&warning);\n }\n result?;\n\n Ok((config, analytics))\n}\n```"}], "func_name": "create_config_and_analytics", "docstring": "Resolves the [`LayerConfig`] and creates [`AnalyticsReporter`] whilst reporting any warnings.\n\nUses [`ExecutionKind::Container`] to create the [`AnalyticsReporter`].\n\nUses the given `progress` to pass warnings from [`LayerConfig`] verification.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/container.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/container.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bafa590fe29e1714e6ab95784b031c5144e003a20c6c3dc224657318fa431024"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prepare_proxies\n\nDocumentation:\nMakes the agent connection, spawns the native `mirrord-extproxy` process,\nand starts the `mirrord-intproxy` sidecar container.\n\n# Returns\n\n1. Prepared command to run the user container.\n2. Handle to the external proxy.\n3. Handle to temporary files containing intproxy-extproxy TLS configs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn prepare_proxies(\n analytics: &mut AnalyticsReporter,\n progress: &P,\n config: &mut LayerConfig,\n runtime: ContainerRuntime,\n) -> CliResult<(\n RuntimeCommandBuilder,\n MirrordExecution,\n Option,\n)> {\n let tls_setup = config\n .external_proxy\n .tls_enable\n .then(|| SecureChannelSetup::try_new(MIRRORD_EXTPROXY_TLS_SERVER_NAME, \"intproxy\"))\n .transpose()\n .map_err(ContainerError::from)?;\n\n let mut sub_progress = progress.subtask(\"preparing to launch process\");\n let (execution_info, extproxy_addr) =\n MirrordExecution::start_external(config, &mut sub_progress, analytics, tls_setup.as_ref())\n .await?;\n sub_progress.success(None);\n\n let extproxy_addr = config\n .container\n .override_host_ip\n .map(|host_ip| SocketAddr::new(host_ip, extproxy_addr.port()))\n .unwrap_or(extproxy_addr);\n\n let sidecar =\n IntproxySidecar::create(config, runtime, extproxy_addr, tls_setup.as_ref()).await?;\n\n let mut runtime_command = RuntimeCommandBuilder::new(runtime);\n // Provide remote environment to the user application.\n runtime_command.add_envs(\n execution_info\n .environment\n .iter()\n .map(|(name, value)| (name.as_str(), value.as_str())),\n );\n // Allow the layer to connect with the internal proxy sidecar.\n runtime_command.add_network(format!(\"container:{}\", sidecar.container_id()));\n // Add the layer file to the user application container.\n runtime_command.add_volumes_from(sidecar.container_id());\n // Inject the layer into the user application.\n runtime_command.add_env(\n LINUX_INJECTION_ENV_VAR,\n &config.container.cli_image_lib_path,\n );\n runtime_command.add_env(LayerConfig::RESOLVED_CONFIG_ENV, &config.encode()?);\n\n let (sidecar_intproxy_address, sidecar_intproxy_logs) = sidecar.start().await?;\n let intproxy_logs_pipe =\n pipe_intproxy_sidecar_logs(config, sidecar_intproxy_logs.into_merged_lines()).await?;\n tokio::spawn(intproxy_logs_pipe);\n\n // Provide internal proxy address to the layer.\n runtime_command.add_env(\n MIRRORD_LAYER_INTPROXY_ADDR,\n &sidecar_intproxy_address.to_string(),\n );\n\n Ok((runtime_command, execution_info, tls_setup))\n}\n```"}], "func_name": "prepare_proxies", "docstring": "Makes the agent connection, spawns the native `mirrord-extproxy` process,\nand starts the `mirrord-intproxy` sidecar container.\n\n# Returns\n\n1. Prepared command to run the user container.\n2. Handle to the external proxy.\n3. Handle to temporary files containing intproxy-extproxy TLS configs.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/container.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/container.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "52f99e80e9ccaa440b573f29734424786fdcfb95f337d213e1bf195f5fae146c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ping\n\nDocumentation:\nSends a ping the connection and expects a pong.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn ping(\n sender: &mpsc::Sender,\n receiver: &mut mpsc::Receiver,\n) -> CliResult<()> {\n sender.send(ClientMessage::Ping).await.map_err(|_| {\n CliError::PingPongFailed(\n \"failed to send ping message - agent unexpectedly closed connection\".to_string(),\n )\n })?;\n\n loop {\n let result = match receiver.recv().await {\n Some(DaemonMessage::Pong) => Ok(()),\n Some(DaemonMessage::LogMessage(..)) => continue,\n Some(DaemonMessage::Close(message)) => Err(CliError::PingPongFailed(format!(\n \"agent closed connection with message: {message}\"\n ))),\n Some(message) => Err(CliError::PingPongFailed(format!(\n \"agent sent an unexpected message: {message:?}\"\n ))),\n None => Err(CliError::PingPongFailed(\n \"agent unexpectedly closed connection\".to_string(),\n )),\n };\n\n return result;\n }\n}\n```"}], "func_name": "ping", "docstring": "Sends a ping the connection and expects a pong.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/diagnose.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/diagnose.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "edf37878c14fdde0ee17131830c02db71aa027d7769416a056dfbd526f3230ca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: diagnose_command\n\nDocumentation:\nHandle commands related to the operator `mirrord diagnose ...`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn diagnose_command(args: DiagnoseArgs) -> CliResult<()> {\n match args.command {\n DiagnoseCommand::Latency { config_file } => diagnose_latency(config_file.as_deref()).await,\n }\n}\n```"}], "func_name": "diagnose_command", "docstring": "Handle commands related to the operator `mirrord diagnose ...`", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/diagnose.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/diagnose.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "db5e34a7b38e23df8362140aa4105c47f8e02c8ccf9962042fdf7f267fce6efa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: friendlier_error_or_else\n\nDocumentation:\nHere we give more meaning to some errors, instead of just letting them pass as\nwhatever [`KubeApiError`] we're getting.\n\nIf `error` is not something we're interested in (no need for a special diagnostic message),\nthen we turn it into a `fallback` [`CliError`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn friendlier_error_or_else Self>(\n error: KubeApiError,\n fallback: F,\n ) -> Self {\n use kube::{client::AuthError, Error};\n\n match error {\n KubeApiError::KubeError(Error::Auth(AuthError::AuthExec(error))) => {\n Self::KubeAuthExecFailed(error.to_owned())\n }\n // UGH(alex): Type-erased errors are messy, and this one is especially bad.\n // See `kube_service_error_dependency_is_in_sync` for a \"what's going on here\".\n KubeApiError::KubeError(Error::Service(ref fail))\n if format!(\"{fail:?}\").contains(\"InvalidCertificate\") =>\n {\n Self::InvalidCertificate(error)\n }\n error => fallback(error),\n }\n }\n```"}], "func_name": "friendlier_error_or_else", "docstring": "Here we give more meaning to some errors, instead of just letting them pass as\nwhatever [`KubeApiError`] we're getting.\n\nIf `error` is not something we're interested in (no need for a special diagnostic message),\nthen we turn it into a `fallback` [`CliError`].", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/error.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/error.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fcfecd4712ba0b9208b9ff9ce8283bc75ea8f02e1470e09b0de08a490b3cfbb5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_hyper_tls_server\n\nDocumentation:\nCreates an [`hyper`] server with a broken certificate and a _catch-all_ route on\n`localhost:9669`.\n\nThe certificate is generated here with [`rcgen::generate_simple_self_signed`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_hyper_tls_server(notify: Arc) {\n use rcgen::generate_simple_self_signed;\n\n let addr = SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 9669);\n\n let incoming = TcpListener::bind(&addr).await.unwrap();\n\n // Generate a certificate that should not work with kube.\n let cert_key = generate_simple_self_signed(vec![\"mieszko.i\".to_string()]).unwrap();\n let cert_pem = cert_key.cert.pem().into_bytes();\n let cert = CertificateDer::from_pem_slice(&cert_pem).unwrap();\n\n let key_pem = cert_key.key_pair.serialize_pem().into_bytes();\n let key = PrivateKeyDer::from_pem_slice(&key_pem).unwrap();\n\n // Build TLS configuration.\n let mut server_config = ServerConfig::builder()\n .with_no_client_auth()\n .with_single_cert(vec![cert], key)\n .unwrap();\n\n server_config.alpn_protocols =\n vec![b\"h2\".to_vec(), b\"http/1.1\".to_vec(), b\"http/1.0\".to_vec()];\n let tls_acceptor = TlsAcceptor::from(Arc::new(server_config));\n\n /// Catch-all handler, we don't care about the response, any request is supposed\n /// to fail due to `InvalidCertificate`.\n async fn handle_any_route(\n _: Request,\n ) -> Result>, hyper::Error> {\n Ok(Response::new(Full::default()))\n }\n\n let service = service_fn(handle_any_route);\n\n // We're ready for the client side to start.\n notify.notify_waiters();\n let (tcp_stream, _remote_addr) = incoming.accept().await.unwrap();\n\n let tls_acceptor = tls_acceptor.clone();\n tokio::spawn(async move {\n let tls_stream = tls_acceptor.accept(tcp_stream).await.unwrap();\n\n Builder::new(TokioExecutor::new())\n .serve_connection(TokioIo::new(tls_stream), service)\n .await\n .unwrap();\n });\n }\n```"}], "func_name": "run_hyper_tls_server", "docstring": "Creates an [`hyper`] server with a broken certificate and a _catch-all_ route on\n`localhost:9669`.\n\nThe certificate is generated here with [`rcgen::generate_simple_self_signed`].", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/error.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/error.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c4d93393886b85e97a0f05c7cdaf4de930a0d87468cd5363a6e72bc3ac7c994"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_any_route\n\nDocumentation:\nCatch-all handler, we don't care about the response, any request is supposed\nto fail due to `InvalidCertificate`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_any_route(\n _: Request,\n ) -> Result>, hyper::Error> {\n Ok(Response::new(Full::default()))\n }\n```"}], "func_name": "handle_any_route", "docstring": "Catch-all handler, we don't care about the response, any request is supposed\nto fail due to `InvalidCertificate`.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/error.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/error.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8a26b7d0e00d782a984313decfd5f6df589211afa36a19b5fc70bcaac6ae0463"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: watch_stderr\n\nDocumentation:\nCreates a task that reads stderr and returns a vector of warnings at the end.\nCaller should cancel the token and wait on join handle.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn watch_stderr

(stderr: ChildStderr, progress: &P) -> DropProgress

\nwhere\n P: Progress + Send + Sync,\n{\n let cancellation_token = CancellationToken::new();\n let stderr_reader_token = cancellation_token.clone();\n\n let (stderr_tx, stderr_rx) = mpsc::unbounded_channel();\n\n tokio::spawn(async move {\n let mut stderr = BufReader::new(stderr).lines();\n\n loop {\n select! {\n _ = stderr_reader_token.cancelled() => {\n trace!(\"watch_stderr cancelled\");\n break;\n }\n\n line = stderr.next_line() => {\n match line {\n Ok(Some(line)) => {\n debug!(\"watch_stderr got line {line:?}\",);\n if stderr_tx.send(line).is_err() {\n break;\n }\n },\n Ok(None) => {\n trace!(\"watch_stderr finished\");\n break;\n }\n Err(error) => {\n trace!(\"watch_stderr error: {error}\");\n break;\n }\n }\n }\n }\n }\n });\n\n DropProgress {\n cancellation_token,\n stderr_rx,\n progress,\n }\n}\n```"}], "func_name": "watch_stderr", "docstring": "Creates a task that reads stderr and returns a vector of warnings at the end.\nCaller should cancel the token and wait on join handle.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/execution.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/execution.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a8650296ff07520da5b11217f10c444005ee5d183fcc5c3fb44e48e8dcdcd2a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fetch_env_vars\n\nDocumentation:\nConstruct filter and retrieve remote environment from the connected agent using\n`MirrordExecution::get_remote_env`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn fetch_env_vars(\n config: &LayerConfig,\n connection: &mut AgentConnection,\n ) -> CliResult> {\n let (env_vars_exclude, env_vars_include) = match (\n config\n .feature\n .env\n .exclude\n .clone()\n .map(|exclude| exclude.join(\";\")),\n config\n .feature\n .env\n .include\n .clone()\n .map(|include| include.join(\";\")),\n ) {\n (Some(..), Some(..)) => {\n return Err(CliError::ConfigError(ConfigError::Conflict(\n \"cannot use both `include` and `exclude` filters for environment variables\"\n .to_string(),\n )));\n }\n (Some(exclude), None) => (HashSet::from(EnvVars(exclude)), HashSet::new()),\n (None, Some(include)) => (HashSet::new(), HashSet::from(EnvVars(include))),\n (None, None) => (HashSet::new(), HashSet::from(EnvVars(\"*\".to_owned()))),\n };\n\n let mut env_vars = if !env_vars_exclude.is_empty() || !env_vars_include.is_empty() {\n let communication_timeout =\n Duration::from_secs(config.agent.communication_timeout.unwrap_or(30).into());\n\n tokio::time::timeout(\n communication_timeout,\n Self::get_remote_env(connection, env_vars_exclude, env_vars_include),\n )\n .await\n .map_err(|_| CliError::InitialAgentCommFailed(\"timeout\".to_string()))??\n } else {\n Default::default()\n };\n\n if let Some(file) = &config.feature.env.env_file {\n let envs_from_file = dotenvy::from_path_iter(file)\n .and_then(|iter| iter.collect::, _>>())\n .map_err(|error| CliError::EnvFileAccessError(file.clone(), error))?;\n\n env_vars.extend(envs_from_file);\n }\n\n if let Some(mapping) = config.feature.env.mapping.clone() {\n env_vars = EnvVarsRemapper::new(mapping, env_vars)\n .expect(\"Failed creating regex, this should've been caught when verifying config!\")\n .remapped();\n }\n\n if let Some(overrides) = &config.feature.env.r#override {\n env_vars.extend(overrides.iter().map(|(k, v)| (k.clone(), v.clone())));\n }\n\n Ok(env_vars)\n }\n```"}], "func_name": "fetch_env_vars", "docstring": "Construct filter and retrieve remote environment from the connected agent using\n`MirrordExecution::get_remote_env`.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/execution.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/execution.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "374d7d8f1f0b294417b51d66b10b592d28a078ef334a956d63ae9795e1589cd9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait\n\nDocumentation:\nWait for the internal proxy to exit.\nRequired when called from extension since sometimes the extension\ncleans up the process when the parent process exits, so we need the parent to stay alive\nwhile the internal proxy is running.\nSee \n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn wait(mut self) -> CliResult<()> {\n self.child\n .wait()\n .await\n .map_err(CliError::InternalProxyWaitError)?;\n\n Ok(())\n }\n```"}], "func_name": "wait", "docstring": "Wait for the internal proxy to exit.\nRequired when called from extension since sometimes the extension\ncleans up the process when the parent process exits, so we need the parent to stay alive\nwhile the internal proxy is running.\nSee ", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/execution.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/execution.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6b70527e04f7722dcbec9dfeaaaa158ba9ca72d09ebfe59c8c2ba81c74f692e0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mirrord_exec\n\nDocumentation:\nActually facilitate execution after all preparations were complete\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn mirrord_exec

(\n #[cfg(target_os = \"macos\")] executable: Option<&str>,\n mut config: LayerConfig,\n mut progress: P,\n analytics: &mut AnalyticsReporter,\n) -> CliResult<()>\nwhere\n P: Progress + Send + Sync,\n{\n let execution_info = MirrordExecution::start_internal(\n &mut config,\n #[cfg(target_os = \"macos\")]\n executable,\n &mut progress,\n analytics,\n )\n .await?;\n\n let output = serde_json::to_string(&execution_info)?;\n progress.success(Some(&output));\n execution_info.wait().await?;\n\n Ok(())\n}\n```"}], "func_name": "mirrord_exec", "docstring": "Actually facilitate execution after all preparations were complete", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/extension.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/extension.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8f0d9357c1124307e1efaacb6e6e25810108606e85206b8177da21509c8683c0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extension_exec\n\nDocumentation:\nFacilitate the execution of a process using mirrord by an IDE extension\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn extension_exec(args: ExtensionExecArgs, watch: drain::Watch) -> CliResult<()> {\n let progress = ProgressTracker::try_from_env(\"mirrord preparing to launch\")\n .unwrap_or_else(|| JsonProgress::new(\"mirrord preparing to launch\").into());\n\n let mut cfg_context = ConfigContext::default()\n .override_env_opt(LayerConfig::FILE_PATH_ENV, args.config_file)\n .override_env_opt(\"MIRRORD_IMPERSONATED_TARGET\", args.target);\n\n let mut config = LayerConfig::resolve(&mut cfg_context)?;\n crate::profile::apply_profile_if_configured(&mut config, &progress).await?;\n\n let mut analytics = AnalyticsReporter::only_error(config.telemetry, Default::default(), watch);\n\n let result = config.verify(&mut cfg_context);\n for warning in cfg_context.into_warnings() {\n progress.warning(&warning);\n }\n result?;\n\n #[cfg(target_os = \"macos\")]\n let execution_result =\n mirrord_exec(args.executable.as_deref(), config, progress, &mut analytics).await;\n #[cfg(not(target_os = \"macos\"))]\n let execution_result = mirrord_exec(config, progress, &mut analytics).await;\n\n if execution_result.is_err() && !analytics.has_error() {\n analytics.set_error(AnalyticsError::Unknown);\n }\n\n execution_result\n}\n```"}], "func_name": "extension_exec", "docstring": "Facilitate the execution of a process using mirrord by an IDE extension", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/extension.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/extension.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82436f546190ec3621a5d49cca9dd8070ab253cd221fe9a560ffa544cdc34fd4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_library\n\nDocumentation:\nExtract to given directory, or tmp by default.\nIf prefix is true, add a random prefix to the file name that identifies the specific build\nof the layer. This is useful for debug purposes usually.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn extract_library

(\n dest_dir: Option,\n progress: &P,\n prefix: bool,\n) -> CliResult\nwhere\n P: Progress + Send + Sync,\n{\n let mut progress = progress.subtask(\"extracting layer\");\n let extension = Path::new(env!(\"MIRRORD_LAYER_FILE\"))\n .extension()\n .unwrap()\n .to_str()\n .unwrap();\n\n let file_name = if prefix {\n format!(\"{}-libmirrord_layer.{extension}\", const_random!(u64))\n } else {\n format!(\"libmirrord_layer.{extension}\")\n };\n\n let file_path = match dest_dir {\n Some(dest_dir) => std::path::Path::new(&dest_dir).join(file_name),\n None => temp_dir().as_path().join(file_name),\n };\n if !file_path.exists() {\n let mut file = File::create(&file_path)\n .map_err(|e| CliError::LayerExtractError(file_path.clone(), e))?;\n let bytes = include_bytes!(env!(\"MIRRORD_LAYER_FILE\"));\n file.write_all(bytes).unwrap();\n debug!(\"Extracted library file to {:?}\", &file_path);\n }\n\n progress.success(Some(\"layer extracted\"));\n Ok(file_path)\n}\n```"}], "func_name": "extract_library", "docstring": "Extract to given directory, or tmp by default.\nIf prefix is true, add a random prefix to the file name that identifies the specific build\nof the layer. This is useful for debug purposes usually.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/extract.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/extract.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "96fc6ace75127384062a5f9a5079be3ca82ac34ff3bc088d20b6ddc11329290e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_addr\n\nDocumentation:\nPrint the address for the caller (mirrord cli execution flow) so it can pass it\nback to the layer instances via env var.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_addr(listener: &TcpListener) -> io::Result<()> {\n let addr = listener.local_addr()?;\n println!(\"{addr}\\n\");\n Ok(())\n}\n```"}], "func_name": "print_addr", "docstring": "Print the address for the caller (mirrord cli execution flow) so it can pass it\nback to the layer instances via env var.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/internal_proxy.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/internal_proxy.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c2c8b24e1323010a1b86b5537e9532f556af2207e1581ef9203c99bcadbb3d9b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_targets\n\nDocumentation:\nFetches mirrord targets from the cluster and prints output to stdout.\n\nWhen `rich_output` is set:\n1. targets info is printed as a JSON object containing extra data;\n2. only deployment, rollout, and pod targets are fetched.\n\nOtherwise:\n1. targets are printed as a plain JSON array of strings (backward compatibility);\n2. all available target types are fetched.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn print_targets(args: ListTargetArgs, rich_output: bool) -> CliResult<()> {\n let mut cfg_config =\n ConfigContext::default().override_env_opt(LayerConfig::FILE_PATH_ENV, args.config_file);\n\n let mut layer_config = LayerConfig::resolve(&mut cfg_config)?;\n\n if let Some(namespace) = args.namespace {\n layer_config.target.namespace.replace(namespace);\n };\n\n if !layer_config.use_proxy {\n util::remove_proxy_env();\n }\n\n let target_types = if let Some(target_type) = args.target_type {\n Some(target_type)\n } else {\n match std::env::var(LS_TARGET_TYPES_ENV)\n .ok()\n .map(|val| serde_json::from_str::>(val.as_ref()))\n .transpose()?\n .unwrap_or_default()\n {\n vec if vec.is_empty() => None,\n vec => Some(vec),\n }\n };\n\n let targets = FoundTargets::resolve(layer_config, rich_output, target_types).await?;\n\n match args.output {\n Format::Json => {\n let serialized = if rich_output {\n serde_json::to_string(&targets).unwrap()\n } else {\n serde_json::to_string(&FoundTargetsList(&targets)).unwrap()\n };\n\n println!(\"{serialized}\");\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "print_targets", "docstring": "Fetches mirrord targets from the cluster and prints output to stdout.\n\nWhen `rich_output` is set:\n1. targets info is printed as a JSON object containing extra data;\n2. only deployment, rollout, and pod targets are fetched.\n\nOtherwise:\n1. targets are printed as a plain JSON array of strings (backward compatibility);\n2. all available target types are fetched.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/list.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/list.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d467cf89a182261382f53ea294e405667dae582cb49ee173d87d5d95f3b653fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init_tracing_registry\n\nDocumentation:\nTries to initialize tracing in the current process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn init_tracing_registry(\n command: &Commands,\n watch: drain::Watch,\n) -> Result<(), CliError> {\n // Logging to the mirrord-console always takes precedence.\n if let Ok(console_addr) = std::env::var(\"MIRRORD_CONSOLE_ADDR\") {\n mirrord_console::init_async_logger(&console_addr, watch.clone(), 124).await?;\n\n return Ok(());\n }\n\n let do_init = match command {\n // These commands are usually called from the plugins.\n //\n // They should log only when explicitly instructed.\n Commands::ListTargets(_) | Commands::ExtensionExec(_) | Commands::ExtensionContainer(_) => {\n // The final error has to be in the JSON format.\n let _ = miette::set_hook(Box::new(|_| Box::new(miette::JSONReportHandler::new())));\n\n std::env::var(\"MIRRORD_FORCE_LOG\")\n .ok()\n .and_then(|s| s.parse().ok())\n .unwrap_or(false)\n }\n\n // Proxies initialize tracing independently, after log file setup.\n Commands::InternalProxy { .. } | Commands::ExternalProxy { .. } => false,\n\n _ => true,\n };\n\n if do_init {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::fmt::layer()\n .with_writer(std::io::stderr)\n .with_file(true)\n .with_line_number(true)\n .pretty(),\n )\n .with(tracing_subscriber::EnvFilter::from_default_env())\n .init();\n }\n\n Ok(())\n}\n```"}], "func_name": "init_tracing_registry", "docstring": "Tries to initialize tracing in the current process.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/logging.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/logging.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "86c1a7c4018482e9ffb0b5d3444f73320ff5bcaef928d98712737fd0fdf337f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init_proxy_tracing_registry\n\nDocumentation:\nInitializes mirrord intproxy/extproxy tracing registry.\n\nFails if the specified log file cannot be opened/created for writing.\n\n# Log format\n\nProxies output logs in JSON, which is not really human-readable.\nHowever, it allows us to use some nice tools, like [hl](https://github.com/pamburus/hl).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn init_proxy_tracing_registry(\n log_destination: &Path,\n log_level: &str,\n json_log: bool,\n) -> std::io::Result<()> {\n if std::env::var(\"MIRRORD_CONSOLE_ADDR\").is_ok() {\n return Ok(());\n }\n\n let output_file = OpenOptions::new()\n .create(true)\n .append(true)\n .open(log_destination)?;\n\n let env_filter = EnvFilter::builder().parse_lossy(log_level);\n\n let fmt_layer_base = tracing_subscriber::fmt::layer()\n .with_ansi(false)\n .with_file(true)\n .with_line_number(true)\n .with_writer(output_file);\n let fmt_layer = if json_log {\n fmt_layer_base.json().boxed()\n } else {\n fmt_layer_base.pretty().boxed()\n };\n\n tracing_subscriber::registry()\n .with(fmt_layer)\n .with(env_filter)\n .init();\n\n Ok(())\n}\n```"}], "func_name": "init_proxy_tracing_registry", "docstring": "Initializes mirrord intproxy/extproxy tracing registry.\n\nFails if the specified log file cannot be opened/created for writing.\n\n# Log format\n\nProxies output logs in JSON, which is not really human-readable.\nHowever, it allows us to use some nice tools, like [hl](https://github.com/pamburus/hl).", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/logging.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/logging.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c4c89c696a301b28fa52a2127824a0f12b0477229db83b68bee598faf8ff5d5c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_config\n\nDocumentation:\nPrints config summary as multiple info messages, using the given [`Progress`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_config

(\n progress: &P,\n command: &[String],\n config: &LayerConfig,\n config_file_path: Option<&str>,\n operator_used: bool,\n) where\n P: Progress + Send + Sync,\n{\n progress.info(&format!(\"Running command: {}\", command.join(\" \")));\n\n let target_and_config_path_info = format!(\n \"{}, {}\",\n match &config.target.path {\n Some(path) => {\n format!(\"mirrord will target: {}\", path)\n }\n None => \"mirrord will run without a target\".into(),\n },\n match config_file_path {\n Some(path) => {\n format!(\"the configuration file was loaded from {path}\")\n }\n None => \"no configuration file was loaded\".into(),\n }\n );\n progress.info(&target_and_config_path_info);\n\n let operator_info = format!(\n \"mirrord will run {} the mirrord Operator\",\n if operator_used { \"with\" } else { \"without\" },\n );\n progress.info(&operator_info);\n\n let exclude = config.feature.env.exclude.as_ref();\n let include = config.feature.env.include.as_ref();\n let env_info = if let Some(excluded) = exclude {\n if excluded.clone().to_vec().contains(&String::from(\"*\")) {\n \"no\"\n } else {\n \"not all\"\n }\n } else if include.is_some() {\n \"not all\"\n } else {\n \"all\"\n };\n progress.info(&format!(\n \"env: {} remote environment variables will be fetched\",\n env_info\n ));\n\n let fs_info = match config.feature.fs.mode {\n FsModeConfig::Read => \"read from the remote\",\n FsModeConfig::Write => \"read from and write to the remote\",\n _ => \"read and write locally\",\n };\n progress.info(&format!(\"fs: file operations will default to {}\", fs_info));\n\n let incoming_info = match config.feature.network.incoming.mode {\n IncomingMode::Mirror => \"mirrored\",\n IncomingMode::Steal => \"stolen\",\n IncomingMode::Off => \"ignored\",\n };\n progress.info(&format!(\n \"incoming: incoming traffic will be {}\",\n incoming_info\n ));\n\n // When the http filter is set, the rules of what ports get stolen are different, so make it\n // clear to users in that case which ports are stolen.\n if config.feature.network.incoming.is_steal()\n && config.feature.network.incoming.http_filter.is_filter_set()\n {\n let filtered_ports_str = config\n .feature\n .network\n .incoming\n .http_filter\n .get_filtered_ports()\n .and_then(|filtered_ports| match filtered_ports.len() {\n 0 => None,\n 1 => Some(format!(\n \"port {} (filtered)\",\n filtered_ports.first().unwrap()\n )),\n _ => Some(format!(\"ports {filtered_ports:?} (filtered)\")),\n });\n let unfiltered_ports_str =\n config\n .feature\n .network\n .incoming\n .ports\n .as_ref()\n .and_then(|ports| match ports.len() {\n 0 => None,\n 1 => Some(format!(\n \"port {} (unfiltered)\",\n ports.iter().next().unwrap()\n )),\n _ => Some(format!(\n \"ports [{}] (unfiltered)\",\n ports\n .iter()\n .copied()\n .map(|n| n.to_string())\n .collect::>()\n .join(\", \")\n )),\n });\n let and = if filtered_ports_str.is_some() && unfiltered_ports_str.is_some() {\n \" and \"\n } else {\n \"\"\n };\n let filtered_port_str = filtered_ports_str.unwrap_or_default();\n let unfiltered_ports_str = unfiltered_ports_str.unwrap_or_default();\n progress.info(&format!(\"incoming: traffic will only be stolen from {filtered_port_str}{and}{unfiltered_ports_str}\"));\n }\n\n let outgoing_info = match (\n config.feature.network.outgoing.tcp,\n config.feature.network.outgoing.udp,\n ) {\n (true, true) => \"enabled on TCP and UDP\",\n (true, false) => \"enabled on TCP\",\n (false, true) => \"enabled on UDP\",\n (false, false) => \"disabled on TCP and UDP\",\n };\n progress.info(&format!(\"outgoing: forwarding is {}\", outgoing_info));\n\n let dns_info = match &config.feature.network.dns {\n DnsConfig { enabled: false, .. } => \"locally\",\n DnsConfig {\n enabled: true,\n filter: None,\n } => \"remotely\",\n DnsConfig {\n enabled: true,\n filter: Some(DnsFilterConfig::Remote(filters)),\n } if filters.is_empty() => \"locally\",\n DnsConfig {\n enabled: true,\n filter: Some(DnsFilterConfig::Local(filters)),\n } if filters.is_empty() => \"remotely\",\n DnsConfig {\n enabled: true,\n filter: Some(DnsFilterConfig::Remote(..)),\n } => \"locally with exceptions\",\n DnsConfig {\n enabled: true,\n filter: Some(DnsFilterConfig::Local(..)),\n } => \"remotely with exceptions\",\n };\n progress.info(&format!(\"dns: DNS will be resolved {}\", dns_info));\n progress.info(&format!(\n \"internal proxy: logs will be written to {}\",\n config.internal_proxy.log_destination.display()\n ));\n}\n```"}], "func_name": "print_config", "docstring": "Prints config summary as multiple info messages, using the given [`Progress`].", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/main.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/main.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cceba350e4cb7776d3d36bc9f7f644f5cb6d6bda2197e5a7f8bc3fb994d37b83"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_last_version\n\nDocumentation:\nFetches latest version of mirrord operator from our API\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn get_last_version() -> CliResult {\n let client = reqwest::Client::builder().build()?;\n let response: OperatorVersionResponse = client\n .get(\"https://version.mirrord.dev/v1/operator/version\")\n .send()\n .await?\n .json()\n .await?;\n\n Ok(response.operator)\n}\n```"}], "func_name": "get_last_version", "docstring": "Fetches latest version of mirrord operator from our API", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/operator.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/operator.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2258f5179e79c1347f3570dd355d69317e65d539824af87ab5bad899e8abf490"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: operator_setup\n\nDocumentation:\nSetup the operator into a file or to stdout, with explanation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn operator_setup(\n OperatorSetupParams {\n accept_tos,\n license_key,\n license_path,\n file,\n namespace,\n aws_role_arn,\n sqs_splitting,\n kafka_splitting,\n application_auto_pause,\n }: OperatorSetupParams,\n) -> CliResult<(), OperatorSetupError> {\n if !accept_tos {\n eprintln!(\"Please note that mirrord operator installation requires an active subscription for the mirrord Operator provided by MetalBear Tech LTD.\\nThe service ToS can be read here - https://metalbear.co/legal/terms\\nPass --accept-tos to accept the TOS\");\n\n return Ok(());\n }\n\n let license = match (license_key, license_path) {\n (_, Some(license_path)) => fs::read_to_string(&license_path)\n .await\n .inspect_err(|err| {\n tracing::warn!(\n \"Unable to read license at path {}: {err}\",\n license_path.display()\n )\n })\n .ok()\n .map(LicenseType::Offline),\n (Some(license_key), _) => Some(LicenseType::Online(license_key)),\n (None, None) => None,\n };\n\n // if env var std::env::var(\"MIRRORD_OPERATOR_IMAGE\") exists, use it, otherwise call async\n // function to get it\n let image = match std::env::var(\"MIRRORD_OPERATOR_IMAGE\") {\n Ok(image) => image,\n Err(_) => {\n let version = get_last_version().await?;\n format!(\"ghcr.io/metalbear-co/operator:{version}\")\n }\n };\n\n if let Some(license) = license {\n eprintln!(\n \"Installing mirrord operator with namespace: {}\",\n namespace.name()\n );\n\n let operator = Operator::new(SetupOptions {\n license,\n namespace,\n image,\n aws_role_arn,\n sqs_splitting,\n kafka_splitting,\n application_auto_pause,\n });\n\n match file {\n Some(path) => {\n let writer =\n File::create(&path).map_err(|e| OperatorSetupError::OutputFileOpen(path, e))?;\n operator.to_writer(writer)?;\n }\n None => operator.to_writer(std::io::stdout()).unwrap(), /* unwrap because failing to write to std out.. well.. */\n }\n } else {\n eprintln!(\"--license-key or --license-path is required to install on cluster\");\n }\n\n Ok(())\n}\n```"}], "func_name": "operator_setup", "docstring": "Setup the operator into a file or to stdout, with explanation.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/operator.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/operator.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e276eb0326a51f95e696c158ccccc1788e4fb013adc36e1f0ce65d7699186ec0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: operator_command\n\nDocumentation:\nHandle commands related to the operator `mirrord operator ...`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn operator_command(args: OperatorArgs) -> CliResult<()> {\n match args.command {\n OperatorCommand::Setup(params) => operator_setup(params).await.map_err(CliError::from),\n OperatorCommand::Status { config_file } => {\n StatusCommandHandler::new(config_file)\n .and_then(StatusCommandHandler::handle)\n .await\n }\n OperatorCommand::Session {\n command,\n config_file,\n } => {\n SessionCommandHandler::new(command, config_file)\n .and_then(SessionCommandHandler::handle)\n .await\n }\n }\n}\n```"}], "func_name": "operator_command", "docstring": "Handle commands related to the operator `mirrord operator ...`", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/operator.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/operator.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "403a3cb5945db9668797cf5aa28196ef544c1a942bee71b95426b034314752a9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance from the given [`IncomingConfig`].\n\n# Params\n\n* `config` - [`IncomingConfig`] is taken as `&mut` due to `add_probe_ports_to_http_ports`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(config: &mut IncomingConfig) -> Self {\n if !config.is_steal() {\n return Self::Mirror;\n }\n\n let ports = config\n .http_filter\n .ports\n .get_or_insert_default()\n .iter()\n .copied()\n .collect();\n\n let http_filter_config = &config.http_filter;\n\n // Matching all fields to make this check future-proof.\n let filter = match http_filter_config {\n HttpFilterConfig {\n path_filter: Some(path),\n header_filter: None,\n all_of: None,\n any_of: None,\n ports: _ports,\n } => StealHttpFilter::Filter(HttpFilter::Path(\n Filter::new(path.into()).expect(\"invalid filter expression\"),\n )),\n\n HttpFilterConfig {\n path_filter: None,\n header_filter: Some(header),\n all_of: None,\n any_of: None,\n ports: _ports,\n } => StealHttpFilter::Filter(HttpFilter::Header(\n Filter::new(header.into()).expect(\"invalid filter expression\"),\n )),\n\n HttpFilterConfig {\n path_filter: None,\n header_filter: None,\n all_of: Some(filters),\n any_of: None,\n ports: _ports,\n } => StealHttpFilter::Filter(Self::make_composite_filter(true, filters)),\n\n HttpFilterConfig {\n path_filter: None,\n header_filter: None,\n all_of: None,\n any_of: Some(filters),\n ports: _ports,\n } => StealHttpFilter::Filter(Self::make_composite_filter(false, filters)),\n\n HttpFilterConfig {\n path_filter: None,\n header_filter: None,\n all_of: None,\n any_of: None,\n ports: _ports,\n } => StealHttpFilter::None,\n\n _ => panic!(\"multiple HTTP filters specified, this is a bug\"),\n };\n\n Self::Steal(StealHttpSettings { filter, ports })\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance from the given [`IncomingConfig`].\n\n# Params\n\n* `config` - [`IncomingConfig`] is taken as `&mut` due to `add_probe_ports_to_http_ports`.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/port_forward.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/port_forward.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aec9264443358ba8d79beee5be24dc7445efcf8050205d56e8a29ae922626533"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: subscription\n\nDocumentation:\nReturns [`PortSubscription`] request to be used for the given port.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn subscription(&self, port: Port) -> PortSubscription {\n let Self::Steal(steal) = self else {\n return PortSubscription::Mirror(port);\n };\n\n let steal_type = match &steal.filter {\n _ if !steal.ports.contains(&port) => StealType::All(port),\n StealHttpFilter::None => StealType::All(port),\n StealHttpFilter::Filter(filter) => StealType::FilteredHttpEx(port, filter.clone()),\n };\n\n PortSubscription::Steal(steal_type)\n }\n```"}], "func_name": "subscription", "docstring": "Returns [`PortSubscription`] request to be used for the given port.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/port_forward.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/port_forward.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a3ba658434ba5875e3af74e5b219b9397a251f8d35327715a0fdad18d6db9a07"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: apply_legacy_profile\n\nDocumentation:\nApplies the given legacy [`MirrordProfile`] to the given [`FeatureConfig`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn apply_legacy_profile(\n config: &mut FeatureConfig,\n profile: MirrordProfile,\n) -> Result<(), ProfileError> {\n let MirrordProfileSpec {\n feature_adjustments,\n unknown_fields,\n } = profile.spec;\n\n if let Some(field) = unknown_fields.into_keys().next() {\n return Err(ProfileError::UnknownField(field));\n }\n\n for adjustment in feature_adjustments {\n adjustment.apply_to(config)?;\n }\n\n Ok(())\n}\n```"}], "func_name": "apply_legacy_profile", "docstring": "Applies the given legacy [`MirrordProfile`] to the given [`FeatureConfig`].", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/profile.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/profile.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2d00744d03cf8c43c3d67d3c691c4b26d1277b1fe38f0d644d24c284d315481d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: apply_profile\n\nDocumentation:\nApplies the given [`MirrordClusterProfile`] to the given [`FeatureConfig`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn apply_profile(\n config: &mut FeatureConfig,\n profile: MirrordClusterProfile,\n) -> Result<(), ProfileError> {\n let MirrordClusterProfileSpec {\n feature_adjustments,\n unknown_fields,\n } = profile.spec;\n\n if let Some(field) = unknown_fields.into_keys().next() {\n return Err(ProfileError::UnknownField(field));\n }\n\n for adjustment in feature_adjustments {\n adjustment.apply_to(config)?;\n }\n\n Ok(())\n}\n```"}], "func_name": "apply_profile", "docstring": "Applies the given [`MirrordClusterProfile`] to the given [`FeatureConfig`].", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/profile.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/profile.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ed0ee8feac3c6741f2ac40424a72947f58ec472ea4bd99b294b0f3d8aba7436b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: apply_profile_if_configured\n\nDocumentation:\nIf the [`LayerConfig::profile`] field specifies a [`MirrordProfile`] to use,\nfetches that profile from the cluster and applies it to the config.\n\nVerifies that the fetched profile does not contain any unknown fields or values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn apply_profile_if_configured(\n config: &mut LayerConfig,\n progress: &P,\n) -> Result<(), CliError> {\n let Some(name) = config.profile.as_deref() else {\n return Ok(());\n };\n\n let mut subtask = progress.subtask(&format!(\"fetching mirrord profile `{name}`\"));\n let profile: Result = try {\n let client: Client = create_kube_config(\n config.accept_invalid_certificates,\n config.kubeconfig.as_deref(),\n config.kube_context.clone(),\n )\n .await?\n .try_into()\n .map_err(KubeApiError::from)?;\n\n let api = Api::::all(client);\n api.get(name).await?\n };\n let legacy_profile: Result = try {\n let client: Client = create_kube_config(\n config.accept_invalid_certificates,\n config.kubeconfig.as_deref(),\n config.kube_context.clone(),\n )\n .await?\n .try_into()\n .map_err(KubeApiError::from)?;\n\n let api = Api::::all(client);\n api.get(name).await?\n };\n if legacy_profile.is_ok() {\n subtask.warning(\n &format!(\n \"Legacy resource kind detected, please contact your admin to migrate all resources of kind {} to {}\", \n MirrordProfile::kind(&()),\n MirrordClusterProfile::kind(&()),\n )\n );\n }\n\n match (profile, legacy_profile) {\n (Ok(profile), _) => {\n subtask.success(Some(&format!(\"mirrord cluster profile `{name}` fetched\")));\n let mut subtask = progress.subtask(&format!(\"applying mirrord profile `{name}`\"));\n apply_profile(&mut config.feature, profile)?;\n subtask.success(Some(&format!(\"mirrord profile `{name}` applied\")));\n Ok(())\n }\n (_, Ok(legacy_profile)) => {\n subtask.success(Some(&format!(\"legacy mirrord profile `{name}` fetched\")));\n let mut subtask =\n progress.subtask(&format!(\"applying legacy mirrord profile `{name}`\"));\n apply_legacy_profile(&mut config.feature, legacy_profile)?;\n subtask.success(Some(&format!(\"legacy mirrord profile `{name}` applied\")));\n Ok(())\n }\n (Err(KubeApiError::KubeError(kube::Error::Api(error))), _) if error.code == 404 => {\n Err(CliError::ProfileError(ProfileError::ProfileNotFound))\n }\n (_, Err(KubeApiError::KubeError(kube::Error::Api(error)))) if error.code == 404 => {\n Err(CliError::ProfileError(ProfileError::ProfileNotFound))\n }\n (Err(error), _) => Err(CliError::friendlier_error_or_else(error, |error| {\n CliError::ProfileError(ProfileError::ProfileFetchError(error))\n })),\n }\n}\n```"}], "func_name": "apply_profile_if_configured", "docstring": "If the [`LayerConfig::profile`] field specifies a [`MirrordProfile`] to use,\nfetches that profile from the cluster and applies it to the config.\n\nVerifies that the fetched profile does not contain any unknown fields or values.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/profile.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/profile.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f4ec255137e7122adcb49d211e3a54c6a24e5fb7af7cdcf345fff479cdf03e0b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: navigate_to_intro\n\nDocumentation:\nAttempts to open mirrord for Teams introduction in the default browser.\nIn case of failure, prints the link.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn navigate_to_intro() {\n const MIRRORD_FOR_TEAMS_URL: &str =\n \"https://metalbear.co/mirrord/docs/overview/teams/?utm_source=teamscmd&utm_medium=cli\";\n\n match get_open_command().arg(MIRRORD_FOR_TEAMS_URL).output().await {\n Ok(output) if output.status.success() => {}\n other => {\n tracing::trace!(\"failed to open browser, command result: {other:?}\");\n println!(\"To try mirrord for Teams, visit {MIRRORD_FOR_TEAMS_URL}\");\n }\n }\n}\n```"}], "func_name": "navigate_to_intro", "docstring": "Attempts to open mirrord for Teams introduction in the default browser.\nIn case of failure, prints the link.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/teams.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/teams.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8aba14bd0aba494903fb6aca8ce3987cf6df154dc6dfea67a362161a5529412e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: redirect_fd_to_dev_null\n\nDocumentation:\nUsed to pipe std[in/out/err] to \"/dev/null\" to prevent any printing to prevent any unwanted\nside effects\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn redirect_fd_to_dev_null(fd: libc::c_int) {\n let devnull_fd = libc::open(b\"/dev/null\\0\" as *const [u8; 10] as _, libc::O_RDWR);\n libc::dup2(devnull_fd, fd);\n libc::close(devnull_fd);\n}\n```"}], "func_name": "redirect_fd_to_dev_null", "docstring": "Used to pipe std[in/out/err] to \"/dev/null\" to prevent any printing to prevent any unwanted\nside effects", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/util.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2058030717b0085d403badc734e95c1610589462d02f743d26d36e86b4d56a76"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: detach_io\n\nDocumentation:\nCreate a new session for the proxy process, detaching from the original terminal.\nThis makes the process not to receive signals from the \"mirrord\" process or it's parent\nterminal fixes some side effects such as \n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) unsafe fn detach_io() -> Result<(), nix::Error> {\n nix::unistd::setsid()?;\n\n // flush before redirection\n {\n // best effort\n let _ = std::io::stdout().lock().flush();\n }\n for fd in [libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO] {\n redirect_fd_to_dev_null(fd);\n }\n Ok(())\n}\n```"}], "func_name": "detach_io", "docstring": "Create a new session for the proxy process, detaching from the original terminal.\nThis makes the process not to receive signals from the \"mirrord\" process or it's parent\nterminal fixes some side effects such as ", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/util.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "64bc026874d0cf55a7960e705f5e4f4fe11c6a82b2cb9e33fad27aad99960718"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: intproxy_container_mode\n\nDocumentation:\nReturns whether this internal proxy process runs in the container mode.\n\nUses the [`MIRRORD_INTPROXY_CONTAINER_MODE_ENV`] variable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn intproxy_container_mode() -> bool {\n std::env::var(MIRRORD_INTPROXY_CONTAINER_MODE_ENV)\n .ok()\n .and_then(|value| value.parse::().ok())\n .unwrap_or_default()\n}\n```"}], "func_name": "intproxy_container_mode", "docstring": "Returns whether this internal proxy process runs in the container mode.\n\nUses the [`MIRRORD_INTPROXY_CONTAINER_MODE_ENV`] variable.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/util.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf8fa28dd6bdf51bcc7fd6c066cf46b0260c09c2a4a2f3e9188cbbc52a36755c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_user_git_branch\n\nDocumentation:\nTries to retrieve the user's git branch from [`MIRRORD_BRANCH_NAME_ENV`] in env (set by the\nplugins) and falls back to running 'git branch --show-current' to obtain current user git\nbranch, used for metrics reporting.\n\nIf any error is encountered, including if the user is not on a git branch, the command\nproduces an empty string, and the function returns `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_user_git_branch() -> Option {\n if let Ok(branch_name) = std::env::var(MIRRORD_BRANCH_NAME_ENV) {\n return Some(branch_name);\n }\n\n match Command::new(\"git\")\n .args([\"branch\", \"--show-current\"])\n .output()\n .await\n {\n Ok(output) if output.status.success() => String::from_utf8(output.stdout)\n .ok()\n .map(|output| output.trim().to_string())\n .filter(|string| !string.is_empty()),\n Ok(output) => {\n tracing::debug!(\n status = %output.status,\n stderr = ?String::from_utf8_lossy(&output.stderr),\n \"`git branch --show-current` command failed.\"\n );\n None\n }\n Err(error) => {\n tracing::debug!(\n %error,\n \"Failed to execute `git branch` command, check that git is installed.\"\n );\n None\n }\n }\n}\n```"}], "func_name": "get_user_git_branch", "docstring": "Tries to retrieve the user's git branch from [`MIRRORD_BRANCH_NAME_ENV`] in env (set by the\nplugins) and falls back to running 'git branch --show-current' to obtain current user git\nbranch, used for metrics reporting.\n\nIf any error is encountered, including if the user is not on a git branch, the command\nproduces an empty string, and the function returns `None`.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/util.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dea0aa43924db6795509d8c2b4a400bc3c6322c83daac46cc771c9354dbfa4bc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: verify_config\n\nDocumentation:\nVerifies a config file specified by `path`.\n\n## Usage\n\n```sh\nmirrord verify-config [path]\n```\n\n- Example:\n\n```sh\nmirrord verify-config ./valid-config.json\n\n\n{\n\"type\": \"Success\",\n\"config\": {\n\"path\": {\n\"deployment\": \"sample-deployment\",\n},\n\"namespace\": null\n},\n\"warnings\": [],\n\"compatible_target_types\": [\"targetless\", \"deployment\", \"rollout\", \"pod\"]\n}\n```\n\n```sh\nmirrord verify-config ./broken-config.json\n\n\n{\n\"type\": \"Fail\",\n\"errors\": [\"mirrord-config: IO operation failed with `No such file or directory (os error 2)`\"]\n}\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn verify_config(\n VerifyConfigArgs { ide, path }: VerifyConfigArgs,\n) -> CliResult<()> {\n let mut config_context = ConfigContext::default()\n .empty_target_final(ide)\n .override_env(LayerConfig::FILE_PATH_ENV, path);\n\n let layer_config =\n std::future::ready(LayerConfig::resolve(&mut config_context).map_err(CliError::from))\n .and_then(|mut config| async {\n crate::profile::apply_profile_if_configured(&mut config, &NullProgress).await?;\n Ok(config)\n })\n .and_then(|config| async {\n config.verify(&mut config_context)?;\n Ok(config)\n })\n .await;\n\n let verified = match layer_config {\n Ok(config) => VerifiedConfig::Success {\n config: config.target.into(),\n warnings: config_context.into_warnings(),\n compatible_target_types: TargetType::all()\n .filter(|tt| tt.compatible_with(&config.feature))\n .collect(),\n },\n Err(fail) => VerifiedConfig::Fail {\n errors: vec![fail.to_string()],\n },\n };\n\n println!(\"{}\", serde_json::to_string_pretty(&verified)?);\n\n Ok(())\n}\n```"}], "func_name": "verify_config", "docstring": "Verifies a config file specified by `path`.\n\n## Usage\n\n```sh\nmirrord verify-config [path]\n```\n\n- Example:\n\n```sh\nmirrord verify-config ./valid-config.json\n\n\n{\n\"type\": \"Success\",\n\"config\": {\n\"path\": {\n\"deployment\": \"sample-deployment\",\n},\n\"namespace\": null\n},\n\"warnings\": [],\n\"compatible_target_types\": [\"targetless\", \"deployment\", \"rollout\", \"pod\"]\n}\n```\n\n```sh\nmirrord verify-config ./broken-config.json\n\n\n{\n\"type\": \"Fail\",\n\"errors\": [\"mirrord-config: IO operation failed with `No such file or directory (os error 2)`\"]\n}\n```", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/verify_config.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/verify_config.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0575a7980710b86fee6aea7349c83bf6717e2267f218ec779b175bfac2d39e95"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_command_extension_params\n\nDocumentation:\nConvert to a serializable form to be used in mirrord extensions.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_command_extension_params(self) -> ExtensionRuntimeCommand {\n let RuntimeCommandBuilder {\n runtime,\n extra_args,\n ..\n } = self;\n\n ExtensionRuntimeCommand {\n runtime,\n extra_args,\n }\n }\n```"}], "func_name": "into_command_extension_params", "docstring": "Convert to a serializable form to be used in mirrord extensions.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/container/command_builder.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/container/command_builder.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1676372ef0d8e36c07676fcc7268810bcde1bd90704f4e1c9ff3988536864de4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_command_args\n\nDocumentation:\nReturn completed command with updated arguments.\n\nTo be used when mirrord CLI executes the command.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_command_args(self) -> (String, impl Iterator) {\n let RuntimeCommandBuilder {\n runtime,\n extra_args,\n step,\n } = self;\n\n let (runtime_command, runtime_args) = step.command.into_parts();\n\n (\n runtime.to_string(),\n runtime_command\n .into_iter()\n .chain(extra_args)\n .chain(runtime_args),\n )\n }\n```"}], "func_name": "into_command_args", "docstring": "Return completed command with updated arguments.\n\nTo be used when mirrord CLI executes the command.", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/container/command_builder.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/container/command_builder.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb2386bc5a56bbef418f2627310c4342d447475a1ff0c7ea86563bd8f0851f35"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_ready_lines\n\nDocumentation:\nReads all ready lines from the given reader.\n\nReturns the lines concatenated with `\\n` chars (to indicate line breaks).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_ready_lines(stderr: &mut Lines>) -> String {\n let mut buf = vec![];\n\n while let Some(result) = stderr.next_line().now_or_never() {\n match result {\n Err(..) => break,\n Ok(None) => break,\n Ok(Some(line)) => buf.push(line),\n }\n }\n\n buf.join(\"\\\\n\")\n }\n```"}], "func_name": "read_ready_lines", "docstring": "Reads all ready lines from the given reader.\n\nReturns the lines concatenated with `\\n` chars (to indicate line breaks).", "repo": "metalbear-co/mirrord", "path": "mirrord/cli/src/container/sidecar.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/cli/src/container/sidecar.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a281748c47f2cf49daa7a9ff56ceba878dc8c38f8020482175b867329672483c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_option\n\nDocumentation:\nCheck if field is `Option` and if so return type of `T`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_option(field: &Field) -> Option {\n let seg = if let Type::Path(ty) = &field.ty {\n ty.path.segments.first()\n } else {\n None\n }?;\n\n (seg.ident == \"Option\").then(|| match &seg.arguments {\n PathArguments::AngleBracketed(generics) => match generics.args.first() {\n Some(GenericArgument::Type(ty)) => Some(ty.clone()),\n _ => None,\n },\n _ => None,\n })?\n }\n```"}], "func_name": "is_option", "docstring": "Check if field is `Option` and if so return type of `T`", "repo": "metalbear-co/mirrord", "path": "mirrord/config/derive/src/config/field.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/derive/src/config/field.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f41190d190549fdef548cb8049d82702509c4113186514a616d3f0b7c92a365f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: definition\n\nDocumentation:\nWill create the stuct definition part of the code\n\n#### 1\n```rust\n#[config(env = \"TEST\")]\npub test: String,\n```\nWill output\n```rust\npub test: Option\n```\n\n#### 2\n```rust\n#[config(nested)]\npub test: OtherConfig,\n```\nWill output\n```rust\npub test: ::Generator\n```\n\n#### 3\n```rust\n#[config(rename = \"test2\")]\npub test: OtherConfig,\n```\nWill output\n```rust\n#[serde(rename = \"test2\")]\npub test: Option\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn definition(&self) -> impl ToTokens {\n let ConfigField {\n ident,\n vis,\n ty,\n option,\n flags,\n ..\n } = &self;\n\n let docs = flags.doc.iter().map(ToTokens::to_token_stream);\n\n let ty = option.as_ref().unwrap_or(ty);\n\n let target = if flags.nested {\n let inner = quote! { <#ty as crate::config::FromMirrordConfig>::Generator };\n\n if flags.toggleable {\n quote! { crate::util::ToggleableConfig<#inner> }\n } else {\n inner\n }\n } else {\n quote! { #ty }\n };\n\n let rename = flags\n .rename\n .as_ref()\n .map(|rename| quote! { #[serde(rename = #rename)] });\n\n quote! {\n #(#docs)*\n #rename\n #vis #ident: Option<#target>\n }\n }\n```"}], "func_name": "definition", "docstring": "Will create the stuct definition part of the code\n\n#### 1\n```rust\n#[config(env = \"TEST\")]\npub test: String,\n```\nWill output\n```rust\npub test: Option\n```\n\n#### 2\n```rust\n#[config(nested)]\npub test: OtherConfig,\n```\nWill output\n```rust\npub test: ::Generator\n```\n\n#### 3\n```rust\n#[config(rename = \"test2\")]\npub test: OtherConfig,\n```\nWill output\n```rust\n#[serde(rename = \"test2\")]\npub test: Option\n```", "repo": "metalbear-co/mirrord", "path": "mirrord/config/derive/src/config/field.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/derive/src/config/field.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "32d1a657ba26535b70771c2cb149b64bcf79e428dd0ab09e348a063b96a01249"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: implmentation\n\nDocumentation:\nWill create the actual implementation of the\n\n#### 1\n```rust\n#[config(env = \"TEST\")]\npub test: String,\n```\nWill output\n```rust\ntest: crate::config::from_env::FromEnv::new(\"TEST\").or(self.test)\n.source_value().transpose()?\n.ok_or(crate::config::ConfigError::ValueNotProvided(\"MyConfig\", \"test\", Some(\"TEST\")))?\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn implmentation(&self, parent: &Ident) -> impl ToTokens {\n let ConfigField {\n ident,\n option,\n flags,\n ..\n } = &self;\n\n // Rest of flow is irrelevant for nested config.\n if flags.nested {\n return quote! { #ident: self.#ident.unwrap_or_default().generate_config(context)? };\n }\n\n let mut impls = Vec::new();\n\n if let Some(env) = flags.env.as_ref() {\n impls.push(env.to_token_stream());\n }\n\n impls.push(quote! { self.#ident });\n\n let mut layers = Vec::new();\n\n if let Some(lit) = flags.deprecated.as_ref() {\n layers.push(\n quote! { .layer(|next| crate::config::deprecated::Deprecated::new(#lit, next)) },\n );\n }\n\n if flags.unstable {\n layers.push(\n quote! { .layer(|next| crate::config::unstable::Unstable::new(stringify!(#parent), stringify!(#ident), next)) }\n );\n }\n\n let unwrapper = option.is_none().then(|| {\n let env_override = match &flags.env {\n Some(EnvFlag(flag)) => quote! { Some(#flag) },\n None => quote! { None }\n };\n\n // unwrap to default if exists\n if let Some(default) = flags.default.as_ref() {\n quote! {#default}\n } else {\n quote! { .ok_or(crate::config::ConfigError::ValueNotProvided(stringify!(#parent), stringify!(#ident), #env_override))? }\n }\n });\n\n let impls = impls\n .into_iter()\n .reduce(|acc, impl_| quote! { #acc.or(#impl_) });\n\n if layers.is_empty() {\n quote! { #ident: #impls .source_value(context).transpose()?#unwrapper }\n } else {\n quote! { #ident: #impls #(#layers),* .source_value(context).transpose()?#unwrapper }\n }\n }\n```"}], "func_name": "implmentation", "docstring": "Will create the actual implementation of the\n\n#### 1\n```rust\n#[config(env = \"TEST\")]\npub test: String,\n```\nWill output\n```rust\ntest: crate::config::from_env::FromEnv::new(\"TEST\").or(self.test)\n.source_value().transpose()?\n.ok_or(crate::config::ConfigError::ValueNotProvided(\"MyConfig\", \"test\", Some(\"TEST\")))?\n```", "repo": "metalbear-co/mirrord", "path": "mirrord/config/derive/src/config/field.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/derive/src/config/field.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c6166eb76c6c8cc4dfa161ce55515bb32b8dfcc1d304706afda33c3f04729f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lit_in_meta_name_value\n\nDocumentation:\nRetrieves the [`enum@Lit`] that is inside a [`MetaNameValue`].\n\nThe [`enum@Lit`] can be:\n1. The `CatFile` in `map_to = \"CatFile\"`;\n2. The `JsonSchema` in `derive = \"JsonSchema\"`;\n3. The `CatUserConfig` in `generator = \"CatUserConfig\"`;\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn lit_in_meta_name_value(meta: &MetaNameValue) -> Option {\n if let MetaNameValue {\n path: _,\n eq_token: _,\n value: Expr::Lit(ExprLit { lit, .. }),\n } = meta\n {\n Some(lit.clone())\n } else {\n None\n }\n}\n```"}], "func_name": "lit_in_meta_name_value", "docstring": "Retrieves the [`enum@Lit`] that is inside a [`MetaNameValue`].\n\nThe [`enum@Lit`] can be:\n1. The `CatFile` in `map_to = \"CatFile\"`;\n2. The `JsonSchema` in `derive = \"JsonSchema\"`;\n3. The `CatUserConfig` in `generator = \"CatUserConfig\"`;", "repo": "metalbear-co/mirrord", "path": "mirrord/config/derive/src/config/flag.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/derive/src/config/flag.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f04f232e59f7caa7208a1484dfe20641c0f75620302aafc5b768684406ceb7db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nDigs into the [`syn::MetaList`] of the list of [`Attribute`] to fill up our\n[`ConfigFlags`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(attrs: &[Attribute], mode: ConfigFlagsType) -> Result {\n let mut flags = ConfigFlags {\n doc: attrs\n .iter()\n .filter(|attr| attr.path().is_ident(\"doc\"))\n .cloned()\n .collect(),\n ..Default::default()\n };\n\n for meta_list in attrs\n .iter()\n .filter(|attr| attr.path().is_ident(\"config\"))\n .filter_map(|attr| attr.meta.require_list().ok())\n {\n // The more flexible way of parsing nested `Meta` in a `MetaList` is to use\n // `parse_nested_meta`, but it's also more troublesome, as it parses the meta\n // attribute in a weird way for our usecase.\n // Consider something like\n // `#[config(map_to = \"CatFile\", derive = \"JsonSchema\")]`, it would parse this\n // as `Path {map_to, CatFile}` and the rest of the input would be\n // `, derive = \"JsonSchema\"`, which is a bigger hassle to parse.\n //\n // Also, error handling becomes more problematic with `parse_nested_meta`.\n let nested =\n meta_list.parse_args_with(Punctuated::::parse_terminated)?;\n\n // Let's look into the nested `Meta` to possibly set multiple flags.\n for meta in nested {\n match meta {\n Meta::Path(path)\n if mode == ConfigFlagsType::Field && path.is_ident(\"nested\") =>\n {\n flags.nested = true;\n }\n Meta::Path(path)\n if mode == ConfigFlagsType::Field && path.is_ident(\"toggleable\") =>\n {\n flags.toggleable = true;\n }\n Meta::Path(path)\n if mode == ConfigFlagsType::Field && path.is_ident(\"unstable\") =>\n {\n flags.unstable = true;\n }\n Meta::NameValue(meta)\n if mode == ConfigFlagsType::Field && meta.path.is_ident(\"env\") =>\n {\n flags.env = Some(EnvFlag(meta.value));\n }\n Meta::Path(path)\n if mode == ConfigFlagsType::Field && path.is_ident(\"default\") =>\n {\n flags.default = Some(DefaultFlag::Flag);\n }\n Meta::NameValue(meta)\n if mode == ConfigFlagsType::Field && meta.path.is_ident(\"default\") =>\n {\n flags.default = Some(\n lit_in_meta_name_value(&meta)\n .map(DefaultFlag::Value)\n .unwrap_or_else(|| DefaultFlag::Expr(meta.value)),\n );\n }\n Meta::NameValue(meta)\n if mode == ConfigFlagsType::Field && meta.path.is_ident(\"rename\") =>\n {\n flags.rename = lit_in_meta_name_value(&meta);\n }\n Meta::NameValue(meta)\n if mode == ConfigFlagsType::Field && meta.path.is_ident(\"deprecated\") =>\n {\n flags.deprecated = lit_in_meta_name_value(&meta);\n }\n Meta::NameValue(meta)\n if mode == ConfigFlagsType::Container && meta.path.is_ident(\"map_to\") =>\n {\n lit_in_meta_name_value(&meta).map(|lit| match lit {\n Lit::Str(val) => {\n flags.map_to = Some(Ident::new(&val.value(), Span::call_site()));\n Ok(())\n }\n _ => Err(lit\n .span()\n .error(\"map_to should be a string literal as value\")),\n });\n }\n Meta::NameValue(meta)\n if mode == ConfigFlagsType::Container && meta.path.is_ident(\"derive\") =>\n {\n lit_in_meta_name_value(&meta).map(|lit| match lit {\n Lit::Str(val) => {\n flags.derive.extend(\n val.value()\n .split(',')\n .map(|part| Ident::new(part.trim(), Span::call_site())),\n );\n Ok(())\n }\n _ => Err(lit\n .span()\n .error(\"derive should be a string literal as value\")),\n });\n }\n Meta::NameValue(meta)\n if mode == ConfigFlagsType::Container\n && meta.path.is_ident(\"generator\") =>\n {\n lit_in_meta_name_value(&meta).map(|lit| match lit {\n Lit::Str(val) => {\n flags.generator = Some(Ident::new(&val.value(), Span::call_site()));\n Ok(())\n }\n _ => Err(lit\n .span()\n .error(\"derive should be a string literal as value\")),\n });\n }\n _ => {\n return Err(meta.path().span().error(\n \"unsupported config\n attribute flag\",\n ))\n }\n }\n }\n }\n\n Ok(flags)\n }\n```"}], "func_name": "new", "docstring": "Digs into the [`syn::MetaList`] of the list of [`Attribute`] to fill up our\n[`ConfigFlags`].", "repo": "metalbear-co/mirrord", "path": "mirrord/config/derive/src/config/flag.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/derive/src/config/flag.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d6c9c64730ef48ff1a3e54e526e4bb83ba02144f0001977b1040385386274f64"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: all\n\nDocumentation:\nAll capabilities that can be used by the agent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn all() -> &'static [Self] {\n &[\n Self::SysAdmin,\n Self::SysPtrace,\n Self::NetRaw,\n Self::NetAdmin,\n ]\n }\n```"}], "func_name": "all", "docstring": "All capabilities that can be used by the agent.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/agent.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/agent.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7aadf2ce1dafbb520724c04b5140f0e1ea6c2f894897ca17e9f624d8c28c200c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_config\n\nDocumentation:\nGenerates the [`AgentImageConfig`] from the `agent.image` config, or the\n`MIRRORD_AGENT_IMAGE` env var.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_config(self, context: &mut ConfigContext) -> config::Result {\n let agent_image = match self {\n AgentImageFileConfig::Simple(registry_and_tag) => {\n registry_and_tag.unwrap_or_else(|| {\n format!(\n \"{DEFAULT_AGENT_IMAGE_REGISTRY}:{}\",\n env!(\"CARGO_PKG_VERSION\")\n )\n })\n }\n AgentImageFileConfig::Advanced { registry, tag } => {\n format!(\n \"{}:{}\",\n registry.unwrap_or_else(|| DEFAULT_AGENT_IMAGE_REGISTRY.to_string()),\n tag.unwrap_or_else(|| env!(\"CARGO_PKG_VERSION\").to_string()),\n )\n }\n };\n\n // Env overrides configuration if both there.\n let agent_image = Self::get_image_from_env(context)?.unwrap_or(agent_image);\n\n Ok(AgentImageConfig(agent_image))\n }\n```"}], "func_name": "generate_config", "docstring": "Generates the [`AgentImageConfig`] from the `agent.image` config, or the\n`MIRRORD_AGENT_IMAGE` env var.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/agent.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/agent.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5636aa4bd98f05974e543b4660e83b66577ad15574de2ff0140623007fb741b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decode\n\nDocumentation:\nDecodes an encoded [`LayerConfig`].\n\nYou can encode the config with [`LayerConfig::encode`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn decode(encoded_value: &str) -> Result {\n let decoded = BASE64_STANDARD\n .decode(encoded_value)\n .map_err(|error| ConfigError::DecodeError(error.to_string()))?;\n let deserialized = serde_json::from_slice(&decoded)\n .map_err(|error| ConfigError::DecodeError(error.to_string()))?;\n\n Ok(deserialized)\n }\n```"}], "func_name": "decode", "docstring": "Decodes an encoded [`LayerConfig`].\n\nYou can encode the config with [`LayerConfig::encode`].", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0672c7ef292cea30ceefebdbaa8e42b3bfa0b6dfd57d1ea3e3275a516e4deebe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode\n\nDocumentation:\nEncodes this config to a string.\n\nYou can decode the config with [`LayerConfig::decode`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn encode(&self) -> Result {\n let serialized = serde_json::to_string(self)\n .map_err(|error| ConfigError::EncodeError(error.to_string()))?;\n let encoded = BASE64_STANDARD.encode(serialized);\n\n Ok(encoded)\n }\n```"}], "func_name": "encode", "docstring": "Encodes this config to a string.\n\nYou can decode the config with [`LayerConfig::decode`].", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea0ae20b5058a1dddbd8e99e7575d5e4263bcf300ec090932ea419b03cbb039c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve\n\nDocumentation:\nResolves the config from the environment variables.\n\nOn success, returns the config and a [`ConfigContext`] that holds warnings.\nTo be used from CLI entry points to resolve user config and print warnings.\n\nThis function **does not** use [`LayerConfig::RESOLVED_CONFIG_ENV`] nor\n[`LayerConfig::decode`]. It resolves the config from scratch.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn resolve(context: &mut ConfigContext) -> Result {\n let config = if let Ok(path) = context.get_env(Self::FILE_PATH_ENV) {\n LayerFileConfig::from_path(path)?.generate_config(context)\n } else {\n LayerFileConfig::default().generate_config(context)\n }?;\n\n Ok(config)\n }\n```"}], "func_name": "resolve", "docstring": "Resolves the config from the environment variables.\n\nOn success, returns the config and a [`ConfigContext`] that holds warnings.\nTo be used from CLI entry points to resolve user config and print warnings.\n\nThis function **does not** use [`LayerConfig::RESOLVED_CONFIG_ENV`] nor\n[`LayerConfig::decode`]. It resolves the config from scratch.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6db644c479b787ee42a1ac456f7075b47967d24303d7af778026300e661c48ac"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: verify\n\nDocumentation:\nVerifies that there are no conflicting settings in this config.\n\nFills the given [`ConfigContext`] with warnings.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn verify(&self, context: &mut ConfigContext) -> Result<(), ConfigError> {\n if self.agent.ephemeral && self.agent.namespace.is_some() {\n context.add_warning(\n \"Agent namespace is ignored when using an ephemeral container for the agent.\"\n .to_string(),\n );\n }\n\n if matches!(\n self.feature.network.outgoing.filter,\n Some(OutgoingFilterConfig::Remote(_))\n ) && !self.feature.network.dns.enabled\n {\n context.add_warning(\n \"The mirrord outgoing traffic filter includes host names to be connected remotely, \\\n but the remote DNS feature is disabled, so the addresses of these hosts will be \\\n resolved locally. Consider enabling the remote DNS resolution feature.\".to_string(),\n );\n }\n\n let http_filter = &self.feature.network.incoming.http_filter;\n let used_filters = [\n http_filter.path_filter.is_some(),\n http_filter.header_filter.is_some(),\n http_filter.all_of.is_some(),\n http_filter.any_of.is_some(),\n ]\n .into_iter()\n .filter(|used| *used)\n .count();\n if used_filters > 1 {\n Err(ConfigError::Conflict(\n \"Cannot use multiple types of HTTP filter at the same time, use 'any_of' or 'all_of' to combine filters\".to_string(),\n ))?\n }\n\n if [http_filter.all_of.as_ref(), http_filter.any_of.as_ref()]\n .into_iter()\n .flatten()\n .any(Vec::is_empty)\n {\n Err(ConfigError::Conflict(\n \"Composite HTTP filter cannot be empty\".to_string(),\n ))?;\n }\n\n if !self.feature.network.incoming.ignore_ports.is_empty()\n && self.feature.network.incoming.ports.is_some()\n {\n Err(ConfigError::Conflict(\n \"Cannot use both `incoming.ignore_ports` and `incoming.ports` at the same time\"\n .to_string(),\n ))?\n }\n\n if let (Some(unfiltered_ports), Some(filtered_ports)) = (\n self.feature.network.incoming.ports.as_ref(),\n self.feature\n .network\n .incoming\n .http_filter\n .get_filtered_ports(),\n ) {\n let intersection = filtered_ports\n .iter()\n .copied()\n .filter(|port| unfiltered_ports.contains(port))\n .collect::>();\n if intersection.is_empty().not() {\n Err(ConfigError::Conflict(format!(\n \"Ports {intersection:?} are present in both `feature.network.incoming.ports` and \\\n `feature.network.incoming.http_filter.ports`. These lists must remain disjoint. \\\n If you want traffic to a port to be filtered, \\\n include it only in `feature.network.incoming.http_filter.ports`. \\\n To steal all the traffic from that port without filtering, \\\n include it only in `feature.network.incoming.ports`.\"\n )))?\n }\n }\n\n self.feature\n .network\n .incoming\n .https_delivery\n .verify(context)?;\n\n if !self.feature.copy_target.enabled\n && self\n .target\n .path\n .as_ref()\n .map(Target::requires_copy)\n .unwrap_or_default()\n {\n Err(ConfigError::TargetJobWithoutCopyTarget)?\n }\n\n let is_targetless = match self.target.path.as_ref() {\n Some(Target::Targetless) => true,\n None => context.is_empty_target_final().not(),\n _ => false,\n };\n\n if is_targetless {\n if self.feature.network.incoming.is_steal() {\n Err(ConfigError::Conflict(\"Steal mode is not compatible with a targetless agent, please either disable this option or specify a target.\".into()))?\n }\n\n if self.agent.ephemeral {\n Err(ConfigError::Conflict(\n \"Using an ephemeral container for the agent is not \\\n compatible with a targetless agent, please either disable this option or \\\n specify a target.\"\n .into(),\n ))?\n }\n\n if self.agent.namespace.is_some() {\n context.add_warning(\n \"Agent namespace is ignored in targetless runs. \\\n To specify a namespace for a targetless run, use target namespace.\"\n .into(),\n );\n }\n }\n\n if self.feature.copy_target.enabled {\n if self.operator == Some(false) {\n return Err(ConfigError::Conflict(\n \"The copy target feature requires a mirrord operator, \\\n please either disable this option or use the operator.\"\n .into(),\n ));\n }\n\n // Target may also be set later in the UI.\n if is_targetless {\n return Err(ConfigError::Conflict(\n \"The copy target feature is not compatible with a targetless agent, \\\n please either disable this option or specify a target.\"\n .into(),\n ));\n }\n\n if matches!(self.target.path, Some(Target::Service(..))) {\n return Err(ConfigError::Conflict(\n \"The copy target feature is not yet supported with service targets, \\\n please either disable this option or specify an exact workload covered by this service.\"\n .into()\n ));\n }\n\n if !self.feature.network.incoming.is_steal() {\n context.add_warning(\n \"Using copy target feature without steal mode \\\n may result in unreturned responses in cluster \\\n because the underlying app instance is not copied \\\n and therefore not running in the copied pod\"\n .into(),\n );\n }\n }\n\n // operator is disabled, but target requires it.\n if self\n .target\n .path\n .as_ref()\n .is_some_and(Target::requires_operator)\n && !self.operator.unwrap_or(true)\n {\n return Err(ConfigError::TargetRequiresOperator);\n }\n\n if self\n .feature\n .network\n .incoming\n .port_mapping\n .iter()\n .any(|(to, from)| to == from)\n {\n context.add_warning(\n \"The feature.network.incoming.port_mapping mirrord configuration field \\\n contains a mapping of a local port to the same remote port. \\\n A mapping is only necessary when the local application is listening on \\\n a different port than the remote one.\"\n .into(),\n );\n }\n\n // Env vars\n if self.feature.env.exclude.is_some() && self.feature.env.include.is_some() {\n return Err(ConfigError::Conflict(\n \"cannot use both `include` and `exclude` filters for environment variables\"\n .to_string(),\n ));\n }\n\n if let Some(env_vars_mapping) = self.feature.env.mapping.clone() {\n EnvVarsRemapper::new(env_vars_mapping, HashMap::new())?;\n }\n\n self.feature.network.dns.verify(context)?;\n self.feature.network.outgoing.verify(context)?;\n self.feature.split_queues.verify(context)?;\n\n if self.experimental.readlink {\n context.add_warning(\n \"experimental.readlink config has been deprecated, and `readlink` is now\\\n enabled by default! You may remove it from your config.\"\n .into(),\n );\n }\n\n if self.experimental.readonly_file_buffer.is_some() {\n return Err(ConfigError::Conflict(\n \"cannot use experimental.readonly_file_buffer, as it has been moved. Use feature.fs.readonly_file_buffer instead.\"\n .to_string(),\n ));\n }\n\n if self.feature.fs.readonly_file_buffer > READONLY_FILE_BUFFER_HARD_LIMIT {\n return Err(ConfigError::InvalidValue {\n name: \"feature.fs.readonly_file_buffer\",\n provided: self.feature.fs.readonly_file_buffer.to_string(),\n error: format!(\n \"the value of feature.fs.readonly_file_buffer must be {} Megabytes or less.\",\n READONLY_FILE_BUFFER_HARD_LIMIT / 1024 / 1024\n )\n .into(),\n });\n } else if self.feature.fs.readonly_file_buffer > READONLY_FILE_BUFFER_WARN_LIMIT {\n context.add_warning(format!(\n \"The value of feature.fs.readonly_file_buffer is more than {} Megabyte. \\\n Large values may increase the risk of timeouts.\",\n READONLY_FILE_BUFFER_WARN_LIMIT / 1024 / 1024,\n ));\n }\n\n if let (Some(profile), true) = (&self.profile, context.has_warnings()) {\n // It might be that the user config is fine,\n // but the mirrord profile introduced changes that triggered the warnings.\n context.add_warning(format!(\n \"Config verification was done after applying mirrord profile `{profile}`. \\\n You can inspect the profile with `kubectl get mirrordclusterprofile {profile} -o yaml`.\",\n ));\n }\n\n Ok(())\n }\n```"}], "func_name": "verify", "docstring": "Verifies that there are no conflicting settings in this config.\n\nFills the given [`ConfigContext`] with warnings.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5a7d85eb57725901e53dde4823959d25c0bdc07d6305a5e1e6a0ca7f5853691"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_proxy_logfile_path\n\nDocumentation:\nReturns a default randomized path for proxy logs.\n\n`prefix` can be passed to distinguish between intproxy and extproxy logs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn default_proxy_logfile_path(prefix: &str) -> PathBuf {\n let random_name: String = Alphanumeric.sample_string(&mut rand::rng(), 7);\n let timestamp = SystemTime::UNIX_EPOCH\n .elapsed()\n .expect(\"system time should not be earlier than UNIX EPOCH\")\n .as_secs();\n\n let mut path = std::env::temp_dir();\n path.push(format!(\"{prefix}-{timestamp}-{random_name}.log\"));\n path\n}\n```"}], "func_name": "default_proxy_logfile_path", "docstring": "Returns a default randomized path for proxy logs.\n\n`prefix` can be passed to distinguish between intproxy and extproxy logs.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "328c524dd9d6351102ff03f12fe982b6672d5b6a6ed84c0b9f2c08c5e2a49110"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_schema_to_file\n\nDocumentation:\n\nWrites the config schema to a file (uploaded to the schema store).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_schema_to_file(schema: &RootSchema) -> File {\n println!(\"Writing schema to file.\");\n\n let content = serde_json::to_string_pretty(&schema).expect(\"Failed generating schema!\");\n let mut file = OpenOptions::new()\n .create(true)\n .write(true)\n .truncate(true)\n .read(true)\n .open(SCHEMA_FILE_PATH)\n .expect(\"Failed to create schema file!\");\n\n let _ = file\n .write(content.as_bytes())\n .expect(\"Failed writing schema to file!\");\n\n file\n }\n```"}], "func_name": "write_schema_to_file", "docstring": "\nWrites the config schema to a file (uploaded to the schema store).", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "06eba39c167d63f416c7ac2bc3e5fc2b840e6818b77078a28e2a638f403ac040"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_target_path_from_env\n\nDocumentation:\nGet the target path from the env var, `Ok(None)` if not set, `Err` if invalid value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_target_path_from_env(context: &mut ConfigContext) -> Result> {\n FromEnvWithError::new(\"MIRRORD_IMPERSONATED_TARGET\")\n .source_value(context)\n .transpose()\n }\n```"}], "func_name": "get_target_path_from_env", "docstring": "Get the target path from the env var, `Ok(None)` if not set, `Err` if invalid value.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/target.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/target.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "082f21e22a3fa0314efe66500e17da59d276a8ede2894effb8967f48afb145cb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_target_namespace_from_env\n\nDocumentation:\nGet the target namespace from the env var, `Ok(None)` if not set, `Err` if invalid value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_target_namespace_from_env(context: &mut ConfigContext) -> Result> {\n FromEnv::new(\"MIRRORD_TARGET_NAMESPACE\")\n .source_value(context)\n .transpose()\n }\n```"}], "func_name": "get_target_namespace_from_env", "docstring": "Get the target namespace from the env var, `Ok(None)` if not set, `Err` if invalid value.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/target.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/target.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6c2637f211be351ba5d589d34e422774f5d6afab8b360926859bb3fed907582"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_config\n\nDocumentation:\nGenerate the final config object, out of the configuration parsed from a configuration file,\nfactoring in environment variables (which are also set by the front end - CLI/IDE-plugin).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_config(self, context: &mut ConfigContext) -> Result {\n let (path_from_conf_file, namespace_from_conf_file) = match self {\n TargetFileConfig::Simple(path) => (path, None),\n TargetFileConfig::Advanced { path, namespace } => (path, namespace),\n };\n\n // Env overrides configuration if both there.\n let path = Self::get_target_path_from_env(context)?.or(path_from_conf_file);\n let namespace = Self::get_target_namespace_from_env(context)?.or(namespace_from_conf_file);\n Ok(TargetConfig { path, namespace })\n }\n```"}], "func_name": "generate_config", "docstring": "Generate the final config object, out of the configuration parsed from a configuration file,\nfactoring in environment variables (which are also set by the front end - CLI/IDE-plugin).", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/target.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/target.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6dcdf3e8bdda7f8a5776e1afbea648965c8f3668f3b5648c58a405643d8ace36"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: requires_copy\n\nDocumentation:\n`true` if this [`Target`] is only supported when the copy target feature is enabled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn requires_copy(&self) -> bool {\n matches!(self, Target::Job(_) | Target::CronJob(_))\n }\n```"}], "func_name": "requires_copy", "docstring": "`true` if this [`Target`] is only supported when the copy target feature is enabled.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/target.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/target.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b1814cc70b01f3fc4a1c1639ebc421cf169c0cc8b1c09cb6982348c0518506e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: requires_operator\n\nDocumentation:\n`true` if this [`Target`] is only supported when the operator is enabled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn requires_operator(&self) -> bool {\n matches!(\n self,\n Target::Job(_)\n | Target::CronJob(_)\n | Target::StatefulSet(_)\n | Target::Service(_)\n | Target::ReplicaSet(_)\n )\n }\n```"}], "func_name": "requires_operator", "docstring": "`true` if this [`Target`] is only supported when the operator is enabled.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/target.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/target.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea5db6f27d1c15bf9183f60c049d14f060a74027bb6574df293bea9aca0a0b56"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_resolved_config\n\nDocumentation:\nConvenience function to be used in mirrord-intproxy, mirrord-extproxy and mirrord-layer.\n\nReads the resolved [`LayerConfig`] from the [`LayerConfig::RESOLVED_CONFIG_ENV`]\nenvironment variable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_resolved_config() -> Result {\n let encoded = std::env::var(LayerConfig::RESOLVED_CONFIG_ENV).map_err(|error| {\n ConfigError::DecodeError(format!(\n \"failed to access the {} variable: {error}\",\n LayerConfig::RESOLVED_CONFIG_ENV\n ))\n })?;\n\n LayerConfig::decode(&encoded)\n}\n```"}], "func_name": "read_resolved_config", "docstring": "Convenience function to be used in mirrord-intproxy, mirrord-extproxy and mirrord-layer.\n\nReads the resolved [`LayerConfig`] from the [`LayerConfig::RESOLVED_CONFIG_ENV`]\nenvironment variable.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/util.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d77083bf75e1d4d978053fc98ad77a4f8a645fb014449fd6eaae04e0500491c8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: override_env\n\nDocumentation:\nAdds an override for an environment variable.\n\nThis override will only affect [`Self::get_env`] behavior,\nit will **not** change the process environment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn override_env, V: AsRef>(mut self, key: K, value: V) -> Self {\n self.env_override\n .insert(key.as_ref().into(), value.as_ref().into());\n self\n }\n```"}], "func_name": "override_env", "docstring": "Adds an override for an environment variable.\n\nThis override will only affect [`Self::get_env`] behavior,\nit will **not** change the process environment.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/config/context.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/config/context.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "49fb1836bc6abcb9ac97f5966e4b6c9cb475b6de7fde9cbab5dd6dc9581e7deb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: override_envs\n\nDocumentation:\nAdds overrides for multiple environment variables.\n\nThese overrides will only affect [`Self::get_env`] behavior,\nthey will **not** change the process environment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn override_envs, V: AsRef, I: IntoIterator>(\n mut self,\n envs: I,\n ) -> Self {\n for (key, value) in envs {\n self.env_override\n .insert(key.as_ref().into(), value.as_ref().into());\n }\n self\n }\n```"}], "func_name": "override_envs", "docstring": "Adds overrides for multiple environment variables.\n\nThese overrides will only affect [`Self::get_env`] behavior,\nthey will **not** change the process environment.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/config/context.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/config/context.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1daffe02c2a33116625e48f346c1dfe9f4d299dff16f29fdfd863f0bfffbad2c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: override_env_opt\n\nDocumentation:\nIf the given `value` is [`Some`], adds an override for an environment variable.\n\nOtherwise, does nothing.\n\nThis override will only affect [`Self::get_env`] behavior,\nit will **not** change the process environment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn override_env_opt, V: AsRef>(\n mut self,\n key: K,\n value: Option,\n ) -> Self {\n if let Some(value) = value {\n self.env_override\n .insert(key.as_ref().into(), value.as_ref().into());\n }\n\n self\n }\n```"}], "func_name": "override_env_opt", "docstring": "If the given `value` is [`Some`], adds an override for an environment variable.\n\nOtherwise, does nothing.\n\nThis override will only affect [`Self::get_env`] behavior,\nit will **not** change the process environment.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/config/context.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/config/context.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "edc55dc6e9acf3c01cde25fb1e41a8410768d8cb15d24412a693d8c38a984b08"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: strict_env\n\nDocumentation:\nDisables usage of [`mod@std::env`] in [`Self::get_env`].\n\nEffectively isolates config generation/verification from process environment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn strict_env(mut self, value: bool) -> Self {\n self.strict_env = value;\n self\n }\n```"}], "func_name": "strict_env", "docstring": "Disables usage of [`mod@std::env`] in [`Self::get_env`].\n\nEffectively isolates config generation/verification from process environment.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/config/context.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/config/context.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44df6d4cb809be6c396a522d68a864b8d6c0ed3f27dbef9292d9f6eb750a9ba2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: empty_target_final\n\nDocumentation:\nMarks whether an empty [TargetConfig::path](crate::target::TargetConfig::path) should be\nconsidered final when verifying config.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn empty_target_final(mut self, value: bool) -> Self {\n self.empty_target_final = value;\n self\n }\n```"}], "func_name": "empty_target_final", "docstring": "Marks whether an empty [TargetConfig::path](crate::target::TargetConfig::path) should be\nconsidered final when verifying config.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/config/context.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/config/context.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7084af2900f3c1a0dd1cf34ab14b2f70ff5e205beb0c3cbc3a62b7d5d9100de4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_env\n\nDocumentation:\nReturns value of an environment variable with the given name.\n\nThis is the only way we should read environment when generating or verifying configuration.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_env(&self, name: &str) -> Result {\n let name = OsStr::from_bytes(name.as_bytes());\n\n let os_value = match self.env_override.get(name) {\n Some(value) => Ok(value.clone()),\n None if self.strict_env => Err(VarError::NotPresent),\n None => std::env::var_os(name).ok_or(VarError::NotPresent),\n }?;\n\n std::str::from_utf8(os_value.as_bytes())\n .map(ToString::to_string)\n .map_err(|_| VarError::NotUnicode(os_value))\n }\n```"}], "func_name": "get_env", "docstring": "Returns value of an environment variable with the given name.\n\nThis is the only way we should read environment when generating or verifying configuration.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/config/context.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/config/context.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf8077ea8777d005709c926314bde3babef495093f95b2ebd160008bdd15f788"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: source_value\n\nDocumentation:\nReturns:\n- `None` if there is no env var with that name.\n- `Some(Err(ConfigError::InvalidValue{...}))` if the value of the env var cannot be parsed.\n- `Some(Ok(...))` if the env var exists and was parsed successfully.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn source_value(self, context: &mut ConfigContext) -> Option> {\n context.get_env(self.0).ok().map(|var| {\n var.parse::()\n .map_err(|err| ConfigError::InvalidValue {\n name: self.0,\n provided: var,\n error: Box::new(err),\n })\n })\n }\n```"}], "func_name": "source_value", "docstring": "Returns:\n- `None` if there is no env var with that name.\n- `Some(Err(ConfigError::InvalidValue{...}))` if the value of the env var cannot be parsed.\n- `Some(Ok(...))` if the env var exists and was parsed successfully.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/config/from_env.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/config/from_env.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7f3c8daf12a016fc9a949411b0cd6b86f6bb9be9b125d2b4572880a71c9ec080"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sqs\n\nDocumentation:\nOut of the whole queue splitting config, get only the sqs queues.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sqs(&self) -> impl '_ + Iterator {\n self.0.iter().filter_map(|(name, filter)| match filter {\n QueueFilter::Sqs { message_filter } => Some((name.as_str(), message_filter)),\n _ => None,\n })\n }\n```"}], "func_name": "sqs", "docstring": "Out of the whole queue splitting config, get only the sqs queues.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/feature/split_queues.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/feature/split_queues.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c6017228d1497944ce03317b095bcfa8d632387e225756e54a4918381ff7b858"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: kafka\n\nDocumentation:\nOut of the whole queue splitting config, get only the kafka topics.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn kafka(&self) -> impl '_ + Iterator {\n self.0.iter().filter_map(|(name, filter)| match filter {\n QueueFilter::Kafka { message_filter } => Some((name.as_str(), message_filter)),\n _ => None,\n })\n }\n```"}], "func_name": "kafka", "docstring": "Out of the whole queue splitting config, get only the kafka topics.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/feature/split_queues.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/feature/split_queues.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "26940faed21c80580cabbfd304edd41463be2bbaaca9816727dfa01bedcb7490"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_active\n\nDocumentation:\nChecks if fs operations are active\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_active(&self) -> bool {\n !matches!(self.mode, FsModeConfig::Local)\n }\n```"}], "func_name": "is_active", "docstring": "Checks if fs operations are active", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/feature/fs/advanced.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/feature/fs/advanced.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f6d1a92f9fb72ea112b8a772525e5e6a2f5cdf1d28a1a2c14e721fba56591eda"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: protocol\n\nDocumentation:\n\n\nParses `tcp://`, extracting the `tcp` part, and discarding the `://`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn protocol(input: &str) -> IResult<&str, &str> {\n let (rest, protocol) = opt(terminated(take_until(\"://\"), tag(\"://\")))(input)?;\n let protocol = protocol.unwrap_or(\"any\");\n\n Ok((rest, protocol))\n}\n```"}], "func_name": "protocol", "docstring": "\n\nParses `tcp://`, extracting the `tcp` part, and discarding the `://`.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/feature/network/filter.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/feature/network/filter.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac9c0ff6fc5bddb410f5a0160a5535f38ca34869d5e8d236157c55cdb8dfdd65"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: address\n\nDocumentation:\n\n\nWe try to parse 3 different kinds of values here:\n\n1. `name.with.dots`;\n2. `1.2.3.4.5.6`;\n3. `[dad:1337:fa57::0]`\n\nWhere 1 and 2 are handled by `dotted_address`.\n\nThe parser is not interested in only eating correct values here for hostnames, ip addresses,\netc., it just tries to get a good enough string that could be parsed by\n`SocketAddr::parse`, or `IpNet::parse`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn address(input: &str) -> IResult<&str, Option> {\n let ipv6 = many1(alt((alphanumeric1, tag(\":\"))));\n let ipv6_host = delimited(tag(\"[\"), ipv6, tag(\"]\"));\n\n let host_char = alt((alphanumeric1, tag(\"-\"), tag(\"_\"), tag(\".\")));\n let dotted_address = many1(host_char);\n\n let (rest, address) = opt(alt((dotted_address, ipv6_host)))(input)?;\n\n let address = address.map(|addr| addr.concat());\n\n Ok((rest, address))\n}\n```"}], "func_name": "address", "docstring": "\n\nWe try to parse 3 different kinds of values here:\n\n1. `name.with.dots`;\n2. `1.2.3.4.5.6`;\n3. `[dad:1337:fa57::0]`\n\nWhere 1 and 2 are handled by `dotted_address`.\n\nThe parser is not interested in only eating correct values here for hostnames, ip addresses,\netc., it just tries to get a good enough string that could be parsed by\n`SocketAddr::parse`, or `IpNet::parse`.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/feature/network/filter.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/feature/network/filter.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "21a12801e7699613e065a03901ff8da2edf942d087caba93ae98180ffca46822"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: subnet\n\nDocumentation:\n\n\nParses `/24`, extracting the `24` part, and discarding the `/`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn subnet(input: &str) -> IResult<&str, Option<&str>> {\n let subnet_parser = preceded(tag(\"/\"), digit1);\n let (rest, subnet) = opt(subnet_parser)(input)?;\n\n Ok((rest, subnet))\n}\n```"}], "func_name": "subnet", "docstring": "\n\nParses `/24`, extracting the `24` part, and discarding the `/`.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/feature/network/filter.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/feature/network/filter.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e88d6aaa4e7fcfaf684686bf15b832c8c3dae1deba63fcace467ca21e3e33df5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: port\n\nDocumentation:\n\n\nParses `:1337`, extracting the `1337` part, and discarding the `:`.\n\nReturns [`None`] if it doesn't parse anything.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn port(input: &str) -> IResult<&str, Option<&str>> {\n let port_parser = preceded(tag(\":\"), digit1);\n let (rest, port) = opt(port_parser)(input)?;\n\n Ok((rest, port))\n}\n```"}], "func_name": "port", "docstring": "\n\nParses `:1337`, extracting the `1337` part, and discarding the `:`.\n\nReturns [`None`] if it doesn't parse anything.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/feature/network/filter.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/feature/network/filter.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1bd38ae7f745ef8c3898795acafa50a7bbf9e8ee3247a1c412a02d64ddfe243f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_steal\n\nDocumentation:\n\nHelper function.\n\nUsed by mirrord-layer to identify the incoming network configuration as steal or not.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_steal(&self) -> bool {\n matches!(self.mode, IncomingMode::Steal)\n }\n```"}], "func_name": "is_steal", "docstring": "\nHelper function.\n\nUsed by mirrord-layer to identify the incoming network configuration as steal or not.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/feature/network/incoming.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/feature/network/incoming.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6d7a560bf075f232f22a0be9d3d147958404a6c088cd3f32b9be33da8f424307"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: steals_port_without_filter\n\nDocumentation:\n\nHelper function\n\nChecks whether the given port can be stolen without an HTTP filter.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn steals_port_without_filter(&self, port: u16) -> bool {\n if self.is_steal().not() {\n return false;\n }\n\n if self.http_filter.is_filter_set() {\n if let Some(filter_ports) = self.http_filter.ports.as_ref()\n && filter_ports.contains(&port)\n {\n false\n } else {\n self.ports.as_ref().is_some_and(|set| set.contains(&port))\n }\n } else if self.ignore_ports.contains(&port) {\n false\n } else if let Some(ports) = &self.ports {\n ports.contains(&port)\n } else {\n true\n }\n }\n```"}], "func_name": "steals_port_without_filter", "docstring": "\nHelper function\n\nChecks whether the given port can be stolen without an HTTP filter.", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/feature/network/incoming.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/feature/network/incoming.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94caefc199bcafce939b4b98a548e1d06ffd8bf5edb8f06d752eadf031febf45"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_probe_ports_to_http_filter_ports\n\nDocumentation:\nUpdate the [`HttpFilterConfig::ports`] with the health probes ports from the target.\n\nUsually the user app will be listening on HTTP on the same ports as these probes, so\nwe can insert them in the user config.\n\nIf the user has set anything in [`HttpFilterConfig::ports`], then we do nothing, to\navoid overriding their config. We also take care to not create conflicts with other\nport configs that we have, such as [`IncomingConfig::ignore_ports`]`, and\n[`IncomingConfig::ports`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_probe_ports_to_http_filter_ports(\n &mut self,\n probes_ports: &[u16],\n ) -> Option<&PortList> {\n if self.is_steal() && self.http_filter.is_filter_set() && self.http_filter.ports.is_none() {\n let filtered_ports = probes_ports\n .iter()\n // Avoid conflicts with `incoming.ignore_ports`.\n .filter(|port| self.ignore_ports.contains(port).not())\n .filter(|port| {\n // Avoid conflicts with `incoming.ports`.\n if let Some(ports) = &self.ports {\n ports.contains(port).not()\n } else {\n true\n }\n })\n .copied()\n .collect::>();\n\n // Only add something if we have a port to add, otherwise leave it as `None` so\n // we can use the `PortList::default` when initializing things.\n if filtered_ports.is_empty().not() {\n self.http_filter.ports = Some(filtered_ports.into());\n }\n }\n\n self.http_filter.ports.as_ref()\n }\n```"}], "func_name": "add_probe_ports_to_http_filter_ports", "docstring": "Update the [`HttpFilterConfig::ports`] with the health probes ports from the target.\n\nUsually the user app will be listening on HTTP on the same ports as these probes, so\nwe can insert them in the user config.\n\nIf the user has set anything in [`HttpFilterConfig::ports`], then we do nothing, to\navoid overriding their config. We also take care to not create conflicts with other\nport configs that we have, such as [`IncomingConfig::ignore_ports`]`, and\n[`IncomingConfig::ports`].", "repo": "metalbear-co/mirrord", "path": "mirrord/config/src/feature/network/incoming.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/config/src/feature/network/incoming.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b325bbbc93b63ec63806dd994b78b7ef8f40c9f570f2f3d9456b5c9aa4ee83e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_hello\n\nDocumentation:\nSend hello message, containing information about the connected process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn send_hello(stream: &mut TcpStream) -> Result<()> {\n let hello = Hello::from_env();\n\n let mut encoder: AsyncEncoder = AsyncEncoder::new(stream);\n encoder.send(&hello).await?;\n\n Ok(())\n}\n```"}], "func_name": "send_hello", "docstring": "Send hello message, containing information about the connected process.", "repo": "metalbear-co/mirrord", "path": "mirrord/console/src/async_logger.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/console/src/async_logger.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d59ea566c96ce34f48c04254dffdb96eec42aae2965a3cf6a37d52794a1287cc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init_async_logger\n\nDocumentation:\nInitializes the [`AsyncConsoleLogger`] and sets the global logger to use it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn init_async_logger(address: &str, watch: Watch, channel_size: usize) -> Result<()> {\n let mut stream = TcpStream::connect(address).await?;\n stream.set_nodelay(true)?;\n send_hello(&mut stream).await?;\n\n let (tx, rx) = mpsc::channel(channel_size);\n\n let logger = AsyncConsoleLogger { tx };\n log::set_boxed_logger(Box::new(logger)).map(|()| log::set_max_level(LevelFilter::Trace))?;\n\n let cancellation_token = CancellationToken::new();\n let task = LoggerTask::new(rx, cancellation_token.clone(), stream);\n tokio::spawn(watch.watch(Box::pin(task.run()), move |_| cancellation_token.cancel()));\n\n Ok(())\n}\n```"}], "func_name": "init_async_logger", "docstring": "Initializes the [`AsyncConsoleLogger`] and sets the global logger to use it.", "repo": "metalbear-co/mirrord", "path": "mirrord/console/src/async_logger.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/console/src/async_logger.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9527f7c12fe0a5f49a80524cd61d27fb3bb38f867a838898c51736099810087"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: log\n\nDocumentation:\nSerialize the logs into our protocol then send it over the wire.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn log(&self, record: &log::Record) {\n if self.enabled(record.metadata()) {\n let msg = Record::from(record);\n\n let mut guard = match self.encoder.lock() {\n Ok(guard) => guard,\n Err(e) => {\n eprintln!(\"Error sending log message: {e:?}\");\n return;\n }\n };\n\n if let Err(e) = guard.send(&msg) {\n eprintln!(\"Error sending log message: {e:?}\");\n }\n // Crucial for getting as many of the most interesting logs as possible right before\n // the process exits.\n let _ = guard.flush();\n }\n }\n```"}], "func_name": "log", "docstring": "Serialize the logs into our protocol then send it over the wire.", "repo": "metalbear-co/mirrord", "path": "mirrord/console/src/logger.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/console/src/logger.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1e701ac04da44190a50fb3bdd83122967f308134d60a8c7d9be858886f2a10e8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init_logger\n\nDocumentation:\nInitializes the [`ConsoleLogger`] and sets the global logger to use it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn init_logger(address: &str) -> Result<()> {\n let mut stream = TcpStream::connect(address)?;\n stream.set_nodelay(true)?;\n\n send_hello(&mut stream)?;\n\n let writer = BufWriter::new(stream);\n let logger = ConsoleLogger {\n encoder: Mutex::new(SyncEncoder::new(writer)),\n };\n\n log::set_boxed_logger(Box::new(logger)).map(|()| log::set_max_level(LevelFilter::Trace))?;\n\n Ok(())\n}\n```"}], "func_name": "init_logger", "docstring": "Initializes the [`ConsoleLogger`] and sets the global logger to use it.", "repo": "metalbear-co/mirrord", "path": "mirrord/console/src/logger.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/console/src/logger.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f529c8bb5ce4b009e868e081d50a17cf7c299009e63b3852a28a8a197deca3b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_env\n\nDocumentation:\nCreates a new [`Hello`] message from the environment of the current process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_env() -> Self {\n Self {\n process_info: ProcessInfo {\n args: env::args().collect(),\n env: env::vars().map(|(k, v)| format!(\"{k}={v}\")).collect(),\n cwd: env::current_dir()\n .map(|p| p.to_str().map(String::from))\n .unwrap_or(None),\n id: process::id().into(),\n },\n }\n }\n```"}], "func_name": "from_env", "docstring": "Creates a new [`Hello`] message from the environment of the current process.", "repo": "metalbear-co/mirrord", "path": "mirrord/console/src/protocol.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/console/src/protocol.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e5b89f136c1d2066855b1ac5e670ecec0e4fe189f8db9f2f84ae55a9f98dbc80"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send\n\nDocumentation:\nEncodes the given value into the inner IO handler.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn send(&mut self, value: &T) -> Result<()> {\n self.buffer.resize(PREFIX_BYTES, 0);\n let bytes: u32 =\n bincode::encode_into_std_write(value, &mut self.buffer, bincode::config::standard())?\n .try_into()?;\n self.buffer\n .get_mut(..PREFIX_BYTES)\n .expect(\"buffer too short\")\n .copy_from_slice(&bytes.to_be_bytes());\n\n self.writer.write_all(&self.buffer)?;\n\n Ok(())\n }\n```"}], "func_name": "send", "docstring": "Encodes the given value into the inner IO handler.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/protocol/src/codec.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/protocol/src/codec.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f219e10ff5ac1a48ff5e4931c4dbb64139b39b3278e5fe5cd87c929da93b71ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: receive\n\nDocumentation:\nDecodes the next message from the underlying IO handler.\nDoes not read any excessive bytes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn receive(&mut self) -> Result> {\n let mut len_buffer = [0; 4];\n match self.reader.read_exact(&mut len_buffer) {\n Ok(..) => {}\n Err(e) if e.kind() == ErrorKind::UnexpectedEof => return Ok(None),\n Err(e) => Err(e)?,\n }\n let len = u32::from_be_bytes(len_buffer);\n\n self.buffer.resize(len as usize, 0);\n self.reader.read_exact(&mut self.buffer)?;\n\n let value = bincode::decode_from_slice(&self.buffer, bincode::config::standard())?.0;\n\n Ok(Some(value))\n }\n```"}], "func_name": "receive", "docstring": "Decodes the next message from the underlying IO handler.\nDoes not read any excessive bytes.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/protocol/src/codec.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/protocol/src/codec.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc94aaf04517aee8a37666f29403358ef2bbd6ac9f380ec72b6ea096ee57fb9b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_sync_framed\n\nDocumentation:\nCreates a new pair of [`SyncEncoder`] and [`SyncDecoder`], using the given synchronous\n[`TcpStream`](std::net::TcpStream).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn make_sync_framed>(\n stream: std::net::TcpStream,\n) -> Result<(\n SyncEncoder,\n SyncDecoder,\n)> {\n let stream_cloned = stream.try_clone()?;\n\n let sender = SyncEncoder::new(stream);\n let receiver = SyncDecoder::new(stream_cloned);\n\n Ok((sender, receiver))\n}\n```"}], "func_name": "make_sync_framed", "docstring": "Creates a new pair of [`SyncEncoder`] and [`SyncDecoder`], using the given synchronous\n[`TcpStream`](std::net::TcpStream).", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/protocol/src/codec.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/protocol/src/codec.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e274c2ca7343fa3e8998e35038146ffa3c4b3af492e82f5fdad7ade88104671"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_async_framed\n\nDocumentation:\nCreates a new pair of [`AsyncEncoder`] and [`AsyncDecoder`], using the given asynchronous\n[`TcpStream`](tokio::net::TcpStream).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn make_async_framed>(\n stream: tokio::net::TcpStream,\n) -> (\n AsyncEncoder,\n AsyncDecoder,\n) {\n let (reader, writer) = stream.into_split();\n\n let sender = AsyncEncoder::new(writer);\n let receiver = AsyncDecoder::new(reader);\n\n (sender, receiver)\n}\n```"}], "func_name": "make_async_framed", "docstring": "Creates a new pair of [`AsyncEncoder`] and [`AsyncDecoder`], using the given asynchronous\n[`TcpStream`](tokio::net::TcpStream).", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/protocol/src/codec/codec_async.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/protocol/src/codec/codec_async.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "02a547ae735eae43dc7cc0f9d42e621080730a6ba2cb99c90fce7f3042c0f255"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send\n\nDocumentation:\nAttempts to send a message to this task's parent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn send>(&self, msg: M) {\n let _ = self.tx.send(msg.into()).await;\n }\n```"}], "func_name": "send", "docstring": "Attempts to send a message to this task's parent.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/background_tasks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/background_tasks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "581d5abd4d381659007ab24a12182aa88e0180261b8dfc53acb4288d5ccc8eda"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: recv\n\nDocumentation:\nReceives a message from this task's parent.\n[`None`] means that the channel is closed and there will be no more messages.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn recv(&mut self) -> Option {\n tokio::select! {\n _ = self.tx.closed() => None,\n msg = self.rx.recv() => msg,\n }\n }\n```"}], "func_name": "recv", "docstring": "Receives a message from this task's parent.\n[`None`] means that the channel is closed and there will be no more messages.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/background_tasks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/background_tasks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a32c21d2c39f333457ac1f1dad00beb7a6c92f21e0f2804e93a8680ca8422f97"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cancel_on_close\n\nDocumentation:\nResolves the given [`Future`], unless the origin [`MessageBus`] closes first.\n\n# Returns\n\n* [`Some`] holding the future output - if the future resolved first\n* [`None`] - if the [`MessageBus`] closed first\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn cancel_on_close(&self, future: F) -> Option {\n tokio::select! {\n _ = self.0.closed() => None,\n output = future => Some(output)\n }\n }\n```"}], "func_name": "cancel_on_close", "docstring": "Resolves the given [`Future`], unless the origin [`MessageBus`] closes first.\n\n# Returns\n\n* [`Some`] holding the future output - if the future resolved first\n* [`None`] - if the [`MessageBus`] closed first", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/background_tasks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/background_tasks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "92cf3f1a48fe71fd8e97304be765c59de3f16a023c20a1aa47253c54315b3643"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: register\n\nDocumentation:\nRegisters a new background task in this struct. Returns a [`TaskSender`] that can be used to\nsend messages to the task. Dropping this sender will close the channel of messages\nconsumed by the task (see [`MessageBus`]). This should trigger task exit.\n\n# Arguments\n\n* `task` - the [`BackgroundTask`] to be spawned and managed.\n* `id` - unique identifier of the task.\n* `channel_size` - size of [`mpsc`] channels used to communicate with the task.\n\n# Panics\n\nThis method panics when attempting to register a task with a duplicate id.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn register(&mut self, mut task: T, id: Id, channel_size: usize) -> TaskSender\n where\n T: 'static + BackgroundTask + Send,\n Err: From,\n T::MessageIn: Send,\n {\n if self.streams.contains_key(&id) {\n panic!(\"duplicate task id {id:?}\");\n }\n\n let (in_msg_tx, in_msg_rx) = mpsc::channel(channel_size);\n let (out_msg_tx, out_msg_rx) = mpsc::channel(channel_size);\n\n self.streams.insert(\n id.clone(),\n StreamNotifyClose::new(ReceiverStream::new(out_msg_rx)),\n );\n\n let mut message_bus = MessageBus:: {\n tx: out_msg_tx,\n rx: in_msg_rx,\n };\n\n self.handles.insert(\n id.clone(),\n tokio::spawn(async move { task.run(&mut message_bus).await.map_err(Into::into) }),\n );\n\n TaskSender(in_msg_tx)\n }\n```"}], "func_name": "register", "docstring": "Registers a new background task in this struct. Returns a [`TaskSender`] that can be used to\nsend messages to the task. Dropping this sender will close the channel of messages\nconsumed by the task (see [`MessageBus`]). This should trigger task exit.\n\n# Arguments\n\n* `task` - the [`BackgroundTask`] to be spawned and managed.\n* `id` - unique identifier of the task.\n* `channel_size` - size of [`mpsc`] channels used to communicate with the task.\n\n# Panics\n\nThis method panics when attempting to register a task with a duplicate id.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/background_tasks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/background_tasks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a2ee0234b8f59e8ce1a8f44660cc2b6b432c2cfc0f59657badc44764957e9ccc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next\n\nDocumentation:\nReturns the next update from one of registered tasks.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn next(&mut self) -> Option<(Id, TaskUpdate)> {\n let (id, msg) = self.streams.next().await?;\n\n let msg = match msg {\n Some(msg) => (id, TaskUpdate::Message(msg)),\n None => {\n let res = self\n .handles\n .remove(&id)\n .expect(\"task handles and streams are out of sync\")\n .await;\n match res {\n Err(error) => {\n tracing::error!(?error, \"task panicked\");\n (id, TaskUpdate::Finished(Err(TaskError::Panic)))\n }\n Ok(res) => (id, TaskUpdate::Finished(res.map_err(TaskError::Error))),\n }\n }\n };\n\n Some(msg)\n }\n```"}], "func_name": "next", "docstring": "Returns the next update from one of registered tasks.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/background_tasks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/background_tasks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5a22dd4f4517795e7be89dcdf84f02dcec5e169e15b3a51c35459f81d8ce201f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: results\n\nDocumentation:\nWaits for all registered tasks to finish and returns their results.\nThis method does not signalize the tasks to finish. Instead, one should drop all\n[`TaskSender`]s first.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn results(self) -> Vec<(Id, Result<(), TaskError>)> {\n std::mem::drop(self.streams);\n\n let mut results = Vec::with_capacity(self.handles.len());\n for (id, handle) in self.handles {\n let result = match handle.await {\n Err(error) => {\n tracing::error!(?error, \"task panicked\");\n Err(TaskError::Panic)\n }\n Ok(res) => res.map_err(TaskError::Error),\n };\n results.push((id, result));\n }\n\n results\n }\n```"}], "func_name": "results", "docstring": "Waits for all registered tasks to finish and returns their results.\nThis method does not signalize the tasks to finish. Instead, one should drop all\n[`TaskSender`]s first.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/background_tasks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/background_tasks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63dd430c086955bf3a4557278c95b80f87c2a940498edad5c4224499b57bdb0f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: suspend_messages\n\nDocumentation:\nTemporarily suspends messages from the registered task with the given id.\n\n[Self::next] will not return messages from this task,\nuntil you resume the messages with [`Self::resume_messages`].\n\nIf the messages from this task are already suspended or the task is not registered, does\nnothing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn suspend_messages(&mut self, id: Id) {\n if let Some(stream) = self.streams.remove(&id) {\n self.suspended_streams.insert(id, stream);\n }\n }\n```"}], "func_name": "suspend_messages", "docstring": "Temporarily suspends messages from the registered task with the given id.\n\n[Self::next] will not return messages from this task,\nuntil you resume the messages with [`Self::resume_messages`].\n\nIf the messages from this task are already suspended or the task is not registered, does\nnothing.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/background_tasks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/background_tasks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "595697e5324b5727d74da01354312d709fb9b3be94d3d4e60246b65701cd0e05"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resume_messages\n\nDocumentation:\nResumes messages from the registered task with the given id.\n\nIf the messages from this task are not suspended or the task is not registered, does\nnothing.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn resume_messages(&mut self, id: Id) {\n if let Some(stream) = self.suspended_streams.remove(&id) {\n self.streams.insert(id, stream);\n }\n }\n```"}], "func_name": "resume_messages", "docstring": "Resumes messages from the registered task with the given id.\n\nIf the messages from this task are not suspended or the task is not registered, does\nnothing.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/background_tasks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/background_tasks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8ac3ffc632410b66bab92e7593e98410eb6e4958f2bda97d3103c29b18c55438"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send\n\nDocumentation:\nAttempt to send a message to the task.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn send>(&self, msg: M) {\n let _ = self.0.send(msg.into()).await;\n }\n```"}], "func_name": "send", "docstring": "Attempt to send a message to the task.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/background_tasks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/background_tasks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b44f9d2f463b18e3e6eb8ecbff29ac5acce444186f9ec61aecdca2b69ad584ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nWraps a raw [`TcpStream`] to be used as a `layer <-> proxy` connection.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(stream: TcpStream, layer_id: LayerId) -> Self {\n let (layer_codec_tx, layer_codec_rx) = codec::make_async_framed(stream);\n\n Self {\n layer_codec_rx,\n layer_codec_tx,\n layer_id,\n }\n }\n```"}], "func_name": "new", "docstring": "Wraps a raw [`TcpStream`] to be used as a `layer <-> proxy` connection.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/layer_conn.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/layer_conn.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9c0ab032271fe050f0b4946ebe5db4e9dd49bff59e12b0589619589a934a3cd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_with_connection\n\nDocumentation:\nCreates a new [`IntProxy`] using existing [`AgentConnection`].\nThe returned instance will accept connections from the layers using the given\n[`TcpListener`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_with_connection(\n agent_conn: AgentConnection,\n listener: TcpListener,\n file_buffer_size: u64,\n idle_local_http_connection_timeout: Duration,\n https_delivery: LocalHttpsDelivery,\n ) -> Self {\n let mut background_tasks: BackgroundTasks =\n Default::default();\n\n let agent = background_tasks.register_restartable(\n agent_conn,\n MainTaskId::AgentConnection,\n Self::CHANNEL_SIZE,\n );\n let layer_initializer = background_tasks.register(\n LayerInitializer::new(listener),\n MainTaskId::LayerInitializer,\n Self::CHANNEL_SIZE,\n );\n // We need to negotiate mirrord-protocol version\n // before we can process layers' requests.\n //\n // If we don't do this, we risk responding with `NotImplemented`\n // to requests that have a requirement on the mirrord-protocol version.\n background_tasks.suspend_messages(MainTaskId::LayerInitializer);\n let ping_pong = background_tasks.register(\n PingPong::new(Self::PING_INTERVAL),\n MainTaskId::PingPong,\n Self::CHANNEL_SIZE,\n );\n let simple = background_tasks.register(\n SimpleProxy::default(),\n MainTaskId::SimpleProxy,\n Self::CHANNEL_SIZE,\n );\n let outgoing = background_tasks.register(\n OutgoingProxy::default(),\n MainTaskId::OutgoingProxy,\n Self::CHANNEL_SIZE,\n );\n let incoming = background_tasks.register(\n IncomingProxy::new(idle_local_http_connection_timeout, https_delivery),\n MainTaskId::IncomingProxy,\n Self::CHANNEL_SIZE,\n );\n let files = background_tasks.register(\n FilesProxy::new(file_buffer_size),\n MainTaskId::FilesProxy,\n Self::CHANNEL_SIZE,\n );\n\n let mut ping_pong_update_debounce = time::interval(Self::PING_INTERVAL / 10);\n ping_pong_update_debounce.set_missed_tick_behavior(MissedTickBehavior::Delay);\n\n Self {\n any_connection_accepted: false,\n background_tasks,\n task_txs: TaskTxs {\n layers: Default::default(),\n _layer_initializer: layer_initializer,\n agent,\n simple,\n outgoing,\n incoming,\n ping_pong,\n files,\n },\n protocol_version: None,\n reconnect_task_queue: Default::default(),\n ping_pong_update_debounce,\n ping_pong_update_allowed: false,\n }\n }\n```"}], "func_name": "new_with_connection", "docstring": "Creates a new [`IntProxy`] using existing [`AgentConnection`].\nThe returned instance will accept connections from the layers using the given\n[`TcpListener`].", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48c11f6372b95e03c29c45391b290a0914f2dcb0e65b9e7ae39f2fa382cba448"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRuns main event loop of this proxy.\nExpects to accept the first layer connection within the given `first_timeout`.\nExits after `idle_timeout` when there are no more layer connections.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run(\n mut self,\n first_timeout: Duration,\n idle_timeout: Duration,\n ) -> Result<(), IntProxyError> {\n self.task_txs\n .agent\n .send(ClientMessage::SwitchProtocolVersion(\n mirrord_protocol::VERSION.clone(),\n ))\n .await;\n\n loop {\n tokio::select! {\n Some((task_id, task_update)) = self.background_tasks.next() => {\n tracing::trace!(\n %task_id,\n ?task_update,\n \"Received a task update\",\n );\n\n self.handle_task_update(task_id, task_update).await?;\n }\n\n _ = self.ping_pong_update_debounce.tick(), if self.has_layer_connections() => {\n self.ping_pong_update_allowed = true;\n }\n\n _ = time::sleep(first_timeout), if !self.any_connection_accepted => {\n return Err(IntProxyError::ConnectionAcceptTimeout);\n },\n\n _ = time::sleep(idle_timeout), if self.any_connection_accepted && !self.has_layer_connections() => {\n tracing::info!(\"Reached the idle timeout with no active layer connections\");\n break;\n },\n }\n }\n\n std::mem::drop(self.task_txs);\n\n tracing::info!(\"Collecting background task results before exiting\");\n let results = self.background_tasks.results().await;\n\n for (task_id, result) in results {\n tracing::trace!(\n %task_id,\n ?result,\n \"Collected a background task result\",\n );\n }\n\n Ok(())\n }\n```"}], "func_name": "run", "docstring": "Runs main event loop of this proxy.\nExpects to accept the first layer connection within the given `first_timeout`.\nExits after `idle_timeout` when there are no more layer connections.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "663e73a610243f58867f201f9a82ad08bd4c6145d27393c7419142195628d6e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle\n\nDocumentation:\nRoutes a [`ProxyMessage`] to the correct background task.\n[`ProxyMessage::NewLayer`] is handled here, as an exception.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle(&mut self, msg: ProxyMessage) -> Result<(), IntProxyError> {\n match msg {\n ProxyMessage::NewLayer(_) | ProxyMessage::FromLayer(_) | ProxyMessage::ToAgent(_)\n if self.reconnect_task_queue.is_some() =>\n {\n // We are in reconnect state so should queue this message.\n self.reconnect_task_queue\n .as_mut()\n .unwrap_or_else(|| {\n tracing::error!(\"Unexpected state: reconnect_task_queue should contain a value when the proxy is in reconnect state\");\n panic!(\"reconnect_task_queue should contain value when in reconnect state\")\n })\n .push_back(msg);\n }\n ProxyMessage::NewLayer(new_layer) => {\n self.any_connection_accepted = true;\n\n let tx = self.background_tasks.register(\n LayerConnection::new(new_layer.stream, new_layer.id),\n MainTaskId::LayerConnection(new_layer.id),\n Self::CHANNEL_SIZE,\n );\n self.task_txs.layers.insert(new_layer.id, tx);\n\n if let Some(parent) = new_layer.parent_id {\n let msg = LayerForked {\n child: new_layer.id,\n parent,\n };\n\n self.task_txs\n .files\n .send(FilesProxyMessage::LayerForked(msg))\n .await;\n self.task_txs\n .incoming\n .send(IncomingProxyMessage::LayerForked(msg))\n .await;\n }\n }\n ProxyMessage::FromAgent(msg) => self.handle_agent_message(msg).await?,\n ProxyMessage::FromLayer(msg) => self.handle_layer_message(msg).await?,\n ProxyMessage::ToAgent(msg) => self.task_txs.agent.send(msg).await,\n ProxyMessage::ToLayer(msg) => {\n let ToLayer {\n message,\n message_id,\n layer_id,\n } = msg;\n\n if let Some(tx) = self.task_txs.layers.get(&layer_id) {\n tx.send(LocalMessage {\n message_id,\n inner: message,\n })\n .await;\n }\n }\n ProxyMessage::ConnectionRefresh(kind) => self.handle_connection_refresh(kind).await?,\n }\n\n Ok(())\n }\n```"}], "func_name": "handle", "docstring": "Routes a [`ProxyMessage`] to the correct background task.\n[`ProxyMessage::NewLayer`] is handled here, as an exception.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "233a4a1026385b5ef373ef0f77d731b171a84e8bd8f94d468eda747c5ce99d58"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_task_update\n\nDocumentation:\nHandles a [`TaskUpdate`] from one of the main tasks (see [`MainTaskId`]).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_task_update(\n &mut self,\n task_id: MainTaskId,\n update: TaskUpdate,\n ) -> Result<(), IntProxyError> {\n match (task_id, update) {\n (MainTaskId::LayerConnection(LayerId(id)), TaskUpdate::Finished(Ok(()))) => {\n tracing::trace!(layer_id = id, \"Layer connection closed\");\n\n let msg = LayerClosed { id: LayerId(id) };\n\n self.task_txs\n .files\n .send(FilesProxyMessage::LayerClosed(msg))\n .await;\n self.task_txs\n .incoming\n .send(IncomingProxyMessage::LayerClosed(msg))\n .await;\n\n self.task_txs.layers.remove(&LayerId(id));\n }\n\n (task_id, TaskUpdate::Finished(res)) => match res {\n Ok(()) => {\n tracing::error!(%task_id, \"One of the main tasks finished unexpectedly\");\n return Err(IntProxyError::TaskExit(task_id));\n }\n Err(TaskError::Error(error)) => {\n tracing::error!(%task_id, %error, \"One of the main tasks failed\");\n return Err(error);\n }\n Err(TaskError::Panic) => {\n tracing::error!(%task_id, \"One of the main tasks panicked\");\n return Err(IntProxyError::TaskPanic(task_id));\n }\n },\n\n (_, TaskUpdate::Message(msg)) => self.handle(msg).await?,\n }\n\n Ok(())\n }\n```"}], "func_name": "handle_task_update", "docstring": "Handles a [`TaskUpdate`] from one of the main tasks (see [`MainTaskId`]).", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "548b0fc512ed5356830fc81199ec8fa83c44603650311eacfd26ab76810cb856"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_agent_message\n\nDocumentation:\nRoutes most messages from the agent to the correct background task.\nSome messages are handled here.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_agent_message(&mut self, message: DaemonMessage) -> Result<(), IntProxyError> {\n if self.ping_pong_update_allowed\n && !matches!(message, DaemonMessage::Pong | DaemonMessage::Close(_))\n {\n self.task_txs\n .ping_pong\n .send(PingPongMessage::AgentSentMessage)\n .await;\n self.ping_pong_update_allowed = false;\n }\n\n match message {\n DaemonMessage::Pong => {\n self.task_txs\n .ping_pong\n .send(PingPongMessage::AgentSentPong)\n .await\n }\n DaemonMessage::Close(reason) => return Err(IntProxyError::AgentFailed(reason)),\n DaemonMessage::TcpOutgoing(msg) => {\n self.task_txs\n .outgoing\n .send(OutgoingProxyMessage::AgentStream(msg))\n .await\n }\n DaemonMessage::UdpOutgoing(msg) => {\n self.task_txs\n .outgoing\n .send(OutgoingProxyMessage::AgentDatagrams(msg))\n .await\n }\n DaemonMessage::File(msg) => {\n self.task_txs\n .files\n .send(FilesProxyMessage::FileRes(msg))\n .await\n }\n DaemonMessage::GetAddrInfoResponse(msg) => {\n self.task_txs\n .simple\n .send(SimpleProxyMessage::AddrInfoRes(msg))\n .await\n }\n DaemonMessage::Tcp(msg) => {\n self.task_txs\n .incoming\n .send(IncomingProxyMessage::AgentMirror(msg))\n .await\n }\n DaemonMessage::TcpSteal(msg) => {\n self.task_txs\n .incoming\n .send(IncomingProxyMessage::AgentSteal(msg))\n .await\n }\n DaemonMessage::SwitchProtocolVersionResponse(protocol_version) => {\n let previous = self.protocol_version.replace(protocol_version.clone());\n if previous.is_none() {\n // We can now process layers' requests.\n self.background_tasks\n .resume_messages(MainTaskId::LayerInitializer);\n }\n\n if CLIENT_READY_FOR_LOGS.matches(&protocol_version) {\n self.task_txs.agent.send(ClientMessage::ReadyForLogs).await;\n }\n\n self.task_txs\n .files\n .send(FilesProxyMessage::ProtocolVersion(protocol_version.clone()))\n .await;\n\n self.task_txs\n .simple\n .send(SimpleProxyMessage::ProtocolVersion(\n protocol_version.clone(),\n ))\n .await;\n\n self.task_txs\n .incoming\n .send(IncomingProxyMessage::AgentProtocolVersion(protocol_version))\n .await;\n }\n DaemonMessage::LogMessage(log) => match log.level {\n LogLevel::Error => tracing::error!(\n message = log.message,\n \"Received a log message from the agent\"\n ),\n LogLevel::Warn => tracing::warn!(\n message = log.message,\n \"Received a log message from the agent\"\n ),\n LogLevel::Info => tracing::info!(\n message = log.message,\n \"Received a log message from the agent\"\n ),\n },\n DaemonMessage::GetEnvVarsResponse(res) => {\n self.task_txs\n .simple\n .send(SimpleProxyMessage::GetEnvRes(res))\n .await\n }\n other => {\n return Err(IntProxyError::UnexpectedAgentMessage(\n UnexpectedAgentMessage(other),\n ));\n }\n }\n\n Ok(())\n }\n```"}], "func_name": "handle_agent_message", "docstring": "Routes most messages from the agent to the correct background task.\nSome messages are handled here.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1e467d3f46b0e27bcb51bbb4aa53dd243c49b8d5afc06f4bbe1fa66e78e0bbab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_layer_message\n\nDocumentation:\nRoutes a message from the layer to the correct background task.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_layer_message(&self, message: FromLayer) -> Result<(), IntProxyError> {\n let FromLayer {\n message_id,\n layer_id,\n message,\n } = message;\n\n match message {\n LayerToProxyMessage::File(req) => {\n self.task_txs\n .files\n .send(FilesProxyMessage::FileReq(message_id, layer_id, req))\n .await;\n }\n LayerToProxyMessage::GetAddrInfo(req) => {\n self.task_txs\n .simple\n .send(SimpleProxyMessage::AddrInfoReq(message_id, layer_id, req))\n .await\n }\n LayerToProxyMessage::OutgoingConnect(req) => {\n self.task_txs\n .outgoing\n .send(OutgoingProxyMessage::LayerConnect(\n req, message_id, layer_id,\n ))\n .await\n }\n LayerToProxyMessage::Incoming(req) => {\n self.task_txs\n .incoming\n .send(IncomingProxyMessage::LayerRequest(\n message_id, layer_id, req,\n ))\n .await\n }\n LayerToProxyMessage::GetEnv(req) => {\n self.task_txs\n .simple\n .send(SimpleProxyMessage::GetEnvReq(message_id, layer_id, req))\n .await\n }\n other => return Err(IntProxyError::UnexpectedLayerMessage(other)),\n }\n\n Ok(())\n }\n```"}], "func_name": "handle_layer_message", "docstring": "Routes a message from the layer to the correct background task.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "42ae14998acd5944d0efa5433b49aa4095aa03747bbfc0f9918ab3f7706de01b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance of this struct.\n\n# Arguments\n\n* frequency - how often the task should send pings\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(frequency: Duration) -> Self {\n let mut ticker = time::interval(frequency);\n ticker.set_missed_tick_behavior(MissedTickBehavior::Skip);\n\n Self {\n ticker,\n awaiting_pongs: 0,\n reconnecting: false,\n last_agent_message: None,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance of this struct.\n\n# Arguments\n\n* frequency - how often the task should send pings", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/ping_pong.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/ping_pong.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3b15d4b32fb8466b1d7e960622f59b69384e30a1cb2d34e9d251114463831339"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wrap_raw_connection\n\nDocumentation:\nMakes a TLS connection to the external proxy within the given [`TcpStream`].\n\nRequires that the external proxy provides a certificate with the\n[`MIRRORD_EXTPROXY_TLS_SERVER_NAME`].\n\nSpawns a background [`tokio::task`] that handles IO on the connection\nand returns [`mpsc`] channels to send/receive messages.\n\n# Params\n\n* `stream` - [`TcpStream`] to use for establishing the TLS connection.\n* `tls_pem` - path to a PEM file generated with [`SecureChannelSetup::try_new`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn wrap_raw_connection(\n stream: TcpStream,\n tls_pem: &Path,\n) -> Result<(mpsc::Sender, mpsc::Receiver), ConnectionTlsError> {\n let connector = SecureChannelSetup::create_connector(tls_pem).await?;\n\n let server_name =\n ServerName::try_from(MIRRORD_EXTPROXY_TLS_SERVER_NAME).expect(\"valid hostname\");\n\n Ok(mirrord_kube::api::wrap_raw_connection(\n connector\n .connect(server_name, stream)\n .await\n .map_err(ConnectionTlsError::ConnectionError)?,\n ))\n}\n```"}], "func_name": "wrap_raw_connection", "docstring": "Makes a TLS connection to the external proxy within the given [`TcpStream`].\n\nRequires that the external proxy provides a certificate with the\n[`MIRRORD_EXTPROXY_TLS_SERVER_NAME`].\n\nSpawns a background [`tokio::task`] that handles IO on the connection\nand returns [`mpsc`] channels to send/receive messages.\n\n# Params\n\n* `stream` - [`TcpStream`] to use for establishing the TLS connection.\n* `tls_pem` - path to a PEM file generated with [`SecureChannelSetup::try_new`].", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/agent_conn/tls.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/agent_conn/tls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a615b2146ec93bc22f14381442d00de9d8f2c932b8ff3d34f7c17ba6c5c0ef6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_from_buffer\n\nDocumentation:\nAttempts to read `amount` bytes from [`Self::buffer`], starting from `position` in the file.\n\nReturns [`None`] when the read does not fit in the buffer in whole.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_from_buffer(&self, amount: u64, position: u64) -> Option<&[u8]> {\n let start_from = position.checked_sub(self.buffer_position)? as usize;\n let end_before = start_from + amount as usize;\n self.buffer.get(start_from..end_before)\n }\n```"}], "func_name": "read_from_buffer", "docstring": "Attempts to read `amount` bytes from [`Self::buffer`], starting from `position` in the file.\n\nReturns [`None`] when the read does not fit in the buffer in whole.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/files.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5ec9b1c1232bb8097f5aa5c14fe8bc3ccd5ff84d81e207a60078b134e9cb2d53"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new files proxy instance.\nProxy can be used as a [`BackgroundTask`].\n\n`file_buffer_size` sets size of the readonly files buffer.\nSize 0 disables buffering.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(file_buffer_size: u64) -> Self {\n Self {\n protocol_version: Default::default(),\n file_buffer_size,\n\n request_queue: Default::default(),\n\n remote_files: Default::default(),\n buffered_files: Default::default(),\n\n remote_dirs: Default::default(),\n buffered_dirs: Default::default(),\n\n reconnect_tracker: Default::default(),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new files proxy instance.\nProxy can be used as a [`BackgroundTask`].\n\n`file_buffer_size` sets size of the readonly files buffer.\nSize 0 disables buffering.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/files.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63c2e326990a7d605557178628d8ecacbcd0b7855c17d2065825be2874b005b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: buffer_dirs\n\nDocumentation:\nReturns whether [`mirrord_protocol`] version allows for buffering directories.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn buffer_dirs(&self) -> bool {\n self.protocol_version\n .as_ref()\n .is_some_and(|version| READDIR_BATCH_VERSION.matches(version))\n }\n```"}], "func_name": "buffer_dirs", "docstring": "Returns whether [`mirrord_protocol`] version allows for buffering directories.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/files.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2596520e34e37eacf24fd285d7ee7b0e9af8aa9199e1177d481498b75c829d51"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: buffer_reads\n\nDocumentation:\nReturns whether this proxy is configured to buffer readonly files.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn buffer_reads(&self) -> bool {\n self.file_buffer_size > 0\n }\n```"}], "func_name": "buffer_reads", "docstring": "Returns whether this proxy is configured to buffer readonly files.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/files.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8463347a0dc8a91b98b2ff0a26d5896e9ef5cfc149a1b66377c4296c5190ba31"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: setup_proxy\n\nDocumentation:\nSets up a [`TaskSender`] and [`BackgroundTasks`] for a functioning [`FilesProxy`].\n\n- `protocol_version`: allows specifying the version of the protocol to use for testing out\npotential mismatches in messages.\n- `buffer_reads`: configures buffering readonly files\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn setup_proxy(\n protocol_version: Version,\n file_buffer_size: u64,\n ) -> (\n TaskSender,\n BackgroundTasks,\n ) {\n let mut tasks: BackgroundTasks =\n Default::default();\n\n let proxy = tasks.register(\n FilesProxy::new(file_buffer_size),\n MainTaskId::FilesProxy,\n 32,\n );\n\n proxy\n .send(FilesProxyMessage::ProtocolVersion(protocol_version))\n .await;\n\n (proxy, tasks)\n }\n```"}], "func_name": "setup_proxy", "docstring": "Sets up a [`TaskSender`] and [`BackgroundTasks`] for a functioning [`FilesProxy`].\n\n- `protocol_version`: allows specifying the version of the protocol to use for testing out\npotential mismatches in messages.\n- `buffer_reads`: configures buffering readonly files", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/files.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "860c61133469addab271e6389de2dbbcce0010194fc5807876c4dcbddcba1c03"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open_file\n\nDocumentation:\nHelper function for opening a file in a running [`FilesProxy`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn open_file(\n proxy: &TaskSender,\n tasks: &mut BackgroundTasks,\n readonly: bool,\n ) -> u64 {\n let message_id = rand::random();\n let fd = rand::random();\n\n let request = FileRequest::Open(OpenFileRequest {\n path: PathBuf::from(\"/some/path\"),\n open_options: OpenOptionsInternal {\n read: true,\n write: !readonly,\n ..Default::default()\n },\n });\n proxy\n .send(FilesProxyMessage::FileReq(\n message_id,\n LayerId(0),\n request.clone(),\n ))\n .await;\n let update = tasks.next().await.unwrap().1.unwrap_message();\n assert_eq!(\n update,\n ProxyMessage::ToAgent(ClientMessage::FileRequest(request)),\n );\n\n let response = FileResponse::Open(Ok(OpenFileResponse { fd }));\n proxy\n .send(FilesProxyMessage::FileRes(response.clone()))\n .await;\n let update = tasks.next().await.unwrap().1.unwrap_message();\n assert_eq!(\n update,\n ProxyMessage::ToLayer(ToLayer {\n message_id,\n layer_id: LayerId(0),\n message: ProxyToLayerMessage::File(response),\n })\n );\n\n fd\n }\n```"}], "func_name": "open_file", "docstring": "Helper function for opening a file in a running [`FilesProxy`].", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/files.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/files.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8061e1a35b80fbe16812b88cb1eddd7f61fa2a67ee11f749224b48b2e74eac62"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_chunked_request\n\nDocumentation:\nHandles [`ChunkedRequest`] message from the agent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_chunked_request(\n &mut self,\n request: ChunkedRequest,\n is_steal: bool,\n message_bus: &mut MessageBus,\n ) {\n match request {\n ChunkedRequest::StartV1(request) => {\n let (body_tx, body_rx) = mpsc::channel(128);\n let request = request.map_body(|frames| StreamingBody::new(body_rx, frames));\n self.start_http_gateway(\n request,\n Some(body_tx),\n IncomingTrafficTransportType::Tcp,\n is_steal,\n message_bus,\n )\n .await;\n }\n\n ChunkedRequest::StartV2(request) => {\n let (body, body_tx) = if request.request.body.is_last {\n (StreamingBody::from(request.request.body.frames), None)\n } else {\n let (body_tx, body_rx) = mpsc::channel(128);\n (\n StreamingBody::new(body_rx, request.request.body.frames),\n Some(body_tx),\n )\n };\n\n let transport = request.transport;\n\n let HttpRequestMetadata::V1 { destination, .. } = request.metadata;\n let request = HttpRequest {\n connection_id: request.connection_id,\n request_id: request.request_id,\n internal_request: InternalHttpRequest {\n method: request.request.method,\n uri: request.request.uri,\n headers: request.request.headers,\n version: request.request.version,\n body,\n },\n port: destination.port(),\n };\n\n self.start_http_gateway(request, body_tx, transport, is_steal, message_bus)\n .await;\n }\n\n ChunkedRequest::Body(ChunkedRequestBodyV1 {\n frames,\n is_last,\n connection_id,\n request_id,\n }) => {\n let gateway = self\n .http_gateways\n .get_mut(is_steal)\n .get_mut(&connection_id)\n .and_then(|gateways| gateways.get_mut(&request_id));\n let Some(gateway) = gateway else {\n tracing::debug!(\n connection_id,\n request_id,\n frames = ?frames,\n last_body_chunk = is_last,\n is_steal,\n \"Received a body chunk for a request that is no longer alive locally\"\n );\n\n return;\n };\n\n let Some(tx) = gateway.body_tx.as_ref() else {\n tracing::debug!(\n connection_id,\n request_id,\n frames = ?frames,\n last_body_chunk = is_last,\n is_steal,\n \"Received a body chunk for a request with a closed body\"\n );\n\n return;\n };\n\n for frame in frames {\n if let Err(err) = tx.send(frame).await {\n tracing::debug!(\n frame = ?err.0,\n connection_id,\n request_id,\n is_steal,\n \"Failed to send an HTTP request body frame to the HttpGatewayTask, channel is closed\"\n );\n break;\n }\n }\n\n if is_last {\n gateway.body_tx = None;\n }\n }\n\n ChunkedRequest::ErrorV1(ChunkedRequestErrorV1 {\n connection_id,\n request_id,\n }) => {\n tracing::debug!(\n connection_id,\n request_id,\n is_steal,\n \"Received an error in an HTTP request body\",\n );\n\n if let Some(gateways) = self.http_gateways.get_mut(is_steal).get_mut(&connection_id)\n {\n gateways.remove(&request_id);\n };\n }\n\n ChunkedRequest::ErrorV2(ChunkedRequestErrorV2 {\n connection_id,\n request_id,\n error_message,\n }) => {\n tracing::debug!(\n connection_id,\n request_id,\n error = error_message,\n is_steal,\n \"Received an error in an HTTP request body\",\n );\n\n if let Some(gateways) = self.http_gateways.get_mut(is_steal).get_mut(&connection_id)\n {\n gateways.remove(&request_id);\n };\n }\n }\n }\n```"}], "func_name": "handle_chunked_request", "docstring": "Handles [`ChunkedRequest`] message from the agent.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b6fa0d4a96ad6ee8d33b0a3f5b377fa189b3a4a09224eb9fb6fa7e305482313"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: queue\n\nDocumentation:\nRetrieves correct [`RequestQueue`] for the given [`NetProtocol`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn queue(&mut self, protocol: NetProtocol) -> &mut RequestQueue {\n match protocol {\n NetProtocol::Datagrams => &mut self.datagrams_reqs,\n NetProtocol::Stream => &mut self.stream_reqs,\n }\n }\n```"}], "func_name": "queue", "docstring": "Retrieves correct [`RequestQueue`] for the given [`NetProtocol`].", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/outgoing.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/outgoing.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f56fc0dd6994d2c0da3cdf00198d9a44b607ee2d8e50e33e1ad007e42270e4de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: addr_info_v2\n\nDocumentation:\nReturns whether [`mirrord_protocol`] version allows for a V2 addrinfo request.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn addr_info_v2(&self) -> bool {\n self.protocol_version\n .as_ref()\n .is_some_and(|version| ADDRINFO_V2_VERSION.matches(version))\n }\n```"}], "func_name": "addr_info_v2", "docstring": "Returns whether [`mirrord_protocol`] version allows for a V2 addrinfo request.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/simple.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/simple.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "08bb9d7f158c9e06e9fdae0123d24b1d7353c171564e1e08e8d187517a1363ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: can_retry\n\nDocumentation:\nChecks if we can retry sending the request, given that the previous attempt resulted in this\nerror.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn can_retry(&self) -> bool {\n match self {\n Self::SocketSetupFailed(..)\n | Self::UnsupportedHttpVersion(..)\n | Self::TlsSetupError(..) => false,\n Self::ConnectTcpFailed(..) | Self::ConnectTlsFailed(..) => true,\n Self::HandshakeFailed(err) | Self::SendFailed(err) | Self::ReadBodyFailed(err) => (err\n .is_parse()\n || err.is_parse_status()\n || err.is_parse_too_large()\n || err.is_user())\n .not(),\n }\n }\n```"}], "func_name": "can_retry", "docstring": "Checks if we can retry sending the request, given that the previous attempt resulted in this\nerror.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/http.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/http.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d00a793861e8bec39e4825c3d48870d44f849c29289252e4068fad6ec9f6339b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handshake\n\nDocumentation:\nPerforms an HTTP handshake over the given IO stream.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handshake(version: Version, target_stream: IO) -> Result\n where\n IO: 'static + AsyncRead + AsyncWrite + Unpin + Send,\n {\n match version {\n Version::HTTP_2 => {\n let (sender, connection) =\n http2::handshake(TokioExecutor::default(), TokioIo::new(target_stream))\n .await\n .map_err(LocalHttpError::HandshakeFailed)?;\n\n tokio::spawn(async move {\n match connection.await {\n Ok(()) => {\n tracing::trace!(\"HTTP connection with the local application finished\");\n }\n Err(error) => {\n tracing::warn!(%error, \"HTTP connection with the local application failed\");\n }\n }\n });\n\n Ok(HttpSender::V2(sender))\n }\n\n Version::HTTP_3 => Err(LocalHttpError::UnsupportedHttpVersion(version)),\n\n _http_v1 => {\n let (sender, connection) = http1::handshake(TokioIo::new(target_stream))\n .await\n .map_err(LocalHttpError::HandshakeFailed)?;\n\n tokio::spawn(async move {\n match connection.with_upgrades().await {\n Ok(()) => {\n tracing::trace!(\"HTTP connection with the local application finished\");\n }\n Err(error) => {\n tracing::warn!(%error, \"HTTP connection with the local application failed\");\n }\n }\n });\n\n Ok(HttpSender::V1(sender))\n }\n }\n }\n```"}], "func_name": "handshake", "docstring": "Performs an HTTP handshake over the given IO stream.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/http.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/http.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c16fba36635a779aa127a066051dc334b12b2cf8ff0aa6def28b1dde5ed0506b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_request\n\nDocumentation:\nTries to send the given [`HttpRequest`] to the server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn send_request(\n &mut self,\n request: HttpRequest,\n ) -> Result, LocalHttpError> {\n match self {\n Self::V1(sender) => {\n // Solves a \"connection was not ready\" client error.\n // https://rust-lang.github.io/wg-async/vision/submitted_stories/status_quo/barbara_tries_unix_socket.html#the-single-magical-line\n sender.ready().await.map_err(LocalHttpError::SendFailed)?;\n\n sender\n .send_request(request.internal_request.into())\n .await\n .map_err(LocalHttpError::SendFailed)\n }\n Self::V2(sender) => {\n let mut hyper_request: Request<_> = request.internal_request.into();\n\n // fixes https://github.com/metalbear-co/mirrord/issues/2497\n // inspired by https://github.com/linkerd/linkerd2-proxy/blob/c5d9f1c1e7b7dddd9d75c0d1a0dca68188f38f34/linkerd/proxy/http/src/h2.rs#L175\n if hyper_request.uri().authority().is_none()\n && hyper_request.version() != Version::HTTP_11\n {\n tracing::trace!(\n original_version = ?hyper_request.version(),\n \"Request URI has no authority, changing HTTP version to {:?}\",\n Version::HTTP_11,\n );\n\n *hyper_request.version_mut() = Version::HTTP_11;\n }\n\n // Solves a \"connection was not ready\" client error.\n // https://rust-lang.github.io/wg-async/vision/submitted_stories/status_quo/barbara_tries_unix_socket.html#the-single-magical-line\n sender.ready().await.map_err(LocalHttpError::SendFailed)?;\n\n sender\n .send_request(hyper_request)\n .await\n .map_err(LocalHttpError::SendFailed)\n }\n }\n }\n```"}], "func_name": "send_request", "docstring": "Tries to send the given [`HttpRequest`] to the server.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/http.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/http.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b56ec9d41efda8ec649279290301cc36ccdcd5395f354bd5eb7219549fedab0a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: upgrade_req_handler\n\nDocumentation:\nHandles requests upgrading to the [`TEST_PROTO`] protocol.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn upgrade_req_handler(\n mut req: Request,\n ) -> hyper::Result>> {\n async fn dummy_echo(upgraded: Upgraded) -> io::Result<()> {\n let mut upgraded = TokioIo::new(upgraded);\n let mut buf = [0_u8; 64];\n\n upgraded.write_all(INITIAL_MESSAGE).await?;\n\n loop {\n let bytes_read = upgraded.read(&mut buf[..]).await?;\n if bytes_read == 0 {\n break;\n }\n\n let echo_back = buf.get(0..bytes_read).unwrap();\n upgraded.write_all(echo_back).await?;\n }\n\n Ok(())\n }\n\n let mut res = Response::new(Empty::new());\n\n let contains_expected_upgrade = req\n .headers()\n .get(UPGRADE)\n .filter(|proto| *proto == TEST_PROTO)\n .is_some();\n if !contains_expected_upgrade {\n *res.status_mut() = StatusCode::BAD_REQUEST;\n return Ok(res);\n }\n\n task::spawn(async move {\n match hyper::upgrade::on(&mut req).await {\n Ok(upgraded) => {\n if let Err(e) = dummy_echo(upgraded).await {\n eprintln!(\"server foobar io error: {}\", e)\n };\n }\n Err(e) => eprintln!(\"upgrade error: {}\", e),\n }\n });\n\n *res.status_mut() = StatusCode::SWITCHING_PROTOCOLS;\n res.headers_mut()\n .insert(UPGRADE, HeaderValue::from_static(TEST_PROTO));\n res.headers_mut()\n .insert(CONNECTION, HeaderValue::from_static(\"upgrade\"));\n Ok(res)\n }\n```"}], "func_name": "upgrade_req_handler", "docstring": "Handles requests upgrading to the [`TEST_PROTO`] protocol.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/http_gateway.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/http_gateway.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "523011849b97b477c81c5e934e365d4ebe82a2d91dcb87a54381324a3bd7c395"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dummy_echo_server\n\nDocumentation:\nRuns a [`hyper`] server that accepts only requests upgrading to the [`TEST_PROTO`] protocol.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn dummy_echo_server(\n listener: TcpListener,\n acceptor: Option,\n mut shutdown: watch::Receiver,\n ) {\n loop {\n let (stream, _) = tokio::select! {\n res = listener.accept() => res.expect(\"dummy echo server failed to accept a TCP connection\"),\n _ = shutdown.changed() => break,\n };\n\n let mut shutdown = shutdown.clone();\n\n match acceptor.clone() {\n Some(acceptor) => {\n task::spawn(async move {\n let stream = acceptor\n .accept(stream)\n .await\n .expect(\"dummy echo server failed to accept a TLS connection\");\n let conn = http1::Builder::new().serve_connection(\n TokioIo::new(stream),\n service_fn(upgrade_req_handler),\n );\n let mut conn = conn.with_upgrades();\n let mut conn = Pin::new(&mut conn);\n\n tokio::select! {\n res = &mut conn => {\n res.expect(\"dummy echo server failed to serve connection\");\n }\n\n _ = shutdown.changed() => {\n conn.graceful_shutdown();\n }\n }\n });\n }\n\n None => {\n task::spawn(async move {\n let conn = http1::Builder::new().serve_connection(\n TokioIo::new(stream),\n service_fn(upgrade_req_handler),\n );\n let mut conn = conn.with_upgrades();\n let mut conn = Pin::new(&mut conn);\n\n tokio::select! {\n res = &mut conn => {\n res.expect(\"dummy echo server failed to serve connection\");\n }\n\n _ = shutdown.changed() => {\n conn.graceful_shutdown();\n }\n }\n });\n }\n }\n }\n }\n```"}], "func_name": "dummy_echo_server", "docstring": "Runs a [`hyper`] server that accepts only requests upgrading to the [`TEST_PROTO`] protocol.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/http_gateway.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/http_gateway.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "07fa221d60bce8fde982f5ccd0af50ac800f48808452345b5c30ba0a208eb56d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nRetrieves remote addresses for the given pair of local addresses.\n\nIf the mapping is not found, returns the local addresses unchanged.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(&mut self, req: ConnMetadataRequest) -> ConnMetadataResponse {\n self.prepared_responses\n .remove(&req)\n .unwrap_or_else(|| ConnMetadataResponse {\n remote_source: req.peer_address,\n local_address: req.listener_address.ip(),\n })\n }\n```"}], "func_name": "get", "docstring": "Retrieves remote addresses for the given pair of local addresses.\n\nIf the mapping is not found, returns the local addresses unchanged.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/metadata_store.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/metadata_store.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1088e6d8ec769ef69e3d16d2cb0c756e9f3744054c427abf826bdd3528d068e7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect\n\nDocumentation:\nAdds a new `req`->`res` mapping to this struct.\n\nMarks that the mapping is related to the remote connection with the given id.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expect(\n &mut self,\n req: ConnMetadataRequest,\n connection: ConnectionId,\n res: ConnMetadataResponse,\n ) {\n self.expected_requests.insert(connection, req.clone());\n self.prepared_responses.insert(req, res);\n }\n```"}], "func_name": "expect", "docstring": "Adds a new `req`->`res` mapping to this struct.\n\nMarks that the mapping is related to the remote connection with the given id.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/metadata_store.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/metadata_store.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eea85d4049161f5a2363ad2d78d2dd73801958b46934f5c19eeb970e49cd8e44"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: no_longer_expect\n\nDocumentation:\nClears mapping related to the remote connection with the given id.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn no_longer_expect(&mut self, connection: ConnectionId) {\n let Some(req) = self.expected_requests.remove(&connection) else {\n return;\n };\n self.prepared_responses.remove(&req);\n }\n```"}], "func_name": "no_longer_expect", "docstring": "Clears mapping related to the remote connection with the given id.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/metadata_store.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/metadata_store.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "13ca7746da432928bc7451ab7e2c461c7a786963ddc34e209e27e801343947da"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_port\n\nDocumentation:\nRetrieves subscribed port from the given [`StealType`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_port(steal_type: &StealType) -> Port {\n match steal_type {\n StealType::All(port) => *port,\n StealType::FilteredHttp(port, _) => *port,\n StealType::FilteredHttpEx(port, _) => *port,\n }\n}\n```"}], "func_name": "get_port", "docstring": "Retrieves subscribed port from the given [`StealType`].", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/port_subscription_ext.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/port_subscription_ext.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc424e4f66fabcf5a385e267439f4f2b12cb57633802e0f583a741373682eb0b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new subscription from the given [`Source`].\nAdditionally returns a message to be sent to the agent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(source: Source) -> (Self, ClientMessage) {\n let message = source.request.subscription.agent_subscribe();\n\n (\n Self {\n queued_sources: Default::default(),\n active_source: source,\n confirmed: false,\n },\n message,\n )\n }\n```"}], "func_name": "new", "docstring": "Creates a new subscription from the given [`Source`].\nAdditionally returns a message to be sent to the agent.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d78111fcc4da47ddd8a664687296dee7bfe2b336590866045a2c4c36601ca24c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_source\n\nDocumentation:\nOverwrites the active subscription [`Source`].\nReturns a message to be sent to the layer.\nReturns [`None`] if this subscription is still waiting for confirmation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn push_source(&mut self, source: Source) -> Option {\n let message = if self.confirmed {\n // Agent already confirmed this subscription.\n Some(ToLayer {\n message_id: source.message,\n layer_id: source.layer,\n message: ProxyToLayerMessage::Incoming(IncomingResponse::PortSubscribe(Ok(()))),\n })\n } else {\n // Waiting for agent confirmation.\n None\n };\n\n let previous_source = std::mem::replace(&mut self.active_source, source);\n self.queued_sources.push(previous_source);\n\n message\n }\n```"}], "func_name": "push_source", "docstring": "Overwrites the active subscription [`Source`].\nReturns a message to be sent to the layer.\nReturns [`None`] if this subscription is still waiting for confirmation.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3809db0e297ef4db7b3e23d9fa374e8890ce21c97b24f9a2e1a6c33936d90bcc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: confirm\n\nDocumentation:\nConfirms this subscription.\nReturns messages to be sent to the layers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn confirm(&mut self) -> Vec {\n if self.confirmed {\n return vec![];\n }\n\n self.confirmed = true;\n\n self.queued_sources\n .iter()\n .chain(std::iter::once(&self.active_source))\n .map(|source| ToLayer {\n layer_id: source.layer,\n message_id: source.message,\n message: ProxyToLayerMessage::Incoming(IncomingResponse::PortSubscribe(Ok(()))),\n })\n .collect()\n }\n```"}], "func_name": "confirm", "docstring": "Confirms this subscription.\nReturns messages to be sent to the layers.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d40da82a7a0ea4fb923343aa1fe2a58cc05c0d357cf16450be71d435a3784071"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reject\n\nDocumentation:\nRejects this subscription with the given `reason`.\nReturns messages to be sent to the layers.\nReturns [`Err`] if this subscription was already confirmed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reject(self, reason: ResponseError) -> Result, Self> {\n if self.confirmed {\n return Err(self);\n }\n\n let responses = self\n .queued_sources\n .into_iter()\n .chain(std::iter::once(self.active_source))\n .map(|source| ToLayer {\n layer_id: source.layer,\n message_id: source.message,\n message: ProxyToLayerMessage::Incoming(IncomingResponse::PortSubscribe(Err(\n reason.clone(),\n ))),\n })\n .collect();\n\n Ok(responses)\n }\n```"}], "func_name": "reject", "docstring": "Rejects this subscription with the given `reason`.\nReturns messages to be sent to the layers.\nReturns [`Err`] if this subscription was already confirmed.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "702a8ba426def9c044d4b9af2a4d5bccbd017b94594863e72a14c1e0b2c77457"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_source\n\nDocumentation:\nRemoved a source from this subscription.\nIf this source is the last one, returns [`Err`] with a message to be sent to the agent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn remove_source(mut self, listening_on: SocketAddr) -> Result> {\n let queue_size = self.queued_sources.len();\n self.queued_sources\n .retain(|source| source.request.listening_on != listening_on);\n if queue_size != self.queued_sources.len() {\n return Ok(self);\n }\n\n if self.active_source.request.listening_on != listening_on {\n return Ok(self);\n }\n\n match self.queued_sources.pop() {\n Some(next_in_queue) => {\n self.active_source = next_in_queue;\n Ok(self)\n }\n None => Err(Box::new(\n self.active_source\n .request\n .subscription\n .wrap_agent_unsubscribe(),\n )),\n }\n }\n```"}], "func_name": "remove_source", "docstring": "Removed a source from this subscription.\nIf this source is the last one, returns [`Err`] with a message to be sent to the agent.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e358927d26bdaf817b0c729410c02657d2f254a5574dd38d2dc3da180139ce6b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturns active [`PortSubscribe`] request for the given [`Port`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(&self, port: Port) -> Option<&PortSubscribe> {\n self.subscriptions\n .get(&port)\n .map(|sub| &sub.active_source.request)\n }\n```"}], "func_name": "get", "docstring": "Returns active [`PortSubscribe`] request for the given [`Port`].", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0614f41f899a304d68f810bb5caf1379a93f26c05f7bf700341955df0475db51"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: layer_closed\n\nDocumentation:\nNotifies this struct about layer closing.\nReturns messages to be sent to the agent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn layer_closed(&mut self, layer_id: LayerId) -> Vec {\n self.remote_ports\n .remove_all(layer_id)\n .filter_map(|(port, listening_on)| {\n let subscription = self.subscriptions.remove(&port)?;\n match subscription.remove_source(listening_on) {\n Ok(subscription) => {\n self.subscriptions.insert(port, subscription);\n None\n }\n Err(message) => Some(*message),\n }\n })\n .collect()\n }\n```"}], "func_name": "layer_closed", "docstring": "Notifies this struct about layer closing.\nReturns messages to be sent to the agent.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc66f5cb5d85c26806b88a32dee369adb2f3b0ac9c3c295b930b09dfb4d358a0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: layer_forked\n\nDocumentation:\nNotifies this struct about layer forking.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn layer_forked(&mut self, parent: LayerId, child: LayerId) {\n self.remote_ports.clone_all(parent, child);\n }\n```"}], "func_name": "layer_forked", "docstring": "Notifies this struct about layer forking.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/subscriptions.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d3b7956066e3f46745f135de6698742cc6221fba88fdb1b379cffc7ce43f6881"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nMakes the connection, returning the IO stream and data ready to be sent to the agent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn connect(self) -> Result<(MaybeTls, Vec), InProxyTaskError> {\n match self {\n LocalTcpConnection::FromTheStart {\n socket,\n peer,\n transport,\n tls_setup,\n } => {\n let stream = socket.connect(peer).await?;\n let stream = match (transport, tls_setup) {\n (IncomingTrafficTransportType::Tcp, ..) => MaybeTls::NoTls(stream),\n (.., None) => MaybeTls::NoTls(stream),\n (\n IncomingTrafficTransportType::Tls {\n alpn_protocol,\n server_name: original_server_name,\n },\n Some(setup),\n ) => {\n let (connector, server_name) = setup.get(alpn_protocol).await?;\n let server_name = server_name\n .or_else(|| {\n let name = original_server_name.clone()?;\n ServerName::try_from(name).ok()\n })\n .unwrap_or_else(|| {\n ServerName::try_from(\"localhost\")\n .expect(\"'localhost' is a valid DNS name\")\n });\n let stream = connector.connect(server_name, stream).await?;\n MaybeTls::Tls(Box::new(stream))\n }\n };\n\n Ok((stream, Default::default()))\n }\n\n LocalTcpConnection::AfterUpgrade(on_upgrade) => {\n let upgraded = on_upgrade.await.map_err(InProxyTaskError::Upgrade)?;\n let parts = upgraded\n .downcast::>()\n .expect(\"IO type is known\");\n\n Ok((parts.io.into_inner(), parts.read_buf.into()))\n }\n }\n }\n```"}], "func_name": "connect", "docstring": "Makes the connection, returning the IO stream and data ready to be sent to the agent.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/tcp_proxy.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/tcp_proxy.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "66fd8447084cd9025ee988ae83b179e641f11d3bb4a0d1b0a015d7d9c7ad3f9e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new task.\n\n* This task will talk with the user application using the given [`LocalTcpConnection`].\n* If `discard_data` is set, this task will silently discard all data coming from the user\napplication.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n connection_id: ConnectionId,\n connection: LocalTcpConnection,\n discard_data: bool,\n ) -> Self {\n Self {\n _connection_id: connection_id,\n connection: Some(connection),\n discard_data,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new task.\n\n* This task will talk with the user application using the given [`LocalTcpConnection`].\n* If `discard_data` is set, this task will silently discard all data coming from the user\napplication.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/tcp_proxy.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/tcp_proxy.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6af77b613b5fd8db7649f7009e31dad6a8b2064ed2faf9e09f1d908c82d26755"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturns a [`TlsConnector`] and an optional [`ServerName`] to use when making the TLS\nconnection.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get(\n &self,\n alpn_protocol: Option>,\n ) -> Result<(TlsConnector, Option>), LocalTlsSetupError> {\n let (mut config, server_name) = self\n .resolved\n .get_or_try_init(|| self.resolve())\n .await?\n .clone();\n config.alpn_protocols.extend(alpn_protocol);\n\n Ok((TlsConnector::from(Arc::new(config)), server_name))\n }\n```"}], "func_name": "get", "docstring": "Returns a [`TlsConnector`] and an optional [`ServerName`] to use when making the TLS\nconnection.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/tls.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/tls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "baacdfd35ad94c347082d8d27efb7ef045f2f7aad696fee614e8279b276ea4ac"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_with_timeout\n\nDocumentation:\nCreates a new store.\n\nThe store will keep unused clients alive for at least the given time.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_with_timeout(timeout: Duration, tls_setup: Option>) -> Self {\n let store = Self {\n clients: Default::default(),\n notify: Default::default(),\n tls_setup,\n };\n\n tokio::spawn(cleanup_task(store.clone(), timeout));\n\n store\n }\n```"}], "func_name": "new_with_timeout", "docstring": "Creates a new store.\n\nThe store will keep unused clients alive for at least the given time.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/http/client_store.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/http/client_store.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f1366ab26f12f639017400907780b32e99f5211a818f357e9d612eb0e543746"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cleanup_task\n\nDocumentation:\nCleans up stale [`LocalHttpClient`]s from the [`ClientStore`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn cleanup_task(store: ClientStore, idle_client_timeout: Duration) {\n let clients = Arc::downgrade(&store.clients);\n let notify = store.notify.clone();\n std::mem::drop(store);\n\n loop {\n let Some(clients) = clients.upgrade() else {\n // Failed `upgrade` means that all `ClientStore` instances were dropped.\n // This task is no longer needed.\n break;\n };\n\n let now = Instant::now();\n let mut min_last_used = None;\n let notified = {\n let Ok(mut guard) = clients.lock() else {\n tracing::error!(\"ClientStore mutex is poisoned, this is a bug\");\n return;\n };\n\n guard.retain(|client| {\n if client.last_used + idle_client_timeout > now {\n // We determine how long to sleep before cleaning the store again.\n min_last_used = min_last_used\n .map(|previous| cmp::min(previous, client.last_used))\n .or(Some(client.last_used));\n\n true\n } else {\n // We drop the idle clients that have gone beyond the timeout.\n tracing::trace!(?client, \"Dropping an idle client\");\n false\n }\n });\n\n // Acquire [`Notified`] while still holding the lock.\n // Prevents missed updates.\n notify.notified()\n };\n\n if let Some(min_last_used) = min_last_used {\n time::sleep_until(min_last_used + idle_client_timeout).await;\n } else {\n notified.await;\n }\n }\n}\n```"}], "func_name": "cleanup_task", "docstring": "Cleans up stale [`LocalHttpClient`]s from the [`ClientStore`].", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/http/client_store.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/http/client_store.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c85e30268fa32ad716ba614ff4f9048b0b4a2784bb679a5ae0c8879bc083a305"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_cert\n\nDocumentation:\nGenerates a new [`CertifiedKey`] with a random [`KeyPair`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_cert(\n name: &str,\n issuer: Option<&CertifiedKey>,\n can_sign_others: bool,\n ) -> CertifiedKey {\n let key_pair = KeyPair::generate().unwrap();\n\n let mut params = CertificateParams::new(vec![name.to_string()]).unwrap();\n params\n .distinguished_name\n .push(DnType::CommonName, DnValue::Utf8String(name.into()));\n\n if can_sign_others {\n params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);\n params.key_usages = vec![KeyUsagePurpose::KeyCertSign];\n }\n\n let cert = match issuer {\n Some(issuer) => params\n .signed_by(&key_pair, &issuer.cert, &issuer.key_pair)\n .unwrap(),\n None => params.self_signed(&key_pair).unwrap(),\n };\n\n CertifiedKey { cert, key_pair }\n }\n```"}], "func_name": "generate_cert", "docstring": "Generates a new [`CertifiedKey`] with a random [`KeyPair`].", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/http/client_store.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/http/client_store.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c6427e755e5156fdd18b228341753b69a6082fb8c667fee954818c47e4bbf7b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance of this [`Body`].\n\nIt will first read all frames from the vector given as `first_frames`.\nFollowing frames will be fetched from the given `rx`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n rx: Receiver,\n first_frames: Vec,\n ) -> Self {\n Self {\n shared_state: Arc::new(Mutex::new((rx, first_frames))),\n idx: 0,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance of this [`Body`].\n\nIt will first read all frames from the vector given as `first_frames`.\nFollowing frames will be fetched from the given `rx`.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/incoming/http/streaming_body.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/incoming/http/streaming_body.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a1904c11dbb26d94f65b20ffb1963706e7222c1e008bf00e39ac698ebb6ab757"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance. This instance will use the provided [`PreparedSocket`] to accept the\nlayer's connection and manage it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(id: InterceptorId, socket: PreparedSocket) -> Self {\n Self {\n id,\n socket: Some(socket),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance. This instance will use the provided [`PreparedSocket`] to accept the\nlayer's connection and manage it.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/outgoing/interceptor.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/outgoing/interceptor.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f493bbcab1268412b432d30ff39d3af2b62117a10caf135dcaa88d1841344d2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: local_address\n\nDocumentation:\nReturns the address of this socket.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn local_address(&self) -> io::Result {\n let address = match self {\n Self::TcpListener(listener) => listener.local_addr()?.into(),\n Self::UdpSocket(socket) => socket.local_addr()?.into(),\n Self::UnixListener(listener) => {\n let addr = listener.local_addr()?;\n let pathname = addr.as_pathname().unwrap().to_path_buf();\n SocketAddress::Unix(UnixAddr::Pathname(pathname))\n }\n };\n\n Ok(address)\n }\n```"}], "func_name": "local_address", "docstring": "Returns the address of this socket.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/outgoing/net_protocol_ext.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/outgoing/net_protocol_ext.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "10d543bc3f85b055ce9856f3e42907fc61d1bea3ca848739fc0f10c068f7bc09"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accept\n\nDocumentation:\nAccepts one connection on this socket and returns a new socket for sending and receiving\ndata.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn accept(self) -> io::Result {\n let (inner, is_really_connected) = match self {\n Self::TcpListener(listener) => {\n let (stream, _) = listener.accept().await?;\n (InnerConnectedSocket::TcpStream(stream), true)\n }\n Self::UdpSocket(socket) => (InnerConnectedSocket::UdpSocket(socket), false),\n Self::UnixListener(listener) => {\n let (stream, _) = listener.accept().await?;\n (InnerConnectedSocket::UnixStream(stream), true)\n }\n };\n\n Ok(ConnectedSocket {\n inner,\n is_really_connected,\n buffer: BytesMut::with_capacity(64 * 1024),\n })\n }\n```"}], "func_name": "accept", "docstring": "Accepts one connection on this socket and returns a new socket for sending and receiving\ndata.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/outgoing/net_protocol_ext.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/outgoing/net_protocol_ext.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "59a68288fbe79115930fb8856e506875ca76ec4514bc3cf53c2aedf245182d81"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send\n\nDocumentation:\nSends all given data to the layer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn send(&mut self, bytes: &[u8]) -> io::Result<()> {\n match &mut self.inner {\n InnerConnectedSocket::UdpSocket(socket) => {\n let bytes_sent = socket.send(bytes).await?;\n\n if bytes_sent != bytes.len() {\n Err(io::Error::new(\n io::ErrorKind::Other,\n \"failed to send all bytes\",\n ))?;\n }\n\n Ok(())\n }\n InnerConnectedSocket::TcpStream(stream) => stream.write_all(bytes).await,\n InnerConnectedSocket::UnixStream(stream) => stream.write_all(bytes).await,\n }\n }\n```"}], "func_name": "send", "docstring": "Sends all given data to the layer.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/outgoing/net_protocol_ext.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/outgoing/net_protocol_ext.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "15bcf3ded185fe6808f389fec23a7b9c881c530e5951d7aee2c78b42776824f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: receive\n\nDocumentation:\nReceives some data from the layer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn receive(&mut self) -> io::Result> {\n match &mut self.inner {\n InnerConnectedSocket::UdpSocket(socket) => {\n if !self.is_really_connected {\n let peer = socket.peek_sender().await?;\n socket.connect(peer).await?;\n self.is_really_connected = true;\n }\n\n socket.recv_buf(&mut self.buffer).await?;\n let bytes = self.buffer.to_vec();\n self.buffer.clear();\n Ok(bytes)\n }\n InnerConnectedSocket::TcpStream(stream) => {\n stream.read_buf(&mut self.buffer).await?;\n let bytes = self.buffer.to_vec();\n self.buffer.clear();\n Ok(bytes)\n }\n InnerConnectedSocket::UnixStream(stream) => {\n stream.read_buf(&mut self.buffer).await?;\n let bytes = self.buffer.to_vec();\n self.buffer.clear();\n Ok(bytes)\n }\n }\n }\n```"}], "func_name": "receive", "docstring": "Receives some data from the layer.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/outgoing/net_protocol_ext.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/outgoing/net_protocol_ext.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "83b1ef1c0a8b66448622ff3da664a38437774ae99aafbcb9225a748afa3047ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shutdown\n\nDocumentation:\nShuts the connection down. See [`AsyncWriteExt::shutdown`].\n\n# Note\n\nThis is a no-op for UDP sockets.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn shutdown(&mut self) -> io::Result<()> {\n match &mut self.inner {\n InnerConnectedSocket::TcpStream(stream) => stream.shutdown().await,\n InnerConnectedSocket::UnixStream(stream) => stream.shutdown().await,\n InnerConnectedSocket::UdpSocket(..) => Ok(()),\n }\n }\n```"}], "func_name": "shutdown", "docstring": "Shuts the connection down. See [`AsyncWriteExt::shutdown`].\n\n# Note\n\nThis is a no-op for UDP sockets.", "repo": "metalbear-co/mirrord", "path": "mirrord/intproxy/src/proxies/outgoing/net_protocol_ext.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/intproxy/src/proxies/outgoing/net_protocol_ext.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d25a27133748ef1753bd10ec6c4975b0b442cf0af1ea2873e4278568b435e804"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wrap_raw_connection\n\nDocumentation:\nSpawns a background [`tokio::task`] that sends and receives [`mirrord_protocol`] messages\nover the given IO stream.\n\nThe task handles the encoding/decoding of the [`mirrord_protocol`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn wrap_raw_connection(\n stream: IO,\n) -> (mpsc::Sender, mpsc::Receiver)\nwhere\n IO: AsyncRead + AsyncWrite + Unpin + Send + 'static,\n{\n let mut codec = actix_codec::Framed::new(stream, ClientCodec::default());\n\n let (in_tx, mut in_rx) = mpsc::channel(CONNECTION_CHANNEL_SIZE);\n let (out_tx, out_rx) = mpsc::channel(CONNECTION_CHANNEL_SIZE);\n\n tokio::spawn(\n async move {\n // Generally, this loop should not be exited early with any `return` statement.\n // We want the `close` below to happen.\n loop {\n tokio::select! {\n msg = in_rx.recv() => match msg {\n Some(msg) => {\n if let Err(error) = codec.send(msg).await {\n tracing::error!(%error, \"Failed to send a client message\");\n break;\n }\n }\n None => {\n tracing::trace!(\"No more client messages, disconnecting\");\n break;\n }\n },\n\n msg = codec.next() => match msg {\n Some(Ok(msg)) => {\n if let Err(error) = out_tx.send(msg).await {\n tracing::error!(%error, \"Failed to send an agent message\");\n break;\n }\n }\n Some(Err(error)) => {\n tracing::error!(%error, \"Failed to receive an agent message\");\n break;\n }\n None => {\n tracing::trace!(\"No more agent messages, disconnecting\");\n break;\n }\n },\n }\n }\n\n let _ = codec.close().await;\n }\n .instrument(tracing::span!(\n Level::TRACE,\n \"mirrord_protocol_connection_wrapper_task\"\n )),\n );\n\n (in_tx, out_rx)\n}\n```"}], "func_name": "wrap_raw_connection", "docstring": "Spawns a background [`tokio::task`] that sends and receives [`mirrord_protocol`] messages\nover the given IO stream.\n\nThe task handles the encoding/decoding of the [`mirrord_protocol`].", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "402afcd67ff9d6965921ed90506680ebfb1a65a9c0a8ba09a25c3cccd266d8e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: missing_field\n\nDocumentation:\nUse when a resource fetched with [`kube`] is missing some expected field.\nPass full path to the field, e.g. `.spec.selector.matchLabels`.\n\nProduces [`KubeApiError::MalformedResource`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn missing_field>(resource: &R, field_path: &str) -> Self {\n let kind = R::kind(&());\n let name = resource.meta().name.as_ref();\n let namespace = resource.meta().namespace.as_deref().unwrap_or(\"default\");\n\n let message = match name {\n Some(name) => format!(\"{kind} `{namespace}/{name}` is missing field `{field_path}`\"),\n None => format!(\"{kind} is missing field `{field_path}`\"),\n };\n\n Self::MalformedResource(message)\n }\n```"}], "func_name": "missing_field", "docstring": "Use when a resource fetched with [`kube`] is missing some expected field.\nPass full path to the field, e.g. `.spec.selector.matchLabels`.\n\nProduces [`KubeApiError::MalformedResource`].", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/error.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/error.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9585118d63e66b097d3c6cc82a20cc4a13c15012cde2c914e2d5d9e003880f55"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: invalid_value\n\nDocumentation:\nUse when a resource fetched with [`kube`] is has an invalid field (e.g. node IP does not\nparse into [`IpAddr`](std::net::IpAddr)). Pass full path to the field, e.g.\n`.spec.selector.matchLabels`.\n\nProduces [`KubeApiError::MalformedResource`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn invalid_value, T: fmt::Display>(\n resource: &R,\n field_path: &str,\n info: T,\n ) -> Self {\n let kind = R::kind(&());\n let name = resource.meta().name.as_ref();\n let namespace = resource.meta().namespace.as_deref().unwrap_or(\"default\");\n\n let message = match name {\n Some(name) => {\n format!(\"field `{field_path}` in {kind} `{namespace}/{name}` is invalid: {info}\")\n }\n None => format!(\"field `{field_path}` in a {kind} is invalid: {info}\"),\n };\n\n Self::MalformedResource(message)\n }\n```"}], "func_name": "invalid_value", "docstring": "Use when a resource fetched with [`kube`] is has an invalid field (e.g. node IP does not\nparse into [`IpAddr`](std::net::IpAddr)). Pass full path to the field, e.g.\n`.spec.selector.matchLabels`.\n\nProduces [`KubeApiError::MalformedResource`].", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/error.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/error.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f4e884a2f8131f836f8cf683f12679f4ee674a8ad24846e8360a668113f0dfa0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: invalid_state\n\nDocumentation:\nUse when a resource fetched with [`kube`] is in invalid state, e.g. node is hosting too many\npods or pod is not running the selected container.\n\nProduces [`KubeApiError::InvalidResourceState`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn invalid_state, T: fmt::Display>(\n resource: &R,\n info: T,\n ) -> Self {\n let kind = R::kind(&());\n let name = resource.meta().name.as_ref();\n let namespace = resource.meta().namespace.as_deref().unwrap_or(\"default\");\n\n let message = match name {\n Some(name) => {\n format!(\"{kind} `{namespace}/{name}` is in invalid state: {info}\")\n }\n None => format!(\"{kind} is in invalid state: {info}\"),\n };\n\n Self::InvalidResourceState(message)\n }\n```"}], "func_name": "invalid_state", "docstring": "Use when a resource fetched with [`kube`] is in invalid state, e.g. node is hosting too many\npods or pod is not running the selected container.\n\nProduces [`KubeApiError::InvalidResourceState`].", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/error.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/error.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "352aefc804deedf7d2565017f2dc82c05c891fbeff9c56e6a76aaab4db5790e1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_labels\n\nDocumentation:\nConvert [`ResolvedTarget`] into `.metadata.labels`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_labels(self) -> Option> {\n match self {\n ResolvedTarget::Deployment(ResolvedResource { resource, .. }) => {\n resource.metadata.labels\n }\n ResolvedTarget::Rollout(ResolvedResource { resource, .. }) => resource.metadata.labels,\n ResolvedTarget::Pod(ResolvedResource { resource, .. }) => resource.metadata.labels,\n ResolvedTarget::Job(ResolvedResource { resource, .. }) => resource.metadata.labels,\n ResolvedTarget::CronJob(ResolvedResource { resource, .. }) => resource.metadata.labels,\n ResolvedTarget::StatefulSet(ResolvedResource { resource, .. }) => {\n resource.metadata.labels\n }\n ResolvedTarget::Service(ResolvedResource { resource, .. }) => resource.metadata.labels,\n ResolvedTarget::ReplicaSet(ResolvedResource { resource, .. }) => {\n resource.metadata.labels\n }\n ResolvedTarget::Targetless(_) => None,\n }\n }\n```"}], "func_name": "into_labels", "docstring": "Convert [`ResolvedTarget`] into `.metadata.labels`", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/resolved.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/resolved.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f24d63d104315ad0d87d375ce5e7da8e086479a8283251dd5a37669f8ef2a222"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: container\n\nDocumentation:\nConvenient way of getting the container from this target.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn container(&self) -> Option<&str> {\n match self {\n ResolvedTarget::Deployment(ResolvedResource { container, .. })\n | ResolvedTarget::Rollout(ResolvedResource { container, .. })\n | ResolvedTarget::Job(ResolvedResource { container, .. })\n | ResolvedTarget::CronJob(ResolvedResource { container, .. })\n | ResolvedTarget::StatefulSet(ResolvedResource { container, .. })\n | ResolvedTarget::Service(ResolvedResource { container, .. })\n | ResolvedTarget::Pod(ResolvedResource { container, .. })\n | ResolvedTarget::ReplicaSet(ResolvedResource { container, .. }) => {\n container.as_deref()\n }\n ResolvedTarget::Targetless(..) => None,\n }\n }\n```"}], "func_name": "container", "docstring": "Convenient way of getting the container from this target.", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/resolved.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/resolved.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4b1278eaa6b2251c354cac054cb635527f9f561efdbd2be4167a7269dfc0ab11"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: empty_deployment\n\nDocumentation:\nIs this a [`ResolvedTarget::Deployment`], and is it empty?\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn empty_deployment(&self) -> bool {\n if let Self::Deployment(ResolvedResource { resource, .. }) = self {\n !resource\n .status\n .as_ref()\n .map(|status| status.available_replicas > Some(0))\n .unwrap_or_default()\n } else {\n false\n }\n }\n```"}], "func_name": "empty_deployment", "docstring": "Is this a [`ResolvedTarget::Deployment`], and is it empty?", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/resolved.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/resolved.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c63811e2e5d95cc44b4b2ff537b7beb9fd1bd63925e7bef036eccaf26b2c46d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create\n\nDocumentation:\nCreates a new instance from the given [`LayerConfig`].\n\nIf [`LayerConfig::target`] specifies a targetless run,\nreplaces [`AgentConfig::namespace`] with the target namespace.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn create(config: &LayerConfig) -> Result {\n let client = create_kube_config(\n config.accept_invalid_certificates,\n config.kubeconfig.clone(),\n config.kube_context.clone(),\n )\n .await?\n .try_into()?;\n\n let mut agent = config.agent.clone();\n if config\n .target\n .path\n .as_ref()\n .is_none_or(|path| matches!(path, Target::Targetless))\n {\n agent.namespace = config.target.namespace.clone();\n }\n\n Ok(KubernetesAPI::new(client, agent))\n }\n```"}], "func_name": "create", "docstring": "Creates a new instance from the given [`LayerConfig`].\n\nIf [`LayerConfig::target`] specifies a targetless run,\nreplaces [`AgentConfig::namespace`] with the target namespace.", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00216b7edcc9090d2b11e0a9d6955452a95e9d1af8d9f5da9988ac5921944d8c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_pod\n\nDocumentation:\nExtracts data needed to create the mirrord-agent targeting the given [`Pod`].\nVerifies that the [`Pod`] is ready to be a target:\n1. pod is in \"Running\" phase,\n2. pod is not in deletion,\n3. target container is ready.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_pod(pod: &Pod, container_name: Option<&str>) -> Result {\n let pod_name = pod\n .metadata\n .name\n .as_ref()\n .ok_or_else(|| KubeApiError::missing_field(pod, \".metadata.name\"))?\n .to_owned();\n let pod_namespace = pod\n .metadata\n .namespace\n .as_ref()\n .ok_or_else(|| KubeApiError::missing_field(pod, \".metadata.namespace\"))?\n .to_owned();\n\n let phase = pod\n .status\n .as_ref()\n .and_then(|status| status.phase.as_ref())\n .ok_or_else(|| KubeApiError::missing_field(pod, \".status.phase\"))?;\n if phase != \"Running\" {\n return Err(KubeApiError::invalid_state(pod, \"not in 'Running' phase\"));\n }\n\n if pod.metadata.deletion_timestamp.is_some() {\n return Err(KubeApiError::invalid_state(pod, \"in deletion\"));\n }\n\n let node_name = pod\n .spec\n .as_ref()\n .and_then(|spec| spec.node_name.as_ref())\n .ok_or_else(|| KubeApiError::missing_field(pod, \".spec.nodeName\"))?\n .to_owned();\n\n let containers_probe_ports: Vec = pod\n .spec\n .as_ref()\n .ok_or_else(|| KubeApiError::missing_field(pod, \".spec\"))?\n .containers\n .iter()\n .flat_map(Self::probe_ports)\n .collect();\n\n let pod_ips = pod\n .status\n .as_ref()\n .and_then(|spec| spec.pod_ips.as_ref())\n .ok_or_else(|| KubeApiError::missing_field(pod, \".status.podIPs\"))?\n .iter()\n .filter_map(|pod_ip| {\n pod_ip\n .ip\n .parse::()\n .inspect_err(|e| {\n tracing::warn!(\"failed to parse pod IP {ip}: {e:#?}\", ip = pod_ip.ip);\n })\n .ok()\n })\n .collect();\n\n let container_statuses = pod\n .status\n .as_ref()\n .and_then(|status| status.container_statuses.as_ref())\n .ok_or_else(|| KubeApiError::missing_field(pod, \".status.containerStatuses\"))?;\n\n if container_name.is_none() && container_statuses.len() > 1 {\n tracing::trace!(\n \"Target has multiple containers and no container name was specified.\\\n Now filtering out mesh containers etc.\"\n );\n }\n\n let (chosen_container, guessed_container) =\n choose_container(container_name, container_statuses.as_ref());\n\n if guessed_container {\n tracing::warn!(\"mirrord picked first eligible container out of many\");\n }\n\n let chosen_status = chosen_container.ok_or_else(|| match container_name {\n Some(name) => KubeApiError::invalid_state(\n pod,\n format_args!(\"target container `{name}` not found\"),\n ),\n None => KubeApiError::invalid_state(pod, \"no viable target container found\"),\n })?;\n\n if !chosen_status.ready {\n return Err(KubeApiError::invalid_state(\n pod,\n format_args!(\"target container `{}` is not ready\", chosen_status.name),\n ));\n }\n\n let container_name = chosen_status.name.clone();\n let container_id_full = chosen_status.container_id.as_ref().ok_or_else(|| {\n KubeApiError::missing_field(pod, \".status.containerStatuses.[].containerID\")\n })?;\n\n let mut split = container_id_full.split(\"://\");\n\n let (container_runtime, container_id) = match (\n split.next().map(ContainerRuntime::from_str),\n split.next(),\n ) {\n (Some(Ok(runtime)), Some(id)) => (runtime, id.to_string()),\n _ => {\n return Err(KubeApiError::invalid_value(\n pod,\n \".status.containerStatuses.[].containerID\",\n format_args!(\"failed to extract container runtime for `{container_name}`: `{container_id_full}`\"),\n ));\n }\n };\n\n let mesh = check_mesh_vendor(pod);\n\n Ok(RuntimeData {\n pod_ips,\n pod_name,\n pod_namespace,\n node_name,\n container_id,\n container_runtime,\n container_name,\n guessed_container,\n mesh,\n share_process_namespace: pod\n .spec\n .as_ref()\n .and_then(|spec| spec.share_process_namespace)\n .unwrap_or_default(),\n containers_probe_ports,\n })\n }\n```"}], "func_name": "from_pod", "docstring": "Extracts data needed to create the mirrord-agent targeting the given [`Pod`].\nVerifies that the [`Pod`] is ready to be a target:\n1. pod is in \"Running\" phase,\n2. pod is not in deletion,\n3. target container is ready.", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/runtime.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/runtime.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5adee6c17c11f4e82b885e913207ccd1ee6a9395ef5bf22a48e026670bf2d0df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: probe_ports\n\nDocumentation:\nReturns a list of ports used by the container's readiness and liveness probes.\n\n* Startup probes are ignored: target needs to be ready to start a new session anyway\n* TCP probes are ignored: the agent will accept the connection anyway\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn probe_ports(container: &Container) -> Vec {\n fn port_to_int(port: &IntOrString, container_ports: &[ContainerPort]) -> Option {\n match port {\n IntOrString::Int(p) => Some(*p as u16),\n IntOrString::String(port_name) => container_ports\n .iter()\n .find(|p| p.name.as_ref() == Some(port_name))\n .and_then(|p| p.container_port.try_into().ok()),\n }\n }\n\n fn get_probe_ports(probe: &Probe, container_ports: &[ContainerPort]) -> Vec {\n let mut ports = Vec::new();\n\n if let Some(port) = probe\n .http_get\n .as_ref()\n .and_then(|get| port_to_int(&get.port, container_ports))\n {\n ports.push(port);\n }\n\n if let Some(port) = probe\n .grpc\n .as_ref()\n .and_then(|grpc| grpc.port.try_into().ok())\n {\n ports.push(port);\n }\n\n ports\n }\n\n let mut ports = Vec::new();\n\n if let Some(liveness) = &container.liveness_probe {\n ports.extend(get_probe_ports(\n liveness,\n container.ports.as_deref().unwrap_or_default(),\n ));\n }\n\n if let Some(readiness) = &container.readiness_probe {\n ports.extend(get_probe_ports(\n readiness,\n container.ports.as_deref().unwrap_or_default(),\n ));\n }\n\n ports\n }\n```"}], "func_name": "probe_ports", "docstring": "Returns a list of ports used by the container's readiness and liveness probes.\n\n* Startup probes are ignored: target needs to be ready to start a new session anyway\n* TCP probes are ignored: the agent will accept the connection anyway", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/runtime.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/runtime.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "491acdbced1aa422a999e4d660fd5202159518c3e33eb223a9c5e80e6af8f850"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_pods\n\nDocumentation:\nReturns a list of pods matching the selector of the given `resource`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_pods(\n resource: &Self::Resource,\n client: &Client,\n ) -> impl Future>> {\n async {\n let api: Api<::Resource> =\n get_k8s_resource_api(client, resource.meta().namespace.as_deref());\n let name = resource\n .meta()\n .name\n .as_deref()\n .ok_or_else(|| KubeApiError::missing_field(resource, \".metadata.name\"))?;\n let resource = api.get(name).await?;\n\n let labels = Self::get_selector_match_labels(&resource)?;\n\n let formatted_labels = labels\n .iter()\n .map(|(key, value)| format!(\"{key}={value}\"))\n .collect::>()\n .join(\",\");\n let list_params = ListParams {\n label_selector: Some(formatted_labels),\n ..Default::default()\n };\n\n let pod_api: Api =\n get_k8s_resource_api(client, resource.meta().namespace.as_deref());\n let pods = pod_api.list(&list_params).await?;\n\n Ok(pods.items)\n }\n }\n```"}], "func_name": "get_pods", "docstring": "Returns a list of pods matching the selector of the given `resource`.", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/runtime.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/runtime.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8587c555dd8db4cfcf40863a69560402333e7f156e3bb7fbf74773916cf85002"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_capabilities\n\nDocumentation:\nRetrieve a list of Linux capabilities for the agent container.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn get_capabilities(agent: &AgentConfig) -> Vec {\n let disabled = agent.disabled_capabilities.clone().unwrap_or_default();\n\n LinuxCapability::all()\n .iter()\n .copied()\n .filter(|c| !disabled.contains(c))\n .collect()\n}\n```"}], "func_name": "get_capabilities", "docstring": "Retrieve a list of Linux capabilities for the agent container.", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/container/util.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/container/util.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0f4261f87ffd2be4dc5883d9b6b49dacc65e3a094d4353ead139b1de179caeff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: poll_shutdown\n\nDocumentation:\nDoes nothing, call `manual_shutdown` for actuall inner shutdown call\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn poll_shutdown(\n self: Pin<&mut Self>,\n _: &mut Context<'_>,\n ) -> Poll> {\n Poll::Ready(Ok(()))\n }\n```"}], "func_name": "poll_shutdown", "docstring": "Does nothing, call `manual_shutdown` for actuall inner shutdown call", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes/portforwarder.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes/portforwarder.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "466bd5d5bc831c35b21ca555ba59ce24bbd30e7a836ade2e68bb664b0cd8eb4b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_pod_template\n\nDocumentation:\nGet the pod template spec out of a rollout spec.\nMake requests to k8s if necessary when the template is not directly included in the\nrollout spec ([`RolloutSpec::template`]), but only referenced via a workload_ref\n([`RolloutSpec::workload_ref`]).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_pod_template<'a>(\n &'a self,\n client: &Client,\n ) -> Result, KubeApiError> {\n let spec = self\n .spec\n .as_ref()\n .ok_or_else(|| KubeApiError::missing_field(self, \".spec\"))?;\n\n match spec {\n RolloutSpec {\n template: Some(..),\n workload_ref: Some(..),\n ..\n } => Err(KubeApiError::invalid_state(\n self,\n \"both `.spec.template` and `.spec.workladRef` fields are filled\",\n )),\n\n RolloutSpec {\n template: None,\n workload_ref: None,\n ..\n } => Err(KubeApiError::invalid_state(\n self,\n \"both `.spec.template` and `.spec.workloadRef` fields are empty\",\n )),\n\n RolloutSpec {\n template: Some(template),\n ..\n } => Ok(Cow::Borrowed(template.as_ref())),\n\n RolloutSpec {\n workload_ref: Some(workload_ref),\n ..\n } => workload_ref\n .get_pod_template(client, self.metadata.namespace.as_deref())\n .await?\n .ok_or_else(|| {\n KubeApiError::invalid_state(\n self,\n format_args!(\n \"field `.spec.workloadRef` refers to an unknown resource `{}/{}`\",\n workload_ref.api_version, workload_ref.kind\n ),\n )\n })\n .map(Cow::Owned),\n }\n }\n```"}], "func_name": "get_pod_template", "docstring": "Get the pod template spec out of a rollout spec.\nMake requests to k8s if necessary when the template is not directly included in the\nrollout spec ([`RolloutSpec::template`]), but only referenced via a workload_ref\n([`RolloutSpec::workload_ref`]).", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes/rollout.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes/rollout.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bee2e8c481ec095a39b92cb2d773bb5f0b3d8b22a951e7231db4afeb2e19ac17"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_match_labels\n\nDocumentation:\nExtracts [`LabelSelector`] from the [`Rollout`] or from the inner [`WorkloadRef`]\n\nUnlike `RuntimeDataFromLabels` trait the selector may also exist inside of the workloadRef\ntarget thus we need an async variant to fetch with a client.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_match_labels<'a>(\n &'a self,\n client: &Client,\n ) -> Result, KubeApiError> {\n let spec = self\n .spec\n .as_ref()\n .ok_or_else(|| KubeApiError::missing_field(self, \".spec\"))?;\n\n match spec {\n RolloutSpec {\n selector: None,\n workload_ref: None,\n ..\n } => Err(KubeApiError::invalid_state(\n self,\n \"both `.spec.selector` and `.spec.workloadRef` fields are empty\",\n )),\n\n // Selector from the rollout spec overwrites the selector from the referenced workload\n // (if any).\n RolloutSpec {\n selector: Some(selector),\n ..\n } => Ok(Cow::Borrowed(selector)),\n\n RolloutSpec {\n workload_ref: Some(workload_ref),\n ..\n } => workload_ref\n .get_match_labels(client, self.metadata.namespace.as_deref())\n .await?\n .ok_or_else(|| {\n KubeApiError::invalid_state(\n self,\n format_args!(\n \"field `.spec.workloadRef` refers to an unknown resource `{}/{}`\",\n workload_ref.api_version, workload_ref.kind\n ),\n )\n })\n .map(Cow::Owned),\n }\n }\n```"}], "func_name": "get_match_labels", "docstring": "Extracts [`LabelSelector`] from the [`Rollout`] or from the inner [`WorkloadRef`]\n\nUnlike `RuntimeDataFromLabels` trait the selector may also exist inside of the workloadRef\ntarget thus we need an async variant to fetch with a client.", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes/rollout.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes/rollout.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5666da54ff2151addc3122234bd2d1ab6c68351569d815866a3e8c01e9259d17"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: all_open_source\n\nDocumentation:\nReturns all resource types that don't require the operator to operate ie. [`Pod`],\n[`Deployment`] and [`Rollout`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn all_open_source(&self) -> Result> {\n let (pods, deployments, rollouts) = tokio::try_join!(\n self.pods(),\n self.deployments(),\n self.simple_list_resource::(\"rollout\")\n )?;\n\n Ok(pods\n .into_iter()\n .chain(deployments)\n .chain(rollouts)\n .collect())\n }\n```"}], "func_name": "all_open_source", "docstring": "Returns all resource types that don't require the operator to operate ie. [`Pod`],\n[`Deployment`] and [`Rollout`]", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes/seeker.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes/seeker.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "899b3168b529d622fdd6db67db773771b557f0892838816d0408cccf3bc520a3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: all\n\nDocumentation:\nReturns all resource of all types:\n1. [`Deployment`]s,\n2. [`Rollout`]s,\n3. [`StatefulSet`]s\n4. [`CronJob`]s\n5. [`Job`]s\n6. [`Service`]s\n7. [`ReplicaSet`]s\n8. [`Pod`]s\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn all(&self) -> Result> {\n let (pods, deployments, rollouts, jobs, cronjobs, statefulsets, services, replicasets) = tokio::try_join!(\n self.pods(),\n self.simple_list_resource::(\"deployment\"),\n self.simple_list_resource::(\"rollout\"),\n self.simple_list_resource::(\"job\"),\n self.simple_list_resource::(\"cronjob\"),\n self.simple_list_resource::(\"statefulset\"),\n self.simple_list_resource::(\"service\"),\n self.simple_list_resource::(\"replicaset\"),\n )?;\n\n Ok(deployments\n .into_iter()\n .chain(rollouts)\n .chain(statefulsets)\n .chain(cronjobs)\n .chain(jobs)\n .chain(services)\n .chain(replicasets)\n .chain(pods)\n .collect())\n }\n```"}], "func_name": "all", "docstring": "Returns all resource of all types:\n1. [`Deployment`]s,\n2. [`Rollout`]s,\n3. [`StatefulSet`]s\n4. [`CronJob`]s\n5. [`Job`]s\n6. [`Service`]s\n7. [`ReplicaSet`]s\n8. [`Pod`]s", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes/seeker.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes/seeker.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "536fb16ee3e0042901976e2857c282a833a7cc620a3bb797177f5624ea181939"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: filtered\n\nDocumentation:\nReturns the targets of the specified resource type(s), as long as the operator is active or\nno given types require the operator.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn filtered(\n &self,\n resource_types: Vec,\n operator_active: bool,\n ) -> Result> {\n Ok(futures::future::try_join_all(\n resource_types\n .into_iter()\n .map(|resource_type| self.filtered_single(resource_type, operator_active)),\n )\n .await?\n .concat())\n }\n```"}], "func_name": "filtered", "docstring": "Returns the targets of the specified resource type(s), as long as the operator is active or\nno given types require the operator.", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes/seeker.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes/seeker.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a25ef7bfe336a2a63dde3527f6e425fa09e7ee0f79de4be921e46cb862ea43cd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: filtered_single\n\nDocumentation:\nReturns the targets of a single specified resource type, as long as either:\n1. The resource type doesn't require the operator\n2. The operator is being used\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn filtered_single(\n &self,\n resource_type: TargetType,\n operator_active: bool,\n ) -> Result> {\n match resource_type {\n TargetType::Deployment if operator_active => {\n self.simple_list_resource::(\"deployment\").await\n }\n TargetType::Deployment => self.deployments().await,\n TargetType::Pod => self.pods().await,\n TargetType::Rollout => self.simple_list_resource::(\"rollout\").await,\n TargetType::Job if operator_active => self.simple_list_resource::(\"job\").await,\n TargetType::CronJob if operator_active => {\n self.simple_list_resource::(\"cronjob\").await\n }\n TargetType::StatefulSet if operator_active => {\n self.simple_list_resource::(\"statefulset\")\n .await\n }\n TargetType::Service if operator_active => {\n self.simple_list_resource::(\"service\").await\n }\n TargetType::ReplicaSet if operator_active => {\n self.simple_list_resource::(\"replicaset\").await\n }\n TargetType::Targetless => Err(KubeApiError::InvalidTargetType(resource_type)),\n resource_type if !operator_active => {\n Err(KubeApiError::TargetTypeRequiresOperator(resource_type))\n }\n resource_type => Err(KubeApiError::InvalidTargetTypeBug(resource_type)),\n }\n }\n```"}], "func_name": "filtered_single", "docstring": "Returns the targets of a single specified resource type, as long as either:\n1. The resource type doesn't require the operator\n2. The operator is being used", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes/seeker.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes/seeker.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c24789098eb1647f9e7ee361492aef0bc046c207478af72ea666f2f5bb90c24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pods\n\nDocumentation:\nReturns a list of (pod name, [container names]) pairs, filtering out mesh side cars\nas well as any pods which are not ready or have crashed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn pods(&self) -> Result> {\n fn check_pod_status(pod: &Pod) -> bool {\n pod.status\n .as_ref()\n .and_then(|status| status.conditions.as_ref())\n .map(|conditions| {\n // filter out pods without the Ready condition\n conditions\n .iter()\n .any(|condition| condition.type_ == \"Ready\" && condition.status == \"True\")\n })\n .unwrap_or(false)\n }\n\n fn create_pod_container_map(pod: Pod) -> Option<(String, Vec)> {\n let name = pod.metadata.name.clone()?;\n let containers = pod\n .spec\n .as_ref()?\n .containers\n .iter()\n .filter(|&container| (!SKIP_NAMES.contains(container.name.as_str())))\n .map(|container| container.name.clone())\n .collect();\n\n Some((name, containers))\n }\n\n self.list_all_namespaced(Some(\"status.phase=Running\"))\n .try_filter(|pod| std::future::ready(check_pod_status(pod)))\n .try_filter_map(|pod| std::future::ready(Ok(create_pod_container_map(pod))))\n .map_ok(|(pod, containers)| {\n stream::iter(if containers.len() == 1 {\n vec![Ok(format!(\"pod/{pod}\"))]\n } else {\n containers\n .iter()\n .map(move |container| Ok(format!(\"pod/{pod}/container/{container}\")))\n .collect()\n })\n })\n .try_flatten()\n .try_collect()\n .await\n .map_err(KubeApiError::KubeError)\n }\n```"}], "func_name": "pods", "docstring": "Returns a list of (pod name, [container names]) pairs, filtering out mesh side cars\nas well as any pods which are not ready or have crashed.", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes/seeker.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes/seeker.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "40cb060fae0fe2f8e5099889414081684879512f32a31ad91dd855f8de17a288"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: deployments\n\nDocumentation:\nThe list of deployments that have at least 1 `Replicas` and a deployment name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn deployments(&self) -> Result> {\n fn check_deployment_replicas(deployment: &Deployment) -> bool {\n deployment\n .status\n .as_ref()\n .map(|status| status.available_replicas >= Some(1))\n .unwrap_or(false)\n }\n\n self.list_all_namespaced::(None)\n .filter(|response| std::future::ready(response.is_ok()))\n .try_filter(|deployment| std::future::ready(check_deployment_replicas(deployment)))\n .try_filter_map(|deployment| {\n std::future::ready(Ok(deployment\n .metadata\n .name\n .map(|name| format!(\"deployment/{name}\"))))\n })\n .try_collect()\n .await\n .map_err(From::from)\n }\n```"}], "func_name": "deployments", "docstring": "The list of deployments that have at least 1 `Replicas` and a deployment name.", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes/seeker.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes/seeker.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "644ae07dd1286a6f19e99d0f96a88ce022eddf578766a748d06a5c81f3282a4e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_all_namespaced\n\nDocumentation:\nReturns a [`Stream`] of all objects in this [`KubeResourceSeeker`]'s namespace.\n\n1. `field_selector` can be used for filtering.\n2. Our own resources are excluded.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_all_namespaced(\n &self,\n field_selector: Option<&str>,\n ) -> impl 'static + Stream> + Send\n where\n R: 'static\n + Resource\n + fmt::Debug\n + Clone\n + DeserializeOwned\n + Send,\n {\n let namespace = self.namespace.to_string();\n let api = Api::namespaced(self.client.clone(), &namespace);\n let mut params = Self::make_list_params(field_selector);\n\n async_stream::stream! {\n loop {\n let start = Instant::now();\n let response = api.list(¶ms).await?;\n let elapsed = start.elapsed();\n\n tracing::debug!(\n resource_kind = %R::kind(&()),\n elapsed_s = elapsed.as_secs_f32(),\n fetched_resources = response.items.len(),\n continue_token = ?response.metadata.continue_,\n list_params = ?params,\n namespace,\n \"Made a resource list request\",\n );\n\n for resource in response.items {\n yield Ok(resource);\n }\n\n let continue_token = response.metadata.continue_.unwrap_or_default();\n if continue_token.is_empty() {\n break;\n }\n params.continue_token.replace(continue_token);\n }\n }\n }\n```"}], "func_name": "list_all_namespaced", "docstring": "Returns a [`Stream`] of all objects in this [`KubeResourceSeeker`]'s namespace.\n\n1. `field_selector` can be used for filtering.\n2. Our own resources are excluded.", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes/seeker.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes/seeker.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9707830d8be5cb3aabfde56cf207f26042cf5e466aecba560bee539e711250a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_all_clusterwide\n\nDocumentation:\nReturns a [`Stream`] of all objects in the cluster.\n\n1. `field_selector` can be used for filtering.\n2. Our own resources are excluded.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_all_clusterwide(\n &self,\n field_selector: Option<&str>,\n ) -> impl 'static + Stream> + Send\n where\n R: 'static\n + Resource\n + fmt::Debug\n + Clone\n + DeserializeOwned\n + Send,\n {\n let api = Api::all(self.client.clone());\n let mut params = Self::make_list_params(field_selector);\n\n async_stream::stream! {\n loop {\n let start = Instant::now();\n let response = api.list(¶ms).await?;\n let elapsed = start.elapsed();\n\n tracing::debug!(\n resource_kind = %R::kind(&()),\n elapsed_s = elapsed.as_secs_f32(),\n fetched_resources = response.items.len(),\n continue_token = ?response.metadata.continue_,\n list_params = ?params,\n \"Made a resource list request\",\n );\n\n for resource in response.items {\n yield Ok(resource);\n }\n\n let continue_token = response.metadata.continue_.unwrap_or_default();\n if continue_token.is_empty() {\n break;\n }\n params.continue_token.replace(continue_token);\n }\n }\n }\n```"}], "func_name": "list_all_clusterwide", "docstring": "Returns a [`Stream`] of all objects in the cluster.\n\n1. `field_selector` can be used for filtering.\n2. Our own resources are excluded.", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes/seeker.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes/seeker.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "77caddbf180a14ce8960f405e9575a5a24b774437ffd9778fc33ce5c9d795d2c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_pod_template\n\nDocumentation:\nFetched the referenced resource and extracts [`PodTemplateSpec`].\nSupports references to:\n1. [`Deployment`]s\n2. [`ReplicaSet`]s\n3. [`PodTemplate`]s (uses `.metadata.labels`)\n4. [`StatefulSet`]s\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_pod_template(\n &self,\n client: &Client,\n namespace: Option<&str>,\n ) -> Result, KubeApiError> {\n match (self.api_version.as_str(), self.kind.as_str()) {\n (Deployment::API_VERSION, Deployment::KIND) => {\n let mut deployment = get_k8s_resource_api::(client, namespace)\n .get(&self.name)\n .await?;\n\n deployment\n .spec\n .take()\n .ok_or_else(|| KubeApiError::missing_field(&deployment, \".spec\"))\n .map(|spec| Some(spec.template))\n }\n (ReplicaSet::API_VERSION, ReplicaSet::KIND) => {\n let mut replica_set = get_k8s_resource_api::(client, namespace)\n .get(&self.name)\n .await?;\n\n replica_set\n .spec\n .take()\n .ok_or_else(|| KubeApiError::missing_field(&replica_set, \".spec\"))?\n .template\n .ok_or_else(|| KubeApiError::missing_field(&replica_set, \".spec.template\"))\n .map(Some)\n }\n (PodTemplate::API_VERSION, PodTemplate::KIND) => {\n let mut pod_template = get_k8s_resource_api::(client, namespace)\n .get(&self.name)\n .await?;\n\n pod_template\n .template\n .take()\n .ok_or_else(|| KubeApiError::missing_field(&pod_template, \".template\"))\n .map(Some)\n }\n (StatefulSet::API_VERSION, StatefulSet::KIND) => {\n let mut stateful_set = get_k8s_resource_api::(client, namespace)\n .get(&self.name)\n .await?;\n\n stateful_set\n .spec\n .take()\n .ok_or_else(|| KubeApiError::missing_field(&stateful_set, \".spec\"))\n .map(|spec| Some(spec.template))\n }\n _ => Ok(None),\n }\n }\n```"}], "func_name": "get_pod_template", "docstring": "Fetched the referenced resource and extracts [`PodTemplateSpec`].\nSupports references to:\n1. [`Deployment`]s\n2. [`ReplicaSet`]s\n3. [`PodTemplate`]s (uses `.metadata.labels`)\n4. [`StatefulSet`]s", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes/rollout/workload_ref.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes/rollout/workload_ref.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4072d9d82b519f34d3b864db80d725eb5d8244fd18cc68e356545d6264256324"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_match_labels\n\nDocumentation:\nFetched the referenced resource and extracts [`LabelSelector`].\nSupports references to:\n1. [`Deployment`]s\n2. [`ReplicaSet`]s\n3. [`PodTemplate`]s\n4. [`StatefulSet`]s\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_match_labels(\n &self,\n client: &Client,\n namespace: Option<&str>,\n ) -> Result, KubeApiError> {\n match (self.api_version.as_str(), self.kind.as_str()) {\n (Deployment::API_VERSION, Deployment::KIND) => {\n let mut deployment = get_k8s_resource_api::(client, namespace)\n .get(&self.name)\n .await?;\n\n deployment\n .spec\n .take()\n .ok_or_else(|| KubeApiError::missing_field(&deployment, \".spec\"))\n .map(|spec| Some(spec.selector))\n }\n (ReplicaSet::API_VERSION, ReplicaSet::KIND) => {\n let mut replica_set = get_k8s_resource_api::(client, namespace)\n .get(&self.name)\n .await?;\n\n replica_set\n .spec\n .take()\n .ok_or_else(|| KubeApiError::missing_field(&replica_set, \".spec\"))\n .map(|spec| Some(spec.selector))\n }\n (PodTemplate::API_VERSION, PodTemplate::KIND) => {\n let mut pod_template = get_k8s_resource_api::(client, namespace)\n .get(&self.name)\n .await?;\n\n pod_template\n .metadata\n .labels\n .take()\n .ok_or_else(|| KubeApiError::missing_field(&pod_template, \".metadata.labels\"))\n .map(|match_labels| {\n Some(LabelSelector {\n match_labels: Some(match_labels),\n ..Default::default()\n })\n })\n }\n (StatefulSet::API_VERSION, StatefulSet::KIND) => {\n let mut stateful_set = get_k8s_resource_api::(client, namespace)\n .get(&self.name)\n .await?;\n\n stateful_set\n .spec\n .take()\n .ok_or_else(|| KubeApiError::missing_field(&stateful_set, \".spec\"))\n .map(|spec| Some(spec.selector))\n }\n _ => Ok(None),\n }\n }\n```"}], "func_name": "get_match_labels", "docstring": "Fetched the referenced resource and extracts [`LabelSelector`].\nSupports references to:\n1. [`Deployment`]s\n2. [`ReplicaSet`]s\n3. [`PodTemplate`]s\n4. [`StatefulSet`]s", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/kubernetes/rollout/workload_ref.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/kubernetes/rollout/workload_ref.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f6d5ae06dd7a0601b24b8e1a04b40b353e97621ee548ccfca67424a8b7c60519"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_selector_match_labels\n\nDocumentation:\nDigs into `resource` to return its `.spec.selector.matchLabels`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_selector_match_labels(resource: &Self::Resource) -> Result> {\n resource\n .spec\n .clone()\n .ok_or_else(|| KubeApiError::missing_field(resource, \".spec\"))?\n .selector\n .ok_or_else(|| KubeApiError::missing_field(resource, \".spec.selector\"))?\n .match_labels\n .ok_or_else(|| KubeApiError::missing_field(resource, \".spec.selector.matchLabels\"))\n }\n```"}], "func_name": "get_selector_match_labels", "docstring": "Digs into `resource` to return its `.spec.selector.matchLabels`.", "repo": "metalbear-co/mirrord", "path": "mirrord/kube/src/api/runtime/rollout.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/kube/src/api/runtime/rollout.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "06c4cb370b3cb89366df0722428ce8ae67855a4968670fb078d093b377ed0611"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_proxy_request_with_response\n\nDocumentation:\nMakes a request to the internal proxy using global [`PROXY_CONNECTION`].\nBlocks until the proxy responds.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn make_proxy_request_with_response(request: T) -> HookResult\nwhere\n T: IsLayerRequestWithResponse + Debug,\n T::Response: Debug,\n{\n // SAFETY: mutation happens only on initialization.\n #[allow(static_mut_refs)]\n unsafe {\n PROXY_CONNECTION\n .get()\n .ok_or(HookError::CannotGetProxyConnection)?\n .make_request_with_response(request)\n .map_err(Into::into)\n }\n}\n```"}], "func_name": "make_proxy_request_with_response", "docstring": "Makes a request to the internal proxy using global [`PROXY_CONNECTION`].\nBlocks until the proxy responds.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/common.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/common.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc7fa54aa45bf0e4a129700cc1114f0cd407217323375f0e8778369087db9913"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_proxy_request_no_response\n\nDocumentation:\nMakes a request to the internal proxy using global [`PROXY_CONNECTION`].\nBlocks until the request is sent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn make_proxy_request_no_response(\n request: T,\n) -> HookResult {\n // SAFETY: mutation happens only on initialization.\n #[allow(static_mut_refs)]\n unsafe {\n PROXY_CONNECTION\n .get()\n .ok_or(HookError::CannotGetProxyConnection)?\n .make_request_no_response(request)\n .map_err(Into::into)\n }\n}\n```"}], "func_name": "make_proxy_request_no_response", "docstring": "Makes a request to the internal proxy using global [`PROXY_CONNECTION`].\nBlocks until the request is sent.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/common.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/common.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "50b9638457271373cdeba9eb00ed01574d3c84994ce1bfa82e45dcb96a29dd89"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: checked_into\n\nDocumentation:\nDo the checked conversion to str, bypass if the str starts with temp dir's path, construct\na `PathBuf` out of the str.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn checked_into(self) -> Detour {\n let str_det = CheckedInto::<&str>::checked_into(self);\n #[cfg(target_os = \"macos\")]\n let str_det = str_det.and_then(|path_str| {\n let optional_stripped_path = strip_mirrord_path(path_str);\n if let Some(stripped_path) = optional_stripped_path {\n // actually stripped, so bypass and provide a pointer to after the temp dir.\n // `stripped_path` is a reference to a later character in the same string as\n // `path_str`, `stripped_path.as_ptr()` returns a pointer to a later index\n // in the same string owned by the caller (the hooked program).\n Detour::Bypass(Bypass::FileOperationInMirrordBinTempDir(\n stripped_path.as_ptr() as _,\n ))\n } else {\n Detour::Success(path_str) // strip is None, path not in temp dir.\n }\n });\n str_det.map(From::from)\n }\n```"}], "func_name": "checked_into", "docstring": "Do the checked conversion to str, bypass if the str starts with temp dir's path, construct\na `PathBuf` out of the str.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/common.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/common.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc562c27e6e5d033d1b7b9a4db3061118a07cd2e19d63cbb3e46fc4ecc1ee725"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_ports\n\nDocumentation:\nRetrieves the port used by debugger of this type from the command.\nMay return multiple ports when using the inspect flags with node.\nAlso returns the value to set into MIRRORD_DETECT_DEBUGGER_PORT_ENV, if any\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_ports Option>(\n self,\n args: &[String],\n mut get_env: F,\n ) -> (Vec, Option) {\n let ports = match self {\n Self::DebugPy => {\n let is_python = args\n .first()\n .map(String::as_str)\n .unwrap_or_default()\n .rsplit('/')\n .next()\n .unwrap_or_default()\n .starts_with(\"py\");\n let runs_debugpy = if args.get(1).map(String::as_str).unwrap_or_default().starts_with(\"-X\") {\n args.get(3).map(String::as_str).unwrap_or_default().ends_with(\"debugpy\") // newer args layout\n } else {\n args.get(1).map(String::as_str).unwrap_or_default().ends_with(\"debugpy\") // older args layout\n };\n\n if is_python && runs_debugpy {\n args.windows(2).find_map(|window| match window {\n [opt, val] if opt == \"--connect\" => val.parse::().ok(),\n _ => None,\n })\n } else {\n None\n }\n .into_iter()\n .collect::>()\n }\n Self::PyDevD => {\n let is_python = args\n .first()\n .map(String::as_str)\n .unwrap_or_default()\n .rsplit('/')\n .next()\n .unwrap_or_default()\n .starts_with(\"py\");\n let runs_pydevd = args\n .get(1)\n .map(String::as_str)\n .unwrap_or_default()\n .rsplit('/')\n .next()\n .unwrap_or_default()\n .contains(\"pydevd\");\n\n if is_python && runs_pydevd {\n let client = args.windows(2).find_map(|window| match window {\n [opt, val] if opt == \"--client\" => val.parse::().ok(),\n _ => None,\n });\n let port = args.windows(2).find_map(|window| match window {\n [opt, val] if opt == \"--port\" => val.parse::().ok(),\n _ => None,\n });\n\n if let (Some(client), Some(port)) = (client, port) {\n SocketAddr::new(client, port).into()\n } else {\n None\n }\n } else {\n None\n }\n .into_iter()\n .collect::>()\n }\n Self::ReSharper => {\n let is_dotnet = args.first().map(String::as_str).unwrap_or_default().ends_with(\"dotnet\");\n let runs_debugger = args.get(2).map(String::as_str).unwrap_or_default().contains(\"Debugger\");\n\n if is_dotnet && runs_debugger {\n args.iter()\n .find_map(|arg| arg.strip_prefix(\"--frontend-port=\"))\n .and_then(|port| port.parse::().ok())\n .map(|port| SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port))\n } else {\n None\n }\n .into_iter()\n .collect::>()\n }\n Self::JavaAgent => {\n let is_java = args.first().map(String::as_str).unwrap_or_default().ends_with(\"java\");\n\n if is_java {\n args.iter()\n .find_map(|arg| arg.strip_prefix(\"-agentlib:jdwp=transport=dt_socket\"))\n .and_then(|agent_lib_args| {\n agent_lib_args\n .split(',')\n .find_map(|arg| arg.strip_prefix(\"address=\"))\n })\n .and_then(|full_address| full_address.split(':').next_back())\n .and_then(|port| port.parse::().ok())\n .map(|port| SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port))\n } else {\n None\n }\n .into_iter()\n .collect::>()\n }\n Self::NodeInspector => {\n if let Some(value) = get_env(\"NODE_OPTIONS\") {\n // matching specific flags so we avoid matching on, for example,\n // `--inspect-publish-uid=http`\n value.split_ascii_whitespace()\n .filter_map(|flag| match flag.split_once('=') {\n Some((\"--inspect\" | \"--inspect-brk\" | \"--inspect-wait\", port)) => port.parse::().ok(),\n None if [\"--inspect\", \"--inspect-brk\", \"--inspect-wait\"].contains(&flag) => Some(NODE_INSPECTOR_DEFAULT_PORT),\n _ => None,\n })\n .map(|port| SocketAddr::new(Ipv4Addr::LOCALHOST.into(), port))\n .collect::>()\n } else if let Some(value) = get_env(\"NODE_INSPECTOR_INFO\") {\n value.split(',').filter_map(|var| match var.split_once(':')? {\n (\"inspectorURL\", url) => url.parse::().ok()?.port_u16(),\n _ => None,\n })\n .map(|port| SocketAddr::new(Ipv4Addr::LOCALHOST.into(), port))\n .collect::>()\n } else {\n vec![]\n }\n }\n }.iter().filter_map(|addr| match addr.ip() {\n IpAddr::V4(Ipv4Addr::LOCALHOST) | IpAddr::V6(Ipv6Addr::LOCALHOST) => Some(addr.port()),\n other => {\n tracing::debug!(\n \"Debugger uses a remote socket address {other}! This case is not yet handled properly.\",\n );\n None\n }\n })\n .collect::>();\n\n let next_type = match self {\n // node may require several rounds of port ignoring when used in the VSCode plugin\n DebuggerType::NodeInspector => Some(DebuggerType::NodeInspector),\n _ => None,\n };\n (ports, next_type)\n }\n```"}], "func_name": "get_ports", "docstring": "Retrieves the port used by debugger of this type from the command.\nMay return multiple ports when using the inspect flags with node.\nAlso returns the value to set into MIRRORD_DETECT_DEBUGGER_PORT_ENV, if any", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/debugger_ports.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/debugger_ports.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "19658a40b765828933868aa239f05ebd9951f9f8fc23342a6c6eabb66a2e5452"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_str\n\nDocumentation:\nParses [`DebuggerPorts`] from a string.\nThe string should look like one of:\n1. ``\n2. `-`\n3. Comma-separated sequence of previous two variants\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_str(s: &str) -> Result {\n let vec = s\n .split(',')\n .filter_map(|entry| {\n let chunks = entry\n .split('-')\n .map(u16::from_str)\n .collect::, _>>()\n .ok();\n\n match chunks.as_deref() {\n Some(&[p]) => Some(Self::Single(p)),\n Some(&[p1, p2]) if p1 <= p2 => Some(Self::FixedRange(p1..=p2)),\n _ => {\n tracing::debug!(\n full_variable = s,\n entry,\n \"Failed to decode debugger ports entry from {} env variable\",\n MIRRORD_IGNORE_DEBUGGER_PORTS_ENV,\n );\n None\n }\n }\n })\n .collect::>();\n\n let result = match vec.len() {\n 0 => Self::None,\n 1 => vec.into_iter().next().unwrap(),\n _ => Self::Combination(vec),\n };\n\n Ok(result)\n }\n```"}], "func_name": "from_str", "docstring": "Parses [`DebuggerPorts`] from a string.\nThe string should look like one of:\n1. ``\n2. `-`\n3. Comma-separated sequence of previous two variants", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/debugger_ports.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/debugger_ports.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7af823a83a79b687907c3166bd88da28ee6f3930f7350faa95a665021467ae59"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fmt\n\nDocumentation:\nWrites [`DebuggerPorts`] into the given [`fmt::Formatter`],\nusing format recognized by [`FromStr`] implementation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match self {\n Self::Single(port) => port.fmt(f),\n Self::FixedRange(range) => write!(f, \"{}-{}\", range.start(), range.end()),\n Self::Combination(vec) => {\n let value = vec\n .iter()\n .map(ToString::to_string)\n .collect::>()\n .join(\",\");\n f.write_str(&value)\n }\n Self::None => Ok(()),\n }\n }\n```"}], "func_name": "fmt", "docstring": "Writes [`DebuggerPorts`] into the given [`fmt::Formatter`],\nusing format recognized by [`FromStr`] implementation.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/debugger_ports.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/debugger_ports.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dd07fd23ad43d452a057ee1becb9b8b4f66506ad6d2b94bcad77f7fa6bff712d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_env\n\nDocumentation:\nCreate a new instance of this enum based on the environment variables\n([`MIRRORD_DETECT_DEBUGGER_PORT_ENV`] and [`MIRRORD_IGNORE_DEBUGGER_PORTS_ENV`]) and command\nline arguments.\n\nLog errors (like malformed env variables) but do not panic.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_env() -> Self {\n let (detected, next) = match env::var(MIRRORD_DETECT_DEBUGGER_PORT_ENV)\n .ok()\n .and_then(|s| {\n DebuggerType::from_str(&s)\n .inspect_err(|error| {\n tracing::debug!(\n error,\n \"Failed to decode debugger type from {} env variable\",\n MIRRORD_DETECT_DEBUGGER_PORT_ENV,\n )\n })\n .ok()\n }) {\n Some(debugger) => debugger.get_ports(&std::env::args().collect::>(), |name| {\n std::env::var(name).ok()\n }),\n None => (vec![], None),\n };\n if !detected.is_empty() {\n let mut dbg_ports = detected\n .iter()\n .map(|&port| Some(Self::Single(port)))\n .collect::>();\n if let Ok(existing) = env::var(MIRRORD_IGNORE_DEBUGGER_PORTS_ENV) {\n dbg_ports.push(DebuggerPorts::from_str(&existing).ok());\n }\n let dbg_ports = dbg_ports.into_iter().flatten().collect::>();\n let dbg_port = Self::Combination(dbg_ports);\n env::set_var(MIRRORD_IGNORE_DEBUGGER_PORTS_ENV, dbg_port.to_string());\n\n if let Some(next_type) = next {\n env::set_var(MIRRORD_DETECT_DEBUGGER_PORT_ENV, next_type.to_string());\n } else {\n env::remove_var(MIRRORD_DETECT_DEBUGGER_PORT_ENV);\n }\n return dbg_port;\n }\n\n // IGNORE_DEBUGGER_PORTS may have a combination of single, multiple or ranges of ports\n // separated by a comma they need to be parsed individually\n env::var(MIRRORD_IGNORE_DEBUGGER_PORTS_ENV)\n .ok()\n .and_then(|s| Self::from_str(&s).ok())\n .unwrap_or(Self::None)\n }\n```"}], "func_name": "from_env", "docstring": "Create a new instance of this enum based on the environment variables\n([`MIRRORD_DETECT_DEBUGGER_PORT_ENV`] and [`MIRRORD_IGNORE_DEBUGGER_PORTS_ENV`]) and command\nline arguments.\n\nLog errors (like malformed env variables) but do not panic.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/debugger_ports.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/debugger_ports.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "53df036f748425d40cef90f78a1a9b0e45b74ac2e55b5446b026b113331de67d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: contains\n\nDocumentation:\nReturn whether the given [SocketAddr] is used by the debugger.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn contains(&self, addr: &SocketAddr) -> bool {\n let is_localhost = matches!(\n addr.ip(),\n IpAddr::V4(Ipv4Addr::LOCALHOST) | IpAddr::V6(Ipv6Addr::LOCALHOST)\n );\n if !is_localhost {\n return false;\n }\n\n match self {\n Self::Single(port) => port == &addr.port(),\n Self::FixedRange(range) => range.contains(&addr.port()),\n Self::Combination(vec) => vec\n .iter()\n .map(|ports| ports.contains(addr))\n .fold(false, |acc, ports| ports || acc),\n Self::None => false,\n }\n }\n```"}], "func_name": "contains", "docstring": "Return whether the given [SocketAddr] is used by the debugger.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/debugger_ports.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/debugger_ports.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "61253cf78386a59f521a060644d73057e621610bbf556c73a4755acf616a40bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: detour_bypass_off\n\nDocumentation:\nSets [`DETOUR_BYPASS`] to `false`.\n\nPrefer relying on the [`Drop`] implementation of [`DetourGuard`] instead.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn detour_bypass_off() {\n DETOUR_BYPASS.with(|enabled| {\n if let Ok(mut bypass) = enabled.try_borrow_mut() {\n *bypass = false\n }\n });\n}\n```"}], "func_name": "detour_bypass_off", "docstring": "Sets [`DETOUR_BYPASS`] to `false`.\n\nPrefer relying on the [`Drop`] implementation of [`DetourGuard`] instead.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/detour.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/detour.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b8b2f41b2d887f7cbfdab152dbcd665a8b76c0913b8df92f8daf0b313ffa1e23"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new DetourGuard if it's not already enabled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn new() -> Option {\n DETOUR_BYPASS.with(|enabled| {\n if let Ok(bypass) = enabled.try_borrow()\n && *bypass\n {\n None\n } else if let Ok(mut bypass) = enabled.try_borrow_mut() {\n *bypass = true;\n Some(Self)\n } else {\n None\n }\n })\n }\n```"}], "func_name": "new", "docstring": "Create a new DetourGuard if it's not already enabled.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/detour.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/detour.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ce95657899af4f45a2384a848998f29a0ba5f83acf0ae9c90812274470017bed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: and_then\n\nDocumentation:\nCalls `op` if the result is `Success`, otherwise returns the `Bypass` or `Error` value of\nself.\n\nThis function can be used for control flow based on `Detour` values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn and_then Detour>(self, op: F) -> Detour {\n match self {\n Detour::Success(s) => op(s),\n Detour::Bypass(b) => Detour::Bypass(b),\n Detour::Error(e) => Detour::Error(e),\n }\n }\n```"}], "func_name": "and_then", "docstring": "Calls `op` if the result is `Success`, otherwise returns the `Bypass` or `Error` value of\nself.\n\nThis function can be used for control flow based on `Detour` values.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/detour.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/detour.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb0bf035d1b8755702cb0330614e1bfca0d1b12bb8d266004323903c2315dea2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: map\n\nDocumentation:\nMaps a `Detour` to `Detour` by applying a function to a contained `Success` value,\nleaving a `Bypass` or `Error` value untouched.\n\nThis function can be used to compose the results of two functions.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn map U>(self, op: F) -> Detour {\n match self {\n Detour::Success(s) => Detour::Success(op(s)),\n Detour::Bypass(b) => Detour::Bypass(b),\n Detour::Error(e) => Detour::Error(e),\n }\n }\n```"}], "func_name": "map", "docstring": "Maps a `Detour` to `Detour` by applying a function to a contained `Success` value,\nleaving a `Bypass` or `Error` value untouched.\n\nThis function can be used to compose the results of two functions.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/detour.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/detour.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fbe921b82ca85aac655a5aff440494b8b22facbab4793e03871d8e927c92d4ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unwrap_or_bypass_with\n\nDocumentation:\nHelper function for returning a detour return value from a hook.\n\n- `Success` -> Return the contained value.\n- `Bypass` -> Call the bypass and return its value.\n- `Error` -> Convert to libc value and return it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn unwrap_or_bypass_with S>(self, op: F) -> S {\n match self {\n Detour::Success(s) => s,\n Detour::Bypass(b) => op(b),\n Detour::Error(e) => e.into(),\n }\n }\n```"}], "func_name": "unwrap_or_bypass_with", "docstring": "Helper function for returning a detour return value from a hook.\n\n- `Success` -> Return the contained value.\n- `Bypass` -> Call the bypass and return its value.\n- `Error` -> Convert to libc value and return it.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/detour.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/detour.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6a1f0b2d42b7f4219e8322d22e39d309cab844320523f9025b64d01a2ade3bb3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unwrap_or_bypass\n\nDocumentation:\nHelper function for returning a detour return value from a hook.\n\n`Success` -> Return the contained value.\n`Bypass` -> Return provided value.\n`Error` -> Convert to libc value and return it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn unwrap_or_bypass(self, value: S) -> S {\n match self {\n Detour::Success(s) => s,\n Detour::Bypass(_) => value,\n Detour::Error(e) => e.into(),\n }\n }\n```"}], "func_name": "unwrap_or_bypass", "docstring": "Helper function for returning a detour return value from a hook.\n\n`Success` -> Return the contained value.\n`Bypass` -> Return provided value.\n`Error` -> Convert to libc value and return it.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/detour.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/detour.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8734d8ac8dfa3a399284b25140f147263e0048d4adbd285afb23ad2bff4ff824"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_ignored_code\n\nDocumentation:\nChecks if an error code from some [`libc`] function should be treated as a hard error, or\nnot.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn is_ignored_code(code: Option) -> bool {\n if let Some(code) = code {\n IGNORE_ERROR_CODES.contains(&code)\n } else {\n false\n }\n }\n```"}], "func_name": "is_ignored_code", "docstring": "Checks if an error code from some [`libc`] function should be treated as a hard error, or\nnot.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/error.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/error.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f841297fa1080a595c4edeabc687bb49248c39f9768e34c60aeaba2cb590f5ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: leak\n\nDocumentation:\nTurns this list of [`CString`] into a C list of pointers (null-terminated).\n\nWe leak the [`CString`]s, so that they may live in C-land.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn leak(self) -> *const *const c_char {\n // Leaks the strings.\n let mut list = self\n .0\n .into_iter()\n .map(|value| value.into_raw().cast_const())\n .collect::>();\n\n // Null-terminated.\n list.push(ptr::null());\n\n // Leaks the list itself.\n list.into_raw_parts().0.cast_const()\n }\n```"}], "func_name": "leak", "docstring": "Turns this list of [`CString`] into a C list of pointers (null-terminated).\n\nWe leak the [`CString`]s, so that they may live in C-land.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/exec_hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/exec_hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69d482d574080ed5ab3640a69f00e81a8f90f218d8bc850b58cfd837776e9a10"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: intercept_tmp_dir\n\nDocumentation:\nCheck if the arguments to the new executable contain paths to mirrord's temp dir.\nIf they do, create a new array with the original paths instead of the patched paths.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn intercept_tmp_dir(argv_arr: &Nul<*const c_char>) -> Detour {\n let mut c_string_vec = Argv::default();\n\n // Iterate through args, if an argument is a path inside our temp dir, save pointer to\n // after that prefix instead.\n // Example:\n // \"/path-to-mirrord-temp/file1\"\n // If argv[1] is a pointer to a string ptr: --^ ^\n // Then save a pointer to after the temp dir prefix instead: -----|\n for (i, arg) in argv_arr.iter().enumerate() {\n if i > MAX_ARGC {\n // the iterator will go until there is a null pointer, so stop after MAX_ARGC so\n // that we don't just keep going indefinitely if a bad argv was passed.\n return Bypass(TooManyArgs);\n }\n let arg_str: &str = arg.checked_into()?;\n trace!(\"exec arg: {arg_str}\");\n\n // SAFETY: We only slice after we find the string in the path\n // so it must be valid\n #[allow(clippy::indexing_slicing)]\n let stripped = arg_str\n .find(MIRRORD_PATCH_DIR)\n .map(|index| &arg_str[(MIRRORD_PATCH_DIR.len() + index)..])\n .inspect(|original_path| {\n trace!(\n \"Intercepted mirrord's temp dir in argv: {}. Replacing with original path: {}.\",\n arg_str,\n original_path\n );\n })\n .unwrap_or(arg_str) // No temp-dir prefix found, use arg as is.\n // As the string slice we get here is a slice of memory allocated and managed by\n // the user app, we copy the data and create new CStrings out of the copy\n // without consuming the original data.\n .to_owned();\n\n c_string_vec.push(CString::new(stripped)?)\n }\n Success(c_string_vec)\n}\n```"}], "func_name": "intercept_tmp_dir", "docstring": "Check if the arguments to the new executable contain paths to mirrord's temp dir.\nIf they do, create a new array with the original paths instead of the patched paths.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/exec_utils.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/exec_utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "06babd16f17ce95fb42e906541c8e29a9d8805d1ad34c4bd3c9ed95492631aed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: intercept_environment\n\nDocumentation:\nVerifies that mirrord environment is passed to child process\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn intercept_environment(envp_arr: &Nul<*const c_char>) -> Detour {\n let mut c_string_vec = Argv::default();\n\n let mut found_dyld = false;\n for arg in envp_arr.iter() {\n let Detour::Success(arg_str): Detour<&str> = arg.checked_into() else {\n tracing::debug!(\"Failed to convert envp argument to string. Skipping.\");\n c_string_vec.push(unsafe { CStr::from_ptr(*arg).to_owned() });\n continue;\n };\n\n if arg_str.split('=').next() == Some(\"DYLD_INSERT_LIBRARIES\") {\n found_dyld = true;\n }\n\n c_string_vec.push(CString::new(arg_str)?)\n }\n\n if !found_dyld {\n for (key, value) in crate::setup().env_backup() {\n c_string_vec.push(CString::new(format!(\"{key}={value}\"))?);\n }\n }\n Success(c_string_vec)\n}\n```"}], "func_name": "intercept_environment", "docstring": "Verifies that mirrord environment is passed to child process", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/exec_utils.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/exec_utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63c9920cb7b3ff3b9fbaab5b1627f1de9ffa57271d2f7888dfc6e79a4b3046ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_mode\n\nDocumentation:\nWARN: Using the wrong mode is undefined behavior, according to the C standard, we're not\ndeviating from it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_mode(mode: String) -> Self {\n mode.chars()\n .fold(OpenOptionsInternal::default(), |mut open_options, value| {\n match value {\n 'r' => open_options.read = true,\n 'w' => {\n open_options.write = true;\n open_options.create = true;\n open_options.truncate = true;\n }\n 'a' => {\n open_options.append = true;\n open_options.create = true;\n }\n '+' => {\n open_options.read = true;\n open_options.write = true;\n }\n 'x' => {\n open_options.create_new = true;\n }\n // Only has meaning for `fmemopen`.\n 'b' => {}\n invalid => {\n tracing::warn!(\"Invalid mode for fopen {:#?}\", invalid);\n }\n }\n\n open_options\n })\n }\n```"}], "func_name": "from_mode", "docstring": "WARN: Using the wrong mode is undefined behavior, according to the C standard, we're not\ndeviating from it.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "85ef97b7605b6a21f7cc9c1de6c830f3aae11aa34dbfecadbe0cbe1b0174d97a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_modules\n\nDocumentation:\nGets available modules in current process.\nNOTE: Gum must be initialized or it will crash.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_modules() -> Vec {\n Module::obtain(&GUM)\n .enumerate_modules()\n .iter()\n .map(|m| m.name.clone())\n .collect()\n}\n```"}], "func_name": "get_modules", "docstring": "Gets available modules in current process.\nNOTE: Gum must be initialized or it will crash.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3b525f704826969db1c0c554f86bdcdda9d09ecabc98a0963784bebb4f11dd7e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_export_by_name\n\nDocumentation:\nWrapper function that maps it to our error for convinence.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_export_by_name(module: Option<&str>, symbol: &str) -> Result {\n Module::obtain(&GUM)\n .find_export_by_name(module, symbol)\n .ok_or_else(|| LayerError::NoExportName(symbol.to_string()))\n}\n```"}], "func_name": "get_export_by_name", "docstring": "Wrapper function that maps it to our error for convinence.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2c408c0571d95c29185461784af309bdd3771ce1988e6ac8053d048c53eea809"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: hook_any_lib_export\n\nDocumentation:\nHook the first function exported from a lib that is in modules and is hooked succesfully\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn hook_any_lib_export(\n &mut self,\n symbol: &str,\n detour: *mut libc::c_void,\n ) -> Result {\n for module in &self.modules {\n // In this case we only want libs, no \"main binaries\"\n if !module.starts_with(\"lib\") {\n continue;\n }\n if let Ok(function) = get_export_by_name(Some(module), symbol) {\n trace!(\"found {symbol:?} in {module:?}, hooking\");\n match self.interceptor.replace(\n function,\n NativePointer(detour),\n NativePointer(null_mut()),\n ) {\n Ok(original) => return Ok(original),\n Err(err) => {\n trace!(\"hook {symbol:?} in {module:?} failed with err {err:?}\")\n }\n }\n }\n }\n Err(LayerError::NoExportName(symbol.to_string()))\n }\n```"}], "func_name": "hook_any_lib_export", "docstring": "Hook the first function exported from a lib that is in modules and is hooked succesfully", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "644a46c3fe82f9028df5bd3170fd8c72ece99a7d4ecfb921f7f1b90b76916f6a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: hook_export_or_any\n\nDocumentation:\nHook an exported symbol, suitable for most libc use cases.\nIf it fails to hook the first one found, it will try to hook each matching export\nuntil it succeeds.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn hook_export_or_any(\n &mut self,\n symbol: &str,\n detour: *mut libc::c_void,\n ) -> Result {\n // First try to hook the default exported one, if it fails, fallback to first lib that\n // provides it.\n let function = get_export_by_name(None, symbol)?;\n\n self.interceptor\n .replace(function, NativePointer(detour), NativePointer(null_mut()))\n .or_else(|_| self.hook_any_lib_export(symbol, detour))\n }\n```"}], "func_name": "hook_export_or_any", "docstring": "Hook an exported symbol, suitable for most libc use cases.\nIf it fails to hook the first one found, it will try to hook each matching export\nuntil it succeeds.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f47d4fcf898193cb74fb87140f426ec0aa1e1c5e9c4edd308bbc6802946e114"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: hook_symbol\n\nDocumentation:\nHook a symbol that isn't exported.\nIt is valuable when hooking internal stuff. (Go)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn hook_symbol(\n &mut self,\n module: &str,\n symbol: &str,\n detour: *mut libc::c_void,\n ) -> Result {\n let function = Module::obtain(&GUM)\n .find_symbol_by_name(module, symbol)\n .ok_or_else(|| LayerError::NoSymbolName(symbol.to_string()))?;\n\n // on Go we use `replace_fast` since we don't use the original function.\n self.interceptor\n .replace_fast(function, NativePointer(detour))\n .map_err(Into::into)\n }\n```"}], "func_name": "hook_symbol", "docstring": "Hook a symbol that isn't exported.\nIt is valuable when hooking internal stuff. (Go)", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2c2401e2a9e3d64f76bf813d51e820389258544b78be0598b2432e598689f6af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: hook_symbol_main_module\n\nDocumentation:\nHook a symbol in the first module (main module, binary)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn hook_symbol_main_module(\n &mut self,\n symbol: &str,\n detour: *mut libc::c_void,\n ) -> Result {\n // This can't fail\n let module = self.modules.first().unwrap().clone();\n self.hook_symbol(&module, symbol, detour)\n }\n```"}], "func_name": "hook_symbol_main_module", "docstring": "Hook a symbol in the first module (main module, binary)", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b41dc4951b9848fe404eaa794ba1d77beecc2d5bd560b4eab701cf92308c7b5d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: layer_pre_initialization\n\nDocumentation:\nLoads mirrord configuration and does some patching (SIP, dotnet, etc)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn layer_pre_initialization() -> Result<(), LayerError> {\n let given_process = EXECUTABLE_ARGS.get_or_try_init(ExecuteArgs::from_env)?;\n\n EXECUTABLE_PATH.get_or_try_init(|| {\n std::env::current_exe().map(|arg| arg.to_string_lossy().into_owned())\n })?;\n\n let config = mirrord_config::util::read_resolved_config()?;\n\n #[cfg(target_os = \"macos\")]\n let patch_binaries = config\n .sip_binaries\n .clone()\n .map(|x| x.to_vec())\n .unwrap_or_default();\n\n #[cfg(target_os = \"macos\")]\n let skip_patch_binaries = config.skip_sip.to_vec();\n\n // SIP Patch the process' binary then re-execute it. Needed\n // for https://github.com/metalbear-co/mirrord/issues/1529\n #[cfg(target_os = \"macos\")]\n if given_process.ends_with(\"dotnet\") {\n let path = EXECUTABLE_PATH\n .get()\n .expect(\"EXECUTABLE_PATH needs to be set!\");\n if let Ok(Some(binary)) = mirrord_sip::sip_patch(\n path,\n mirrord_sip::SipPatchOptions {\n patch: &patch_binaries,\n skip: &skip_patch_binaries,\n },\n ) {\n let err = exec::execvp(\n binary,\n EXECUTABLE_ARGS\n .get()\n .expect(\"EXECUTABLE_ARGS needs to be set!\")\n .args\n .clone(),\n );\n tracing::error!(\"Couldn't execute {:?}\", err);\n return Err(LayerError::ExecFailed(err));\n }\n }\n\n match given_process.load_type(&config) {\n LoadType::Full => layer_start(config),\n #[cfg(target_os = \"macos\")]\n LoadType::SIPOnly => sip_only_layer_start(config, patch_binaries, skip_patch_binaries),\n LoadType::Skip => load_only_layer_start(&config),\n }\n\n Ok(())\n}\n```"}], "func_name": "layer_pre_initialization", "docstring": "Loads mirrord configuration and does some patching (SIP, dotnet, etc)", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "38fcefad4b8739a95a803e6e1a6f20fea342d1fc714cb7468ad824eb3005d3c2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_only_layer_start\n\nDocumentation:\nInitialize a new session with the internal proxy and set [`PROXY_CONNECTION`]\nif not in trace only mode.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn load_only_layer_start(config: &LayerConfig) {\n // Check if we're in trace only mode (no agent)\n let trace_only = std::env::var(TRACE_ONLY_ENV)\n .unwrap_or_default()\n .parse()\n .unwrap_or(false);\n if trace_only {\n return;\n }\n\n let address = std::env::var(MIRRORD_LAYER_INTPROXY_ADDR)\n .expect(\"missing internal proxy address\")\n .parse::()\n .expect(\"malformed internal proxy address\");\n\n let new_connection = ProxyConnection::new(\n address,\n NewSessionRequest::New(\n EXECUTABLE_ARGS\n .get()\n .expect(\"EXECUTABLE_ARGS MUST BE SET\")\n .to_process_info(config),\n ),\n *PROXY_CONNECTION_TIMEOUT\n .get_or_init(|| Duration::from_secs(config.internal_proxy.socket_timeout)),\n )\n .expect(\"failed to initialize proxy connection\");\n\n unsafe {\n // SAFETY\n // Called only from library constructor.\n #[allow(static_mut_refs)]\n PROXY_CONNECTION\n .set(new_connection)\n .expect(\"setting PROXY_CONNECTION singleton\")\n }\n}\n```"}], "func_name": "load_only_layer_start", "docstring": "Initialize a new session with the internal proxy and set [`PROXY_CONNECTION`]\nif not in trace only mode.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f1678f14db035d898dae8978d564bc4eee81326f9bac5b8b5c1bfb453928f39d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init_tracing\n\nDocumentation:\nInitialize logger. Set the logs to go according to the layer's config either to a trace file, to\nmirrord-console or to stderr.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn init_tracing() {\n if let Ok(console_addr) = std::env::var(\"MIRRORD_CONSOLE_ADDR\") {\n mirrord_console::init_logger(&console_addr).expect(\"logger initialization failed\");\n } else {\n tracing_subscriber::registry()\n .with(\n tracing_subscriber::fmt::layer()\n .with_thread_ids(true)\n .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)\n .compact()\n .with_writer(std::io::stderr),\n )\n .with(tracing_subscriber::EnvFilter::from_default_env())\n .init();\n };\n}\n```"}], "func_name": "init_tracing", "docstring": "Initialize logger. Set the logs to go according to the layer's config either to a trace file, to\nmirrord-console or to stderr.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3fd95ba990d660174734c96787a54f024b78e657d764a23e57d8699258cc2fce"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: layer_start\n\nDocumentation:\nOccurs after [`layer_pre_initialization`] has succeeded.\n\nInitialized the main parts of mirrord-layer.\n\n## Details\n\nSets up a few things based on the [`LayerConfig`] given by the user:\n\n1. [`tracing_subscriber`] or [`mirrord_console`];\n\n2. Global [`SETUP`];\n\n3. Global [`PROXY_CONNECTION`];\n\n4. Replaces the [`libc`] calls with our hooks with [`enable_hooks`];\n\n5. Fetches remote environment from the agent (if enabled with\n[`EnvFileConfig::load_from_process`](mirrord_config::feature::env::EnvFileConfig::load_from_process)).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn layer_start(mut config: LayerConfig) {\n if config.target.path.is_none() && config.feature.fs.mode.ne(&FsModeConfig::Local) {\n // Use localwithoverrides on targetless regardless of user config, unless fs-mode is already\n // set to local.\n config.feature.fs.mode = FsModeConfig::LocalWithOverrides;\n }\n\n // Check if we're in trace only mode (no agent)\n let trace_only = std::env::var(TRACE_ONLY_ENV)\n .unwrap_or_default()\n .parse()\n .unwrap_or(false);\n\n // Disable all features that require the agent\n if trace_only {\n config.feature.fs.mode = FsModeConfig::Local;\n config.feature.network.dns.enabled = false;\n config.feature.network.incoming.mode = IncomingMode::Off;\n config.feature.network.outgoing.tcp = false;\n config.feature.network.outgoing.udp = false;\n }\n\n init_tracing();\n\n let proxy_connection_timeout = *PROXY_CONNECTION_TIMEOUT\n .get_or_init(|| Duration::from_secs(config.internal_proxy.socket_timeout));\n\n let debugger_ports = DebuggerPorts::from_env();\n let local_hostname = trace_only || !config.feature.hostname;\n let process_info = EXECUTABLE_ARGS\n .get()\n .expect(\"EXECUTABLE_ARGS MUST BE SET\")\n .to_process_info(&config);\n let state = LayerSetup::new(config, debugger_ports, local_hostname);\n SETUP.set(state).unwrap();\n\n let state = setup();\n enable_hooks(state);\n\n let _detour_guard = DetourGuard::new();\n\n // remove resolved encoded config from env vars when logging them\n let env_vars_print_only: Vec<_> = std::env::vars()\n .filter(|(k, _v)| k != LayerConfig::RESOLVED_CONFIG_ENV)\n .collect();\n tracing::info!(\"Initializing mirrord-layer!\");\n tracing::debug!(\n executable = ?EXECUTABLE_PATH.get(),\n args = ?EXECUTABLE_ARGS.get(),\n pid = std::process::id(),\n parent_pid = parent_id(),\n env_vars = ?env_vars_print_only,\n \"Loaded into executable (base64 config omitted)\",\n );\n\n if trace_only {\n tracing::debug!(\"Skipping new intproxy connection (trace only)\");\n return;\n }\n\n #[allow(static_mut_refs)]\n unsafe {\n let address = setup().proxy_address();\n let new_connection = ProxyConnection::new(\n address,\n NewSessionRequest::New(process_info),\n proxy_connection_timeout,\n )\n .unwrap_or_else(|_| panic!(\"failed to initialize proxy connection at {address}\"));\n PROXY_CONNECTION\n .set(new_connection)\n .expect(\"setting PROXY_CONNECTION singleton\")\n }\n\n let fetch_env = setup().env_config().load_from_process.unwrap_or(false)\n && !std::env::var(REMOTE_ENV_FETCHED)\n .unwrap_or_default()\n .parse::()\n .unwrap_or(false);\n if fetch_env {\n let env = fetch_env_vars();\n for (key, value) in env {\n std::env::set_var(key, value);\n }\n\n std::env::set_var(REMOTE_ENV_FETCHED, \"true\");\n }\n\n if let Some(unset) = setup().env_config().unset.as_ref() {\n let unset = unset.iter().map(|s| s.to_lowercase()).collect::>();\n std::env::vars().for_each(|(key, _)| {\n if unset.contains(&key.to_lowercase()) {\n std::env::remove_var(&key);\n }\n });\n }\n}\n```"}], "func_name": "layer_start", "docstring": "Occurs after [`layer_pre_initialization`] has succeeded.\n\nInitialized the main parts of mirrord-layer.\n\n## Details\n\nSets up a few things based on the [`LayerConfig`] given by the user:\n\n1. [`tracing_subscriber`] or [`mirrord_console`];\n\n2. Global [`SETUP`];\n\n3. Global [`PROXY_CONNECTION`];\n\n4. Replaces the [`libc`] calls with our hooks with [`enable_hooks`];\n\n5. Fetches remote environment from the agent (if enabled with\n[`EnvFileConfig::load_from_process`](mirrord_config::feature::env::EnvFileConfig::load_from_process)).", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "98ec5dded5990d19dbece93028691c2dc78231583f6e3306988ea47218ae4b7b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fetch_env_vars\n\nDocumentation:\nFetches remote environment from the agent.\nUses [`SETUP`] and [`PROXY_CONNECTION`] globals.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fetch_env_vars() -> HashMap {\n let (env_vars_exclude, env_vars_include) = match (\n setup()\n .env_config()\n .exclude\n .clone()\n .map(|exclude| exclude.join(\";\")),\n setup()\n .env_config()\n .include\n .clone()\n .map(|include| include.join(\";\")),\n ) {\n (Some(..), Some(..)) => {\n panic!(\"invalid env config\");\n }\n (Some(exclude), None) => (HashSet::from(EnvVars(exclude)), HashSet::new()),\n (None, Some(include)) => (HashSet::new(), HashSet::from(EnvVars(include))),\n (None, None) => (HashSet::new(), HashSet::from(EnvVars(\"*\".to_owned()))),\n };\n\n let mut env_vars = (!env_vars_exclude.is_empty() || !env_vars_include.is_empty())\n .then(|| {\n make_proxy_request_with_response(GetEnvVarsRequest {\n env_vars_filter: env_vars_exclude,\n env_vars_select: env_vars_include,\n })\n .expect(\"failed to make request to proxy\")\n .expect(\"failed to fetch remote env\")\n })\n .unwrap_or_default();\n\n if let Some(file) = &setup().env_config().env_file {\n let envs_from_file = dotenvy::from_path_iter(file)\n .and_then(|iter| iter.collect::, _>>())\n .expect(\"failed to access the env file\");\n\n env_vars.extend(envs_from_file);\n }\n\n if let Some(mapping) = setup().env_config().mapping.clone() {\n env_vars = EnvVarsRemapper::new(mapping, env_vars)\n .expect(\"Failed creating regex, this should've been caught when verifying config!\")\n .remapped();\n }\n\n if let Some(overrides) = setup().env_config().r#override.as_ref() {\n env_vars.extend(overrides.iter().map(|(k, v)| (k.clone(), v.clone())));\n }\n\n env_vars\n}\n```"}], "func_name": "fetch_env_vars", "docstring": "Fetches remote environment from the agent.\nUses [`SETUP`] and [`PROXY_CONNECTION`] globals.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ebf99722533cf433f48c9747cbeb270761082a6c191877401eef59c357303b56"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_env\n\nDocumentation:\nCreates a new instance of this struct using [`std::env::current_exe`] and\n[`std::env::args`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn from_env() -> Result {\n let exec_name = std::env::current_exe()\n .ok()\n .and_then(|arg| {\n arg.file_name()\n .and_then(|os_str| os_str.to_str())\n .map(String::from)\n })\n .ok_or(LayerError::NoProcessFound)?;\n\n let args = std::env::args_os().collect();\n let invoked_as = std::env::args()\n .next()\n .as_ref()\n .and_then(|arg| arg.rsplit('/').next())\n .ok_or(LayerError::NoProcessFound)?\n .to_string();\n\n Ok(Self {\n exec_name,\n invoked_as,\n args,\n })\n }\n```"}], "func_name": "from_env", "docstring": "Creates a new instance of this struct using [`std::env::current_exe`] and\n[`std::env::args`].", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/load.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/load.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ffca5abbcef8afeb1748310d110e22e6d600986de5d2890b238a98359d99f9fd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: should_load\n\nDocumentation:\nChecks if mirrord-layer should load with this process.\n\n## Details\n\nSome processes may start other processes (like an IDE launching a program to be debugged),\nand we don't want to hook mirrord-layer into those.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn should_load>(\n &self,\n skip_processes: &[S],\n skip_build_tools: bool,\n skip_extra_build_tools: Option<&[String]>,\n ) -> bool {\n if skip_build_tools && self.is_build_tool(skip_extra_build_tools) {\n return false;\n }\n\n // ignore intellij debugger https://github.com/metalbear-co/mirrord/issues/2408\n // don't put it in build tools since we don't want to SIP load on macOS. (leads to above\n // issue)\n if self\n .exec_name\n .as_str()\n .ends_with(\"JetBrains.Debugger.Worker\")\n || self\n .invoked_as\n .as_str()\n .ends_with(\"JetBrains.Debugger.Worker\")\n {\n return false;\n }\n\n !skip_processes\n .iter()\n .any(|name| name.as_ref() == self.exec_name || name.as_ref() == self.invoked_as)\n }\n```"}], "func_name": "should_load", "docstring": "Checks if mirrord-layer should load with this process.\n\n## Details\n\nSome processes may start other processes (like an IDE launching a program to be debugged),\nand we don't want to hook mirrord-layer into those.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/load.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/load.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6228750c2ac1289df9e188e58173525eff15caf9e0e0319318469cd777c2108"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_type\n\nDocumentation:\nDetermine the [`LoadType`] for this process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load_type(&self, config: &LayerConfig) -> LoadType {\n let skip_processes = config.skip_processes.as_deref().unwrap_or(&[]);\n\n if self.should_load(\n skip_processes,\n config.skip_build_tools,\n config.skip_extra_build_tools.as_deref(),\n ) {\n trace!(\"Loading into process: {self}.\");\n LoadType::Full\n } else {\n #[cfg(target_os = \"macos\")]\n if sip::is_sip_only(self, config.skip_extra_build_tools.as_deref()) {\n trace!(\"Loading into process: {self}, but only hooking exec/spawn.\");\n return LoadType::SIPOnly;\n }\n\n trace!(\"Not loading into process: {self}.\");\n LoadType::Skip\n }\n }\n```"}], "func_name": "load_type", "docstring": "Determine the [`LoadType`] for this process.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/load.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/load.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81e3562e772ef36f94199d52ab9b6199f374c0e1d7961f9b9abefbdfbd3eb2f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nBuilds a new instance from the user config, removing filters\nthat would create inconsitencies, by checking if their protocol is enabled for outgoing\ntraffic, and thus we avoid making this check on every [`ops::connect`] call.\n\nIt also removes duplicated filters, by putting them into a [`HashSet`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(config: &OutgoingConfig) -> Self {\n match &config.filter {\n None => Self::Unfiltered,\n Some(OutgoingFilterConfig::Remote(list)) | Some(OutgoingFilterConfig::Local(list))\n if list.is_empty() =>\n {\n panic!(\"outgoing traffic filter cannot be empty\");\n }\n Some(OutgoingFilterConfig::Remote(list)) => Self::Remote(Self::build_selector(\n list.iter().map(String::as_str),\n config.tcp,\n config.udp,\n )),\n Some(OutgoingFilterConfig::Local(list)) => Self::Local(Self::build_selector(\n list.iter().map(String::as_str),\n config.tcp,\n config.udp,\n )),\n }\n }\n```"}], "func_name": "new", "docstring": "Builds a new instance from the user config, removing filters\nthat would create inconsitencies, by checking if their protocol is enabled for outgoing\ntraffic, and thus we avoid making this check on every [`ops::connect`] call.\n\nIt also removes duplicated filters, by putting them into a [`HashSet`].", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/socket.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/socket.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa7720ff762c68b3dab57754f8a2db9b25c2103039fd46e0acb37081c4a70c85"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shared_sockets\n\nDocumentation:\nConverts the [`SOCKETS`] map into a vector of pairs `(Fd, UserSocket)`, so we can rebuild\nit as a map.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn shared_sockets() -> Detour> {\n Detour::Success(\n SOCKETS\n .lock()?\n .iter()\n .map(|(key, value)| (*key, value.as_ref().clone()))\n .collect::>(),\n )\n}\n```"}], "func_name": "shared_sockets", "docstring": "Converts the [`SOCKETS`] map into a vector of pairs `(Fd, UserSocket)`, so we can rebuild\nit as a map.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/exec_hooks/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/exec_hooks/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a4f820c7eefe253d401ea4d30e4d17e90f4758ef05cbc5f1389145c9632f1e08"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prepare_execve_envp\n\nDocumentation:\nTakes an [`Argv`] with the enviroment variables from an `exec` call, extending it with\nan encoded version of our [`SOCKETS`].\n\nThe check for [`libc::FD_CLOEXEC`] is performed during the [`SOCKETS`] initialization\nby the child process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn prepare_execve_envp(env_vars: Detour) -> Detour {\n let mut env_vars = env_vars.or_bypass(|reason| match reason {\n Bypass::EmptyOption => Detour::Success(Argv(Vec::new())),\n other => Detour::Bypass(other),\n })?;\n\n let encoded = bincode::encode_to_vec(shared_sockets()?, bincode::config::standard())\n .map(|bytes| BASE64_URL_SAFE.encode(bytes))?;\n\n env_vars.insert_env(SHARED_SOCKETS_ENV_VAR, &encoded)?;\n\n Detour::Success(env_vars)\n}\n```"}], "func_name": "prepare_execve_envp", "docstring": "Takes an [`Argv`] with the enviroment variables from an `exec` call, extending it with\nan encoded version of our [`SOCKETS`].\n\nThe check for [`libc::FD_CLOEXEC`] is performed during the [`SOCKETS`] initialization\nby the child process.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/exec_hooks/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/exec_hooks/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ded971562090e91f0346e4628c3fe2e777f97e3ca2edd3e734279a56fae0cc40"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_local_set\n\nDocumentation:\nList of files that mirrord should use locally, as they probably exist only in the local user\nmachine, or are system configuration files (that could break the process if we used the remote\nversion).\n\nYou most likely do **NOT** want to include any of these, but if have a reason to do so, then\nsetting any of the overrides - `MIRRORD_FILE_X_PATTERN` allows you to override this list.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_local_set() -> RegexSet {\n // To handle the problem of injecting `open` and friends into project runners (like in a call to\n // `node app.js`, or `cargo run app`), we're ignoring files from the current working directory.\n read_local_by_default::regex_set_builder()\n .case_insensitive(true)\n .build()\n .expect(\"Building local path regex set failed\")\n}\n```"}], "func_name": "generate_local_set", "docstring": "List of files that mirrord should use locally, as they probably exist only in the local user\nmachine, or are system configuration files (that could break the process if we used the remote\nversion).\n\nYou most likely do **NOT** want to include any of these, but if have a reason to do so, then\nsetting any of the overrides - `MIRRORD_FILE_X_PATTERN` allows you to override this list.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/filter.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/filter.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2fa2ff427c712e9bd5310f4531c2352cb8a9b374cf555a8af8837891416c6ec4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_remote_ro_set\n\nDocumentation:\nList of files that mirrord should use remotely read only\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_remote_ro_set() -> RegexSet {\n let patterns = read_remote_by_default::PATHS;\n RegexSetBuilder::new(patterns)\n .case_insensitive(true)\n .build()\n .expect(\"Building remote readonly path regex set failed\")\n}\n```"}], "func_name": "generate_remote_ro_set", "docstring": "List of files that mirrord should use remotely read only", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/filter.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/filter.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25efa9b3e2d66e39879d59d8b0efbf9255a5c72af64b611a4b22f564c73f9513"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ensure_remote\n\nDocumentation:\nChecks whether the given [`Path`] should be accessed remotely.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ensure_remote(&self, path: &Path, write: bool) -> Detour<()> {\n let text = path.to_str().unwrap_or_default();\n\n match self.mode {\n FsModeConfig::Local => Detour::Bypass(Bypass::ignored_file(text)),\n _ if self.not_found.is_match(text) => Detour::Error(HookError::FileNotFound),\n _ if self.read_write.is_match(text) => Detour::Success(()),\n _ if self.read_only.is_match(text) => {\n if write {\n Detour::Bypass(Bypass::ignored_file(text))\n } else {\n Detour::Success(())\n }\n }\n _ if self.local.is_match(text) => Detour::Bypass(Bypass::ignored_file(text)),\n _ if self.default_not_found.is_match(text) => Detour::Error(HookError::FileNotFound),\n _ if self.default_remote_ro.is_match(text) && !write => Detour::Success(()),\n _ if self.default_local.is_match(text) => Detour::Bypass(Bypass::ignored_file(text)),\n FsModeConfig::LocalWithOverrides => Detour::Bypass(Bypass::ignored_file(text)),\n FsModeConfig::Write => Detour::Success(()),\n FsModeConfig::Read if write => Detour::Bypass(Bypass::ReadOnly(text.into())),\n FsModeConfig::Read => Detour::Success(()),\n }\n }\n```"}], "func_name": "ensure_remote", "docstring": "Checks whether the given [`Path`] should be accessed remotely.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/filter.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/filter.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8be913ad793f45ada551c823c008de2725b68693abf91276b93d0b6337a8ff91"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_ptr_from_bypass\n\nDocumentation:\nTake the original raw c_char pointer and a resulting bypass, and either the original pointer or\na different one according to the bypass.\nWe pass reference to bypass to make sure the bypass lives with the pointer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn update_ptr_from_bypass(ptr: *const c_char, bypass: &Bypass) -> *const c_char {\n match bypass {\n // For some reason, the program is trying to carry out an operation on a path that is\n // inside mirrord's temp bin dir. The detour has returned us the original path of the file\n // (stripped mirrord's dir path), so now we carry out the operation locally, on the stripped\n // path.\n #[cfg(target_os = \"macos\")]\n Bypass::FileOperationInMirrordBinTempDir(stripped_ptr) => *stripped_ptr,\n Bypass::RelativePath(path) | Bypass::IgnoredFile(path) => path.as_ptr(),\n _ => ptr,\n }\n}\n```"}], "func_name": "update_ptr_from_bypass", "docstring": "Take the original raw c_char pointer and a resulting bypass, and either the original pointer or\na different one according to the bypass.\nWe pass reference to bypass to make sure the bypass lives with the pointer.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b719c9886094320b0c855098e1ca88423dcb6557c0ec29b969197f0dde4c91a3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pwrite_logic\n\nDocumentation:\nCommon code between the `pwrite` detours.\n\nHandle the `.unwrap_or_bypass` in their respective functions though.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn pwrite_logic(\n fd: RawFd,\n in_buffer: *const c_void,\n amount_to_write: size_t,\n offset: off_t,\n) -> Detour {\n // Convert the given buffer into a u8 slice, upto the amount to write.\n let casted_in_buffer: &[u8] = slice::from_raw_parts(in_buffer.cast(), amount_to_write);\n\n pwrite(fd, casted_in_buffer, offset as u64).map(|write_response| {\n let WriteFileResponse { written_amount } = write_response;\n written_amount as ssize_t\n })\n}\n```"}], "func_name": "pwrite_logic", "docstring": "Common code between the `pwrite` detours.\n\nHandle the `.unwrap_or_bypass` in their respective functions though.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c13a568143e20e60bb4f97b05cdda3ee268ee60c3f93475d85384e66556e041"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: best_effort_cast\n\nDocumentation:\nTries to convert input to type O, if it fails it returns the max value of O.\nFor example, if you put u32::MAX into a u8, it will return u8::MAX.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn best_effort_cast + Bounded>(input: I) -> O {\n input.try_into().unwrap_or_else(|_| O::max_value())\n}\n```"}], "func_name": "best_effort_cast", "docstring": "Tries to convert input to type O, if it fails it returns the max value of O.\nFor example, if you put u32::MAX into a u8, it will return u8::MAX.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8d07737e2d7efdea83d3f5b3a8718715674b66491a9558875b52b72519ad4098"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fill_stat\n\nDocumentation:\nFills the `stat` struct with the metadata\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe extern \"C\" fn fill_stat(out_stat: *mut stat64, metadata: &MetadataInternal) {\n out_stat.write_bytes(0, 1);\n let out = &mut *out_stat;\n // on macOS the types might be different, so we try to cast and do our best..\n out.st_mode = best_effort_cast(metadata.mode);\n out.st_size = best_effort_cast(metadata.size);\n out.st_atime_nsec = metadata.access_time;\n out.st_mtime_nsec = metadata.modification_time;\n out.st_ctime_nsec = metadata.creation_time;\n out.st_atime = nano_to_secs(metadata.access_time);\n out.st_mtime = nano_to_secs(metadata.modification_time);\n out.st_ctime = nano_to_secs(metadata.creation_time);\n out.st_nlink = best_effort_cast(metadata.hard_links);\n out.st_uid = metadata.user_id;\n out.st_gid = metadata.group_id;\n out.st_dev = best_effort_cast(metadata.device_id);\n out.st_ino = best_effort_cast(metadata.inode);\n out.st_rdev = best_effort_cast(metadata.rdevice_id);\n out.st_blksize = best_effort_cast(metadata.block_size);\n out.st_blocks = best_effort_cast(metadata.blocks);\n}\n```"}], "func_name": "fill_stat", "docstring": "Fills the `stat` struct with the metadata", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b680dd50e4556a7a2268ff71dc50e6aaa5e9befffa3709186b583dd3a3678d22"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fill_statfs\n\nDocumentation:\nFills the `statfs` struct with the metadata\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe extern \"C\" fn fill_statfs(out_stat: *mut statfs, metadata: &FsMetadataInternalV2) {\n // Acording to linux documentation \"Fields that are undefined for a particular file system are\n // set to 0.\"\n out_stat.write_bytes(0, 1);\n let out = &mut *out_stat;\n out.f_type = best_effort_cast(metadata.filesystem_type);\n out.f_bsize = best_effort_cast(metadata.block_size);\n out.f_blocks = metadata.blocks;\n out.f_bfree = metadata.blocks_free;\n out.f_bavail = metadata.blocks_available;\n out.f_files = metadata.files;\n out.f_ffree = metadata.files_free;\n #[cfg(target_os = \"linux\")]\n {\n // SAFETY: fsid_t has C repr and holds just an array with two i32s.\n out.f_fsid = std::mem::transmute::<[i32; 2], libc::fsid_t>(metadata.filesystem_id);\n out.f_namelen = metadata.name_len;\n out.f_frsize = metadata.fragment_size;\n }\n}\n```"}], "func_name": "fill_statfs", "docstring": "Fills the `statfs` struct with the metadata", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a170849a8ccbe324eecc29f83c5bedcf6e2f43b53ec8485354f98307352e887d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fstatat_logic\n\nDocumentation:\nSeparated out logic for `fstatat` so that it can be used by go to match on the xstat result.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) unsafe fn fstatat_logic(\n fd: RawFd,\n raw_path: *const c_char,\n out_stat: *mut stat,\n flag: c_int,\n) -> Detour {\n if out_stat.is_null() {\n return Detour::Error(HookError::BadPointer);\n }\n\n let follow_symlink = (flag & libc::AT_SYMLINK_NOFOLLOW) == 0;\n xstat(Some(raw_path.checked_into()), Some(fd), follow_symlink).map(|res| {\n let res = res.metadata;\n fill_stat(out_stat as *mut _, &res);\n 0\n })\n}\n```"}], "func_name": "fstatat_logic", "docstring": "Separated out logic for `fstatat` so that it can be used by go to match on the xstat result.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9784cacc7c24266bf8d06dc9ea10c29d336d8debc37351c3512a74c9e4ed0b1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: enable_file_hooks\n\nDocumentation:\nConvenience function to setup file hooks (`x_detour`) with `frida_gum`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) unsafe fn enable_file_hooks(hook_manager: &mut HookManager) {\n replace!(hook_manager, \"open\", open_detour, FnOpen, FN_OPEN);\n replace!(hook_manager, \"open64\", open64_detour, FnOpen64, FN_OPEN64);\n replace!(\n hook_manager,\n \"open$NOCANCEL\",\n open_nocancel_detour,\n FnOpen_nocancel,\n FN_OPEN_NOCANCEL\n );\n\n replace!(hook_manager, \"openat\", openat_detour, FnOpenat, FN_OPENAT);\n replace!(\n hook_manager,\n \"openat64\",\n openat64_detour,\n FnOpenat64,\n FN_OPENAT64\n );\n replace!(\n hook_manager,\n \"_openat$NOCANCEL\",\n _openat_nocancel_detour,\n Fn_openat_nocancel,\n FN__OPENAT_NOCANCEL\n );\n\n replace!(hook_manager, \"read\", read_detour, FnRead, FN_READ);\n replace!(\n hook_manager,\n \"_read$NOCANCEL\",\n _read_nocancel_detour,\n Fn_read_nocancel,\n FN__READ_NOCANCEL\n );\n\n replace!(\n hook_manager,\n \"read$NOCANCEL\",\n read_nocancel_detour,\n FnRead_nocancel,\n FN_READ_NOCANCEL\n );\n\n replace!(\n hook_manager,\n \"closedir\",\n closedir_detour,\n FnClosedir,\n FN_CLOSEDIR\n );\n\n replace!(hook_manager, \"dirfd\", dirfd_detour, FnDirfd, FN_DIRFD);\n\n replace!(hook_manager, \"pread\", pread_detour, FnPread, FN_PREAD);\n replace!(hook_manager, \"readv\", readv_detour, FnReadv, FN_READV);\n replace!(hook_manager, \"preadv\", preadv_detour, FnPreadv, FN_PREADV);\n replace!(\n hook_manager,\n \"_pread$NOCANCEL\",\n _pread_nocancel_detour,\n Fn_pread_nocancel,\n FN__PREAD_NOCANCEL\n );\n\n replace!(\n hook_manager,\n \"readlink\",\n readlink_detour,\n FnReadlink,\n FN_READLINK\n );\n\n replace!(hook_manager, \"mkdir\", mkdir_detour, FnMkdir, FN_MKDIR);\n replace!(\n hook_manager,\n \"mkdirat\",\n mkdirat_detour,\n FnMkdirat,\n FN_MKDIRAT\n );\n\n replace!(hook_manager, \"rmdir\", rmdir_detour, FnRmdir, FN_RMDIR);\n\n replace!(hook_manager, \"unlink\", unlink_detour, FnUnlink, FN_UNLINK);\n replace!(\n hook_manager,\n \"unlinkat\",\n unlinkat_detour,\n FnUnlinkat,\n FN_UNLINKAT\n );\n\n replace!(hook_manager, \"lseek\", lseek_detour, FnLseek, FN_LSEEK);\n\n replace!(hook_manager, \"write\", write_detour, FnWrite, FN_WRITE);\n replace!(\n hook_manager,\n \"_write$NOCANCEL\",\n _write_nocancel_detour,\n Fn_write_nocancel,\n FN__WRITE_NOCANCEL\n );\n\n replace!(hook_manager, \"pwrite\", pwrite_detour, FnPwrite, FN_PWRITE);\n replace!(\n hook_manager,\n \"_pwrite$NOCANCEL\",\n _pwrite_nocancel_detour,\n Fn_pwrite_nocancel,\n FN__PWRITE_NOCANCEL\n );\n\n replace!(hook_manager, \"access\", access_detour, FnAccess, FN_ACCESS);\n replace!(\n hook_manager,\n \"faccessat\",\n faccessat_detour,\n FnFaccessat,\n FN_FACCESSAT\n );\n\n replace!(hook_manager, \"fsync\", fsync_detour, FnFsync, FN_FSYNC);\n replace!(\n hook_manager,\n \"fdatasync\",\n fdatasync_detour,\n FnFdatasync,\n FN_FDATASYNC\n );\n\n replace!(\n hook_manager,\n \"realpath\",\n realpath_detour,\n FnRealpath,\n FN_REALPATH\n );\n\n replace!(\n hook_manager,\n \"realpath$DARWIN_EXTSN\",\n realpath_darwin_extsn_detour,\n FnRealpath_darwin_extsn,\n FN_REALPATH_DARWIN_EXTSN\n );\n\n #[cfg(target_os = \"linux\")]\n {\n replace!(hook_manager, \"statx\", statx_detour, FnStatx, FN_STATX);\n replace!(\n hook_manager,\n \"fstatfs64\",\n fstatfs64_detour,\n FnFstatfs64,\n FN_FSTATFS64\n );\n replace!(\n hook_manager,\n \"statfs64\",\n statfs64_detour,\n FnStatfs64,\n FN_STATFS64\n );\n }\n\n #[cfg(not(all(target_os = \"macos\", target_arch = \"x86_64\")))]\n {\n replace!(\n hook_manager,\n \"__xstat\",\n __xstat_detour,\n Fn__xstat,\n FN___XSTAT\n );\n replace!(\n hook_manager,\n \"__xstat64\",\n __xstat64_detour,\n Fn__xstat64,\n FN___XSTAT64\n );\n replace!(\n hook_manager,\n \"__lxstat\",\n __lxstat_detour,\n Fn__lxstat,\n FN___LXSTAT\n );\n replace!(\n hook_manager,\n \"__lxstat64\",\n __lxstat64_detour,\n Fn__lxstat64,\n FN___LXSTAT64\n );\n replace!(hook_manager, \"lstat\", lstat_detour, FnLstat, FN_LSTAT);\n crate::replace_with_fallback!(\n hook_manager,\n \"fstat\",\n fstat_detour,\n FnFstat,\n FN_FSTAT,\n libc::fstat\n );\n replace!(hook_manager, \"stat\", stat_detour, FnStat, FN_STAT);\n replace!(\n hook_manager,\n \"fstatat\",\n fstatat_detour,\n FnFstatat,\n FN_FSTATAT\n );\n replace!(\n hook_manager,\n \"fstatfs\",\n fstatfs_detour,\n FnFstatfs,\n FN_FSTATFS\n );\n replace!(hook_manager, \"statfs\", statfs_detour, FnStatfs, FN_STATFS);\n replace!(\n hook_manager,\n \"fdopendir\",\n fdopendir_detour,\n FnFdopendir,\n FN_FDOPENDIR\n );\n replace!(\n hook_manager,\n \"readdir_r\",\n readdir_r_detour,\n FnReaddir_r,\n FN_READDIR_R\n );\n #[cfg(target_os = \"linux\")]\n replace!(\n hook_manager,\n \"readdir64_r\",\n readdir64_r_detour,\n FnReaddir64_r,\n FN_READDIR64_R\n );\n #[cfg(target_os = \"linux\")]\n replace!(\n hook_manager,\n \"readdir64\",\n readdir64_detour,\n FnReaddir64,\n FN_READDIR64\n );\n replace!(\n hook_manager,\n \"readdir\",\n readdir_detour,\n FnReaddir,\n FN_READDIR\n );\n // aarch + macOS hooks fail\n // because macOs internally calls this with pointer authentication\n // and we don't compile to arm64e yet, so it breaks.\n // but it seems we'll be able to compile to arm64e soon.\n // https://github.com/rust-lang/rust/pull/115526\n replace!(\n hook_manager,\n \"opendir\",\n opendir_detour,\n FnOpendir,\n FN_OPENDIR\n );\n }\n // on non aarch64 (Intel) we need to hook also $INODE64 variants\n #[cfg(all(target_os = \"macos\", target_arch = \"x86_64\"))]\n {\n replace!(\n hook_manager,\n \"lstat$INODE64\",\n lstat_detour,\n FnLstat,\n FN_LSTAT\n );\n replace!(\n hook_manager,\n \"fstat$INODE64\",\n fstat_detour,\n FnFstat,\n FN_FSTAT\n );\n replace!(hook_manager, \"stat$INODE64\", stat_detour, FnStat, FN_STAT);\n replace!(\n hook_manager,\n \"fstatat$INODE64\",\n fstatat_detour,\n FnFstatat,\n FN_FSTATAT\n );\n replace!(\n hook_manager,\n \"fstatfs$INODE64\",\n fstatfs_detour,\n FnFstatfs,\n FN_FSTATFS\n );\n replace!(\n hook_manager,\n \"statfs$INODE64\",\n statfs_detour,\n FnStatfs,\n FN_STATFS\n );\n replace!(\n hook_manager,\n \"fdopendir$INODE64\",\n fdopendir_detour,\n FnFdopendir,\n FN_FDOPENDIR\n );\n replace!(\n hook_manager,\n \"readdir_r$INODE64\",\n readdir_r_detour,\n FnReaddir_r,\n FN_READDIR_R\n );\n replace!(\n hook_manager,\n \"readdir$INODE64\",\n readdir_detour,\n FnReaddir,\n FN_READDIR\n );\n replace!(\n hook_manager,\n \"opendir$INODE64\",\n opendir_detour,\n FnOpendir,\n FN_OPENDIR\n );\n }\n}\n```"}], "func_name": "enable_file_hooks", "docstring": "Convenience function to setup file hooks (`x_detour`) with `frida_gum`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/hooks.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/hooks.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b0c83f4c17b44d0060c120f1100ec80d5de19e1494786a6a6484e39f0ba29ee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nInserts a new entry into this state.\n\n# Arguments\n\n* `local_dir_fd` - opaque identifier\n* `remote_fd` - descriptor of the remote directory (received from the agent)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert(\n &self,\n local_dir_fd: DirStreamFd,\n remote_fd: RemoteFd,\n base_fd: LocalFd,\n ) -> Detour<()> {\n self.inner.lock()?.insert(\n local_dir_fd,\n Mutex::new(OpenDir::new(local_dir_fd, remote_fd, base_fd)).into(),\n );\n Detour::Success(())\n }\n```"}], "func_name": "insert", "docstring": "Inserts a new entry into this state.\n\n# Arguments\n\n* `local_dir_fd` - opaque identifier\n* `remote_fd` - descriptor of the remote directory (received from the agent)", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/open_dirs.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/open_dirs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6c0db9d533ef7779e72d911b209f81316fe4a57dd7c332f1c12755927ac09e40"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_r\n\nDocumentation:\nReads next entry from the open directory with the given [`DirStreamFd`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_r(&self, local_dir_fd: DirStreamFd) -> Detour> {\n let dir = self\n .inner\n .lock()?\n .get(&local_dir_fd)\n .ok_or(Bypass::LocalDirStreamNotFound(local_dir_fd))?\n .clone();\n\n let guard = dir.lock().expect(\"lock poisoned\");\n\n guard.read_r()\n }\n```"}], "func_name": "read_r", "docstring": "Reads next entry from the open directory with the given [`DirStreamFd`].", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/open_dirs.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/open_dirs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "12179bd98a39e6bbd13df37a2af0cec6eb9bed412963e5f91c086a1a56aa5eba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_fd\n\nDocumentation:\nGets fd used to open dir [`DirStreamFd`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_fd(&self, local_dir_fd: DirStreamFd) -> Detour {\n let dir = self\n .inner\n .lock()?\n .get(&local_dir_fd)\n .ok_or(Bypass::LocalDirStreamNotFound(local_dir_fd))?\n .clone();\n\n let guard = dir.lock().expect(\"lock poisoned\");\n\n Detour::Success(guard.get_base_fd())\n }\n```"}], "func_name": "get_fd", "docstring": "Gets fd used to open dir [`DirStreamFd`].", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/open_dirs.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/open_dirs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b206ee063d7224dda9e552166701d078ad3c30702a6a584fb5c2f0611eef98fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read\n\nDocumentation:\nReads next entry from the open directory with the given [`DirStreamFd`] and copies the data\ninto an internal buffer. Returns a raw pointer to that buffer.\n\nIf there are no more entries, returns [`std::ptr::null`].\n\n# Notes\n\n1. There is exactly one buffer of this type for each open directory.\n2. The returned pointer is valid as long as the directory remains open.\n3. Consecutive calls of this method overwrite the buffer.\n\nGiven above, the returned pointer is good enough to be used as a result of `readdir`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read(&self, local_dir_fd: DirStreamFd) -> Detour<*const libc::dirent> {\n let dir = self\n .inner\n .lock()?\n .get(&local_dir_fd)\n .ok_or(Bypass::LocalDirStreamNotFound(local_dir_fd))?\n .clone();\n\n let mut guard = dir.lock().expect(\"lock poisoned\");\n\n let Some(entry) = guard.read_r()? else {\n return Detour::Success(std::ptr::null());\n };\n\n assign_direntry(entry, &mut guard.dirent, false)?;\n\n Detour::Success(&guard.dirent)\n }\n```"}], "func_name": "read", "docstring": "Reads next entry from the open directory with the given [`DirStreamFd`] and copies the data\ninto an internal buffer. Returns a raw pointer to that buffer.\n\nIf there are no more entries, returns [`std::ptr::null`].\n\n# Notes\n\n1. There is exactly one buffer of this type for each open directory.\n2. The returned pointer is valid as long as the directory remains open.\n3. Consecutive calls of this method overwrite the buffer.\n\nGiven above, the returned pointer is good enough to be used as a result of `readdir`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/open_dirs.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/open_dirs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "680586ac3235d5cc3e297513484c7a49320ce285b69d699b2c2af4f6f974c4c9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: close\n\nDocumentation:\nCloses the open directory with the given [`DirStreamFd`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn close(&self, local_dir_fd: DirStreamFd) -> Detour {\n let dir = self\n .inner\n .lock()?\n .remove(&local_dir_fd)\n .ok_or(Bypass::LocalDirStreamNotFound(local_dir_fd))?;\n\n let mut guard = dir.lock().expect(\"lock poisoned\");\n guard.closed = true;\n OPEN_FILES.lock()?.remove(&guard.base_fd);\n common::make_proxy_request_no_response(CloseDirRequest {\n remote_fd: guard.remote_fd,\n })?;\n\n Detour::Success(0)\n }\n```"}], "func_name": "close", "docstring": "Closes the open directory with the given [`DirStreamFd`].", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/open_dirs.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/open_dirs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "896d776057a555bbbcb64277a5c0cce08807cf85ee7431a9694bbb3d07eef6f8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: assign_direntry\n\nDocumentation:\nMoves [`DirEntryInternal`] content to the given [`libc::dirent`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn assign_direntry(\n in_entry: DirEntryInternal,\n out_entry: &mut libc::dirent,\n getdents: bool,\n) -> Result<(), HookError> {\n out_entry.d_ino = in_entry.inode;\n out_entry.d_reclen = if getdents {\n // The structs written by the kernel for the getdents syscall do not have a fixed size.\n in_entry.get_d_reclen64()\n } else {\n std::mem::size_of::() as u16\n };\n out_entry.d_type = in_entry.file_type;\n\n let dir_name = CString::new(in_entry.name)?;\n let dir_name_bytes = cstr_as_slice_for_d_name(&dir_name);\n out_entry\n .d_name\n .get_mut(..dir_name_bytes.len())\n .expect(\"directory name length exceeds limit\")\n .copy_from_slice(dir_name_bytes);\n\n #[cfg(target_os = \"macos\")]\n {\n out_entry.d_seekoff = in_entry.position;\n // name length should be without null\n out_entry.d_namlen = dir_name.to_bytes().len() as u16;\n }\n\n #[cfg(target_os = \"linux\")]\n {\n out_entry.d_off = in_entry.position as i64;\n }\n Ok(())\n}\n```"}], "func_name": "assign_direntry", "docstring": "Moves [`DirEntryInternal`] content to the given [`libc::dirent`].", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/open_dirs.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/open_dirs.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c1fa5786c5e88d8d0587ef0808f4d055a97bf12857668cff528ff22b43867b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: common_path_check\n\nDocumentation:\nPerforms standard verification of paths accessed by the user application.\n\nOperations in order:\n1. Bypass if the path is not relative.\n2. Remap the file according to the config.\n3. Bypass if the new path should be accessed locally.\n\nReturns the remapped path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn common_path_check(path: PathBuf, write: bool) -> Detour {\n path.ensure_not_relative()?;\n let path = crate::setup().file_remapper().change_path(path);\n crate::setup().file_filter().ensure_remote(&path, write)?;\n Detour::Success(path)\n}\n```"}], "func_name": "common_path_check", "docstring": "Performs standard verification of paths accessed by the user application.\n\nOperations in order:\n1. Bypass if the path is not relative.\n2. Remap the file according to the config.\n3. Bypass if the new path should be accessed locally.\n\nReturns the remapped path.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/ops.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/ops.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00aea0786a9510ff96f55fee7b0a1829252d6a1e3155b024bfa6c79a20e11954"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_remote_fd\n\nDocumentation:\nHelper function that retrieves the `remote_fd` (which is generated by\n`mirrord_agent::util::IndexAllocator`).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_remote_fd(local_fd: RawFd) -> Detour {\n // don't add a trace here since it causes deadlocks in some cases.\n Detour::Success(\n OPEN_FILES\n .lock()?\n .get(&local_fd)\n .map(|remote_file| remote_file.fd)\n // Bypass if we're not managing the relative part.\n .ok_or(Bypass::LocalFdNotFound(local_fd))?,\n )\n}\n```"}], "func_name": "get_remote_fd", "docstring": "Helper function that retrieves the `remote_fd` (which is generated by\n`mirrord_agent::util::IndexAllocator`).", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/ops.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/ops.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "74ecc3934725745365bb23b574a46bcd194a28657affd5206cfdd2492a54d8b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read\n\nDocumentation:\nBlocking wrapper around [`libc::read`] call.\n\n**Bypassed** when trying to load system files, and files from the current working directory, see\n`open`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn read(local_fd: RawFd, read_amount: u64) -> Detour {\n get_remote_fd(local_fd).and_then(|remote_fd| RemoteFile::remote_read(remote_fd, read_amount))\n}\n```"}], "func_name": "read", "docstring": "Blocking wrapper around [`libc::read`] call.\n\n**Bypassed** when trying to load system files, and files from the current working directory, see\n`open`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/ops.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/ops.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dc1960fbe435aa7f69bc7240be561e962819d4667c548f006a1a4108e1df6252"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: readv\n\nDocumentation:\nHelper for dealing with a potential null pointer being passed to `*const iovec` from\n`readv_detour` and `preadv_detour`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn readv(iovs: Option<&[iovec]>) -> Detour<(&[iovec], u64)> {\n let iovs = iovs?;\n let read_size: u64 = iovs.iter().fold(0, |sum, iov| sum + iov.iov_len as u64);\n\n Detour::Success((iovs, read_size))\n}\n```"}], "func_name": "readv", "docstring": "Helper for dealing with a potential null pointer being passed to `*const iovec` from\n`readv_detour` and `preadv_detour`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/ops.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/ops.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00f96f5f4687c7f7e2a4fe2ce9c289d84bc630e107f1f0a3843093be2676add2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: nanos_to_statx\n\nDocumentation:\nConverts a nanosecond timestamp from\n[`MetadataInternal`](mirrord_protocol::file::MetadataInternal) to [`statx_timestamp`]\nformat.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn nanos_to_statx(nanos: i64) -> statx_timestamp {\n let duration = Duration::from_nanos(nanos.try_into().unwrap_or(0));\n\n // Safety: This is just initializing a C-type, we should be fine.\n let mut result = unsafe { mem::zeroed::() };\n result.tv_sec = duration.as_secs().try_into().unwrap_or(i64::MAX);\n result.tv_nsec = duration.subsec_nanos();\n\n result\n }\n```"}], "func_name": "nanos_to_statx", "docstring": "Converts a nanosecond timestamp from\n[`MetadataInternal`](mirrord_protocol::file::MetadataInternal) to [`statx_timestamp`]\nformat.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/ops.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/ops.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8a527d1d604dbd3619aae2f3bd81090a737e9de6f3c34b2f1f29015edc2bd9e1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: device_id_to_statx\n\nDocumentation:\nConverts a device id from [`MetadataInternal`](mirrord_protocol::file::MetadataInternal) to\nformat expected by [`statx`]: (major,minor) number.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn device_id_to_statx(id: u64) -> (u32, u32) {\n (libc::major(id), libc::minor(id))\n }\n```"}], "func_name": "device_id_to_statx", "docstring": "Converts a device id from [`MetadataInternal`](mirrord_protocol::file::MetadataInternal) to\nformat expected by [`statx`]: (major,minor) number.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/ops.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/ops.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "520038a59b40f36fd9a2a8321daedbc946a272e0c018c442f035fe840a07ff09"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: absolute_path\n\nDocumentation:\nResolves ./ and ../ in the path, and returns an absolute path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn absolute_path(path: PathBuf) -> PathBuf {\n use std::path::Component;\n let mut temp_path = PathBuf::new();\n temp_path.push(\"/\");\n for c in path.components() {\n match c {\n Component::RootDir => {}\n Component::CurDir => {}\n Component::Normal(p) => temp_path.push(p),\n Component::ParentDir => {\n temp_path.pop();\n }\n Component::Prefix(_) => {}\n }\n }\n temp_path\n}\n```"}], "func_name": "absolute_path", "docstring": "Resolves ./ and ../ in the path, and returns an absolute path.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/ops.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/ops.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b089ed36facb0debfca87e609d2f8cfe177bcca58613ba5eb9bc258357cd1bf7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: regex_set_builder\n\nDocumentation:\nThis is the list of path patterns that are read locally by default in all fs modes. If you want\nto read or write in the cluster a path covered by those patterns, you need to include it in a\npattern in the `feature.fs.read_only` or `feature.fs.read_write` configuration field,\nrespectively.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn regex_set_builder() -> RegexSetBuilder {\n let mut patterns: Vec = [\n r\".\\.so$\",\n r\".\\.d$\",\n r\".\\.pyc$\",\n r\".\\.py$\",\n r\".\\.jar$\",\n r\".\\.class$\",\n r\".\\.js$\",\n r\".\\.pth$\",\n r\".\\.plist$\",\n r\"venv\\.cfg$\",\n r\"^/proc(/|$)\",\n r\"^/sys(/|$)\",\n r\"^/lib(/|$)\",\n r\"^/etc(/|$)\",\n r\"^/usr(/|$)\",\n r\"^/home(/|$)\",\n r\"^/bin(/|$)\",\n r\"^/sbin(/|$)\",\n r\"^/dev(/|$)\",\n r\"^/opt(/|$)\",\n r\"^/tmp(/|$)\",\n r\"^/var/tmp(/|$)\",\n r\"^/snap(/|$)\",\n // support for nixOS.\n r\"^/nix(/|$)\",\n r\".+\\.asdf/.+\",\n r\"^/home/iojs(/|$)\",\n r\"^/home/runner(/|$)\",\n // dotnet: `/tmp/clr-debug-pipe-1`\n r\"clr-.*-pipe-\",\n // dotnet: `/home/{username}/{project}.pdb`\n r\"\\.pdb$\",\n // dotnet: `/home/{username}/{project}.dll`\n r\"\\.dll$\",\n // jvm.cfg or ANYTHING/jvm.cfg\n r\".*(^|/)jvm\\.cfg$\",\n // TODO: `node` searches for this file in multiple directories, bypassing some of our\n // ignore regexes, maybe other \"project runners\" will do the same.\n r\"/package\\.json$\",\n r\"/\\.yarnrc$\",\n r\"/\\.yarnrc.yml$\",\n r\"/\\.yarnrc.json$\",\n r\"/node_modules\",\n // asdf\n r\".*/\\.tool-versions$\",\n // macOS\n #[cfg(target_os = \"macos\")]\n \"^/Volumes(/|$)\",\n #[cfg(target_os = \"macos\")]\n r\"^/private(/|$)\",\n #[cfg(target_os = \"macos\")]\n r\"^/var/folders(/|$)\",\n #[cfg(target_os = \"macos\")]\n r\"^/Users\",\n #[cfg(target_os = \"macos\")]\n r\"^/Library\",\n #[cfg(target_os = \"macos\")]\n r\"^/Applications\",\n #[cfg(target_os = \"macos\")]\n r\"^/System\",\n #[cfg(target_os = \"macos\")]\n r\"^/var/run/com.apple\",\n #[cfg(target_os = \"macos\")]\n r\"^/Network\",\n // Any path under the standard temp directory.\n &format!(\"^{}\", regex::escape(&env::temp_dir().to_string_lossy())),\n \"^/$\", // root\n ]\n .iter()\n .map(|s| s.to_string())\n .collect();\n\n if let Ok(cwd) = env::current_dir() {\n patterns.push(format!(\n \"^{}(/|$)\",\n // We trim any trailing '/' and add it above, so that the regex is correct whether\n // current_dir returns a trailing '/' or not.\n regex::escape(cwd.to_string_lossy().trim_end_matches('/'))\n ));\n }\n if let Ok(executable) = env::current_exe() {\n patterns.push(format!(\"{}$\", regex::escape(&executable.to_string_lossy())));\n }\n\n // Hidden files and directories in $HOME.\n if let Ok(home) = env::var(\"HOME\") {\n patterns.push(format!(\n \"^{}/\\\\.\",\n regex::escape(home.trim_end_matches('/'))\n ))\n }\n\n RegexSetBuilder::new(patterns)\n}\n```"}], "func_name": "regex_set_builder", "docstring": "This is the list of path patterns that are read locally by default in all fs modes. If you want\nto read or write in the cluster a path covered by those patterns, you need to include it in a\npattern in the `feature.fs.read_only` or `feature.fs.read_write` configuration field,\nrespectively.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/file/filter/read_local_by_default.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/file/filter/read_local_by_default.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b39e6837749565f43c0fe72a6f5fe7541a3653288a6a492046a41a175dbad181"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mirrord_syscall_handler\n\nDocumentation:\nasmcgocall can pass a pointer, so this is a conversion call to `c_abi_syscall6_handler`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe extern \"C\" fn mirrord_syscall_handler(syscall_struct: *const SyscallArgs) -> i64 {\n c_abi_syscall6_handler(\n (*syscall_struct).syscall,\n (*syscall_struct).arg1,\n (*syscall_struct).arg2,\n (*syscall_struct).arg3,\n (*syscall_struct).arg4,\n (*syscall_struct).arg5,\n (*syscall_struct).arg6,\n )\n}\n```"}], "func_name": "mirrord_syscall_handler", "docstring": "asmcgocall can pass a pointer, so this is a conversion call to `c_abi_syscall6_handler`", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/go/linux_aarch64.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/go/linux_aarch64.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "03a5c67eca76b087586b8f26a77608ff339c2f35743c60d5acb63b4c7377a9cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: post_go1_19\n\nDocumentation:\nHooks for when hooking a go binary between 1.19 and 1.23\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn post_go1_19(hook_manager: &mut HookManager) {\n unsafe {\n FN_ASMCGOCALL = std::mem::transmute::<\n frida_gum::NativePointer,\n std::option::Option,\n >(\n hook_manager\n .resolve_symbol_main_module(\"runtime.asmcgocall\")\n .expect(\"found go but couldn't find runtime.asmcgocall please file a bug\"),\n );\n }\n hook_symbol!(\n hook_manager,\n \"runtime/internal/syscall.Syscall6.abi0\",\n go_syscall_new_detour\n );\n}\n```"}], "func_name": "post_go1_19", "docstring": "Hooks for when hooking a go binary between 1.19 and 1.23", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/go/linux_aarch64.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/go/linux_aarch64.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "042668e6971123713e13b3b88711304a6f4f740329886cb07cb418f2f4a58f26"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: post_go1_23\n\nDocumentation:\nHooks for when hooking a post go 1.23 binary\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn post_go1_23(hook_manager: &mut HookManager) {\n unsafe {\n FN_ASMCGOCALL = std::mem::transmute::<\n frida_gum::NativePointer,\n std::option::Option,\n >(\n hook_manager\n .resolve_symbol_main_module(\"runtime.asmcgocall\")\n .expect(\"found go but couldn't find runtime.asmcgocall please file a bug\"),\n );\n }\n hook_symbol!(\n hook_manager,\n \"internal/runtime/syscall.Syscall6.abi0\",\n go_syscall_new_detour\n );\n}\n```"}], "func_name": "post_go1_23", "docstring": "Hooks for when hooking a post go 1.23 binary", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/go/linux_aarch64.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/go/linux_aarch64.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "422f08be7e58f0edf87f08940e50578635385c9bb061449ba5ea8a5768dec25c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: enable_hooks\n\nDocumentation:\nNote: We only hook \"RawSyscall\", \"Syscall6\", and \"Syscall\" because for our usecase,\nwhen testing with \"Gin\", only these symbols were used to make syscalls.\nRefer:\n- File zsyscall_linux_amd64.go generated using mksyscall.pl.\n- \n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn enable_hooks(hook_manager: &mut HookManager) {\n if let Some(version_symbol) =\n hook_manager.resolve_symbol_main_module(\"runtime.buildVersion.str\")\n {\n // Version str is `go1.xx` - take only last 4 characters.\n let version = unsafe {\n std::str::from_utf8_unchecked(std::slice::from_raw_parts(\n version_symbol.0.add(2) as *const u8,\n 4,\n ))\n };\n let version_parsed: f32 = version.parse().unwrap();\n if version_parsed >= 1.23 {\n trace!(\"found version >= 1.23\");\n post_go1_23(hook_manager);\n } else if version_parsed >= 1.19 {\n trace!(\"found version >= 1.19\");\n post_go1_19(hook_manager);\n } else {\n trace!(\"found version < 1.19, arm64 not supported - not hooking\");\n }\n }\n}\n```"}], "func_name": "enable_hooks", "docstring": "Note: We only hook \"RawSyscall\", \"Syscall6\", and \"Syscall\" because for our usecase,\nwhen testing with \"Gin\", only these symbols were used to make syscalls.\nRefer:\n- File zsyscall_linux_amd64.go generated using mksyscall.pl.\n- ", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/go/linux_aarch64.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/go/linux_aarch64.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f538dcbe5e34bc3b039fef3fe6fb8ac6dc853f311ad9522f0d30e5d60be0e6a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pre_go1_19\n\nDocumentation:\nHooks for when hooking a pre go 1.19 binary\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn pre_go1_19(hook_manager: &mut HookManager) {\n hook_symbol!(\n hook_manager,\n \"syscall.RawSyscall.abi0\",\n go_rawsyscall_detour\n );\n hook_symbol!(hook_manager, \"syscall.Syscall6.abi0\", go_syscall6_detour);\n hook_symbol!(hook_manager, \"syscall.Syscall.abi0\", go_syscall_detour);\n}\n```"}], "func_name": "pre_go1_19", "docstring": "Hooks for when hooking a pre go 1.19 binary", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/go/linux_x64.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/go/linux_x64.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "263a7830624d016cea5a15fe961f2089b547a4294eb66424d7bb684f056b0f7c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_ignored_tcp_port\n\nDocumentation:\nChecks if given TCP port needs to be ignored\nbased on http_filter/ports logic\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_ignored_tcp_port(addr: &SocketAddr, config: &IncomingConfig) -> bool {\n let mapped_port = crate::setup()\n .incoming_config()\n .port_mapping\n .get_by_left(&addr.port())\n .copied()\n .unwrap_or_else(|| addr.port());\n let http_filter_used = config.mode == IncomingMode::Steal && config.http_filter.is_filter_set();\n\n // this is a bit weird but it makes more sense configured ports are the remote port\n // and not the local, so the check is done on the mapped port\n // see https://github.com/metalbear-co/mirrord/issues/2397\n let not_a_filtered_port = config\n .http_filter\n .ports\n .as_ref()\n .is_some_and(|filter_ports| filter_ports.contains(&mapped_port))\n .not();\n\n let not_stolen_with_filter = !http_filter_used || not_a_filtered_port;\n\n // Unfiltered ports were specified and the requested port is not one of them, or an HTTP filter\n // is set and no unfiltered ports were specified.\n let not_whitelisted = config\n .ports\n .as_ref()\n .map(|ports| !ports.contains(&mapped_port))\n .unwrap_or(http_filter_used);\n\n is_ignored_port(addr) || (not_stolen_with_filter && not_whitelisted)\n}\n```"}], "func_name": "is_ignored_tcp_port", "docstring": "Checks if given TCP port needs to be ignored\nbased on http_filter/ports logic", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/socket/ops.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/socket/ops.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e86e74fd0f8c5cae20d68ffa9c96d94571f084622ee1f9c6177f63490bf7b244"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: warn_on_suspected_unintentional_ignore\n\nDocumentation:\nWarn the user if they are filtering HTTP, and it looks like they might have intended to also\nsteal another port unfiltered, but didn't know they had to set `feature.network.incoming.ports`\nfor that.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn warn_on_suspected_unintentional_ignore(sockfd: RawFd) {\n let incoming_config = crate::setup().incoming_config();\n let http_filter_used =\n incoming_config.mode == IncomingMode::Steal && incoming_config.http_filter.is_filter_set();\n\n // User specified a filter that does not include this port, and did not specify any\n // unfiltered ports?\n // It's plausible that the user did not know the port has to be in either port list to be\n // stolen when an HTTP filter is set, so show a warning.\n if http_filter_used && incoming_config.ports.is_none() {\n let port_text = if let Some(port) = nix::sys::socket::getsockname::(sockfd)\n .inspect_err(|err| {\n tracing::debug!(\n \"Calling getsockname failed. Ignoring as this is not critical. Error: {err:?}.\"\n )\n })\n .ok()\n .and_then(|addr_storage| {\n addr_storage\n .as_sockaddr_in()\n .map(SockaddrIn::port)\n .or_else(|| addr_storage.as_sockaddr_in6().map(SockaddrIn6::port))\n }) {\n if let Some(mapped_port) = incoming_config.port_mapping.get_by_left(&port) {\n format!(\"Remote port {mapped_port} (mapped from local port {port})\",)\n } else {\n format!(\"Port {port}\")\n }\n } else {\n // `getsockname` returned an error, or a non-IP address. Not stopping execution on\n // that, as it does not mean anything else went wrong in this run. Just emitting a\n // warning without the port number.\n tracing::debug!(\"Could not determine the bound port of a socket, for the purpose of displaying it in a warning.\");\n \"A port\".to_string()\n };\n warn!(\n \"{port_text} was not included in the filtered ports, and also not in the non-filtered \\\n ports, and will therefore be bound locally. If this is intentional, ignore this \\\n warning. If you want the http filter to apply to this port, add it to \\\n `feature.network.incoming.http_filter.ports`. \\\n If you want to steal all the traffic of this port, add it to \\\n `feature.network.incoming.ports`.\"\n );\n }\n}\n```"}], "func_name": "warn_on_suspected_unintentional_ignore", "docstring": "Warn the user if they are filtering HTTP, and it looks like they might have intended to also\nsteal another port unfiltered, but didn't know they had to set `feature.network.incoming.ports`\nfor that.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/socket/ops.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/socket/ops.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f97c51fcda7028b00b7ef488f993c5b84c37414dc2a0f9012a2c8da3fb96cb91"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remote_hostname_string\n\nDocumentation:\nRetrieves the `hostname` from the agent's `/etc/hostname` to be used by [`gethostname`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn remote_hostname_string() -> Detour {\n if crate::setup().local_hostname() {\n Detour::Bypass(Bypass::LocalHostname)?;\n }\n\n let hostname_path = PathBuf::from(\"/etc/hostname\");\n\n let OpenFileResponse { fd } = file::ops::RemoteFile::remote_open(\n hostname_path,\n OpenOptionsInternal {\n read: true,\n ..Default::default()\n },\n )?;\n\n let ReadFileResponse { bytes, read_amount } = file::ops::RemoteFile::remote_read(fd, 256)?;\n\n let _ = file::ops::RemoteFile::remote_close(fd).inspect_err(|fail| {\n trace!(\"Leaking remote file fd (should be harmless) due to {fail:#?}!\")\n });\n\n CString::new(\n bytes\n .into_iter()\n .take(read_amount as usize - 1)\n .collect::>(),\n )\n .map(Detour::Success)?\n}\n```"}], "func_name": "remote_hostname_string", "docstring": "Retrieves the `hostname` from the agent's `/etc/hostname` to be used by [`gethostname`]", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/src/socket/ops.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/src/socket/ops.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b1c1ca32bca7f657756e4d832af4e171e5dfa659038067c9e1e4ca0913ec3d14"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: outgoing_tcp_logic\n\nDocumentation:\nTest outgoing TCP.\nApplication, for each remote peer in [`RUST_OUTGOING_PEERS`]:\n1. Opens a TCP port at [`RUST_OUTGOING_LOCAL`]\n2. Connects to the remote peer\n3. Sends some data\n4. Expects the peer to send the same data back\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn outgoing_tcp_logic(with_config: Option<&str>, dylib_path: &Path, config_dir: &Path) {\n let config = with_config.map(|config| {\n let mut config_path = config_dir.to_path_buf();\n config_path.push(config);\n config_path\n });\n\n let (mut test_process, mut intproxy) = Application::RustOutgoingTcp\n .start_process_with_layer(dylib_path, vec![], config.as_deref())\n .await;\n\n let peers = RUST_OUTGOING_PEERS\n .split(',')\n .map(|s| s.parse::().unwrap())\n .collect::>();\n\n for peer in peers {\n let msg = intproxy.recv().await;\n let ClientMessage::TcpOutgoing(LayerTcpOutgoing::Connect(LayerConnect {\n remote_address: SocketAddress::Ip(addr),\n })) = msg\n else {\n panic!(\"Invalid message received from layer: {msg:?}\");\n };\n assert_eq!(addr, peer);\n intproxy\n .send(DaemonMessage::TcpOutgoing(DaemonTcpOutgoing::Connect(Ok(\n DaemonConnect {\n connection_id: 0,\n remote_address: addr.into(),\n local_address: RUST_OUTGOING_LOCAL.parse::().unwrap().into(),\n },\n ))))\n .await;\n\n let msg = intproxy.recv().await;\n let ClientMessage::TcpOutgoing(LayerTcpOutgoing::Write(LayerWrite {\n connection_id: 0,\n bytes,\n })) = msg\n else {\n panic!(\"Invalid message received from layer: {msg:?}\");\n };\n intproxy\n .send(DaemonMessage::TcpOutgoing(DaemonTcpOutgoing::Read(Ok(\n DaemonRead {\n connection_id: 0,\n bytes,\n },\n ))))\n .await;\n intproxy\n .send(DaemonMessage::TcpOutgoing(DaemonTcpOutgoing::Close(0)))\n .await;\n }\n\n test_process.wait_assert_success().await;\n}\n```"}], "func_name": "outgoing_tcp_logic", "docstring": "Test outgoing TCP.\nApplication, for each remote peer in [`RUST_OUTGOING_PEERS`]:\n1. Opens a TCP port at [`RUST_OUTGOING_LOCAL`]\n2. Connects to the remote peer\n3. Sends some data\n4. Expects the peer to send the same data back", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/outgoing.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/outgoing.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d1bce5e490cdbb0f0f95712e5b1359a924ec24de3b0e38a1a3872c334e5d4c49"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: symlink_app\n\nDocumentation:\nCreates a new [`Application`], which is a symlink to the existing executable.\nThe link is created in the temporary directory and its name is randomized.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn symlink_app(app: &Application) -> Application {\n let path = temp_dir().join(format!(\"test-dynamic-app-{}\", rand::random::()));\n println!(\"{}\", app.get_executable().await);\n\n fs::symlink(app.get_executable().await, &path).expect(\"failed to create executable symlink\");\n\n Application::DynamicApp(path.to_str().unwrap().to_string(), vec![])\n}\n```"}], "func_name": "symlink_app", "docstring": "Creates a new [`Application`], which is a symlink to the existing executable.\nThe link is created in the temporary directory and its name is randomized.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/skipping_process.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/skipping_process.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e46dcad23747a5e405bfb3e4ade417886ab252c42fc13e4207cd15d7ecf77397"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: main\n\nDocumentation:\nTests that cloned TCP listener works fine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn main() {\n println!(\"test issue 1054: START\");\n let address: SocketAddr = \"0.0.0.0:80\".parse().expect(\"failed to bind\");\n let listener = TcpListener::bind(address).unwrap();\n let cloned = listener\n .try_clone()\n .expect(\"failed to clone listneer\");\n\n assert_eq!(listener.local_addr().unwrap(), address);\n assert_eq!(listener.local_addr().unwrap(), cloned.local_addr().unwrap());\n\n let (mut connection, _) = cloned\n .accept()\n .inspect_err(|fail| {\n eprintln!(\"Failed accept operation for cloned listener with {fail:#?}!\")\n })\n .expect(\"failed to accept\");\n\n // Note - if we just open the connection and immediately close it on the other side,\n // intproxy may clean up its metadata before the layer has a chance to fetch it.\n // This fails the `local_addr` assert below. Hence, we send some data first.\n let mut buf = [0_u8; 16];\n let bytes_read = connection.read(&mut buf).expect(\"failed to read\");\n assert_eq!(bytes_read, 5);\n assert_eq!(&buf[..bytes_read], b\"hello\");\n\n assert_eq!(\n connection.local_addr().unwrap(),\n \"1.1.1.1:80\".parse().unwrap()\n );\n\n println!(\"test issue 1054: SUCCESS\");\n}\n```"}], "func_name": "main", "docstring": "Tests that cloned TCP listener works fine.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/apps/issue1054/issue1054.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/apps/issue1054/issue1054.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c813f28e74615ab82288ac168cf26eabe75962abe6d32cd64a19f5f58ea7c8ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: main\n\nDocumentation:\nTest that double binding on the same address:port combination fails the second time around.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn main() {\n println!(\"test issue 1123: START\");\n let localhost: SocketAddr = \"127.0.0.1:41222\".parse().unwrap();\n let _listener_1 = TcpListener::bind(localhost).expect(\"first bind failed\");\n TcpListener::bind(localhost).expect_err(\"second bind did not fail!\");\n println!(\"test issue 1123: SUCCESS\");\n}\n```"}], "func_name": "main", "docstring": "Test that double binding on the same address:port combination fails the second time around.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/apps/issue1123/issue1123.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/apps/issue1123/issue1123.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "273ede9e1b00f5eaed8018350779950f665e4b9f03cc2a087526c3b81f56d6cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: main\n\nDocumentation:\nTest that java [`netty`](https://netty.io/) can resolve DNS with UDP `send_to` and `recv_from`.\n\nUsing a rust sample to simplify testing this.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn main() {\n println!(\"test issue 1458: START\");\n\n let local_addr: SocketAddr = \"127.0.0.1:0\".parse().unwrap();\n let remote_addr: SocketAddr = \"1.2.3.4:53\".parse().unwrap();\n\n let socket = UdpSocket::bind(local_addr).unwrap();\n\n // mirrord should intercept this\n let amount = socket.send_to(&vec![0; 1], remote_addr).unwrap();\n assert_eq!(amount, 1);\n\n let mut recv_buffer = vec![0; 1];\n let (amount, remote) = socket.recv_from(&mut recv_buffer).unwrap();\n assert_eq!(amount, 1);\n assert_eq!(remote_addr, remote);\n assert_eq!(recv_buffer, vec![1; 1]);\n\n println!(\"test issue 1458: SUCCESS\");\n}\n```"}], "func_name": "main", "docstring": "Test that java [`netty`](https://netty.io/) can resolve DNS with UDP `send_to` and `recv_from`.\n\nUsing a rust sample to simplify testing this.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/apps/issue1458/issue1458.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/apps/issue1458/issue1458.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "871bed739db57a166959bd620f57a79db1b36e68647d0998900e6b990f51347a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: main\n\nDocumentation:\nCounterpart test for issue 1458, where we check that mirrord doesn't intercept UDP when `sendto`\nis used on a port other than `53`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn main() {\n println!(\"test issue 1458 port not 53: START\");\n\n let unbound_local_addr: SocketAddr = \"127.0.0.1:0\".parse().unwrap();\n let unbound_remote_addr: SocketAddr = \"127.0.0.1:7777\".parse().unwrap();\n\n let socket = UdpSocket::bind(unbound_local_addr).unwrap();\n let recv_socket = UdpSocket::bind(unbound_remote_addr).unwrap();\n println!(\"socket {socket:?} and recv {recv_socket:?} are bound\");\n\n let local_addr = socket.local_addr().unwrap();\n let remote_addr = recv_socket.local_addr().unwrap();\n\n assert_eq!(\n local_addr,\n SocketAddr::new(unbound_local_addr.ip(), local_addr.port())\n );\n assert_eq!(remote_addr, unbound_remote_addr);\n\n let recv_thread = std::thread::spawn(move || {\n let mut recv_buffer = vec![0; 1];\n let (amount, remote) = recv_socket.recv_from(&mut recv_buffer).unwrap();\n assert_eq!(amount, 1);\n assert_ne!(remote_addr, remote);\n assert_eq!(local_addr, remote);\n assert_eq!(recv_buffer, vec![0; 1]);\n });\n\n // mirrord should NOT intercept this\n let amount = socket.send_to(&vec![0; 1], remote_addr).unwrap();\n assert_eq!(amount, 1);\n\n recv_thread.join().unwrap();\n\n println!(\"test issue 1458 port not 53: SUCCESS\");\n}\n```"}], "func_name": "main", "docstring": "Counterpart test for issue 1458, where we check that mirrord doesn't intercept UDP when `sendto`\nis used on a port other than `53`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/apps/issue1458portnot53/issue1458portnot53.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/apps/issue1458portnot53/issue1458portnot53.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9d4cc9b00813cd585e8527671ce27e4d153f19f5ab2ed95b84bcdc1df50e7c5b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: main\n\nDocumentation:\nTest that C# `mongodb+srv` protocol can resolve DNS with udp `sendmsg` and `recvmsg`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn main() {\n println!(\"test issue 1776: START\");\n\n let local_addr: SocketAddr = \"127.0.0.1:0\".parse().unwrap();\n let remote_addr: SocketAddr = \"1.2.3.4:53\".parse().unwrap();\n\n let socket = UdpSocket::bind(local_addr).unwrap();\n let socket_fd = socket.as_raw_fd();\n\n // mirrord should intercept this\n unsafe {\n let mut outgoing_msg_hdr: libc::msghdr = mem::zeroed();\n\n let rawish_remote_addr = SockAddr::from(remote_addr);\n let remote_addr_ptr = rawish_remote_addr.as_ptr() as *mut c_void;\n let remote_addr_len = rawish_remote_addr.len();\n\n outgoing_msg_hdr.msg_name = remote_addr_ptr;\n outgoing_msg_hdr.msg_namelen = remote_addr_len;\n\n let bytes = &mut [0u8, 1, 2, 3];\n let bytes_ptr = bytes.as_mut_ptr() as *mut c_void;\n let mut iov = iovec {\n iov_base: bytes_ptr,\n iov_len: 4,\n };\n\n outgoing_msg_hdr.msg_iov = &mut iov;\n outgoing_msg_hdr.msg_iovlen = 1;\n\n let amount = libc::sendmsg(socket_fd, &outgoing_msg_hdr, 0);\n assert_eq!(amount, 4, \"with errno {}\", errno::errno());\n\n let mut incoming_msg_hdr: libc::msghdr = mem::zeroed();\n let incoming_name =\n alloc::alloc_zeroed(Layout::array::(size_of::()).unwrap())\n as *mut _;\n let incoming_name_len = remote_addr_len;\n\n incoming_msg_hdr.msg_name = incoming_name;\n incoming_msg_hdr.msg_namelen = incoming_name_len;\n\n let recv_buffer = &mut vec![0u8; 4];\n let recv_buffer_ptr = recv_buffer.as_mut_ptr() as *mut c_void;\n let mut iov = iovec {\n iov_base: recv_buffer_ptr,\n iov_len: recv_buffer.len(),\n };\n\n incoming_msg_hdr.msg_iov = &mut iov;\n incoming_msg_hdr.msg_iovlen = 1;\n\n let amount = libc::recvmsg(socket_fd, &mut incoming_msg_hdr, 0);\n\n let raw_incoming_addr = incoming_msg_hdr.msg_name as *const libc::sockaddr;\n let raw_incoming_addr_len = incoming_msg_hdr.msg_namelen;\n let incoming_addr = address_from_raw(raw_incoming_addr, raw_incoming_addr_len).unwrap();\n assert_eq!(amount, 4, \"with errno {}\", errno::errno());\n assert_eq!(incoming_addr, remote_addr);\n }\n\n println!(\"test issue 1776: SUCCESS\");\n}\n```"}], "func_name": "main", "docstring": "Test that C# `mongodb+srv` protocol can resolve DNS with udp `sendmsg` and `recvmsg`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/apps/issue1776/src/main.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/apps/issue1776/src/main.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1dada81fca3962ef423fc66603fb12d23eae10849e1c4f4087d14fb5d25590df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init_tracing\n\nDocumentation:\nInitializes tracing for the current thread, allowing us to have multiple tracing subscribers\nwritin logs to different files.\n\nWe take advantage of how Rust's thread naming scheme for tests to create the log files,\nand if we have no thread name, then we just write the logs to `stderr`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn init_tracing() -> DefaultGuard {\n let subscriber = tracing_subscriber::fmt()\n .with_env_filter(EnvFilter::new(\"mirrord=trace\"))\n .without_time()\n .with_ansi(false)\n .with_file(true)\n .with_line_number(true)\n .with_span_events(FmtSpan::ACTIVE)\n .pretty();\n\n // Sets the default subscriber for the _current thread_, returning a guard that unsets\n // the default subscriber when it is dropped.\n match std::thread::current()\n .name()\n .map(|name| name.replace(':', \"_\"))\n {\n Some(test_name) => {\n let mut logs_file = PathBuf::from(\"/tmp/intproxy_logs\");\n\n #[cfg(target_os = \"macos\")]\n logs_file.push(\"macos\");\n #[cfg(not(target_os = \"macos\"))]\n logs_file.push(\"linux\");\n\n let _ = std::fs::create_dir_all(&logs_file).ok();\n\n logs_file.push(&test_name);\n match File::create(&logs_file) {\n // Writes the logs to the file.\n Ok(file) => {\n println!(\"Created intproxy log file: {}\", logs_file.display());\n let subscriber = subscriber.with_writer(Arc::new(file)).finish();\n tracing::subscriber::set_default(subscriber)\n }\n // File creation failure makes the output go to `stderr`.\n Err(error) => {\n println!(\"Failed to create intproxy log file at {}: {error}. Intproxy logs will be flushed to stderr\", logs_file.display());\n let subscriber = subscriber.with_writer(io::stderr).finish();\n tracing::subscriber::set_default(subscriber)\n }\n }\n }\n // No thread name makes the output go to `stderr`.\n None => {\n println!(\n \"Failed to obtain current thread name, intproxy logs will be flushed to stderr\"\n );\n let subscriber = subscriber.with_writer(io::stderr).finish();\n tracing::subscriber::set_default(subscriber)\n }\n }\n}\n```"}], "func_name": "init_tracing", "docstring": "Initializes tracing for the current thread, allowing us to have multiple tracing subscribers\nwritin logs to different files.\n\nWe take advantage of how Rust's thread naming scheme for tests to create the log files,\nand if we have no thread name, then we just write the logs to `stderr`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "14539d34b3759949b64ec70cc596ef7024ff280acedf04be764c8fa049319aea"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_gethostname\n\nDocumentation:\nHandles the `gethostname` hook that fiddles with the agent's file system by opening\n`/etc/hostname` remotely.\n\nThis hook leverages our ability of opening a file on the agent's `FileManager` to `open`,\n`read`, and `close` the `/etc/hostname` file, and thus some of the integration tests that\nrely on hostname resolving must handle these messages before we resume the normal flow for\nmirroring/stealing/outgoing traffic.\n\n## Args\n\n- `FIRST_CALL`: some tests will consume the first message from [`Self::codec`], so we use\nthis `const` to check if we should call `codec.next` or if it was already called for us.\nIf you're using [`LayerConnection::get_initialized_connection_with_port`], you should set\nthis to `false`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn handle_gethostname(\n &mut self,\n app_port: Option,\n ) -> Option<()> {\n // Should we call `codec.next` or was it called outside already?\n if FIRST_CALL {\n // open file\n let open_file_request = self.recv().await;\n\n assert_eq!(\n open_file_request,\n ClientMessage::FileRequest(FileRequest::Open(OpenFileRequest {\n path: PathBuf::from(\"/etc/hostname\"),\n open_options: OpenOptionsInternal {\n read: true,\n write: false,\n append: false,\n truncate: false,\n create: false,\n create_new: false\n }\n }))\n );\n }\n self.answer_file_open().await;\n\n // read file\n let read_request = self\n .codec\n .next()\n .await\n .expect(\"Read request success!\")\n .expect(\"Read request exists!\");\n assert_eq!(\n read_request,\n ClientMessage::FileRequest(FileRequest::Read(ReadFileRequest {\n remote_fd: 0xb16,\n buffer_size: 256,\n }))\n );\n\n self.answer_file_read(b\"metalbear-hostname\".to_vec()).await;\n\n // TODO(alex): Add a wait time here, we can end up in the \"Close request success\" error.\n // close file (very rarely?).\n let close_request = self\n .codec\n .next()\n .await\n .expect(\"Close request success!\")\n .expect(\"Close request exists!\");\n\n println!(\"Should be a close file request: {close_request:#?}\");\n assert_eq!(\n close_request,\n ClientMessage::FileRequest(FileRequest::Close(\n mirrord_protocol::file::CloseFileRequest { fd: 0xb16 }\n ))\n );\n\n let port = app_port?;\n let port_subscribe = self\n .codec\n .next()\n .await\n .expect(\"PortSubscribe request success!\")\n .expect(\"PortSubscribe request exists!\");\n assert_eq!(\n port_subscribe,\n ClientMessage::Tcp(LayerTcp::PortSubscribe(port))\n );\n\n self.codec\n .send(DaemonMessage::Tcp(DaemonTcp::SubscribeResult(Ok(port))))\n .await\n .expect(\"failed to send PortSubscribe result\");\n\n Some(())\n }\n```"}], "func_name": "handle_gethostname", "docstring": "Handles the `gethostname` hook that fiddles with the agent's file system by opening\n`/etc/hostname` remotely.\n\nThis hook leverages our ability of opening a file on the agent's `FileManager` to `open`,\n`read`, and `close` the `/etc/hostname` file, and thus some of the integration tests that\nrely on hostname resolving must handle these messages before we resume the normal flow for\nmirroring/stealing/outgoing traffic.\n\n## Args\n\n- `FIRST_CALL`: some tests will consume the first message from [`Self::codec`], so we use\nthis `const` to check if we should call `codec.next` or if it was already called for us.\nIf you're using [`LayerConnection::get_initialized_connection_with_port`], you should set\nthis to `false`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e516b5685ca0098edb4f43dfb4fc1a374c982c52ad204b6e15cfea71b831b440"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_new_connection\n\nDocumentation:\nSend the layer a message telling it the target got a new incoming connection.\nThere is no such actual connection, because there is no target, but the layer should start\na mirror connection with the application.\nReturn the id of the new connection.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn send_new_connection(&mut self, port: u16) -> u64 {\n let new_connection_id = self.num_connections;\n self.codec\n .send(DaemonMessage::Tcp(DaemonTcp::NewConnectionV1(\n NewTcpConnectionV1 {\n connection_id: new_connection_id,\n remote_address: \"127.0.0.1\".parse().unwrap(),\n destination_port: port,\n source_port: \"31415\".parse().unwrap(),\n local_address: \"1.1.1.1\".parse().unwrap(),\n },\n )))\n .await\n .unwrap();\n self.num_connections += 1;\n new_connection_id\n }\n```"}], "func_name": "send_new_connection", "docstring": "Send the layer a message telling it the target got a new incoming connection.\nThere is no such actual connection, because there is no target, but the layer should start\na mirror connection with the application.\nReturn the id of the new connection.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "343efc0372b312f77e07cdf69777537948abd1541fce529f6ee034bee658dcde"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_connection_then_data\n\nDocumentation:\nTell the layer there is a new incoming connection, then send data \"from that connection\".\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn send_connection_then_data(&mut self, message_data: &str, port: u16) {\n let new_connection_id = self.send_new_connection(port).await;\n self.send_tcp_data(message_data, new_connection_id).await;\n self.send_close(new_connection_id).await;\n }\n```"}], "func_name": "send_connection_then_data", "docstring": "Tell the layer there is a new incoming connection, then send data \"from that connection\".", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d04de152158de69c0ca71272d8a778d0a1e28ae7a7bca4dd533e89a4c6a2b389"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_file_open_for_reading\n\nDocumentation:\nVerify layer hooks an `open` of file `file_name` with only read flag set. Send back answer\nwith given `fd`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_file_open_for_reading(&mut self, file_name: &str, fd: u64) {\n self.expect_file_open_with_options(\n file_name,\n fd,\n OpenOptionsInternal {\n read: true,\n write: false,\n append: false,\n truncate: false,\n create: false,\n create_new: false,\n },\n )\n .await\n }\n```"}], "func_name": "expect_file_open_for_reading", "docstring": "Verify layer hooks an `open` of file `file_name` with only read flag set. Send back answer\nwith given `fd`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "af333a15ccd53409b11d0f710cfea51e4474805fc7ec35a35673391075bc6ff7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_file_open_with_read_flag\n\nDocumentation:\nVerify layer hooks an `open` of file `file_name` with read flag set, and any other flags.\nSend back answer with given `fd`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_file_open_with_read_flag(&mut self, file_name: &str, fd: u64) {\n // Verify the app tries to open the expected file.\n assert_matches!(\n self.recv().await,\n ClientMessage::FileRequest(FileRequest::Open(\n mirrord_protocol::file::OpenFileRequest {\n path,\n open_options: OpenOptionsInternal { read: true, .. },\n }\n )) if path.to_str().unwrap() == file_name\n );\n\n // Answer open.\n self.codec\n .send(DaemonMessage::File(mirrord_protocol::FileResponse::Open(\n Ok(mirrord_protocol::file::OpenFileResponse { fd }),\n )))\n .await\n .unwrap();\n }\n```"}], "func_name": "expect_file_open_with_read_flag", "docstring": "Verify layer hooks an `open` of file `file_name` with read flag set, and any other flags.\nSend back answer with given `fd`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18264f5914dfeca0a56b5f465a12115096a9c9e592b1340ad385386d4d42ec5e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_file_open_for_writing\n\nDocumentation:\nVerify layer hooks an `open` of file `file_name` with write, truncate and create flags set.\nSend back answer with given `fd`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_file_open_for_writing(&mut self, file_name: &str, fd: u64) {\n self.expect_file_open_with_options(\n file_name,\n fd,\n OpenOptionsInternal {\n read: true,\n write: true,\n append: false,\n truncate: true,\n create: true,\n create_new: false,\n },\n )\n .await\n }\n```"}], "func_name": "expect_file_open_for_writing", "docstring": "Verify layer hooks an `open` of file `file_name` with write, truncate and create flags set.\nSend back answer with given `fd`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e7940f107f444e8cd91fbebac9bd0c1fb50dde1066d993ebdc2922a960b1337c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_file_open_with_options\n\nDocumentation:\nVerify layer hooks an `open` of file `file_name` with given open options, send back answer\nwith given `fd`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_file_open_with_options(\n &mut self,\n file_name: &str,\n fd: u64,\n open_options: OpenOptionsInternal,\n ) {\n // Verify the app tries to open the expected file.\n assert_eq!(\n self.recv().await,\n ClientMessage::FileRequest(FileRequest::Open(\n mirrord_protocol::file::OpenFileRequest {\n path: file_name.to_string().into(),\n open_options,\n }\n ))\n );\n\n // Answer open.\n self.codec\n .send(DaemonMessage::File(mirrord_protocol::FileResponse::Open(\n Ok(mirrord_protocol::file::OpenFileResponse { fd }),\n )))\n .await\n .unwrap();\n }\n```"}], "func_name": "expect_file_open_with_options", "docstring": "Verify layer hooks an `open` of file `file_name` with given open options, send back answer\nwith given `fd`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4eef818d7669fc8af5b76b7ea756abf73930cdb76d67afa1f83e5a5e0c6ab7e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_file_open_with_whatever_options\n\nDocumentation:\nLike the other expect_file_open_... but where we don't compare to predefined open options.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_file_open_with_whatever_options(&mut self, file_name: &str, fd: u64) {\n // Verify the app tries to open the expected file.\n assert_matches!(\n self.recv().await,\n ClientMessage::FileRequest(FileRequest::Open(\n mirrord_protocol::file::OpenFileRequest {\n path,\n open_options: _,\n }\n )) if path.to_str().unwrap() == file_name\n );\n\n // Answer open.\n self.codec\n .send(DaemonMessage::File(mirrord_protocol::FileResponse::Open(\n Ok(mirrord_protocol::file::OpenFileResponse { fd }),\n )))\n .await\n .unwrap();\n }\n```"}], "func_name": "expect_file_open_with_whatever_options", "docstring": "Like the other expect_file_open_... but where we don't compare to predefined open options.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b90a0119a2c7508a92818fb2d1cd921dd22dae9277bef0271eaf98c4fe5c8041"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_read_link\n\nDocumentation:\nMakes a [`FileRequest::ReadLink`], and answers it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_read_link(&mut self, file_name: &str) {\n // Expecting `readlink` call with path.\n assert_matches!(\n self.recv().await,\n ClientMessage::FileRequest(FileRequest::ReadLink(\n mirrord_protocol::file::ReadLinkFileRequest { path }\n )) if path.to_str().unwrap() == file_name\n );\n\n // Answer `readlink`.\n self.codec\n .send(DaemonMessage::File(\n mirrord_protocol::FileResponse::ReadLink(Ok(\n mirrord_protocol::file::ReadLinkFileResponse {\n path: PathBuf::from_str(\"/gatos/rajado.txt\")\n .expect(\"Valid path `rajado.txt`!\"),\n },\n )),\n ))\n .await\n .unwrap();\n }\n```"}], "func_name": "expect_read_link", "docstring": "Makes a [`FileRequest::ReadLink`], and answers it.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "245080943c59a35e911efad3971268b95b9915e478e06222c0249dc78a97b63e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_make_dir\n\nDocumentation:\nMakes a [`FileRequest::MakeDir`] and answers it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_make_dir(&mut self, expected_dir_name: &str, expected_mode: u32) {\n // Expecting `mkdir` call with path.\n assert_matches!(\n self.recv().await,\n ClientMessage::FileRequest(FileRequest::MakeDir(\n mirrord_protocol::file::MakeDirRequest { pathname, mode }\n )) if pathname.to_str().unwrap() == expected_dir_name && mode == expected_mode\n );\n\n // Answer `mkdir`.\n self.codec\n .send(DaemonMessage::File(\n mirrord_protocol::FileResponse::MakeDir(Ok(())),\n ))\n .await\n .unwrap();\n }\n```"}], "func_name": "expect_make_dir", "docstring": "Makes a [`FileRequest::MakeDir`] and answers it.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "670b2064c02648b43a198a478627990afa44d4700d8d6caa08bb4b39fe4d66cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_statfs\n\nDocumentation:\nMakes a [`FileRequest::Statefs`] and answers it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_statfs(&mut self, expected_path: &str) {\n // Expecting `statfs` call with path.\n assert_matches!(\n self.recv().await,\n ClientMessage::FileRequest(FileRequest::StatFsV2(\n mirrord_protocol::file::StatFsRequestV2 { path }\n )) if path.to_str().unwrap() == expected_path\n );\n\n // Answer `statfs`.\n self.codec\n .send(DaemonMessage::File(FileResponse::XstatFsV2(Ok(\n XstatFsResponseV2 {\n metadata: Default::default(),\n },\n ))))\n .await\n .unwrap();\n }\n```"}], "func_name": "expect_statfs", "docstring": "Makes a [`FileRequest::Statefs`] and answers it.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9c0ec261f7dcc2f7b4d7e3ccc1f8613cba191d820f17125d9c7afea35ab6257"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_fstatfs\n\nDocumentation:\nMakes a [`FileRequest::Xstatefs`] and answers it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_fstatfs(&mut self, expected_fd: u64) {\n // Expecting `fstatfs` call with path.\n assert_matches!(\n self.recv().await,\n ClientMessage::FileRequest(FileRequest::XstatFsV2(\n mirrord_protocol::file::XstatFsRequestV2 { fd }\n )) if expected_fd == fd\n );\n\n // Answer `fstatfs`.\n self.codec\n .send(DaemonMessage::File(FileResponse::XstatFsV2(Ok(\n XstatFsResponseV2 {\n metadata: Default::default(),\n },\n ))))\n .await\n .unwrap();\n }\n```"}], "func_name": "expect_fstatfs", "docstring": "Makes a [`FileRequest::Xstatefs`] and answers it.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "503dbe0ed316e196240e612d0a6726e2b6e129ecbb773b9f17a0621369f7d1d9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_remove_dir\n\nDocumentation:\nMakes a [`FileRequest::RemoveDir`] and answers it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_remove_dir(&mut self, expected_dir_name: &str) {\n // Expecting `rmdir` call with path.\n assert_matches!(\n self.recv().await,\n ClientMessage::FileRequest(FileRequest::RemoveDir(\n mirrord_protocol::file::RemoveDirRequest { pathname }\n )) if pathname.to_str().unwrap() == expected_dir_name\n );\n\n // Answer `rmdir`.\n self.codec\n .send(DaemonMessage::File(\n mirrord_protocol::FileResponse::RemoveDir(Ok(())),\n ))\n .await\n .unwrap();\n }\n```"}], "func_name": "expect_remove_dir", "docstring": "Makes a [`FileRequest::RemoveDir`] and answers it.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e8477c610540cf2377784491d26446f6f21dbce40d63fdcbe08f1e56ec6b09a7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_message_file_read\n\nDocumentation:\nVerify that the passed message (not the next message from self.codec!) is a file read.\nReturn buffer size.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_message_file_read(message: ClientMessage, expected_fd: u64) -> u64 {\n // Verify the app reads the file.\n if let ClientMessage::FileRequest(FileRequest::Read(\n mirrord_protocol::file::ReadFileRequest {\n remote_fd: requested_fd,\n buffer_size,\n },\n )) = message\n {\n assert_eq!(expected_fd, requested_fd);\n return buffer_size;\n }\n panic!(\"Expected Read FileRequest. Got {message:?}\");\n }\n```"}], "func_name": "expect_message_file_read", "docstring": "Verify that the passed message (not the next message from self.codec!) is a file read.\nReturn buffer size.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a48e3853815963640fae4b8fd2429872933f002c548040a11b8f84e5617a2a0e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_only_file_read\n\nDocumentation:\nVerify the layer hooks a read of `expected_fd`, return buffer size.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_only_file_read(&mut self, expected_fd: u64) -> u64 {\n // Verify the app reads the file.\n Self::expect_message_file_read(self.codec.next().await.unwrap().unwrap(), expected_fd).await\n }\n```"}], "func_name": "expect_only_file_read", "docstring": "Verify the layer hooks a read of `expected_fd`, return buffer size.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cbbec82133d3237b6cb7703c33cc92b416542ffdd9014c4f3557039e13528586"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: answer_file_read\n\nDocumentation:\nSend file read response with given `contents`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn answer_file_read(&mut self, contents: Vec) {\n let read_amount = contents.len();\n self.codec\n .send(DaemonMessage::File(FileResponse::Read(Ok(\n mirrord_protocol::file::ReadFileResponse {\n bytes: contents,\n read_amount: read_amount as u64,\n },\n ))))\n .await\n .unwrap();\n }\n```"}], "func_name": "answer_file_read", "docstring": "Send file read response with given `contents`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6cc6074786f005d16bf2ee78cb0517317cf3c2ea44d3b98e8c13f9f79fcf4f1a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: answer_file_read_twice\n\nDocumentation:\nAnswer an already verified file read request, then expect another one and answer with 0\nbytes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn answer_file_read_twice(\n &mut self,\n contents: &str,\n expected_fd: u64,\n buffer_size: u64,\n ) {\n let contents = contents\n .as_bytes()\n .get(0..buffer_size as usize)\n .unwrap_or(contents.as_bytes())\n .to_vec();\n self.answer_file_read(contents).await;\n // last call returns 0.\n let _buffer_size = self.expect_only_file_read(expected_fd).await;\n self.answer_file_read(vec![]).await;\n }\n```"}], "func_name": "answer_file_read_twice", "docstring": "Answer an already verified file read request, then expect another one and answer with 0\nbytes.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3fcc8d0e2671910088db5f43a0dbc302c338ccbd22d3bbc47d4cc4d149c618c9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_single_file_read\n\nDocumentation:\nFor when the application does not keep reading until it gets 0 bytes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_single_file_read(&mut self, contents: &str, expected_fd: u64) {\n let buffer_size = self.expect_only_file_read(expected_fd).await;\n let contents = contents\n .as_bytes()\n .get(0..buffer_size as usize)\n .unwrap_or(contents.as_bytes())\n .to_vec();\n self.answer_file_read(contents).await;\n }\n```"}], "func_name": "expect_single_file_read", "docstring": "For when the application does not keep reading until it gets 0 bytes.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1d9dca85c404866d136fe741902a108bc1fd335645c642eea942740ec938818c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: consume_xstats_then_expect_file_write\n\nDocumentation:\nVerify that the layer sends a file write request with the expected contents.\nSend back response.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn consume_xstats_then_expect_file_write(&mut self, contents: &str, fd: u64) {\n let message = self.consume_xstats().await;\n assert_eq!(\n message,\n ClientMessage::FileRequest(FileRequest::Write(\n mirrord_protocol::file::WriteFileRequest {\n fd,\n write_bytes: contents.as_bytes().to_vec()\n }\n ))\n );\n\n let written_amount = contents.len() as u64;\n self.codec\n .send(DaemonMessage::File(FileResponse::Write(Ok(\n mirrord_protocol::file::WriteFileResponse { written_amount },\n ))))\n .await\n .unwrap();\n }\n```"}], "func_name": "consume_xstats_then_expect_file_write", "docstring": "Verify that the layer sends a file write request with the expected contents.\nSend back response.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "656d215ecc7f7950f8b3458b86f264ab73af5220257b0fcccda50418c37130e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_file_close\n\nDocumentation:\nRead next layer message and verify it's a close request.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_file_close(&mut self, fd: u64) {\n assert_eq!(\n self.codec.next().await.unwrap().unwrap(),\n ClientMessage::FileRequest(FileRequest::Close(\n mirrord_protocol::file::CloseFileRequest { fd }\n ))\n );\n }\n```"}], "func_name": "expect_file_close", "docstring": "Read next layer message and verify it's a close request.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a73594ad25d5650744dde94da1c1bdf9e3d1d27677ea6ceaaac4b428c2f84ab2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_file_access\n\nDocumentation:\nVerify the next message from the layer is an access to the given path with the given mode.\nSend back a response.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_file_access(&mut self, pathname: PathBuf, mode: u8) {\n assert_eq!(\n self.recv().await,\n ClientMessage::FileRequest(FileRequest::Access(AccessFileRequest { pathname, mode }))\n );\n\n self.codec\n .send(DaemonMessage::File(FileResponse::Access(Ok(\n AccessFileResponse {},\n ))))\n .await\n .unwrap();\n }\n```"}], "func_name": "expect_file_access", "docstring": "Verify the next message from the layer is an access to the given path with the given mode.\nSend back a response.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cfb6d3efe479efc4b751e24e321f884dc7e5bf3a2ccb38c663a374a1114abd33"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_xstat\n\nDocumentation:\nAssert that the layer sends an xstat request with the given fd, answer the request.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_xstat(&mut self, path: Option, fd: Option) {\n assert_eq!(\n self.recv().await,\n ClientMessage::FileRequest(FileRequest::Xstat(XstatRequest {\n path,\n fd,\n follow_symlink: true,\n }))\n );\n\n self.codec\n .send(DaemonMessage::File(FileResponse::Xstat(Ok(\n XstatResponse {\n metadata: Default::default(),\n },\n ))))\n .await\n .unwrap();\n }\n```"}], "func_name": "expect_xstat", "docstring": "Assert that the layer sends an xstat request with the given fd, answer the request.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "102530acbbbf0df01167ab2eb9ccf7e2ae387325cc59ffc6f147b8ab04658ba2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: consume_xstats\n\nDocumentation:\nConsume messages from the codec and return the first non-xstat message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn consume_xstats(&mut self) -> ClientMessage {\n let mut message = self.recv().await;\n while let ClientMessage::FileRequest(FileRequest::Xstat(_xstat_request)) = message {\n // Answer xstat.\n self.codec\n .send(DaemonMessage::File(FileResponse::Xstat(Ok(\n XstatResponse {\n metadata: Default::default(),\n },\n ))))\n .await\n .unwrap();\n message = self.recv().await;\n }\n message\n }\n```"}], "func_name": "consume_xstats", "docstring": "Consume messages from the codec and return the first non-xstat message.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "af9749f7a58424724fd41d2db6d020d86520f6ddc5d628adc7330dbea2a3731c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_gethostname\n\nDocumentation:\nExpect all the requested requests for gethostname hook\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn expect_gethostname(&mut self, fd: u64) {\n self.expect_file_open_for_reading(\"/etc/hostname\", fd).await;\n\n self.expect_single_file_read(\"foobar\\n\", fd).await;\n\n self.expect_file_close(fd).await;\n }\n```"}], "func_name": "expect_gethostname", "docstring": "Expect all the requested requests for gethostname hook", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "76441b89d643513806cbbd6663191d8dbc848f03a3f413b847d2af68fdaacbeb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_python3_executable\n\nDocumentation:\nRun python with shell resolving to find the actual executable.\n\nThis is to help tests that run python with mirrord work locally on systems with pyenv.\nIf we run `python3` on a system with pyenv the first executed is not python but bash. On mac\nthat prevents the layer from loading because of SIP.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn get_python3_executable() -> String {\n let mut python = Command::new(\"python3\")\n .stdin(Stdio::piped())\n .stdout(Stdio::piped())\n .spawn()\n .unwrap();\n let child_stdin = python.stdin.as_mut().unwrap();\n child_stdin\n .write_all(b\"import sys\\nprint(sys.executable)\")\n .await\n .unwrap();\n let output = python.wait_with_output().await.unwrap();\n String::from(String::from_utf8_lossy(&output.stdout).trim())\n }\n```"}], "func_name": "get_python3_executable", "docstring": "Run python with shell resolving to find the actual executable.\n\nThis is to help tests that run python with mirrord work locally on systems with pyenv.\nIf we run `python3` on a system with pyenv the first executed is not python but bash. On mac\nthat prevents the layer from loading because of SIP.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "605b2590dcc002cb3283f8a4347e84eed2dfcd0aea0bb4106f45d8066be2536b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_test_process\n\nDocumentation:\nStart the test process with the given env.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_test_process(&self, env: HashMap) -> TestProcess {\n let executable = self.get_executable().await;\n #[cfg(target_os = \"macos\")]\n let executable = sip_patch(&executable, SipPatchOptions::default())\n .unwrap()\n .unwrap_or(executable);\n println!(\"Using executable: {}\", &executable);\n println!(\"Using args: {:?}\", self.get_args());\n TestProcess::start_process(executable, self.get_args(), env).await\n }\n```"}], "func_name": "get_test_process", "docstring": "Start the test process with the given env.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8e1392675475f06481078008b7a9a8980f9995a2d300359b8a575f6da4461212"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_process_with_layer\n\nDocumentation:\nStart the process of this application, with the layer lib loaded.\nWill start it with env from `get_env` plus whatever is passed in `extra_env_vars`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn start_process_with_layer(\n &self,\n dylib_path: &Path,\n extra_env_vars: Vec<(&str, &str)>,\n configuration_file: Option<&Path>,\n ) -> (TestProcess, TestIntProxy) {\n let listener = TcpListener::bind(\"127.0.0.1:0\").await.unwrap();\n let address = listener.local_addr().unwrap();\n let env = get_env(dylib_path, address, extra_env_vars, configuration_file);\n let test_process = self.get_test_process(env).await;\n\n (test_process, TestIntProxy::new(listener).await)\n }\n```"}], "func_name": "start_process_with_layer", "docstring": "Start the process of this application, with the layer lib loaded.\nWill start it with env from `get_env` plus whatever is passed in `extra_env_vars`.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82ef6d47789fc91bfe1b7896d0f76c653a00e89263301839d8538257348c3429"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_process_with_layer_and_port\n\nDocumentation:\nLike `start_process_with_layer`, but also verify a port subscribe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn start_process_with_layer_and_port(\n &self,\n dylib_path: &Path,\n extra_env_vars: Vec<(&str, &str)>,\n configuration_file: Option<&Path>,\n ) -> (TestProcess, TestIntProxy) {\n let listener = TcpListener::bind(\"127.0.0.1:0\").await.unwrap();\n let address = listener.local_addr().unwrap();\n let env = get_env(dylib_path, address, extra_env_vars, configuration_file);\n let test_process = self.get_test_process(env).await;\n\n (\n test_process,\n TestIntProxy::new_with_app_port(listener, self.get_app_port()).await,\n )\n }\n```"}], "func_name": "start_process_with_layer_and_port", "docstring": "Like `start_process_with_layer`, but also verify a port subscribe.", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b3a21b7a7adbdde87ee2999eade2f9be874795c4240aed39b2e70800632bc94f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_env\n\nDocumentation:\nEnvironment for the user application.\n\nThe environment includes:\n1. `RUST_LOG=warn,mirrord=trace`\n2. [`MIRRORD_LAYER_INTPROXY_ADDR`]\n3. Layer injection variable\n4. [`LayerConfig::RESOLVED_CONFIG_ENV`]\n6. Given `extra_vars`\n\n`extra_vars` are also added to the [`ConfigContext`] for [`LayerConfig::resolve`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_env(\n dylib_path: &Path,\n intproxy_addr: SocketAddr,\n extra_vars: Vec<(&str, &str)>,\n config_path: Option<&Path>,\n) -> HashMap {\n let extra_vars_owned = extra_vars\n .iter()\n .map(|(key, value)| (key.to_string(), value.to_string()))\n .collect::>();\n\n let mut cfg_context = ConfigContext::default()\n .override_env(\"MIRRORD_IMPERSONATED_TARGET\", \"pod/mock-target\")\n .override_env(\"MIRRORD_REMOTE_DNS\", \"false\")\n .override_envs(extra_vars)\n .override_env_opt(LayerConfig::FILE_PATH_ENV, config_path)\n .strict_env(true);\n let config = LayerConfig::resolve(&mut cfg_context).unwrap();\n\n [\n (\"RUST_LOG\".to_string(), \"warn,mirrord=debug\".to_string()),\n (\n MIRRORD_LAYER_INTPROXY_ADDR.to_string(),\n intproxy_addr.to_string(),\n ),\n (\n LayerConfig::RESOLVED_CONFIG_ENV.to_string(),\n config.encode().unwrap(),\n ),\n #[cfg(target_os = \"macos\")]\n (\n \"DYLD_INSERT_LIBRARIES\".to_string(),\n dylib_path.to_str().unwrap().to_string(),\n ),\n #[cfg(target_os = \"linux\")]\n (\n \"LD_PRELOAD\".to_string(),\n dylib_path.to_str().unwrap().to_string(),\n ),\n #[cfg(all(target_os = \"macos\", target_arch = \"aarch64\"))]\n (\n // The universal layer library loads arm64 library from the path specified in this\n // environment variable when the host runs arm64e.\n // See `mirorrd/layer/shim.c` for more information.\n \"MIRRORD_MACOS_ARM64_LIBRARY\".to_string(),\n arm64_dylib_path().to_str().unwrap().to_string(),\n ),\n ]\n .into_iter()\n .chain(extra_vars_owned)\n .collect()\n}\n```"}], "func_name": "get_env", "docstring": "Environment for the user application.\n\nThe environment includes:\n1. `RUST_LOG=warn,mirrord=trace`\n2. [`MIRRORD_LAYER_INTPROXY_ADDR`]\n3. Layer injection variable\n4. [`LayerConfig::RESOLVED_CONFIG_ENV`]\n6. Given `extra_vars`\n\n`extra_vars` are also added to the [`ConfigContext`] for [`LayerConfig::resolve`].", "repo": "metalbear-co/mirrord", "path": "mirrord/layer/tests/common/mod.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/layer/tests/common/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0fec7f7d666472b3578d8b63f506abb30d54a4234aaf3f11a6a78091a8a0987"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: base_client_config\n\nDocumentation:\nCreates a base [`Config`] for creating kube [`Client`]s.\nAdds extra headers that we send to the operator with each request:\n1. [`MIRRORD_CLI_VERSION_HEADER`]\n2. [`CLIENT_NAME_HEADER`]\n3. [`CLIENT_HOSTNAME_HEADER`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn base_client_config(layer_config: &LayerConfig) -> OperatorApiResult {\n let mut client_config = create_kube_config(\n layer_config.accept_invalid_certificates,\n layer_config.kubeconfig.clone(),\n layer_config.kube_context.clone(),\n )\n .await\n .map_err(OperatorApiError::CreateKubeClient)?;\n\n client_config.headers.push((\n HeaderName::from_static(MIRRORD_CLI_VERSION_HEADER),\n HeaderValue::from_static(env!(\"CARGO_PKG_VERSION\")),\n ));\n\n let UserIdentity { name, hostname } = UserIdentity::load();\n\n let headers = [\n (CLIENT_NAME_HEADER, name),\n (CLIENT_HOSTNAME_HEADER, hostname),\n ];\n for (name, raw_value) in headers {\n let Some(raw_value) = raw_value else {\n continue;\n };\n\n // Replace non-ascii (not supported in headers) chars and trim.\n let cleaned = raw_value\n .replace(|c: char| !c.is_ascii(), \"\")\n .trim()\n .to_string();\n let value = HeaderValue::from_str(&cleaned);\n match value {\n Ok(value) => client_config\n .headers\n .push((HeaderName::from_static(name), value)),\n Err(error) => {\n tracing::debug!(%error, %name, raw_value = raw_value, cleaned, \"Invalid header value\");\n }\n }\n }\n\n Ok(client_config)\n }\n```"}], "func_name": "base_client_config", "docstring": "Creates a base [`Config`] for creating kube [`Client`]s.\nAdds extra headers that we send to the operator with each request:\n1. [`MIRRORD_CLI_VERSION_HEADER`]\n2. [`CLIENT_NAME_HEADER`]\n3. [`CLIENT_HOSTNAME_HEADER`]", "repo": "metalbear-co/mirrord", "path": "mirrord/operator/src/client.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/operator/src/client.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a3f565f66ab8d8b2a9d659ce3d43fae8ec24e8c78f2e0a7eaee6d4ae2bc7e41"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_feature_support\n\nDocumentation:\nCheck the operator supports all the operator features required by the user's configuration.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_feature_support(&self, layer_config: &LayerConfig) -> OperatorApiResult<()> {\n if layer_config.feature.copy_target.enabled {\n self.operator\n .spec\n .require_feature(NewOperatorFeature::CopyTarget)?\n }\n\n if layer_config.feature.split_queues.sqs().next().is_some() {\n self.operator\n .spec\n .require_feature(NewOperatorFeature::SqsQueueSplitting)?;\n }\n\n if layer_config.feature.split_queues.kafka().next().is_some() {\n self.operator\n .spec\n .require_feature(NewOperatorFeature::KafkaQueueSplitting)?;\n }\n\n Ok(())\n }\n```"}], "func_name": "check_feature_support", "docstring": "Check the operator supports all the operator features required by the user's configuration.", "repo": "metalbear-co/mirrord", "path": "mirrord/operator/src/client.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/operator/src/client.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3da2690c2678733ff64190f620ede5c521a07679975238a2b7e34fbbb2c02b4b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_client_cert_header\n\nDocumentation:\nTransforms the given client [`Certificate`] into a [`HeaderValue`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn make_client_cert_header(certificate: &Certificate) -> Result {\n let as_der = certificate.encode_der().map_err(|error| {\n OperatorApiError::ClientCertError(format!(\n \"failed to encode client certificate: {error}\"\n ))\n })?;\n let as_base64 = general_purpose::STANDARD.encode(as_der);\n HeaderValue::try_from(as_base64)\n .map_err(|error| OperatorApiError::ClientCertError(error.to_string()))\n }\n```"}], "func_name": "make_client_cert_header", "docstring": "Transforms the given client [`Certificate`] into a [`HeaderValue`].", "repo": "metalbear-co/mirrord", "path": "mirrord/operator/src/client.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/operator/src/client.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9dbcaf50aab3f3cca37017550aeb64ade7e420b1cbb9b9e497bfad85a494ec4e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: target_connect_url\n\nDocumentation:\nProduces the URL for making a connection request to the operator.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn target_connect_url(\n use_proxy: bool,\n target: &ResolvedTarget,\n connect_params: &ConnectParams<'_>,\n ) -> String {\n let name = {\n let mut urlfied_name = target.type_().to_string();\n if let Some(target_name) = target.name() {\n urlfied_name.push('.');\n urlfied_name.push_str(target_name);\n }\n if let Some(target_container) = target.container() {\n urlfied_name.push_str(\".container.\");\n urlfied_name.push_str(target_container);\n }\n urlfied_name\n };\n\n let namespace = target.namespace().unwrap_or(\"default\");\n\n if use_proxy {\n let api_version = TargetCrd::api_version(&());\n let plural = TargetCrd::plural(&());\n format!(\n \"/apis/{api_version}/proxy/namespaces/{namespace}/{plural}/{name}?{connect_params}\"\n )\n } else {\n let url_path = TargetCrd::url_path(&(), Some(namespace));\n format!(\"{url_path}/{name}?{connect_params}\")\n }\n }\n```"}], "func_name": "target_connect_url", "docstring": "Produces the URL for making a connection request to the operator.", "repo": "metalbear-co/mirrord", "path": "mirrord/operator/src/client.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/operator/src/client.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fdc6b1ea3481bebe14a49456412e83884da37564520accb57aaf625884ad57eb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy_target_connect_url\n\nDocumentation:\nProduces the URL for making a copied target connection request to the operator.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn copy_target_connect_url(\n crd: &CopyTargetCrd,\n use_proxy: bool,\n profile: Option<&str>,\n branch_name: Option,\n ) -> String {\n let name = crd\n .meta()\n .name\n .as_deref()\n .expect(\"CopyTargetCrd was fetched from the operator and should have a name\");\n let namespace = crd\n .meta()\n .namespace\n .as_deref()\n .expect(\"CopyTargetCrd was fetched from the operator and should have a namespace\");\n let api_version = CopyTargetCrd::api_version(&());\n let plural = CopyTargetCrd::plural(&());\n let url_path = CopyTargetCrd::url_path(&(), Some(namespace));\n\n let connect_params = ConnectParams {\n connect: true,\n on_concurrent_steal: None,\n profile,\n // Kafka and SQS splits are passed in the request body.\n kafka_splits: Default::default(),\n sqs_splits: Default::default(),\n branch_name,\n };\n\n if use_proxy {\n format!(\n \"/apis/{api_version}/proxy/namespaces/{namespace}/{plural}/{name}?{connect_params}\",\n )\n } else {\n format!(\"{url_path}/{name}?{connect_params}\",)\n }\n }\n```"}], "func_name": "copy_target_connect_url", "docstring": "Produces the URL for making a copied target connection request to the operator.", "repo": "metalbear-co/mirrord", "path": "mirrord/operator/src/client.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/operator/src/client.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0fe2f9d568c8b15d1bfe5207d6a2fa9b82091c80f790264a7b306475ad609da0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: urlfied_name\n\nDocumentation:\nCreates a target name in format of `target_type.target_name.[container.container_name]`\nfor example:\n\n- `DeploymentTarget { deployment: \"nginx\", container: None }` -> `deploy.nginx`;\n- `DeploymentTarget { deployment: \"nginx\", container: Some(\"pyrex\") }` ->\n`deploy.nginx.container.pyrex`;\n\nIt's used to connect to a resource through the operator.\n\n# Warning\n\nDo **not** change url paths here, even if the operator recognizes the other format.\nIt can break exisiting [`policy::MirrordPolicy`]s and [`policy::MirrordClusterPolicy`]\n(see [`policy::MirrordPolicySpec::target_path`] and\n[`policy::MirrordClusterPolicySpec::target_path`]).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn urlfied_name(target: &Target) -> String {\n let (type_name, target, container) = match target {\n Target::Deployment(target) => (\"deploy\", &target.deployment, &target.container),\n Target::Pod(target) => (\"pod\", &target.pod, &target.container),\n Target::Rollout(target) => (\"rollout\", &target.rollout, &target.container),\n Target::Job(target) => (\"job\", &target.job, &target.container),\n Target::CronJob(target) => (\"cronjob\", &target.cron_job, &target.container),\n Target::StatefulSet(target) => (\"statefulset\", &target.stateful_set, &target.container),\n Target::Service(target) => (\"service\", &target.service, &target.container),\n Target::ReplicaSet(target) => (\"replicaset\", &target.replica_set, &target.container),\n Target::Targetless => return TARGETLESS_TARGET_NAME.to_string(),\n };\n\n if let Some(container) = container {\n format!(\"{}.{}.container.{}\", type_name, target, container)\n } else {\n format!(\"{}.{}\", type_name, target)\n }\n }\n```"}], "func_name": "urlfied_name", "docstring": "Creates a target name in format of `target_type.target_name.[container.container_name]`\nfor example:\n\n- `DeploymentTarget { deployment: \"nginx\", container: None }` -> `deploy.nginx`;\n- `DeploymentTarget { deployment: \"nginx\", container: Some(\"pyrex\") }` ->\n`deploy.nginx.container.pyrex`;\n\nIt's used to connect to a resource through the operator.\n\n# Warning\n\nDo **not** change url paths here, even if the operator recognizes the other format.\nIt can break exisiting [`policy::MirrordPolicy`]s and [`policy::MirrordClusterPolicy`]\n(see [`policy::MirrordPolicySpec::target_path`] and\n[`policy::MirrordClusterPolicySpec::target_path`]).", "repo": "metalbear-co/mirrord", "path": "mirrord/operator/src/crd.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/operator/src/crd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93b4203b67f627d2bb8b87e1662d4dfc85aec9ffdaf714ee47074128a0fcdbb9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: registry_matches\n\nDocumentation:\nFor self that is the queue consumer of a run, test if a given registry object is the correct\nregistry for this run.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn registry_matches(&self, registry: &MirrordWorkloadQueueRegistry) -> bool {\n let registry_consumer = ®istry.spec.consumer;\n self.workload_type == registry_consumer.workload_type\n && self.name == registry_consumer.name\n && (self.container == registry_consumer.container\n // If registry does not specify a container, it applies to all runs with\n // this target, regardless of what container they are targeting.\n || registry_consumer.container.is_none())\n }\n```"}], "func_name": "registry_matches", "docstring": "For self that is the queue consumer of a run, test if a given registry object is the correct\nregistry for this run.", "repo": "metalbear-co/mirrord", "path": "mirrord/operator/src/crd.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/operator/src/crd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a0d3ed974fc6253d3e4b75f8a220b31c1e924a275bc1753e014a02f2b0f53b5a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_session_ready\n\nDocumentation:\nThe [`kube::runtime::wait::Condition`] trait is auto-implemented for this function.\nTo be used in [`kube::runtime::wait::await_condition`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_session_ready(session: Option<&MirrordSqsSession>) -> bool {\n session\n .and_then(|session| session.status.as_ref())\n .map(|status| {\n matches!(\n status,\n SqsSessionStatus::Ready(..)\n | SqsSessionStatus::StartError(..)\n | SqsSessionStatus::CleanupError { .. }\n )\n })\n .unwrap_or_default()\n}\n```"}], "func_name": "is_session_ready", "docstring": "The [`kube::runtime::wait::Condition`] trait is auto-implemented for this function.\nTo be used in [`kube::runtime::wait::await_condition`].", "repo": "metalbear-co/mirrord", "path": "mirrord/operator/src/crd.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/operator/src/crd.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f972cc2a9a7d526240e32df17cd7e83bbd644941fe314ef288936df702b9c4be"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sec_websocket_key\n\nDocumentation:\nGenerate a random key for the `Sec-WebSocket-Key` header.\nThis must be nonce consisting of a randomly selected 16-byte value in base64.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn sec_websocket_key() -> HeaderValue {\n let random: [u8; 16] = rand::random();\n base64::engine::general_purpose::STANDARD\n .encode(random)\n .parse()\n .expect(\"should be valid\")\n}\n```"}], "func_name": "sec_websocket_key", "docstring": "Generate a random key for the `Sec-WebSocket-Key` header.\nThis must be nonce consisting of a randomly selected 16-byte value in base64.", "repo": "metalbear-co/mirrord", "path": "mirrord/operator/src/client/upgrade.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/operator/src/client/upgrade.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e2980ddacebd769c54b3fc5decd212b6d60c8432503c69d23f93a17d1e513a1f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: value_in_labels\n\nDocumentation:\nIs the label in `labels` with the key `key` one of the values in `opt_allowed_labels`?\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn value_in_labels(\n key: &str,\n labels: &BTreeMap,\n opt_allowed_labels: &Option>,\n) -> bool {\n labels\n .get(key)\n .map(|found_value| {\n opt_allowed_labels\n .as_ref()\n .map(|allowed_labels| allowed_labels.contains(found_value))\n .unwrap_or_default()\n }) // false if list of allowed labels is None.\n .unwrap_or_default() // false if there is no label with that key.\n}\n```"}], "func_name": "value_in_labels", "docstring": "Is the label in `labels` with the key `key` one of the values in `opt_allowed_labels`?", "repo": "metalbear-co/mirrord", "path": "mirrord/operator/src/crd/label_selector.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/operator/src/crd/label_selector.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f9307db32cb2867abf537415ce915d883b5e5c7e64a1408f89b4c0183ffa598b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: matches_optional\n\nDocumentation:\nLike `matches` but accepts an optional map, as present in kube resources.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn matches_optional(&self, labels: &Option>) -> bool {\n // room for optimization: if labels is none we can go over the rules and return weather they\n // are all negatives (`DoesNotExist` or `NotIn`) instead of the normal logic.\n labels\n .as_ref()\n .map(|labels| self.matches(labels))\n .unwrap_or_else(|| self.matches(&Default::default()))\n }\n```"}], "func_name": "matches_optional", "docstring": "Like `matches` but accepts an optional map, as present in kube resources.", "repo": "metalbear-co/mirrord", "path": "mirrord/operator/src/crd/label_selector.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/operator/src/crd/label_selector.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dc401dfdc794435f22def2a24073e9a2ef8e27bfa1324099467060e29ed3a9d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: matches\n\nDocumentation:\nDo all the rules of this selector apply for the given optional `labels`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn matches(&self, labels: &BTreeMap) -> bool {\n if let Some(label_map) = self.match_labels.as_ref() {\n for (req_key, req_value) in label_map {\n let req_fulfilled = labels\n .get(req_key)\n .map(|existing_value| existing_value == req_value)\n .unwrap_or_default();\n if !req_fulfilled {\n return false;\n }\n }\n }\n if let Some(match_reqs) = self.match_expressions.as_ref() {\n for match_req in match_reqs {\n let req_fulfilled = match match_req.operator {\n In => value_in_labels(&match_req.key, labels, &match_req.values),\n NotIn => !value_in_labels(&match_req.key, labels, &match_req.values),\n Exists => labels.contains_key(&match_req.key),\n DoesNotExist => !labels.contains_key(&match_req.key),\n };\n if !req_fulfilled {\n return false;\n }\n }\n }\n true\n }\n```"}], "func_name": "matches", "docstring": "Do all the rules of this selector apply for the given optional `labels`.", "repo": "metalbear-co/mirrord", "path": "mirrord/operator/src/crd/label_selector.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/operator/src/crd/label_selector.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8ffef68d833367ee00c50bfb75bed8256e20135035b714219c1fa29f88565be2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: btreemap\n\nDocumentation:\nConvenient function so that we don't have to write `String::from` 1000 times in the tests\nand can just use string slices because they are shorter to write.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn btreemap(items: &[(&str, &str)]) -> BTreeMap {\n let string_items = items.iter().map(|&(key, value)| (key.into(), value.into()));\n BTreeMap::from_iter(string_items)\n }\n```"}], "func_name": "btreemap", "docstring": "Convenient function so that we don't have to write `String::from` 1000 times in the tests\nand can just use string slices because they are shorter to write.", "repo": "metalbear-co/mirrord", "path": "mirrord/operator/src/crd/label_selector.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/operator/src/crd/label_selector.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb520aa6e9caa00b75c32173d22ff723e5235d4d4dc1844935b896fef0f22d6c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extend_with_ready\n\nDocumentation:\nExtends the given [`Frames`] instance with [`Frame`]s that are available without blocking.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extend_with_ready(\n body: &mut B,\n frames: &mut Frames,\n) -> Result<(), B::Error> {\n loop {\n match body.frame().now_or_never() {\n None => {\n frames.is_last = false;\n break;\n }\n Some(None) => {\n frames.is_last = true;\n break;\n }\n Some(Some(result)) => {\n frames.frames.push(result?);\n frames.is_last = false;\n }\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "extend_with_ready", "docstring": "Extends the given [`Frames`] instance with [`Frame`]s that are available without blocking.", "repo": "metalbear-co/mirrord", "path": "mirrord/protocol/src/batched_body.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/protocol/src/batched_body.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7734da14fd85472fd05edc10e6b5e98933e81e77c5158179d902749a50fdea9f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: policy_name_string\n\nDocumentation:\nIf some then the name with a trailing space, else empty string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn policy_name_string(policy_name: Option<&str>) -> String {\n if let Some(name) = policy_name {\n format!(\"the mirrord policy \\\"{name}\\\"\")\n } else {\n \"a mirrord policy\".to_string()\n }\n}\n```"}], "func_name": "policy_name_string", "docstring": "If some then the name with a trailing space, else empty string.", "repo": "metalbear-co/mirrord", "path": "mirrord/protocol/src/error.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/protocol/src/error.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0c0ee136bb34c7b2985c4562d9d3f8b0d6b9b4f61f7e6fb9d08b889ecce629c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_d_reclen64\n\nDocumentation:\nCalculate the `d_reclen` field of a the kernel's `linux_dirent64` struct.\nThe actual size of an instance is not `sizeof(linux_dirent64)`, since it contains a flexible\narray member.\nThis functions calculates the expected `d_reclen` assuming:\n```C\nsizeof(ino64_t) == 8\nsizeof(off64_t) == 8\nsizeof(unsigned short) == 2\nsizeof(unsinged char) == 1\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_d_reclen64(&self) -> u16 {\n // The 20 is for 19 bytes of fixed size members + the terminating null of the string.\n Self::round_up_to_next_multiple_of_8(20 + self.name.len() as u16)\n }\n```"}], "func_name": "get_d_reclen64", "docstring": "Calculate the `d_reclen` field of a the kernel's `linux_dirent64` struct.\nThe actual size of an instance is not `sizeof(linux_dirent64)`, since it contains a flexible\narray member.\nThis functions calculates the expected `d_reclen` assuming:\n```C\nsizeof(ino64_t) == 8\nsizeof(off64_t) == 8\nsizeof(unsigned short) == 2\nsizeof(unsinged char) == 1\n```", "repo": "metalbear-co/mirrord", "path": "mirrord/protocol/src/file.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/protocol/src/file.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "92f7552b6f94b2ee1de8d7c31e36d3d2cb935a9248ae86f76e4406b37c26e798"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_hex_string\n\nDocumentation:\nHex string from random 20 bytes (results in 40 hexadecimal digits).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_hex_string() -> String {\n let mut rng = rand::rng();\n let mut bytes = [0u8; 20];\n rng.fill_bytes(&mut bytes[..]);\n hex::encode(bytes)\n}\n```"}], "func_name": "generate_hex_string", "docstring": "Hex string from random 20 bytes (results in 40 hexadecimal digits).", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/codesign.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/codesign.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8fc634e21baf921369db540c4dac25b38501f555a39e4d31a2f1b155d9ba4b5d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_temp_bin_str_prefix\n\nDocumentation:\nGet the `PathBuf` of the `mirrord-bin` dir, and return a `String` prefix to remove, without\na trailing `/`, so that the stripped path starts with a `/`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_temp_bin_str_prefix(path: &Path) -> String {\n // lossy: we assume our temp dir path does not contain non-unicode chars.\n path.to_string_lossy()\n .to_string()\n .trim_end_matches('/')\n .to_string()\n }\n```"}], "func_name": "get_temp_bin_str_prefix", "docstring": "Get the `PathBuf` of the `mirrord-bin` dir, and return a `String` prefix to remove, without\na trailing `/`, so that the stripped path starts with a `/`", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "76690052c8a4d735a09ea5a049b22401116a1de6a970fb7872d94757ebeebaed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_cpu_subtype_arm64e\n\nDocumentation:\nCheck if a cpu subtype (already parsed with the correct endianness) is arm64e, given its\nmain cpu type is arm64. We only consider the lowest byte in the check.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_cpu_subtype_arm64e(subtype: u32) -> bool {\n // We only compare the lowest 8 bit since the higher bits may contain \"capability bits\".\n // For example, usually arm64e would be\n // `macho::CPU_SUBTYPE_ARM64E | macho::CPU_SUBTYPE_PTRAUTH_ABI`.\n // Maybe we could also use arm64e binaries without pointer authentication, but we don't\n // know if that exists in the wild so it was decided not to work with any arm64e\n // binaries for now.\n subtype as u8 == macho::CPU_SUBTYPE_ARM64E as u8\n }\n```"}], "func_name": "is_cpu_subtype_arm64e", "docstring": "Check if a cpu subtype (already parsed with the correct endianness) is arm64e, given its\nmain cpu type is arm64. We only consider the lowest byte in the check.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "02b2aae858c403e86c589ec057f8102b9ace1eea7a69c97fad05933ad066f10d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_fat_x64_arch\n\nDocumentation:\nReturn whether a binary that is a member of a fat binary is x64.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_fat_x64_arch(arch: &&impl FatArch) -> bool {\n matches!(arch.architecture(), Architecture::X86_64)\n }\n```"}], "func_name": "is_fat_x64_arch", "docstring": "Return whether a binary that is a member of a fat binary is x64.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf6a1f6288811c77b55e2b9b8851e9ffd76083c16f32b2cd35d39b18a1bd9b19"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_thin_mach_o\n\nDocumentation:\nTakes the cpu type and subtype and the bytes of a file that is a non-fat Mach-O, and\nreturns either an Ok BinaryInfo (which points to the whole file, as it is not\npart of a fat file) if it is of a supported CPU architecture, or a\n`SipError::NoSupportedArchitecture` otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_thin_mach_o(cpu_type: u32, cpu_subtype: u32, bytes: &[u8]) -> Result {\n if cpu_type == macho::CPU_TYPE_X86_64\n || (cpu_type == macho::CPU_TYPE_ARM64 && !is_cpu_subtype_arm64e(cpu_subtype))\n {\n // The binary has an architecture we know how to patch, so proceed.\n // We don't check if this is a thin arm binary on an intel chip because that would\n // not run regardless of SIP.\n Ok(Self::new(0, bytes.len()))\n } else {\n Err(SipError::NoSupportedArchitecture)\n }\n }\n```"}], "func_name": "from_thin_mach_o", "docstring": "Takes the cpu type and subtype and the bytes of a file that is a non-fat Mach-O, and\nreturns either an Ok BinaryInfo (which points to the whole file, as it is not\npart of a fat file) if it is of a supported CPU architecture, or a\n`SipError::NoSupportedArchitecture` otherwise.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0b3abbe6a1c30f16f7e29b7be47daa587c98fc26162036ffb078d24fde9f7604"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_object_bytes\n\nDocumentation:\nReturn the `BinaryInfo` of a supported binary from the file: if the file is a \"thin\"\nbinary of a supported architecture then the offset is 0 and the length is the length\nof the file.\n\nIf the file is a fat binary, then if it contains an arm64 binary (not arm64e) the info\nof that binary is returned. If there is no arm64 but there is an x64 binary, then the\ninfo of that binary is returned.\n\n# Errors\n\n- [`SipError::UnsupportedFileFormat`] if the file is not a valid Mach-O file.\n- [`SipError::NoSupportedArchitecture`] if the file does not contain any binary from a\nsupported architecture (arm64, x64).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_object_bytes(bytes: &[u8]) -> Result {\n match FileKind::parse(bytes)? {\n FileKind::MachO64 => {\n let header: &MachHeader64 =\n MachHeader::parse(bytes, 0).map_err(|_| {\n SipError::UnsupportedFileFormat(\n \"MachO 64 file parsing failed\".to_string(),\n )\n })?;\n Self::from_thin_mach_o(\n header.cputype(Endianness::default()),\n header.cpusubtype(Endianness::default()),\n bytes,\n )\n }\n\n // This is probably where most fat binaries are handled (see comment above\n // `MachOFat64`). A 32 bit archive (fat Mach-O) can contain 64 bit binaries.\n FileKind::MachOFat32 => {\n let fat_slice = read::macho::MachOFatFile32::parse(bytes).map_err(|_| {\n SipError::UnsupportedFileFormat(\"FatMach-O 32-bit\".to_string())\n })?;\n #[cfg(target_arch = \"aarch64\")]\n let found_arch = fat_slice\n .arches()\n .iter()\n .find(is_fat_arm64_arch)\n .or_else(|| fat_slice.arches().iter().find(is_fat_x64_arch));\n\n #[cfg(target_arch = \"x86_64\")]\n let found_arch = fat_slice.arches().iter().find(is_fat_x64_arch);\n\n found_arch\n .map(|arch| Self::new(arch.offset() as usize, arch.size() as usize))\n .ok_or(SipError::NoSupportedArchitecture)\n }\n\n // It seems like 64 bit fat Mach-Os are only used (if at all) when one of the\n // binaries has 2^32 bytes or more (around 4 GB).\n // See https://github.com/Homebrew/ruby-macho/issues/101#issuecomment-403202114\n FileKind::MachOFat64 => {\n let fat_slice = read::macho::MachOFatFile64::parse(bytes).map_err(|_| {\n SipError::UnsupportedFileFormat(\"Mach-O 32-bit\".to_string())\n })?;\n\n #[cfg(target_arch = \"aarch64\")]\n let found_arch = fat_slice\n .arches()\n .iter()\n .find(is_fat_arm64_arch)\n .or_else(|| fat_slice.arches().iter().find(is_fat_x64_arch));\n\n #[cfg(target_arch = \"x86_64\")]\n let found_arch = fat_slice.arches().iter().find(is_fat_x64_arch);\n\n found_arch\n .map(|arch| Self::new(arch.offset() as usize, arch.size() as usize))\n .ok_or(SipError::NoSupportedArchitecture)\n }\n other => Err(SipError::UnsupportedFileFormat(format!(\"{other:?}\"))),\n }\n }\n```"}], "func_name": "from_object_bytes", "docstring": "Return the `BinaryInfo` of a supported binary from the file: if the file is a \"thin\"\nbinary of a supported architecture then the offset is 0 and the length is the length\nof the file.\n\nIf the file is a fat binary, then if it contains an arm64 binary (not arm64e) the info\nof that binary is returned. If there is no arm64 but there is an x64 binary, then the\ninfo of that binary is returned.\n\n# Errors\n\n- [`SipError::UnsupportedFileFormat`] if the file is not a valid Mach-O file.\n- [`SipError::NoSupportedArchitecture`] if the file does not contain any binary from a\nsupported architecture (arm64, x64).", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bce0511b80702ae0c448c665cfa891c75f59180ef9ee28660c571aec2f5797eb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_rpath_entries\n\nDocumentation:\nGet a vector of strings, with a string for each `LC_RPATH` command in `binary`.\nReturns errors if the binary is not a 64 bit thin binary, or if the load commands could not\nbe parsed correctly.\n\n# Arguments\n* `binary`: a slice of just the bytes in a thin 64 bit binary. If the file is a thin binary\nin the first place, the slice will be the whole file. If the file is a fat binary, the\nslice will be just the thin binary we're going to use out of the fat binary.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_rpath_entries(binary: &[u8]) -> Result> {\n let mach_header: &MachHeader64 = // we don't support 32 bit binaries.\n // offset 0 - `binary` should only be the thin binary (not the containing fat one).\n MachHeader::parse(binary, 0).map_err(|_| {\n SipError::UnsupportedFileFormat(\n \"MachO 64 file parsing failed\".to_string(),\n )\n })?;\n let mut load_commands = mach_header.load_commands(Endianness::default(), binary, 0)?;\n let mut rpath_entries = Vec::new();\n while let Some(load_command) = load_commands.next()? {\n if load_command.cmd() == LC_RPATH {\n if let Ok(Rpath(rpath_command)) = load_command.variant() {\n rpath_entries.push(from_utf8(\n load_command.string(Endianness::default(), rpath_command.path)?,\n )?)\n }\n }\n }\n Ok(rpath_entries)\n }\n```"}], "func_name": "get_rpath_entries", "docstring": "Get a vector of strings, with a string for each `LC_RPATH` command in `binary`.\nReturns errors if the binary is not a 64 bit thin binary, or if the load commands could not\nbe parsed correctly.\n\n# Arguments\n* `binary`: a slice of just the bytes in a thin 64 bit binary. If the file is a thin binary\nin the first place, the slice will be the whole file. If the file is a fat binary, the\nslice will be just the thin binary we're going to use out of the fat binary.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7dddeee8296e440a0e1afef997f104b2e1af06025b817a2e4bb7dd6107677749"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_rpath_entries\n\nDocumentation:\nFor each rpath entry in the original path, if that path is in `@executable_path` or\n`@loader_path`, add a new rpath entry to the file, with that special path replaced with the\ndirectory of the original binary.\nE.g. if the original binary is in `/bin/original/binary`, and it has 2 rpath entries:\n- `@loader_path/.`\n- `@loader_path/../lib`\n\nWe'll add to the binary at the output path the following rpath entries:\n- `/bin/original/.`\n- `/bin/original/../lib`\n\nSo the output binary has all 4 entries.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_rpath_entries(\n original_entries: &[&str],\n original_path: &Path,\n output_path: &Path,\n ) -> Result<()> {\n let parent_path_str = original_path\n .parent()\n .unwrap_or(original_path)\n .to_string_lossy()\n .to_string();\n let new_entries = original_entries\n .iter()\n .filter_map(|path| {\n path.strip_prefix(\"@executable_path\")\n .or_else(|| path.strip_prefix(\"@loader_path\"))\n })\n .map(|stripped_path| parent_path_str.clone() + stripped_path)\n .collect();\n rpath::add_rpaths(output_path, new_entries)\n }\n```"}], "func_name": "add_rpath_entries", "docstring": "For each rpath entry in the original path, if that path is in `@executable_path` or\n`@loader_path`, add a new rpath entry to the file, with that special path replaced with the\ndirectory of the original binary.\nE.g. if the original binary is in `/bin/original/binary`, and it has 2 rpath entries:\n- `@loader_path/.`\n- `@loader_path/../lib`\n\nWe'll add to the binary at the output path the following rpath entries:\n- `/bin/original/.`\n- `/bin/original/../lib`\n\nSo the output binary has all 4 entries.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "56dedbcb94af0b2eb8f1ddcaffd56164fc55bab6338e4e5ef96e9e22654f4f06"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: patch_binary\n\nDocumentation:\nRead the contents (or just the x86_64 section in case of a fat file) from the SIP binary at\n`path`, write it into `output`, give it the same permissions, and sign the new binary.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn patch_binary(path: &Path) -> Result {\n set_fallback_frameworks_path_if_mac_app(path);\n\n let output = get_output_path(path)?;\n\n if output.exists() {\n trace!(\n \"Using existing SIP-patched version of {:?}: {:?}\",\n path,\n output\n );\n return Ok(output);\n }\n\n // If the same file is executed in parallel, parallel signing could fail. So do the work on\n // a temp file, and then move it to its final destination once ready and signed.\n let temp_binary = tempfile::NamedTempFile::new()?;\n\n trace!(\n \"{:?} is a SIP protected binary, making non protected version at: {:?}\",\n path,\n output\n );\n let data = std::fs::read(path)?;\n\n // Propagate Err if the binary does not contain any supported architecture (x64/arm64).\n let binary_info = BinaryInfo::from_object_bytes(&data)?;\n\n // Just the thin binary - if the file was a thin binary of a supported architecture to\n // begin with then it's the whole file, if its a fat binary then it's just a part of it.\n let binary = data\n .get(binary_info.offset..binary_info.offset + binary_info.size)\n .expect(\"invalid SIP binary\");\n\n std::fs::write(&temp_binary, binary)?;\n\n if let Err(err) = get_rpath_entries(binary)\n .and_then(|rpath_entries| add_rpath_entries(&rpath_entries, path, temp_binary.as_ref()))\n {\n warn!(\"Adding Rpath loader commands to SIP-patched binary failed with {err:?}.\")\n // Not stopping the SIP-patching as most binaries don't need the rpath fix.\n }\n\n let signed_temp_file = tempfile::NamedTempFile::new()?;\n codesign::sign(&temp_binary, &signed_temp_file)?;\n\n // Give the new file the same permissions as the old file.\n // This needs to happen after the sign because it might change the permissions.\n trace!(\"Setting permissions for {temp_binary:?}\");\n std::fs::set_permissions(&signed_temp_file, std::fs::metadata(path)?.permissions())?;\n\n // Move the temp binary into its final location if no other process/thread already did.\n if let Err(err) = signed_temp_file.persist_noclobber(&output) {\n if err.error.kind() != std::io::ErrorKind::AlreadyExists {\n return Err(SipError::BinaryMoveFailed(err.error));\n }\n }\n Ok(output)\n }\n```"}], "func_name": "patch_binary", "docstring": "Read the contents (or just the x86_64 section in case of a fat file) from the SIP binary at\n`path`, write it into `output`, give it the same permissions, and sign the new binary.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a48fb5fe9eb576fbbad016bcd3be2eb36495bb3c048a7547f52ac90623b9a225"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: patch_script\n\nDocumentation:\nCreate a new file at `patched_path` with the same contents as `original_path` except for\nthe shebang which is `new_shebang`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn patch_script(\n original_path: &Path,\n shebang: ScriptShebang,\n new_shebang: &str,\n ) -> Result {\n let patched_path = get_output_path(original_path)?;\n\n trace!(\n \"Shebang points to: {:?}. Patching the interpreter and making a version of {:?} with an altered shebang at: {:?}\",\n shebang.interpreter_path,\n original_path,\n patched_path,\n );\n\n let data = std::fs::read(original_path)?;\n let contents = data\n .get(shebang.start_of_rest_of_file..)\n .expect(\"original shebang size exceeds file size\");\n let mut new_contents = String::from(\"#!\") + new_shebang;\n if shebang.start_of_rest_of_file == 0 {\n // trailing newline is needed for scripts without an original shebang\n new_contents.push('\\n');\n }\n let mut bytes = new_contents.into_bytes();\n bytes.extend_from_slice(contents);\n\n std::fs::write(&patched_path, bytes)?;\n\n // We set the permissions of the patched script to be like those of the original\n // script, but allowing the user to write, so that in the next run, when we are here\n // again, we have permission to overwrite the patched script (we rewrite the script\n // every run, in case it is a user script that was changed).\n let mut permissions = std::fs::metadata(original_path)?.permissions();\n let mode = permissions.mode() | 0o200; // user can write.\n permissions.set_mode(mode);\n std::fs::set_permissions(&patched_path, permissions)?;\n Ok(patched_path)\n }\n```"}], "func_name": "patch_script", "docstring": "Create a new file at `patched_path` with the same contents as `original_path` except for\nthe shebang which is `new_shebang`.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef80202aa767b96a8f3a15bd3960b3fc6531b20655f8b8f03946caf1928febe3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_shebang_from_string\n\nDocumentation:\nExtract shebang from first line of file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_shebang_from_string(first_line: &str) -> Option {\n let rest = first_line.strip_prefix(\"#!\")?;\n\n let mut char_iter = rest.char_indices().skip_while(|(_, c)| c.is_whitespace()); // any whitespace directly after #!\n let (start_of_path, _first_char_of_path) = char_iter.next()?;\n let mut path_char_iter = char_iter.skip_while(|(_, c)| !c.is_whitespace()); // Any non-whitespace characters after that (path)\n\n let (interpreter, len_with_whitespace) =\n if let Some((path_len, _next_char)) = path_char_iter.next() {\n let total_len = path_len + 2; // +2 for #! because the index is in `rest`\n (first_line.get(start_of_path + 2..total_len)?, total_len)\n } else {\n // There is no next character after the interpreter, so the whole file is just\n // magic, whitespace and path.\n (first_line.get(start_of_path + 2..)?, first_line.len())\n };\n Some(ScriptShebang {\n interpreter_path: PathBuf::from(interpreter),\n start_of_rest_of_file: len_with_whitespace,\n })\n }\n```"}], "func_name": "get_shebang_from_string", "docstring": "Extract shebang from first line of file.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f6cb9c18ac67708457b2cfd3a6342d156ec32886c4179f7b23560d2f929930e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_shebang_from_file\n\nDocumentation:\nIncluding '#!', just until whitespace, no arguments.\nwill not be called on object files\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_shebang_from_file>(path: P) -> Result> {\n let f = std::fs::File::open(path)?;\n let reader = io::BufReader::new(f);\n let mut lines = reader.lines();\n let Some(first_line_res) = lines.next() else {\n trace!(\"No lines in script.\");\n return Ok(None);\n };\n\n match first_line_res {\n Err(e) if e.kind() == io::ErrorKind::InvalidData => {\n trace!(\"First line of file is not utf-8. Can't read a shebang.\");\n Ok(None)\n }\n Err(e) => Err(SipError::IO(e)),\n Ok(line_string) => Ok(get_shebang_from_string(&line_string)),\n }\n }\n```"}], "func_name": "read_shebang_from_file", "docstring": "Including '#!', just until whitespace, no arguments.\nwill not be called on object files", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f9c52ed9ae77b6a1774186ec657f3e5b8ff7505afac1cd173995b0efb144371"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_code_signed\n\nDocumentation:\nChecks if binary is signed with either `RUNTIME` or `RESTRICTED` flags.\nThe code ignores error to allow smoother fallbacks.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_code_signed(data: &[u8]) -> bool {\n if let Ok(mach) = MachFile::parse(data) {\n for macho in mach.into_iter() {\n if let Ok(Some(signature)) = macho.code_signature() {\n if let Ok(Some(blob)) = signature.code_directory() {\n if blob\n .flags\n .intersects(CodeSignatureFlags::RESTRICT | CodeSignatureFlags::RUNTIME)\n {\n return true;\n }\n }\n }\n }\n }\n false\n }\n```"}], "func_name": "is_code_signed", "docstring": "Checks if binary is signed with either `RUNTIME` or `RESTRICTED` flags.\nThe code ignores error to allow smoother fallbacks.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e9282f8fa61b59e045e86a5c50479665d2ee6233c68acb2f2e45104017bca30f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_sip_status\n\nDocumentation:\nChecks the SF_RESTRICTED flags on a file (there might be a better check, feel free to\nsuggest)\nIf file is a script with shebang, the SipStatus is derived from the the SipStatus of the\nfile the shebang points to.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_sip_status(path: &str, opts: SipPatchOptions) -> Result {\n let complete_path = get_complete_path(path)?;\n // If the binary is in our temp bin dir, it's not SIP protected.\n if is_in_mirrord_tmp_dir(&complete_path)? {\n return Ok(NoSip);\n }\n\n // determine if file is object file\n let data = std::fs::read(&complete_path)?;\n if MachFile::parse(data.as_ref()).is_ok() {\n // file is an object file\n is_binary_sip(&complete_path, &data, opts).map(|is_sip| {\n if is_sip {\n SipBinary(complete_path)\n } else {\n NoSip\n }\n })\n } else {\n let shebang = read_shebang_from_file(&complete_path)?.unwrap_or_else(|| {\n trace!(\"Did not find a shebang, defaulting to $SHELL.\");\n ScriptShebang {\n interpreter_path: PathBuf::from(\n env::var(\"SHELL\").expect(\"$SHELL should be present\"),\n ),\n start_of_rest_of_file: 0,\n }\n });\n\n let interpreter_complete_path = get_complete_path(&shebang.interpreter_path)?;\n if is_in_mirrord_tmp_dir(&interpreter_complete_path)? {\n return Ok(NoSip);\n }\n let data = std::fs::read(&interpreter_complete_path)?;\n is_binary_sip(&interpreter_complete_path, &data, opts).map(|is_sip| {\n if is_sip {\n SipScript {\n path: complete_path,\n shebang,\n }\n } else {\n // The interpreter the shebang points to is not protected.\n NoSip\n }\n })\n }\n }\n```"}], "func_name": "get_sip_status", "docstring": "Checks the SF_RESTRICTED flags on a file (there might be a better check, feel free to\nsuggest)\nIf file is a script with shebang, the SipStatus is derived from the the SipStatus of the\nfile the shebang points to.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ee3926d92e9d9a7490450df82162e305c43d418aa7ad6641863e2f23b3bb029"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_fallback_frameworks_path_if_mac_app\n\nDocumentation:\nWhen patching a bundled mac application, it try to load libraries from its frameworks\ndirectory. The patch might cause it to search under the `mirrord-bin` temp dir.\n\nTo make sure it can find the libraries, we set (or add to) the\n`DYLD_FALLBACK_FRAMEWORK_PATH` env var.\n\nExample, if we're running `/Applications/Postman.app/Contents/MacOS/Postman`, we'll add\n`/Applications/Postman.app/Contents/Frameworks` to that env var.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_fallback_frameworks_path_if_mac_app(path: &Path) {\n for ancestor in path.ancestors() {\n if ancestor\n .extension()\n .map(|ext| ext == \"app\")\n .unwrap_or_default()\n {\n let frameworks_dir = ancestor\n .join(\"Contents/Frameworks\")\n .to_string_lossy()\n .to_string();\n let new_value = if let Ok(existing_value) = env::var(FRAMEWORKS_ENV_VAR_NAME) {\n format!(\"{existing_value}:{frameworks_dir}\")\n } else {\n frameworks_dir\n };\n env::set_var(FRAMEWORKS_ENV_VAR_NAME, new_value);\n break;\n }\n }\n }\n```"}], "func_name": "set_fallback_frameworks_path_if_mac_app", "docstring": "When patching a bundled mac application, it try to load libraries from its frameworks\ndirectory. The patch might cause it to search under the `mirrord-bin` temp dir.\n\nTo make sure it can find the libraries, we set (or add to) the\n`DYLD_FALLBACK_FRAMEWORK_PATH` env var.\n\nExample, if we're running `/Applications/Postman.app/Contents/MacOS/Postman`, we'll add\n`/Applications/Postman.app/Contents/Frameworks` to that env var.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3657b6d653c6cb93719b3f23f397a4254df9a171e8b2e1718e37758a7d498ee9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_output_path\n\nDocumentation:\nGet new path for patched version, both as PathBuf and as a string, and make the dir\nof the path, recursively.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_output_path(path: &Path) -> Result {\n // TODO: Change output to be with hash of the contents, so that old versions of changed\n // files do not get used. (Also change back existing file logic to always use.)\n\n let output = MIRRORD_TEMP_BIN_DIR_PATH_BUF.join(\n // Strip root path from binary path, as when joined it will clear the previous.\n path.strip_prefix(\"/\").unwrap_or(path), // No prefix - no problem.\n );\n\n std::fs::create_dir_all(\n output\n .parent()\n .ok_or_else(|| UnlikelyError(\"Failed to get parent directory\".to_string()))?,\n )?;\n\n Ok(output)\n }\n```"}], "func_name": "get_output_path", "docstring": "Get new path for patched version, both as PathBuf and as a string, and make the dir\nof the path, recursively.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c31abfe254fbc2a03abfb3650cac2d64ace65614ec146cfa3736f687cb2f5e47"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sip_patch\n\nDocumentation:\nCheck if the file that the user wants to execute is a SIP protected binary\n\n(or a script starting with a shebang that leads to a SIP protected binary).\nIf it is, create a non-protected version of the file and return `Ok(Some(patched_path)`.\nIf it is not, `Ok(None)`.\nPropagate errors.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sip_patch(binary_path: &str, opts: SipPatchOptions) -> Result> {\n match get_sip_status(binary_path, opts) {\n Ok(SipScript { path, shebang }) => {\n let patched_interpreter = patch_binary(&shebang.interpreter_path)?;\n let patched_script = patch_script(\n &path,\n shebang,\n patched_interpreter.to_string_lossy().as_ref(),\n )\n .map(|path| path.to_string_lossy().to_string());\n Some(patched_script).transpose()\n }\n Ok(SipBinary(binary)) => {\n let patched_binary =\n patch_binary(&binary).map(|path| path.to_string_lossy().to_string());\n Some(patched_binary).transpose()\n }\n Ok(NoSip) => {\n trace!(\"No SIP detected on {:?}\", binary_path);\n Ok(None)\n }\n Err(err) => {\n trace!(\n \"Checking the SIP status of {binary_path} (or of the binary in its shebang, if \\\n applicable) failed with {err:?}. Continuing without SIP-sidestepping.\\\n This is not necessarily an error.\"\n );\n // E.g. `env` tries to execute a bunch of non-existing files and fails, and that's\n // just its valid flow.\n Ok(None)\n }\n }\n }\n```"}], "func_name": "sip_patch", "docstring": "Check if the file that the user wants to execute is a SIP protected binary\n\n(or a script starting with a shebang that leads to a SIP protected binary).\nIf it is, create a non-protected version of the file and return `Ok(Some(patched_path)`.\nIf it is not, `Ok(None)`.\nPropagate errors.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0662d2892b0408137e70cb4b7a55cecfc769b3f5219ea348fdd7cf1c1e3ef63"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_and_verify_dyld_print\n\nDocumentation:\nVerify the SIP-patch worked.\n\nRun the given binary with `DYLD_PRINT_LIBRARIES=1`. This env var asks dyld to print all\nthe mach-o images loaded to the process. However, it is stripped away by SIP, so we can\nuse it to test the patch worked. If we're getting libsystem_kernel.dylib printed, it\nmeans the binary is not SIP protected.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn run_and_verify_dyld_print(patched_bin_path: &Path) {\n let output = std::process::Command::new(patched_bin_path)\n .env(\"DYLD_PRINT_LIBRARIES\", \"1\")\n .output()\n .unwrap();\n assert!(String::from_utf8_lossy(&output.stderr).contains(\"libsystem_kernel.dylib\"));\n }\n```"}], "func_name": "run_and_verify_dyld_print", "docstring": "Verify the SIP-patch worked.\n\nRun the given binary with `DYLD_PRINT_LIBRARIES=1`. This env var asks dyld to print all\nthe mach-o images loaded to the process. However, it is stripped away by SIP, so we can\nuse it to test the patch worked. If we're getting libsystem_kernel.dylib printed, it\nmeans the binary is not SIP protected.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a528ee2840a6a1f2e78c1afcbe90568a960354c0273aa0e1ec8812b6d5574231"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: patch_binary_and_verify_dyld_print\n\nDocumentation:\nCall `patch_binary` directly (it's a private function), verify the patched binary\nis no longer protected, and DYLD_PRINT_LIBRARIES is respected when running with it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn patch_binary_and_verify_dyld_print(bin_path: &str) {\n let patched_bin_path = patch_binary(bin_path.as_ref()).unwrap();\n assert!(matches!(\n get_sip_status(\n patched_bin_path.to_str().unwrap(),\n SipPatchOptions::default()\n )\n .unwrap(),\n NoSip\n ));\n // Check DYLD_* features work on patched binary:\n run_and_verify_dyld_print(&patched_bin_path);\n }\n```"}], "func_name": "patch_binary_and_verify_dyld_print", "docstring": "Call `patch_binary` directly (it's a private function), verify the patched binary\nis no longer protected, and DYLD_PRINT_LIBRARIES is respected when running with it.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b5534010642cf0ea37dd00bcf435d252a3893361158b4cb2a599e9396b2ef4f8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: patch_sip_and_verify_dyld_print\n\nDocumentation:\nCall `sip_patch` (it's the public function this crate exposes), verify the patched\nbinary is no longer protected, and DYLD_PRINT_LIBRARIES is respected when running with\nit.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn patch_sip_and_verify_dyld_print(executable_path: &str) {\n let patched_bin_path = sip_patch(executable_path, SipPatchOptions::default())\n .unwrap()\n .unwrap();\n assert!(matches!(\n get_sip_status(&patched_bin_path, SipPatchOptions::default()).unwrap(),\n NoSip\n ));\n // Check DYLD_* features work on patched binary:\n run_and_verify_dyld_print(patched_bin_path.as_ref());\n }\n```"}], "func_name": "patch_sip_and_verify_dyld_print", "docstring": "Call `sip_patch` (it's the public function this crate exposes), verify the patched\nbinary is no longer protected, and DYLD_PRINT_LIBRARIES is respected when running with\nit.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/lib.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/lib.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e87c0e1ca242844aeba1b236c1335e3f9b2748ed7c67c51e87e85955402c736d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_rpaths\n\nDocumentation:\nRun `install_name_tool` in a child process to add a loader command for each given rpath entry\nto the binary in `path`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn add_rpaths>(path: P, rpath_entries: Vec) -> Result<()> {\n if rpath_entries.is_empty() {\n return Ok(());\n }\n let path_str = path.as_ref().to_string_lossy().to_string();\n\n // args are `-add_rpath RPATH` for each rpath entry, and the binary's path at the end.\n let args = iter::once(String::from(\"-add_rpath\"))\n .chain(\n rpath_entries\n .into_iter()\n .intersperse(String::from(\"-add_rpath\")),\n )\n .chain(iter::once(path_str));\n\n let output = Command::new(\"install_name_tool\") // most forgettable tool name ever.\n .args(args)\n .output()?;\n\n if output.status.success() {\n Ok(())\n } else {\n let code = output.status.into_raw();\n Err(SipError::AddingRpathsFailed(\n code,\n String::from_utf8_lossy(&output.stderr).to_string(),\n ))\n }\n}\n```"}], "func_name": "add_rpaths", "docstring": "Run `install_name_tool` in a child process to add a loader command for each given rpath entry\nto the binary in `path`.", "repo": "metalbear-co/mirrord", "path": "mirrord/sip/src/rpath.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/sip/src/rpath.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27690ae0bc91b6852df5a9cbf7115174a5a050afe64915f6dd74ead8bfa255bb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_cert\n\nDocumentation:\nGenerates a new [`CertifiedKey`] with a random [`KeyPair`].\n\n# Params\n\n* `name` - will be used as the subject alternate name, must be either an IP address or a DNS\nname.\n* `issuer` - optional issuer for this certificate. Pass [`None`] to generate a self-signed\ncertificate.\n* `can_sign_others` - whether the generated certificate should be allowed to sign other\ncertificates. Mind that such certificate cannot be used as an end-entity.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate_cert(\n name: &str,\n issuer: Option<&CertifiedKey>,\n can_sign_others: bool,\n) -> Result {\n let key_pair = KeyPair::generate()?;\n\n let mut params = CertificateParams::new(vec![name.to_string()])?;\n params\n .distinguished_name\n .push(DnType::CommonName, DnValue::Utf8String(name.to_string()));\n\n if can_sign_others {\n params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);\n params.key_usages = vec![KeyUsagePurpose::KeyCertSign];\n }\n\n let cert = match issuer {\n Some(issuer) => params.signed_by(&key_pair, &issuer.cert, &issuer.key_pair)?,\n None => params.self_signed(&key_pair)?,\n };\n\n Ok(CertifiedKey { cert, key_pair })\n}\n```"}], "func_name": "generate_cert", "docstring": "Generates a new [`CertifiedKey`] with a random [`KeyPair`].\n\n# Params\n\n* `name` - will be used as the subject alternate name, must be either an IP address or a DNS\nname.\n* `issuer` - optional issuer for this certificate. Pass [`None`] to generate a self-signed\ncertificate.\n* `can_sign_others` - whether the generated certificate should be allowed to sign other\ncertificates. Mind that such certificate cannot be used as an end-entity.", "repo": "metalbear-co/mirrord", "path": "mirrord/tls-util/src/generate.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/tls-util/src/generate.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "de2e0ebfb4740b2b2e1e7491e82d43f8cee1045cb066148b14fd89437945e46e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_new\n\nDocumentation:\nPrepares a new setup using fresh random certificates and keys.\n\nThe generated certificates will contain the respective subject alternate names\ngiven to this function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_new(server_name: &str, client_name: &str) -> Result {\n let root_cert = crate::generate_cert(\"root\", None, true)?;\n\n Ok(Self {\n server_pem: Self::prepare_single_pem(&root_cert, server_name)?,\n client_pem: Self::prepare_single_pem(&root_cert, client_name)?,\n })\n }\n```"}], "func_name": "try_new", "docstring": "Prepares a new setup using fresh random certificates and keys.\n\nThe generated certificates will contain the respective subject alternate names\ngiven to this function.", "repo": "metalbear-co/mirrord", "path": "mirrord/tls-util/src/secure_channel.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/tls-util/src/secure_channel.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac52f2ffe7b2936457584aebf59656bbe67618e7a6c7ea56e17c545926e31e4e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prepare_single_pem\n\nDocumentation:\nCreates a PEM file containing a certificate chain and a private key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn prepare_single_pem(\n root: &CertifiedKey,\n server_name: &str,\n ) -> Result {\n let cert = crate::generate_cert(server_name, Some(root), false)?;\n\n let pem = pem::encode_many_config(\n &[\n Pem::new(\"CERTIFICATE\", cert.cert.der().to_vec()),\n Pem::new(\"CERTIFICATE\", root.cert.der().to_vec()),\n Pem::new(\"PRIVATE KEY\", cert.key_pair.serialize_der()),\n ],\n EncodeConfig::new().set_line_ending(LineEnding::LF),\n );\n\n let mut file =\n NamedTempFile::with_suffix(\".pem\").map_err(SecureChannelError::TmpFileCreateError)?;\n file.as_file_mut().write_all(pem.as_bytes())?;\n\n Ok(file)\n }\n```"}], "func_name": "prepare_single_pem", "docstring": "Creates a PEM file containing a certificate chain and a private key.", "repo": "metalbear-co/mirrord", "path": "mirrord/tls-util/src/secure_channel.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/tls-util/src/secure_channel.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7bb455b63b816cdf840bab2c62b5319996bd283c9f5f3faeafb9e1216adc8d33"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_acceptor\n\nDocumentation:\nCreates a [`TlsAcceptor`] from the given PEM file.\n\nThis PEM file should be generated with [`SecureChannelSetup::try_new`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn create_acceptor(pem_path: &Path) -> Result {\n let cert_chain = crate::read_cert_chain(pem_path.to_path_buf()).await?;\n let key = crate::read_key_der(pem_path.to_path_buf()).await?;\n\n let mut roots = RootCertStore::empty();\n let root = cert_chain\n .last()\n .ok_or(SecureChannelError::NoRootCert)?\n .clone();\n roots\n .add(root)\n .map_err(SecureChannelError::InvalidRootCert)?;\n\n let client_verifier = WebPkiClientVerifier::builder(roots.into()).build()?;\n\n let tls_config = rustls::ServerConfig::builder()\n .with_client_cert_verifier(client_verifier)\n .with_single_cert(cert_chain, key)\n .map_err(SecureChannelError::InvalidCertChain)?;\n\n Ok(TlsAcceptor::from(Arc::new(tls_config)))\n }\n```"}], "func_name": "create_acceptor", "docstring": "Creates a [`TlsAcceptor`] from the given PEM file.\n\nThis PEM file should be generated with [`SecureChannelSetup::try_new`].", "repo": "metalbear-co/mirrord", "path": "mirrord/tls-util/src/secure_channel.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/tls-util/src/secure_channel.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c3280832f024110654f468cf7f17eeed6659620c57c7dc73445cd0a42b4f361"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_connector\n\nDocumentation:\nCreates a [`TlsConnector`] from the given PEM file.\n\nThis PEM file should be generated with [`SecureChannelSetup::try_new`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn create_connector(pem_path: &Path) -> Result {\n let chain = crate::read_cert_chain(pem_path.to_path_buf()).await?;\n let private_key = crate::read_key_der(pem_path.to_path_buf()).await?;\n\n let root = chain.last().ok_or(SecureChannelError::NoRootCert)?.clone();\n\n let mut root_cert_store = RootCertStore::empty();\n root_cert_store\n .add(root)\n .map_err(SecureChannelError::InvalidRootCert)?;\n\n let tls_config = ClientConfig::builder()\n .with_root_certificates(root_cert_store)\n .with_client_auth_cert(chain, private_key)\n .map_err(SecureChannelError::InvalidCertChain)?;\n\n Ok(TlsConnector::from(Arc::new(tls_config)))\n }\n```"}], "func_name": "create_connector", "docstring": "Creates a [`TlsConnector`] from the given PEM file.\n\nThis PEM file should be generated with [`SecureChannelSetup::try_new`].", "repo": "metalbear-co/mirrord", "path": "mirrord/tls-util/src/secure_channel.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/tls-util/src/secure_channel.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e12d1163827cd778b468e4df980e31c526dd8b653ca907a83cc616cf69bea0e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_server_name\n\nDocumentation:\nAttempts to extract a [`ServerName`] from this [`Uri`].\n\nCopied from [hyper-tls](https://github.com/hyperium/hyper-tls/blob/0265e166a8886f01253050516316a95900315b81/src/client.rs#L140).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_server_name(&self) -> Option> {\n let hostname = self.host()?.trim_matches(|c| c == '[' || c == ']');\n\n ServerName::try_from(hostname).ok()\n }\n```"}], "func_name": "get_server_name", "docstring": "Attempts to extract a [`ServerName`] from this [`Uri`].\n\nCopied from [hyper-tls](https://github.com/hyperium/hyper-tls/blob/0265e166a8886f01253050516316a95900315b81/src/client.rs#L140).", "repo": "metalbear-co/mirrord", "path": "mirrord/tls-util/src/uri_ext.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/mirrord/tls-util/src/uri_ext.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4b8a36744d02c6cfb4fcae1a176fb2f3edff1fc0b4d252ca3e1276b336280478"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_from_queue_by_name\n\nDocumentation:\nReads from queue and prints the contents of each message in a new line.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn read_from_queue_by_name(read_q_name: String, client: Client, queue_num: u8) {\n let read_q_url = client\n .get_queue_url()\n .queue_name(read_q_name)\n .send()\n .await\n .unwrap()\n .queue_url\n .unwrap();\n read_from_queue_by_url(read_q_url, client, queue_num).await;\n}\n```"}], "func_name": "read_from_queue_by_name", "docstring": "Reads from queue and prints the contents of each message in a new line.", "repo": "metalbear-co/mirrord", "path": "tests/rust-sqs-printer/src/main.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/rust-sqs-printer/src/main.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0f6fc14da661504395f120dac53453c168c1ddabcc7956a7ca6e9039d2607c8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: random_string\n\nDocumentation:\nCreates a random string of 7 alphanumeric lowercase characters.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn random_string() -> String {\n Alphanumeric\n .sample_string(&mut rand::rng(), 7)\n .to_ascii_lowercase()\n}\n```"}], "func_name": "random_string", "docstring": "Creates a random string of 7 alphanumeric lowercase characters.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5db7d1734ce93ae1d7923fa011b03376debdc601e8aba80c625e7a0ee4a05229"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: format_time\n\nDocumentation:\nReturns string with time format of hh:mm:ss\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn format_time() -> String {\n let now = Utc::now();\n format!(\"{:02}:{:02}:{:02}\", now.hour(), now.minute(), now.second())\n}\n```"}], "func_name": "format_time", "docstring": "Returns string with time format of hh:mm:ss", "repo": "metalbear-co/mirrord", "path": "tests/src/utils.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c071850dbc8906dc041f5d06dcd38c944144b3800344751ecee5a107aa3adf2e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_ipv6_only\n\nDocumentation:\nChange the `ipFamilies` and `ipFamilyPolicy` fields to make the service IPv6-only.\n\n# Panics\n\nWill panic if the given service does not have a spec.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_ipv6_only(service: &mut Service) {\n let spec = service.spec.as_mut().unwrap();\n spec.ip_families = Some(vec![\"IPv6\".to_string()]);\n spec.ip_family_policy = Some(\"SingleStack\".to_string());\n}\n```"}], "func_name": "set_ipv6_only", "docstring": "Change the `ipFamilies` and `ipFamilyPolicy` fields to make the service IPv6-only.\n\n# Panics\n\nWill panic if the given service does not have a spec.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d6e260245137c2af1506fe10d384b96c370c68a97b0b7c4bbccbad18a093b4a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_request\n\nDocumentation:\nTake a request builder of any method, add headers, send the request, verify success, and\noptionally verify expected response.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn send_request(\n request_builder: RequestBuilder,\n expect_response: Option<&str>,\n headers: reqwest::header::HeaderMap,\n) {\n let (client, request) = request_builder.headers(headers).build_split();\n let request = request.unwrap();\n println!(\n \"Sending an HTTP request with version={:?}, method=({}), url=({}), headers=({:?})\",\n request.version(),\n request.method(),\n request.url(),\n request.headers(),\n );\n\n let response = client.execute(request).await.unwrap();\n\n let status = response.status();\n let body = String::from_utf8_lossy(response.bytes().await.unwrap().as_ref()).into_owned();\n\n assert_eq!(\n status,\n StatusCode::OK,\n \"unexpected status, response body: {body}\"\n );\n\n if let Some(expected_response) = expect_response {\n assert_eq!(body, expected_response);\n }\n}\n```"}], "func_name": "send_request", "docstring": "Take a request builder of any method, add headers, send the request, verify success, and\noptionally verify expected response.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cac58e8b73b5808600e94f831f9cd4d1ccf5190fa06bb85ae6b62a36f92acada"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: block_steal_without_qualifiers\n\nDocumentation:\nBlock all stealing for all targets, stealing should not work for either service.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn block_steal_without_qualifiers() -> PolicyTestCase {\n PolicyTestCase {\n policy: MirrordPolicy::new(\n \"e2e-test-block-steal-without-qualifiers\",\n MirrordPolicySpec {\n target_path: None,\n selector: None,\n block: vec![BlockedFeature::Steal],\n env: Default::default(),\n fs: Default::default(),\n network: Default::default(),\n require_profile: Default::default(),\n profile_allowlist: Default::default(),\n applies_to_copy_targets: Default::default(),\n },\n ),\n service_b_can_steal: No,\n service_a_can_steal: No,\n target_deploy_a: false,\n target_deploy_b: false,\n }\n}\n```"}], "func_name": "block_steal_without_qualifiers", "docstring": "Block all stealing for all targets, stealing should not work for either service.", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/policies.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/policies.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ed55d2d989aaaaaa77f6b81fbcc6f22113eec7b1ed008b8d3978305c30b52158"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: block_steal_with_path_pattern\n\nDocumentation:\nBlock all stealing only for service a by path, stealing should work for service b.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn block_steal_with_path_pattern() -> PolicyTestCase {\n PolicyTestCase {\n policy: MirrordPolicy::new(\n \"e2e-test-block-steal-with-path-pattern\",\n MirrordPolicySpec {\n target_path: Some(\"*-service-a*\".into()),\n selector: None,\n block: vec![BlockedFeature::Steal],\n env: Default::default(),\n fs: Default::default(),\n network: Default::default(),\n require_profile: Default::default(),\n profile_allowlist: Default::default(),\n applies_to_copy_targets: Default::default(),\n },\n ),\n service_b_can_steal: EvenWithoutFilter,\n service_a_can_steal: No,\n target_deploy_a: false,\n target_deploy_b: false,\n }\n}\n```"}], "func_name": "block_steal_with_path_pattern", "docstring": "Block all stealing only for service a by path, stealing should work for service b.", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/policies.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/policies.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b5dac343310f0679ea651e6df8ceaad55e999e31851975f99adbade568b7c9fc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: block_unfiltered_steal_with_path_pattern\n\nDocumentation:\nBlock unfiltered stealing only for service a by path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn block_unfiltered_steal_with_path_pattern() -> PolicyTestCase {\n PolicyTestCase {\n policy: MirrordPolicy::new(\n \"e2e-test-block-unfiltered-steal-with-path-pattern\",\n MirrordPolicySpec {\n target_path: Some(\"*-service-a*\".into()),\n selector: None,\n block: vec![BlockedFeature::StealWithoutFilter],\n env: Default::default(),\n fs: Default::default(),\n network: Default::default(),\n require_profile: Default::default(),\n profile_allowlist: Default::default(),\n applies_to_copy_targets: Default::default(),\n },\n ),\n service_b_can_steal: EvenWithoutFilter,\n service_a_can_steal: OnlyWithFilter,\n target_deploy_a: false,\n target_deploy_b: false,\n }\n}\n```"}], "func_name": "block_unfiltered_steal_with_path_pattern", "docstring": "Block unfiltered stealing only for service a by path.", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/policies.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/policies.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "912aa85fe62cd2cbe30b9a6c46b91b8d63405bb2f972d1fc04423f1fe9787e18"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: block_unfiltered_steal_with_deployment_path_pattern\n\nDocumentation:\nBlock unfiltered stealing only for deployment a by path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn block_unfiltered_steal_with_deployment_path_pattern() -> PolicyTestCase {\n PolicyTestCase {\n policy: MirrordPolicy::new(\n \"e2e-test-block-unfiltered-steal-with-path-pattern\",\n MirrordPolicySpec {\n target_path: Some(\"deploy/*service-a*\".into()),\n selector: None,\n block: vec![BlockedFeature::StealWithoutFilter],\n env: Default::default(),\n fs: Default::default(),\n network: Default::default(),\n require_profile: Default::default(),\n profile_allowlist: Default::default(),\n applies_to_copy_targets: Default::default(),\n },\n ),\n service_a_can_steal: OnlyWithFilter,\n service_b_can_steal: EvenWithoutFilter,\n target_deploy_a: true,\n target_deploy_b: false,\n }\n}\n```"}], "func_name": "block_unfiltered_steal_with_deployment_path_pattern", "docstring": "Block unfiltered stealing only for deployment a by path.", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/policies.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/policies.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2023a23304bd343fd4a989070275a907b749bb4239cd842937fe859fc181c664"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: block_steal_with_label_selector\n\nDocumentation:\nBlock all stealing only for service a by label selector, stealing should work for service b.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn block_steal_with_label_selector() -> PolicyTestCase {\n PolicyTestCase {\n policy: MirrordPolicy::new(\n \"e2e-test-block-steal-with-label-selector\",\n MirrordPolicySpec {\n target_path: None,\n selector: Some(LabelSelector {\n match_expressions: None,\n match_labels: Some(BTreeMap::from([(\n \"test-label-for-pods\".to_string(),\n \"pod-policy-e2e-test-service-a\".to_string(),\n )])),\n }),\n block: vec![BlockedFeature::Steal],\n env: Default::default(),\n fs: Default::default(),\n network: Default::default(),\n require_profile: Default::default(),\n profile_allowlist: Default::default(),\n applies_to_copy_targets: Default::default(),\n },\n ),\n service_b_can_steal: EvenWithoutFilter,\n service_a_can_steal: No,\n target_deploy_a: false,\n target_deploy_b: false,\n }\n}\n```"}], "func_name": "block_steal_with_label_selector", "docstring": "Block all stealing only for service a by label selector, stealing should work for service b.", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/policies.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/policies.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b4f89ec0fc74653ffeef8444c8fc26c5ebe6c3ddbc654af38b5c51283c34434"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: block_steal_with_unmatching_policy\n\nDocumentation:\nBlock all stealing in a policy where the path matches only service a but the labels match only\nservice b. Stealing should work for both, as the policy should not match either.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn block_steal_with_unmatching_policy() -> PolicyTestCase {\n PolicyTestCase {\n policy: MirrordPolicy::new(\n \"e2e-test-block-steal-with-unmatching-policy\",\n MirrordPolicySpec {\n target_path: Some(\"*service-b*\".to_string()),\n selector: Some(LabelSelector {\n match_expressions: None,\n match_labels: Some(BTreeMap::from([(\n \"test-label-for-pods\".to_string(),\n \"pod-service-b\".to_string(),\n )])),\n }),\n block: vec![BlockedFeature::Steal],\n env: Default::default(),\n fs: Default::default(),\n network: Default::default(),\n require_profile: Default::default(),\n profile_allowlist: Default::default(),\n applies_to_copy_targets: Default::default(),\n },\n ),\n service_b_can_steal: EvenWithoutFilter,\n service_a_can_steal: EvenWithoutFilter,\n target_deploy_a: false,\n target_deploy_b: false,\n }\n}\n```"}], "func_name": "block_steal_with_unmatching_policy", "docstring": "Block all stealing in a policy where the path matches only service a but the labels match only\nservice b. Stealing should work for both, as the policy should not match either.", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/policies.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/policies.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "75aaa4982969a09cf089d57ece88c9b69765c9fdba305a206b3f415b8494ccee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: assert_subscription_result\n\nDocumentation:\nAssert that port subscription failed due to policy if `expected_success`, else succeeded.\nThis function should be timed out - caller's responsibility.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn assert_subscription_result(mut test_proc: TestProcess, expected_success: bool) {\n if expected_success {\n test_proc\n .wait_for_line(Duration::from_secs(40), \"daemon subscribed\")\n .await;\n test_proc.child.kill().await.unwrap()\n } else {\n test_proc\n .wait_for_line(Duration::from_secs(40), \"forbidden by the mirrord policy\")\n .await;\n // Make sure process exits on a policy block. (test should have a timeout).\n test_proc.wait_assert_fail().await\n }\n}\n```"}], "func_name": "assert_subscription_result", "docstring": "Assert that port subscription failed due to policy if `expected_success`, else succeeded.\nThis function should be timed out - caller's responsibility.", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/policies.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/policies.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6a497ee1f8cd38ca5421006b381bb15733dae446f594ace4cefa9b590b8d9ef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_mirrord_and_verify_steal_result\n\nDocumentation:\nRun mirrord twice, once without an http filter and once with, and verify it works or fails in\neach run according to `can_steal`. This function should be timed out - caller's responsibility.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_mirrord_and_verify_steal_result(\n kube_service: &KubeService,\n target_deployment: bool,\n can_steal: CanSteal,\n) {\n let application = Application::Go21HTTP;\n\n let target = if target_deployment {\n format!(\"deploy/{}\", kube_service.name)\n } else {\n kube_service.pod_container_target()\n };\n\n let test_proc = application\n .run(\n &target,\n Some(&kube_service.namespace),\n Some(vec![\"--steal\", \"--fs-mode=local\"]),\n None,\n )\n .await;\n\n assert_subscription_result(test_proc, can_steal.should_work_without_filter()).await;\n\n let mut config_path = config_dir().clone();\n config_path.push(\"http_filter_header.json\");\n\n let test_proc = application\n .run(\n &kube_service.pod_container_target(),\n Some(&kube_service.namespace),\n Some(vec![\"--config-file\", config_path.to_str().unwrap()]),\n None,\n )\n .await;\n\n assert_subscription_result(test_proc, can_steal.should_work_with_filter()).await;\n}\n```"}], "func_name": "run_mirrord_and_verify_steal_result", "docstring": "Run mirrord twice, once without an http filter and once with, and verify it works or fails in\neach run according to `can_steal`. This function should be timed out - caller's responsibility.", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/policies.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/policies.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0a8ea3be5f0f32c8906f2e649df965ced1963608c8522a7a04773ce46d346012"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_config\n\nDocumentation:\nProduces a mirrord config file for an application run in the [`two_users`] test.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_config(with_regex: bool, (attribute, pattern): (&str, &str)) -> NamedTempFile {\n let mut config = NamedTempFile::with_suffix(\".json\").unwrap();\n\n let content = if with_regex {\n serde_json::json!({\n \"operator\": true,\n \"feature\": {\n \"split_queues\": {\n \"e2e-test-queues\": {\n \"queue_type\": \"SQS\",\n \"message_filter\": {\n attribute: pattern,\n },\n },\n },\n }\n })\n } else {\n serde_json::json!({\n \"operator\": true,\n \"feature\": {\n \"split_queues\": {\n \"e2e-test-queue1\": {\n \"queue_type\": \"SQS\",\n \"message_filter\": {\n attribute: pattern,\n },\n },\n \"e2e-test-queue2\": {\n \"queue_type\": \"SQS\",\n \"message_filter\": {\n attribute: pattern,\n },\n },\n },\n }\n })\n };\n\n serde_json::to_writer_pretty(config.as_file_mut(), &content).unwrap();\n\n config\n}\n```"}], "func_name": "get_config", "docstring": "Produces a mirrord config file for an application run in the [`two_users`] test.", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/queue_splitting.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/queue_splitting.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e82dcdda9a0d409188922894ab99f28c23a752ac9473264df1877287a14cbce4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_output_lines\n\nDocumentation:\nVerify that the test process printed all the expected messages, and none other.\n\nThe expected lines should all be unique in both arrays together (a line should not appear in\nboth arrays or in any array twice).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn expect_output_lines(\n expected_lines: [&str; N],\n expected_in_order_lines: [&str; M],\n test_process: &TestProcess,\n) {\n let lines = test_process\n .await_exactly_n_lines(\n expected_lines.len() + expected_in_order_lines.len(),\n Duration::from_secs(20),\n )\n .await;\n for expected_line in expected_lines.into_iter() {\n assert!(\n lines.contains(&expected_line.to_string()),\n \"User a was expected to print {expected_line} but did not\"\n );\n }\n let mut last_location = 0;\n for expected_line in expected_in_order_lines.into_iter() {\n let location = lines\n .iter()\n .position(|line| *line == expected_line)\n .expect(\"A fifo message did not reach the correct user.\");\n assert!(last_location <= location, \"Fifo messages out of order!\");\n last_location = location;\n }\n}\n```"}], "func_name": "expect_output_lines", "docstring": "Verify that the test process printed all the expected messages, and none other.\n\nThe expected lines should all be unique in both arrays together (a line should not appear in\nboth arrays or in any array twice).", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/queue_splitting.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/queue_splitting.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "02792f87a19aff054b460d9bccece90eabc8e2756d17f5f4e9b553f13454fed2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_message\n\nDocumentation:\nCall SQS API to delete a message by `queue_url` and message `receipt_handle`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn delete_message(client: &aws_sdk_sqs::Client, queue_url: &str, receipt_handle: &str) {\n client\n .delete_message()\n .queue_url(queue_url)\n .receipt_handle(receipt_handle)\n .send()\n .await\n .inspect_err(|err| eprintln!(\"deleting received message failed: {err:?}\"))\n .expect(\"failed to delete SQS message\");\n}\n```"}], "func_name": "delete_message", "docstring": "Call SQS API to delete a message by `queue_url` and message `receipt_handle`.", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/queue_splitting.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/queue_splitting.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad1facfb72f32700598f79316f6bb18799ece553b7c3dc45ddbc2b2a017600e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_messages_in_queue\n\nDocumentation:\nVerify that the echo queue contains the expected messages, meaning the deployed application\nreceived all the messages no user filtered.\nmessages don't have to arrive in any particular message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn expect_messages_in_queue(\n messages: [&str; N],\n client: &aws_sdk_sqs::Client,\n echo_queue: &QueueInfo,\n) {\n tokio::time::timeout(Duration::from_secs(40), async {\n println!(\"Verifying correct messages in echo queue {} (verifying the deployed application got the messages it was supposed to)\", echo_queue.name);\n let mut expected_messages = HashSet::from(messages);\n loop {\n let receive_message_output = client\n .receive_message()\n .queue_url(&echo_queue.url)\n .visibility_timeout(15)\n .wait_time_seconds(20)\n .send()\n .await;\n println!(\"Receive message request output: {:?}\", receive_message_output);\n if let Ok(ReceiveMessageOutput {\n messages: Some(received_messages),\n ..\n }) = receive_message_output\n {\n for Message {\n receipt_handle, body, ..\n } in received_messages {\n let message = body.expect(\"Received empty bodied message from echo queue.\");\n println!(r#\"got message \"{message}\" in queue \"{}\".\"#, echo_queue.name);\n assert!(expected_messages.remove(message.as_str()));\n delete_message(client, &echo_queue.url, &receipt_handle.expect(\"no receipt handle\")).await;\n if expected_messages.is_empty() {\n return;\n }\n }\n }\n }\n }).await.unwrap();\n}\n```"}], "func_name": "expect_messages_in_queue", "docstring": "Verify that the echo queue contains the expected messages, meaning the deployed application\nreceived all the messages no user filtered.\nmessages don't have to arrive in any particular message.", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/queue_splitting.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/queue_splitting.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7306d23e90f4dbb02a5b47379f8ed1e3f22a2f636dab3dac658ad52b12790585"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expect_messages_in_fifo_queue\n\nDocumentation:\nVerify that the echo queue contains the expected messages, meaning the deployed application\nreceived all the messages no user filtered.\nAlso verify the message order was preserved.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn expect_messages_in_fifo_queue(\n messages: [&str; N],\n client: &aws_sdk_sqs::Client,\n echo_queue: &QueueInfo,\n) {\n tokio::time::timeout(Duration::from_secs(20), async {\n println!(\"Verifying correct messages in echo queue {} (verifying the deployed application got the messages it was supposed to)\", echo_queue.name);\n let mut expected_messages = messages.into_iter();\n let mut expected_message = expected_messages.next().unwrap();\n loop {\n let ReceiveMessageOutput {\n messages,\n ..\n } = client\n .receive_message()\n .queue_url(&echo_queue.url)\n .visibility_timeout(15)\n .wait_time_seconds(20)\n .send()\n .await\n .expect(\"receiving messages from echo queue failed\");\n if let Some(received_messages) = messages {\n for Message {\n body, receipt_handle, ..\n } in received_messages {\n let message = body.expect(\"Received empty bodied message from echo queue.\");\n println!(r#\"got message \"{message}\" in queue \"{}\".\"#, echo_queue.name);\n assert_eq!(message, expected_message,);\n delete_message(client, &echo_queue.url, &receipt_handle.expect(\"no receipt handle\")).await;\n let Some(message) = expected_messages.next() else {\n return;\n };\n expected_message = message;\n }\n }\n }\n }).await.unwrap();\n}\n```"}], "func_name": "expect_messages_in_fifo_queue", "docstring": "Verify that the echo queue contains the expected messages, meaning the deployed application\nreceived all the messages no user filtered.\nAlso verify the message order was preserved.", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/queue_splitting.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/queue_splitting.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "515533933ea03d3d78437f1ed2706226c27c868c80fb6c0514f0ceb5c5512d49"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_tls_configs\n\nDocumentation:\nGenerates:\n1. Configuration for the [`GoServService`] in mTLS mode\n2. [`StealPortTlsConfig`] to configure TLS stealing via the operator\n3. Root certificate for [`GoServService`] clients\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_tls_configs() -> (GoServTlsConfig, StealPortTlsConfig, CertifiedKey) {\n let mut pem_files: BTreeMap = Default::default();\n let mut env: HashMap = Default::default();\n\n let root = generate_cert(\"test.root\", None, true).unwrap();\n pem_files.insert(\n \"root.cert.pem\".into(),\n pem::encode_config(\n &Pem::new(\"CERTIFICATE\", root.cert.der().to_vec()),\n EncodeConfig::new().set_line_ending(LineEnding::LF),\n ),\n );\n env.insert(\n GoServService::TLS_CLIENT_ROOTS_ENV_NAME.into(),\n format!(\"{}/root.cert.pem\", GoServTlsConfig::MOUNT_PATH),\n );\n\n let server_cert = generate_cert(\"go-serv\", Some(&root), false).unwrap();\n pem_files.insert(\n \"server.cert.pem\".into(),\n pem::encode_many_config(\n &[\n Pem::new(\"CERTIFICATE\", server_cert.cert.der().to_vec()),\n Pem::new(\"CERTIFICATE\", root.cert.der().to_vec()),\n ],\n EncodeConfig::new().set_line_ending(LineEnding::LF),\n ),\n );\n env.insert(\n GoServService::TLS_SERVER_CERT_ENV_NAME.into(),\n format!(\"{}/server.cert.pem\", GoServTlsConfig::MOUNT_PATH),\n );\n pem_files.insert(\n \"server.key.pem\".into(),\n pem::encode_config(\n &Pem::new(\"PRIVATE KEY\", server_cert.key_pair.serialize_der()),\n EncodeConfig::new().set_line_ending(LineEnding::LF),\n ),\n );\n env.insert(\n GoServService::TLS_SERVER_KEY_ENV_NAME.into(),\n format!(\"{}/server.key.pem\", GoServTlsConfig::MOUNT_PATH),\n );\n\n let agent_client_cert = generate_cert(\"mirrord-agent\", Some(&root), false).unwrap();\n pem_files.insert(\n \"agent.cert.pem\".into(),\n pem::encode_many_config(\n &[\n Pem::new(\"CERTIFICATE\", agent_client_cert.cert.der().to_vec()),\n Pem::new(\"CERTIFICATE\", root.cert.der().to_vec()),\n ],\n EncodeConfig::new().set_line_ending(LineEnding::LF),\n ),\n );\n pem_files.insert(\n \"agent.key.pem\".into(),\n pem::encode_config(\n &Pem::new(\"PRIVATE KEY\", agent_client_cert.key_pair.serialize_der()),\n EncodeConfig::new().set_line_ending(LineEnding::LF),\n ),\n );\n\n let tls_steal_config = StealPortTlsConfig {\n port: 80,\n agent_as_server: AgentServerConfig {\n authentication: TlsAuthentication {\n cert_pem: env\n .get(GoServService::TLS_SERVER_CERT_ENV_NAME)\n .unwrap()\n .into(),\n key_pem: env\n .get(GoServService::TLS_SERVER_KEY_ENV_NAME)\n .unwrap()\n .into(),\n },\n alpn_protocols: [\"h2\", \"http/1.1\", \"http/1.0\"]\n .into_iter()\n .map(ToString::to_string)\n .collect(),\n verification: Some(TlsClientVerification {\n allow_anonymous: false,\n accept_any_cert: false,\n trust_roots: vec![env\n .get(GoServService::TLS_CLIENT_ROOTS_ENV_NAME)\n .unwrap()\n .into()],\n }),\n },\n agent_as_client: AgentClientConfig {\n authentication: Some(TlsAuthentication {\n cert_pem: format!(\"{}/agent.cert.pem\", GoServTlsConfig::MOUNT_PATH).into(),\n key_pem: format!(\"{}/agent.key.pem\", GoServTlsConfig::MOUNT_PATH).into(),\n }),\n verification: TlsServerVerification {\n accept_any_cert: false,\n trust_roots: vec![env\n .get(GoServService::TLS_CLIENT_ROOTS_ENV_NAME)\n .unwrap()\n .into()],\n },\n },\n };\n\n let go_serv_config = GoServTlsConfig {\n port: 80,\n pem_files,\n env,\n };\n\n (go_serv_config, tls_steal_config, root)\n}\n```"}], "func_name": "generate_tls_configs", "docstring": "Generates:\n1. Configuration for the [`GoServService`] in mTLS mode\n2. [`StealPortTlsConfig`] to configure TLS stealing via the operator\n3. Root certificate for [`GoServService`] clients", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/steal_tls.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/steal_tls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf416d9481a2e6f67f8d292bc00cbe1284d0d07045a4eb9443bc79c2dd4b2217"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_request\n\nDocumentation:\nMakes a request to the test service and verifies that it is stolen/ignored.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn make_request(&self, should_be_stolen: bool) {\n println!(\n \"MAKING A REQUEST: should_be_stolen={should_be_stolen} http1={}\",\n self.http1\n );\n\n let response = self\n .client\n .get(\"https://go-serv/\")\n .header(\"x-steal\", if should_be_stolen { \"yes\" } else { \"no\" })\n .header(\"host\", \"go-serv\")\n .send()\n .await\n .unwrap();\n let status = response.status();\n println!(\"RESPONSE STATUS: {status}\");\n\n let body = response.bytes().await.map(Vec::from).map(String::from_utf8);\n\n assert_eq!(\n status,\n reqwest::StatusCode::OK,\n \"REQUEST FAILED: body=({body:?})\"\n );\n\n if should_be_stolen {\n assert_eq!(body.unwrap().unwrap(), \"GET\");\n } else {\n assert_eq!(\n body.unwrap().unwrap(),\n GoServService::REMOTE_SERVER_RESPONSE\n );\n }\n }\n```"}], "func_name": "make_request", "docstring": "Makes a request to the test service and verifies that it is stolen/ignored.", "repo": "metalbear-co/mirrord", "path": "tests/src/operator/steal_tls.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/operator/steal_tls.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "014756ad4b1b7ff35f3f377dc1a6766bb68fe3e9743a4477819fdcf4b713bd06"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: argo_rollout_from_json\n\nDocumentation:\nCreates an Argo Rollout resource with the given name, image, and env vars\n\nCreates a [`Rollout`] resource following the Argo Rollouts\n[specification](https://argoproj.github.io/argo-rollouts/features/specification/)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn argo_rollout_from_json(name: &str, deployment: &Deployment) -> Rollout {\n serde_json::from_value(json!({\n \"apiVersion\": Rollout::API_VERSION,\n \"kind\": Rollout::KIND,\n \"metadata\": {\n \"name\": name,\n \"labels\": {\n \"app\": name,\n TEST_RESOURCE_LABEL.0: TEST_RESOURCE_LABEL.1,\n \"test-label-for-rollouts\": format!(\"rollout-{name}\")\n }\n },\n \"spec\": {\n \"replicas\": 1,\n \"selector\": {\n \"matchLabels\": {\n \"app\": name\n }\n },\n \"workloadRef\": {\n \"apiVersion\": Deployment::API_VERSION,\n \"kind\": Deployment::KIND,\n \"name\": deployment.name().unwrap()\n },\n \"strategy\": {\n \"canary\": {}\n }\n }\n }))\n .expect(\"Failed creating `rollout` from json spec!\")\n}\n```"}], "func_name": "argo_rollout_from_json", "docstring": "Creates an Argo Rollout resource with the given name, image, and env vars\n\nCreates a [`Rollout`] resource following the Argo Rollouts\n[specification](https://argoproj.github.io/argo-rollouts/features/specification/)", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/cluster_resource.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/cluster_resource.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d814d7c74f42057fc0efc64ebfcd1db397c092eb1e633b973262d34bf87bffca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_request_with_method\n\nDocumentation:\nSend an HTTP request using the referenced `request_sender`, with the provided `method`,\nthen verify a success status code, and a response body that is the used method.\n\n# Panics\n- If the request cannot be sent.\n- If the response's code is not OK\n- If the response's body is not the method's name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn send_request_with_method(\n method: &str,\n request_sender: &mut SendRequest>,\n) {\n let req = Request::builder()\n .method(method)\n .header(\"Host\", \"::\")\n .body(Empty::::new())\n .unwrap();\n\n println!(\"Request: {:?}\", req);\n\n let res = request_sender.send_request(req).await.unwrap();\n println!(\"Response: {:?}\", res);\n assert_eq!(res.status(), hyper::StatusCode::OK);\n let bytes = res.collect().await.unwrap().to_bytes();\n let response_string = String::from_utf8(bytes.to_vec()).unwrap();\n assert_eq!(response_string, method);\n}\n```"}], "func_name": "send_request_with_method", "docstring": "Send an HTTP request using the referenced `request_sender`, with the provided `method`,\nthen verify a success status code, and a response body that is the used method.\n\n# Panics\n- If the request cannot be sent.\n- If the response's code is not OK\n- If the response's body is not the method's name.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/ipv6.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/ipv6.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb74339e12f0f43fcc526504825b8e636a1c515e7dc700c806255399b97078d8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: portforward_http_requests\n\nDocumentation:\nCreate a portforward to the pod of the test service, and send HTTP requests over it.\nSend four HTTP request (GET, POST, PUT, DELETE), using the referenced `request_sender`, with the\nprovided `method`, verify OK status, and a response body that is the used method.\n\n# Panics\n- If a request cannot be sent.\n- If a response's code is not OK\n- If a response's body is not the method's name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn portforward_http_requests(api: &Api, service: KubeService) {\n let mut portforwarder = api\n .portforward(&service.pod_name, &[80])\n .await\n .expect(\"Failed to start portforward to test pod\");\n\n let stream = portforwarder.take_stream(80).unwrap();\n let stream = hyper_util::rt::TokioIo::new(stream);\n\n let (mut request_sender, connection) = conn::http1::handshake(stream).await.unwrap();\n tokio::spawn(async move {\n if let Err(err) = connection.await {\n eprintln!(\"Error in connection from test function to deployed test app {err:#?}\");\n }\n });\n for method in [\"GET\", \"POST\", \"PUT\", \"DELETE\"] {\n send_request_with_method(method, &mut request_sender).await;\n }\n}\n```"}], "func_name": "portforward_http_requests", "docstring": "Create a portforward to the pod of the test service, and send HTTP requests over it.\nSend four HTTP request (GET, POST, PUT, DELETE), using the referenced `request_sender`, with the\nprovided `method`, verify OK status, and a response body that is the used method.\n\n# Panics\n- If a request cannot be sent.\n- If a response's code is not OK\n- If a response's body is not the method's name.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/ipv6.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/ipv6.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7b145d8ead17b86fe9d10096600e5b7a8c763ea222f93cff83bd8614a00d6f3e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a portforwarder for a specific port on a specific pod.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn new(client: Client, pod_name: &str, pod_namespace: &str, port: u16) -> Self {\n let api = Api::namespaced(client, pod_namespace);\n\n let _ = api.portforward(pod_name, &[port]).await.unwrap();\n\n let listener = TcpListener::bind(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0))\n .await\n .unwrap();\n let address = listener.local_addr().unwrap();\n\n let handle = tokio::spawn(Self::background_task(\n listener,\n api,\n pod_name.to_string(),\n port,\n ));\n\n println!(\"Created a portforwarder for {pod_namespace}/{pod_name}:{port}. Local address is {address}\");\n\n Self { address, handle }\n }\n```"}], "func_name": "new", "docstring": "Creates a portforwarder for a specific port on a specific pod.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/port_forwarder.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/port_forwarder.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "638dc54f5135577f8e7456b293673eedc67f71a9e43c3c92f623827ef157fbbd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: background_task\n\nDocumentation:\nLogic of the background [`tokio::task`] that handles connections.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn background_task(listener: TcpListener, api: Api, pod_name: String, port: u16) {\n let mut tasks = JoinSet::new();\n\n loop {\n let (mut local_conn, _) = listener.accept().await.unwrap();\n let api = api.clone();\n let pod_name = pod_name.clone();\n\n tasks.spawn(async move {\n let mut portforwarder = api.portforward(&pod_name, &[port]).await.unwrap();\n let mut pod_conn = portforwarder.take_stream(port).unwrap();\n tokio::io::copy_bidirectional(&mut local_conn, &mut pod_conn)\n .await\n .unwrap();\n std::mem::drop(pod_conn);\n std::mem::drop(local_conn);\n portforwarder.abort();\n });\n }\n }\n```"}], "func_name": "background_task", "docstring": "Logic of the background [`tokio::task`] that handles connections.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/port_forwarder.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/port_forwarder.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2c290cc4c383d1a7dba0899884c7a83ceef5d0c79098a604427a723fcbcb2600"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: await_n_lines\n\nDocumentation:\nWait for the test app to output (at least) the given amount of lines.\n\n# Arguments\n\n* `timeout` - how long to wait for process to output enough lines.\n\n# Panics\nIf `timeout` has passed and stdout still does not contain `n` lines.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn await_n_lines(&self, n: usize, timeout: Duration) -> Vec {\n tokio::time::timeout(timeout, async move {\n loop {\n let stdout = self.get_stdout().await;\n if stdout.lines().count() >= n {\n return stdout\n .lines()\n .map(ToString::to_string)\n .collect::>();\n }\n tokio::time::sleep(Duration::from_millis(100)).await;\n }\n })\n .await\n .expect(\"Test process output did not produce expected amount of lines in time.\")\n }\n```"}], "func_name": "await_n_lines", "docstring": "Wait for the test app to output (at least) the given amount of lines.\n\n# Arguments\n\n* `timeout` - how long to wait for process to output enough lines.\n\n# Panics\nIf `timeout` has passed and stdout still does not contain `n` lines.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/process.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/process.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1e7fc5d9afa088e6ba82fffc032ea584e091b1b98ad04adc3224f685cba9e463"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: await_exactly_n_lines\n\nDocumentation:\nWait for the test app to output the given amount of lines, then assert it did not output\nmore than expected.\n\n> Note: we do not wait to make sure more lines are not printed, we just check the lines we\n> got after waiting for n lines. So it is possible for this to happen:\n1. Test process outputs `n` lines.\n2. `await_n_lines` returns those `n` lines.\n3. This function asserts there are only `n` lines.\n3. The test process outputs more lines.\n\n# Arguments\n\n* `timeout` - how long to wait for process to output enough lines.\n\n# Panics\n- If `timeout` has passed and stdout still does not contain `n` lines.\n- If stdout contains more than `n` lines.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn await_exactly_n_lines(&self, n: usize, timeout: Duration) -> Vec {\n let lines = self.await_n_lines(n, timeout).await;\n assert_eq!(\n lines.len(),\n n,\n \"Test application printed out more lines than expected.\"\n );\n lines\n }\n```"}], "func_name": "await_exactly_n_lines", "docstring": "Wait for the test app to output the given amount of lines, then assert it did not output\nmore than expected.\n\n> Note: we do not wait to make sure more lines are not printed, we just check the lines we\n> got after waiting for n lines. So it is possible for this to happen:\n1. Test process outputs `n` lines.\n2. `await_n_lines` returns those `n` lines.\n3. This function asserts there are only `n` lines.\n3. The test process outputs more lines.\n\n# Arguments\n\n* `timeout` - how long to wait for process to output enough lines.\n\n# Panics\n- If `timeout` has passed and stdout still does not contain `n` lines.\n- If stdout contains more than `n` lines.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/process.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/process.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b7d5a111d49a55ea7a7b9251491a06dfbc2364772b566d3fdf8f77e2b5290cd2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait\n\nDocumentation:\nWaits for process to end and stdout/err to be read. - returns final exit status\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn wait(&mut self) -> ExitStatus {\n eprintln!(\"waiting for process to exit\");\n let exit_status = self.child.wait().await.unwrap();\n eprintln!(\"process exit, waiting for stdout/err to be read\");\n self.stdout_task\n .take()\n .expect(\"can't call wait twice\")\n .await\n .unwrap();\n self.stderr_task\n .take()\n .expect(\"can't call wait twice\")\n .await\n .unwrap();\n eprintln!(\"stdout/err read and finished\");\n exit_status\n }\n```"}], "func_name": "wait", "docstring": "Waits for process to end and stdout/err to be read. - returns final exit status", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/process.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/process.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "41f27e5991148fcb4f270e3d5f2b12c83e9a810a0da276aedfd77e7028365364"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create\n\nDocumentation:\nCreate a kube resource and spawn a task to delete it when this guard is dropped.\nReturn [`Error`] if creating the resource failed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn create<\n K: Resource + Debug + Clone + DeserializeOwned + Serialize + 'static,\n >(\n api: Api,\n data: &K,\n delete_on_fail: bool,\n ) -> Result<(ResourceGuard, K), Error> {\n let name = data.meta().name.clone().unwrap();\n println!(\"Creating {} `{name}`: {data:?}\", K::kind(&()));\n let created = api.create(&PostParams::default(), data).await?;\n println!(\"Created {} `{name}`\", K::kind(&()));\n\n let deleter = async move {\n println!(\"Deleting {} `{name}`\", K::kind(&()));\n let delete_params = DeleteParams {\n grace_period_seconds: Some(0),\n ..Default::default()\n };\n let res = api.delete(&name, &delete_params).await;\n if let Err(e) = res {\n println!(\"Failed to delete {} `{name}`: {e:?}\", K::kind(&()));\n }\n };\n\n Ok((\n Self {\n delete_on_fail,\n deleter: Some(deleter.boxed()),\n },\n created,\n ))\n }\n```"}], "func_name": "create", "docstring": "Create a kube resource and spawn a task to delete it when this guard is dropped.\nReturn [`Error`] if creating the resource failed.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/resource_guard.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/resource_guard.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "df419572b9f04cf33906e9e789aad310b035e68df0eeab1abd51b50d9dab07a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: take_deleter\n\nDocumentation:\nIf the underlying resource should be deleted (e.g. current thread is not panicking or\n`delete_on_fail` was set), return the future to delete it. The future will\ndelete the resource once awaited.\n\nUsed to run deleters from multiple [`ResourceGuard`]s on one runtime.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn take_deleter(&mut self) -> Option> {\n if !std::thread::panicking() || self.delete_on_fail {\n self.deleter.take()\n } else {\n None\n }\n }\n```"}], "func_name": "take_deleter", "docstring": "If the underlying resource should be deleted (e.g. current thread is not panicking or\n`delete_on_fail` was set), return the future to delete it. The future will\ndelete the resource once awaited.\n\nUsed to run deleters from multiple [`ResourceGuard`]s on one runtime.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/resource_guard.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/resource_guard.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ec3319acabbf969abda05337b558b31acca30edee0be0473bac903d7a4f68b3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_exec_targetless\n\nDocumentation:\nRun `mirrord exec` without specifying a target, to run in targetless mode.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_exec_targetless(\n process_cmd: Vec<&str>,\n namespace: Option<&str>,\n args: Option>,\n env: Option>,\n) -> TestProcess {\n run_exec(process_cmd, None, namespace, args, env).await\n}\n```"}], "func_name": "run_exec_targetless", "docstring": "Run `mirrord exec` without specifying a target, to run in targetless mode.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/run_command.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/run_command.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c7147b925c7221e081db02dcd6a12af3b2622e7a4fd48b7917fea8ac1715a43c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_exec\n\nDocumentation:\nRun `mirrord exec` with the given cmd, optional target (`None` for targetless), namespace,\nmirrord args, and env vars.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_exec(\n process_cmd: Vec<&str>,\n target: Option<&str>,\n namespace: Option<&str>,\n args: Option>,\n env: Option>,\n) -> TestProcess {\n let mut mirrord_args = vec![\"exec\", \"-c\"];\n if let Some(target) = target {\n mirrord_args.extend([\"--target\", target].into_iter());\n }\n if let Some(namespace) = namespace {\n mirrord_args.extend([\"--target-namespace\", namespace].into_iter());\n }\n\n if let Some(args) = args {\n mirrord_args.extend(args.into_iter());\n }\n mirrord_args.push(\"--\");\n let args: Vec<&str> = mirrord_args\n .into_iter()\n .chain(process_cmd.into_iter())\n .collect();\n let agent_image_env = \"MIRRORD_AGENT_IMAGE\";\n let agent_image_from_devs_env = std::env::var(agent_image_env);\n // used by the CI, to load the image locally:\n // docker build -t test . -f mirrord/agent/Dockerfile\n // minikube load image test:latest\n let mut base_env = HashMap::new();\n base_env.insert(\n agent_image_env,\n // Let devs running the test specify an agent image per env var.\n agent_image_from_devs_env.as_deref().unwrap_or(\"test\"),\n );\n base_env.insert(\"MIRRORD_CHECK_VERSION\", \"false\");\n base_env.insert(\"MIRRORD_AGENT_RUST_LOG\", \"warn,mirrord=debug\");\n base_env.insert(\"MIRRORD_AGENT_COMMUNICATION_TIMEOUT\", \"180\");\n // We're using k8s portforwarding for sending traffic to test services.\n // The packets arrive to loopback interface.\n base_env.insert(\"MIRRORD_AGENT_NETWORK_INTERFACE\", \"lo\");\n base_env.insert(\"RUST_LOG\", \"warn,mirrord=debug\");\n\n if let Some(env) = env {\n for (key, value) in env {\n base_env.insert(key, value);\n }\n }\n\n run_mirrord(args, base_env).await\n}\n```"}], "func_name": "run_exec", "docstring": "Run `mirrord exec` with the given cmd, optional target (`None` for targetless), namespace,\nmirrord args, and env vars.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/run_command.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/run_command.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e631c68a16aef3ac972eac1d1536f7ea03b2a2603d51d60f05920a7d47a2768"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_verify_config\n\nDocumentation:\nRuns `mirrord verify-config [--ide] \"/path/config.json\"`.\n\n## Attention\n\nThe `verify-config` tests are here to guarantee that your changes do not break backwards\ncompatability, so you should not modify them, only add new tests (unless breakage is\nwanted/required).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_verify_config(args: Option>) -> TestProcess {\n let mut mirrord_args = vec![\"verify-config\"];\n if let Some(args) = args {\n mirrord_args.extend(args);\n }\n\n run_mirrord(mirrord_args, Default::default()).await\n}\n```"}], "func_name": "run_verify_config", "docstring": "Runs `mirrord verify-config [--ide] \"/path/config.json\"`.\n\n## Attention\n\nThe `verify-config` tests are here to guarantee that your changes do not break backwards\ncompatability, so you should not modify them, only add new tests (unless breakage is\nwanted/required).", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/run_command.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/run_command.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cee5c44736b6719acc71667927268a939c80fe5bb81acc58e6a2f7e03b30d2a1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: service_with_env\n\nDocumentation:\nCreate a new [`KubeService`] and related Kubernetes resources.\n\nThe resources will be deleted\nwhen the returned service is dropped, unless it is dropped during panic.\nThis behavior can be changed, see [`PRESERVE_FAILED_ENV_NAME`].\n* `randomize_name` - whether a random suffix should be added to the end of the resource names\n* `env` - `Value`, should be `Value::Array` of kubernetes container env var definitions.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn service_with_env(\n namespace: &str,\n service_type: &str,\n image: &str,\n service_name: &str,\n randomize_name: bool,\n kube_client: Client,\n env: Value,\n) -> KubeService {\n internal_service(\n namespace,\n service_type,\n image,\n service_name,\n randomize_name,\n kube_client,\n env,\n false,\n )\n .await\n}\n```"}], "func_name": "service_with_env", "docstring": "Create a new [`KubeService`] and related Kubernetes resources.\n\nThe resources will be deleted\nwhen the returned service is dropped, unless it is dropped during panic.\nThis behavior can be changed, see [`PRESERVE_FAILED_ENV_NAME`].\n* `randomize_name` - whether a random suffix should be added to the end of the resource names\n* `env` - `Value`, should be `Value::Array` of kubernetes container env var definitions.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/services.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/services.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6e8f15d8c0e2debf6d8cc75ffdd81a865c3842df16c5d03389a5091e347197b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: count_temp_queues\n\nDocumentation:\nCount the temp queues created by the SQS-operator for this test instance.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn count_temp_queues(&self) -> usize {\n self.sqs_client\n .list_queues()\n .queue_name_prefix(\"mirrord-\")\n .send()\n .await\n .unwrap()\n .queue_urls\n .unwrap_or_default()\n .iter()\n .filter(|q_url| q_url.contains(&self.queue1.name) || q_url.contains(&self.queue2.name))\n .count()\n }\n```"}], "func_name": "count_temp_queues", "docstring": "Count the temp queues created by the SQS-operator for this test instance.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/sqs_resources.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/sqs_resources.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b83555e38c3448000f7bb49de9a1c4c568c2bfbd3ed2ebc52ad73f06b47171f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait_for_temp_queue_deletion\n\nDocumentation:\nWait for all the temp queues created by the SQS operator\nfor this test instance to be deleted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn wait_for_temp_queue_deletion(&self) {\n loop {\n if self.count_temp_queues().await == 0 {\n return;\n }\n tokio::time::sleep(Duration::from_secs(2)).await;\n }\n }\n```"}], "func_name": "wait_for_temp_queue_deletion", "docstring": "Wait for all the temp queues created by the SQS operator\nfor this test instance to be deleted.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/sqs_resources.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/sqs_resources.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "066a78d7b4f60fb1cf12ae7a333f14c8d4364dfff238ffb2271e9de6d8006377"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_sqs_client\n\nDocumentation:\nGet an SQS client. If a localstack URL is provided the client will use that localstack service.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn get_sqs_client(mut env: HashMap) -> aws_sdk_sqs::Client {\n let config = aws_config::from_env()\n .empty_test_environment()\n .region(Region::new(env.remove(AWS_REGION_ENV).unwrap()))\n .endpoint_url(env.remove(AWS_ENDPOINT_ENV).unwrap())\n .credentials_provider(TestCredentialsProvider {\n secret_access_key: env.remove(AWS_SECRET_ACCESS_KEY_ENV).unwrap(),\n access_key_id: env.remove(AWS_ACCESS_KEY_ID_ENV).unwrap(),\n });\n\n let config = config.load().await;\n aws_sdk_sqs::Client::new(&config)\n}\n```"}], "func_name": "get_sqs_client", "docstring": "Get an SQS client. If a localstack URL is provided the client will use that localstack service.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/sqs_resources.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/sqs_resources.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "559c0b414c03025a7f8d598bbb3e2b0b9d7fac2c31373ab286f70e1ffa9ba0db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: random_name_sqs_queue_with_echo_queue\n\nDocumentation:\nCreate a new SQS fifo queue with a randomized name, return queue name and url.\nAlso create another SQS queue that has a name that is \"Echo\" + the name of the first queue.\nCreate resource guards for both queues that delete the queue on drop, push into guards vec.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn random_name_sqs_queue_with_echo_queue(\n fifo: bool,\n client: &aws_sdk_sqs::Client,\n guards: &mut Vec,\n) -> (QueueInfo, QueueInfo) {\n let q_name = format!(\n \"E2ETest-{}{}\",\n crate::utils::random_string(),\n if fifo { \".fifo\" } else { \"\" }\n );\n\n let echo_q_name = format!(\"Echo{q_name}\");\n // Create queue and resource guard\n\n (\n sqs_queue(fifo, client, guards, q_name).await,\n sqs_queue(fifo, client, guards, echo_q_name).await,\n )\n}\n```"}], "func_name": "random_name_sqs_queue_with_echo_queue", "docstring": "Create a new SQS fifo queue with a randomized name, return queue name and url.\nAlso create another SQS queue that has a name that is \"Echo\" + the name of the first queue.\nCreate resource guards for both queues that delete the queue on drop, push into guards vec.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/sqs_resources.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/sqs_resources.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5c8a0a8f93a2cc4d716ab7a6206f79e86fba3c5721e9d34df488ecb5c055e2e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sqs_queue\n\nDocumentation:\nCreate a new SQS fifo queue, return queue name and url.\nCreate resource guard that deletes the queue on drop, push into guards vec.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn sqs_queue(\n fifo: bool,\n client: &aws_sdk_sqs::Client,\n guards: &mut Vec,\n name: String,\n) -> QueueInfo {\n println!(\"Creating SQS queue: {name}\");\n let mut builder = client\n .create_queue()\n .queue_name(&name)\n .attributes(MessageRetentionPeriod, \"3600\"); // delete messages after an hour.\n\n // Cannot set FifoQueue to false: https://github.com/aws/aws-cdk/issues/8550\n if fifo {\n builder = builder.attributes(FifoQueue, \"true\")\n }\n\n let queue_url = builder.send().await.unwrap().queue_url.unwrap();\n let url = queue_url.clone();\n let queue_name = name.clone();\n let client = client.clone();\n\n let deleter = Some(\n async move {\n println!(\"deleting SQS queue {queue_name}\");\n if let Err(err) = client.delete_queue().queue_url(queue_url).send().await {\n eprintln!(\"Could not delete SQS queue {queue_name}: {err:?}\");\n }\n }\n .boxed(),\n );\n guards.push(ResourceGuard {\n delete_on_fail: true,\n deleter,\n });\n\n QueueInfo { name, url }\n}\n```"}], "func_name": "sqs_queue", "docstring": "Create a new SQS fifo queue, return queue name and url.\nCreate resource guard that deletes the queue on drop, push into guards vec.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/sqs_resources.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/sqs_resources.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7110fb872021abc61de98fe8a8bd2e824a64cf238e578c757d6971c8623a94ec"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_queue_registry_resource\n\nDocumentation:\nCreate the `MirrordWorkloadQueueRegistry` K8s resource.\nNo ResourceGuard needed, the namespace is guarded.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn create_queue_registry_resource(\n kube_client: &Client,\n namespace: &str,\n deployment_name: &str,\n use_regex: bool,\n) {\n println!(\"Creating MirrordWorkloadQueueRegistry resource\");\n\n let queues = if use_regex {\n BTreeMap::from([(\n \"e2e-test-queues\".to_string(),\n SplitQueue::Sqs(SqsQueueDetails {\n name_source: QueueNameSource::RegexPattern(BOTH_QUEUES_REGEX_PATTERN.to_string()),\n tags: None,\n fallback_name: None,\n names_from_json_map: None,\n }),\n )])\n } else {\n BTreeMap::from([\n (\n \"e2e-test-queue1\".to_string(),\n SplitQueue::Sqs(SqsQueueDetails {\n name_source: QueueNameSource::EnvVar(QUEUE_NAME_ENV_VAR1.to_string()),\n tags: None,\n fallback_name: None,\n names_from_json_map: None,\n }),\n ),\n (\n \"e2e-test-queue2\".to_string(),\n SplitQueue::Sqs(SqsQueueDetails {\n name_source: QueueNameSource::EnvVar(QUEUE2_URL_ENV_VAR.to_string()),\n tags: None,\n fallback_name: None,\n names_from_json_map: None,\n }),\n ),\n ])\n };\n\n let qr_api: Api = Api::namespaced(kube_client.clone(), namespace);\n let queue_registry = MirrordWorkloadQueueRegistry::new(\n QUEUE_REGISTRY_RESOURCE_NAME,\n MirrordWorkloadQueueRegistrySpec {\n queues,\n consumer: QueueConsumer {\n name: deployment_name.to_string(),\n container: None,\n workload_type: QueueConsumerType::Deployment,\n },\n },\n );\n qr_api\n .create(&PostParams::default(), &queue_registry)\n .await\n .expect(\"Could not create queue splitter in E2E test.\");\n println!(\"MirrordWorkloadQueueRegistry resource created at namespace {namespace} with name {QUEUE_REGISTRY_RESOURCE_NAME}\");\n}\n```"}], "func_name": "create_queue_registry_resource", "docstring": "Create the `MirrordWorkloadQueueRegistry` K8s resource.\nNo ResourceGuard needed, the namespace is guarded.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/sqs_resources.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/sqs_resources.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "987f312d3f6efe83e3b0a03924190866bdad9ef78bc3d9da5a7525eae83bcd53"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sqs_consumer_service\n\nDocumentation:\nCreate a microservice for the sqs test application.\nThat service will be configured to use the \"localstack\" service in the \"default\" namespace for\nall AWS stuff.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn sqs_consumer_service(\n kube_client: &Client,\n queue1: &QueueInfo,\n queue2: &QueueInfo,\n echo_queue1: &QueueInfo,\n echo_queue2: &QueueInfo,\n aws_creds: HashMap,\n) -> KubeService {\n let namespace = format!(\"e2e-tests-sqs-splitting-{}\", crate::utils::random_string());\n\n let env = [\n (QUEUE_NAME_ENV_VAR1.into(), queue1.name.clone()),\n (QUEUE2_URL_ENV_VAR.into(), queue2.url.clone()),\n (ECHO_QUEUE_NAME_ENV_VAR1.into(), echo_queue1.name.clone()),\n (ECHO_QUEUE_NAME_ENV_VAR2.into(), echo_queue2.name.clone()),\n ]\n .into_iter()\n .chain(aws_creds)\n .map(|(name, value)| EnvVar {\n name,\n value: Some(value),\n value_from: None,\n })\n .collect::>();\n\n service_with_env(\n &namespace,\n \"ClusterIP\",\n \"ghcr.io/metalbear-co/mirrord-sqs-forwarder:latest\",\n \"queue-forwarder\",\n false,\n kube_client.clone(),\n serde_json::to_value(env).unwrap(),\n )\n .await\n}\n```"}], "func_name": "sqs_consumer_service", "docstring": "Create a microservice for the sqs test application.\nThat service will be configured to use the \"localstack\" service in the \"default\" namespace for\nall AWS stuff.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/sqs_resources.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/sqs_resources.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "189b6dbbb5e08bdb1a23731f35180731c0a5bdbfdf3120b804102c3413326697"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_localstack_service\n\nDocumentation:\nAttempts to find the `localstack` service in the `localstack` namespace.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn get_localstack_service(kube_client: &Client) -> Option {\n let service_api = Api::::namespaced(kube_client.clone(), \"localstack\");\n service_api.get(\"localstack\").await.ok()\n}\n```"}], "func_name": "get_localstack_service", "docstring": "Attempts to find the `localstack` service in the `localstack` namespace.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/sqs_resources.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/sqs_resources.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69034333a0747140fdaa745f57f1d86ccff1a602ad9701c315fcb36b9be239cb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: watch_sqs_sessions\n\nDocumentation:\nWatch [`MirrordSqsSession`] resources in the given namespace and return once two unique sessions\nare ready.\n\nReturn `Err(())` if there was an error while watching or if a session was deleted before 2 were\nready.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn watch_sqs_sessions(kube_client: Client, namespace: &str) {\n let api = Api::::namespaced(kube_client, namespace);\n Watcher::new(api, Default::default(), |sessions| {\n sessions\n .values()\n .filter(|s| is_session_ready(Some(s)))\n .count()\n == 2\n })\n .run()\n .await;\n}\n```"}], "func_name": "watch_sqs_sessions", "docstring": "Watch [`MirrordSqsSession`] resources in the given namespace and return once two unique sessions\nare ready.\n\nReturn `Err(())` if there was an error while watching or if a session was deleted before 2 were\nready.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/sqs_resources.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/sqs_resources.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d35cb2b97480137a6ef19391832d0046bc8b8b128d893dae321509b942048717"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sqs_test_resources\n\nDocumentation:\n- Fetch AWS credentials from the operator container.\n- Create an SQS client (that uses localstack if there).\n- Create 4 guarded SQS queues with partially random names: 2 queues for the test applications to\nconsume from, and two \"echo\" queues from the deployed test application to forward messages to,\nso that the test can verify it received them.\n- Start a task that waits for 2 SQS Sessions to be ready.\n- Deploy a consumer service in a new guarded namespace with a partially random name.\n- Create a `MirrordWorkloadQueueRegistry` resource in the test's namespace.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn sqs_test_resources(kube_client: Client, use_regex: bool) -> SqsTestResources {\n let mut guards = Vec::new();\n\n let aws_creds = fetch_aws_creds(kube_client.clone()).await;\n let mut local_aws_creds = aws_creds.clone();\n\n let aws_endpoint_url = local_aws_creds.get_mut(AWS_ENDPOINT_ENV).unwrap();\n let localstack_portforwarder = if aws_endpoint_url.contains(\"localstack.svc.cluster\") {\n let localstack = get_localstack_service(&kube_client).await.unwrap();\n let localstack_portforwarder =\n PortForwarder::new_for_service(kube_client.clone(), &localstack, 4566).await;\n *aws_endpoint_url = format!(\"http://{}\", localstack_portforwarder.address());\n Some(localstack_portforwarder)\n } else {\n None\n };\n\n let sqs_client = get_sqs_client(local_aws_creds).await;\n\n let (queue1, echo_queue1) =\n random_name_sqs_queue_with_echo_queue(false, &sqs_client, &mut guards).await;\n let (queue2, echo_queue2) =\n random_name_sqs_queue_with_echo_queue(true, &sqs_client, &mut guards).await;\n let k8s_service = sqs_consumer_service(\n &kube_client,\n &queue1,\n &queue2,\n &echo_queue1,\n &echo_queue2,\n aws_creds,\n )\n .await;\n\n create_queue_registry_resource(\n &kube_client,\n &k8s_service.namespace,\n &k8s_service.name,\n use_regex,\n )\n .await;\n\n SqsTestResources {\n kube_client,\n k8s_service,\n queue1,\n echo_queue1,\n queue2,\n echo_queue2,\n sqs_client,\n _guards: guards,\n _localstack_portforwarder: localstack_portforwarder,\n }\n}\n```"}], "func_name": "sqs_test_resources", "docstring": "- Fetch AWS credentials from the operator container.\n- Create an SQS client (that uses localstack if there).\n- Create 4 guarded SQS queues with partially random names: 2 queues for the test applications to\nconsume from, and two \"echo\" queues from the deployed test application to forward messages to,\nso that the test can verify it received them.\n- Start a task that waits for 2 SQS Sessions to be ready.\n- Deploy a consumer service in a new guarded namespace with a partially random name.\n- Create a `MirrordWorkloadQueueRegistry` resource in the test's namespace.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/sqs_resources.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/sqs_resources.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "333a2f311468b29dc7692b90e79987a7666fc5cf671df5908e6720ad08555d5e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fetch_aws_creds\n\nDocumentation:\nFetches AWS client environment from the operator container spec.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn fetch_aws_creds(client: Client) -> HashMap {\n let env_map = Api::::namespaced(client, \"mirrord\")\n .get(OPERATOR_NAME)\n .await\n .unwrap()\n .spec\n .unwrap()\n .template\n .spec\n .unwrap()\n .containers\n .into_iter()\n .find(|container| container.name == OPERATOR_NAME)\n .unwrap()\n .env\n .unwrap()\n .into_iter()\n .filter_map(|env| {\n if AWS_CREDS_ENVS.contains(&env.name.as_str()) {\n Some((env.name, env.value.unwrap()))\n } else {\n None\n }\n })\n .collect::>();\n\n assert_eq!(\n env_map.len(),\n AWS_CREDS_ENVS.len(),\n \"operator is not properly configured for SQS splitting tests, env=[{env_map:?}], expected={AWS_CREDS_ENVS:?}\",\n );\n\n env_map\n}\n```"}], "func_name": "fetch_aws_creds", "docstring": "Fetches AWS client environment from the operator container spec.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/sqs_resources.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/sqs_resources.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "156894cc1c8997b65bba38a47257fc63a576562a52202b55a594d369788e5eec"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_event\n\nDocumentation:\nHandles the given [`runtime::watcher()`] event and returns whether [`Self::condition`] is\nnow fulfilled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_event(&mut self, event: Event) -> bool {\n match event {\n Event::Apply(resource) => {\n let name = resource.meta().name.clone().unwrap();\n self.resources.insert(name, resource);\n (self.condition)(&self.resources)\n }\n Event::Delete(resource) => {\n let name = resource.meta().name.as_deref().unwrap();\n self.resources.remove(name);\n (self.condition)(&self.resources)\n }\n Event::Init => {\n self.resources.clear();\n false\n }\n Event::InitApply(resource) => {\n let name = resource.meta().name.clone().unwrap();\n self.resources.insert(name, resource);\n false\n }\n Event::InitDone => (self.condition)(&self.resources),\n }\n }\n```"}], "func_name": "handle_event", "docstring": "Handles the given [`runtime::watcher()`] event and returns whether [`Self::condition`] is\nnow fulfilled.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/watch.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/watch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ccf1a9f6f0e58910b034f116b4932895b1fad936dbdb51ec8700254d0dead020"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new instance of this watcher.\n\nGiven [`Api`] and [`Config`] will be used to to create the [`runtime::watcher()`] stream.\n\nGiven `condition` will be used to determine whether the set of observed resources reached\nits desired state.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(api: Api, config: Config, condition: C) -> Self\n where\n C: 'static + FnMut(&HashMap) -> bool + Send,\n {\n Self {\n api,\n config,\n resources: Default::default(),\n condition: Box::new(condition),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new instance of this watcher.\n\nGiven [`Api`] and [`Config`] will be used to to create the [`runtime::watcher()`] stream.\n\nGiven `condition` will be used to determine whether the set of observed resources reached\nits desired state.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/watch.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/watch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "522cbce3175fdd94778b25a1d47764bc4407c1fe5bf2b4e411e37aaf91cfadd7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRuns this watcher until the set of observed resources has reached its desired state.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run(&mut self) {\n let mut stream =\n Box::pin(runtime::watcher(self.api.clone(), self.config.clone()).default_backoff());\n\n loop {\n tokio::select! {\n item = stream.next() => match item {\n Some(Ok(event)) => {\n if self.handle_event(event) {\n break;\n }\n },\n Some(Err(error)) => {\n println!(\"Watcher stream for {} {:?} encountered an error and will resume with backoff: {error}\", R::kind(&()), self.config);\n }\n None => {\n panic!(\"Watcher stream for {} {:?} unexpectedly finished\", R::kind(&()), self.config);\n }\n },\n }\n }\n }\n```"}], "func_name": "run", "docstring": "Runs this watcher until the set of observed resources has reached its desired state.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/watch.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/watch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1313ec2e9509867f1580c1451bf0c2f070477024ae2803fc1a2129ca6c48fb5c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait_until_pods_ready\n\nDocumentation:\nWaits until the given [`Service`] has at least `min` ready [`Pod`].\n\nReturns ready pods.\n\nA [`Pod`] is considered to be ready when:\n1. It's in the `Running` phase\n2. All of its containers are ready\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn wait_until_pods_ready(service: &Service, min: usize, client: Client) -> Vec {\n let api = Api::::namespaced(client, service.metadata.namespace.as_deref().unwrap());\n\n let selector = service\n .spec\n .as_ref()\n .unwrap()\n .selector\n .as_ref()\n .unwrap()\n .iter()\n .map(|entry| format!(\"{}={}\", entry.0, entry.1))\n .collect::>()\n .join(\",\");\n let config = Config {\n label_selector: Some(selector),\n ..Default::default()\n };\n\n let mut watcher = Watcher::new(api, config, move |map| {\n map.values().filter(|p| pod_is_ready(p)).count() >= min\n });\n\n watcher.run().await;\n\n watcher\n .resources\n .into_values()\n .filter(pod_is_ready)\n .collect()\n}\n```"}], "func_name": "wait_until_pods_ready", "docstring": "Waits until the given [`Service`] has at least `min` ready [`Pod`].\n\nReturns ready pods.\n\nA [`Pod`] is considered to be ready when:\n1. It's in the `Running` phase\n2. All of its containers are ready", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/watch.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/watch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8111d486cdb8a4c3b2c34edb75a3758485bb09fa19c2720450ea6bc0646e1b9d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pod_is_ready\n\nDocumentation:\nDetermines if the given [`Pod`] is ready.\n\nA [`Pod`] is considered to be ready when:\n1. It's in the `Running` phase\n2. All of its containers are ready\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn pod_is_ready(pod: &Pod) -> bool {\n let Some(status) = pod.status.as_ref() else {\n return false;\n };\n\n if status.phase.as_deref() != Some(\"Running\") {\n return false;\n }\n\n let Some(containers) = status.container_statuses.as_ref() else {\n return false;\n };\n\n containers.iter().all(|status| status.ready)\n}\n```"}], "func_name": "pod_is_ready", "docstring": "Determines if the given [`Pod`] is ready.\n\nA [`Pod`] is considered to be ready when:\n1. It's in the `Running` phase\n2. All of its containers are ready", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/watch.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/watch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69636ea0b3c93a30dd6f5e0d2187a3f62c0fe262ffbafc195d06115f779a8559"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: wait_until_rollout_available\n\nDocumentation:\nWaits until the given [`Rollout`] has at least `min_available` available replicas.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn wait_until_rollout_available(\n rollout_name: &str,\n namespace: &str,\n min_available: usize,\n client: Client,\n) {\n let api = Api::::namespaced(client, namespace);\n let config = Config {\n field_selector: Some(format!(\"metadata.name={}\", rollout_name)),\n ..Default::default()\n };\n\n fn has_available_replicas(rollout: &Rollout, min: usize) -> bool {\n let status = match &rollout.status {\n Some(status) => status,\n None => return false,\n };\n\n match status.available_replicas {\n Some(available) => available >= min as i32,\n None => false,\n }\n }\n\n let mut watcher = Watcher::new(api, config, move |map| {\n map.values()\n .any(|r| has_available_replicas(r, min_available))\n });\n\n println!(\n \"Waiting for rollout '{}' to have at least {} available replica(s)...\",\n rollout_name, min_available\n );\n watcher.run().await;\n println!(\n \"Rollout '{}' now has at least {} available replica(s)\",\n rollout_name, min_available\n );\n}\n```"}], "func_name": "wait_until_rollout_available", "docstring": "Waits until the given [`Rollout`] has at least `min_available` available replicas.", "repo": "metalbear-co/mirrord", "path": "tests/src/utils/watch.rs", "url": "https://github.com/metalbear-co/mirrord/blob/master/tests/src/utils/watch.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8120cf7520b91f84d728a7ee4f6c06f06611de4d52b445f7c20745296ba5ddee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: test_temp_dir_from_thread_name\n\nDocumentation:\ntest_temp_dir if thread name != module path, which is the case in parametrized tests\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn test_temp_dir_from_thread_name(mod_path: &str) -> TestTempDir {\n let path = {\n let (crate_, _) = mod_path.split_once(\"::\").unwrap();\n let thread = std::thread::current();\n let thread = thread.name().unwrap();\n let (t_mod, fn_) = thread.rsplit_once(\"::\").unwrap();\n format!(\"{crate_}::{t_mod}::{fn_}\")\n };\n\n test_temp_dir::TestTempDir::from_complete_item_path(&path)\n}\n```"}], "func_name": "test_temp_dir_from_thread_name", "docstring": "test_temp_dir if thread name != module path, which is the case in parametrized tests", "repo": "Trow-Registry/trow", "path": "src/test_utilities.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/src/test_utilities.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ee60e2e02f51c9968aef4361672883b040dccc84c93738de0823eb875e10e1a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_orphan_blobs\n\nDocumentation:\nDelete blobs not referenced by manifest (slow)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn delete_orphan_blobs(state: &TrowServerState) -> Result {\n let mut bytes_reclaimed = 0;\n // String like is more straightforward than m.json -> config -> digest, ...\n let blobs_to_delete = sqlx::query!(\n r#\"\n SELECT digest, size\n FROM blob b\n WHERE b.last_accessed < strftime('%s', 'now', '-1 day')\n AND NOT EXISTS (\n SELECT 1\n FROM manifest_blob_assoc mba\n WHERE mba.blob_digest = b.digest\n );\n \"#,\n )\n .fetch_all(&state.db_ro)\n .await?;\n for blob in blobs_to_delete {\n sqlx::query!(r#\"DELETE FROM blob WHERE digest = $1\"#, blob.digest)\n .execute(&state.db_rw)\n .await?;\n state.registry.storage.delete_blob(&blob.digest).await?;\n bytes_reclaimed += blob.size as usize;\n }\n if bytes_reclaimed > 0 {\n tracing::info!(\n reclaimed = bytes_humanstring(bytes_reclaimed),\n \"Reclaimed space by deleting orphaned blobs\"\n )\n }\n Ok(bytes_reclaimed)\n}\n```"}], "func_name": "delete_orphan_blobs", "docstring": "Delete blobs not referenced by manifest (slow)", "repo": "Trow-Registry/trow", "path": "src/registry/garbage_collect.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/src/registry/garbage_collect.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2340b064e6365e1853b4bca251e9ad951698b51c69c66e734bf8fbda2e46b471"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_local_blob_digests\n\nDocumentation:\nReturns a Vec of the digests of all blobs referenced in the Manifest\nWith the exception of digests for \"foreign blobs\"\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_local_blob_digests(&self) -> Vec<&str> {\n match self {\n OCIManifest::V2(m2) => {\n let mut digests: Vec<_> = m2\n .layers()\n .iter()\n .filter(|l| layer_is_distributable(l.media_type()))\n .map(|x| x.digest().as_ref())\n .collect();\n digests.push(m2.config().digest().as_ref());\n digests\n }\n OCIManifest::List(_) => Vec::new(),\n }\n }\n```"}], "func_name": "get_local_blob_digests", "docstring": "Returns a Vec of the digests of all blobs referenced in the Manifest\nWith the exception of digests for \"foreign blobs\"", "repo": "Trow-Registry/trow", "path": "src/registry/manifest.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/src/registry/manifest.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a87f259c79adc60bd81f239cd9cc2955400c551cefda980674c606a9089eef76"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_blob_part_stream\n\nDocumentation:\nWrites part of a blob to disk.\nUpload then needs to be \"completed\"\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn write_blob_part_stream(\n &self,\n upload_id: &uuid::Uuid,\n stream: S,\n range: Option>,\n ) -> Result\n where\n S: Stream> + Unpin,\n E: std::error::Error + Send + Sync + 'static,\n {\n tracing::debug!(\"Write blob part {upload_id} ({range:?})\");\n let tmp_location = self.uploads_dir.join(upload_id.to_string());\n let mut tmp_file = FileWrapper::append(tmp_location.clone())\n .await\n .map_err(|e| {\n tracing::error!(\"Could not open tmp file {}: {}\", tmp_location.display(), e);\n match e.kind() {\n io::ErrorKind::NotFound => StorageBackendError::BlobNotFound(tmp_location),\n io::ErrorKind::AlreadyExists => StorageBackendError::InvalidContentRange,\n _ => StorageBackendError::Io(e),\n }\n })?;\n\n let file_size = tmp_file.metadata().await?.len();\n let range_len = range.as_ref().map(|r| r.end() - r.start() + 1);\n\n if let Some(range) = &range {\n if *range.start() != file_size {\n tracing::error!(\n \"Invalid content-range: start={} file_pos={}\",\n range.start(),\n file_size\n );\n return Err(StorageBackendError::InvalidContentRange);\n }\n }\n let bytes_written = tmp_file.write_stream(stream).await.map_err(|_e| {\n StorageBackendError::Internal(Cow::Borrowed(\"Couldn't write stream to file\"))\n })? as u64;\n\n if matches!(range_len, Some(len) if len != bytes_written) {\n tracing::error!(\n \"Invalid content-length: expected={} actual={}\",\n range_len.unwrap(),\n bytes_written\n );\n return Err(StorageBackendError::InvalidContentRange);\n }\n\n Ok(Stored {\n total_stored: bytes_written + file_size,\n chunk: bytes_written,\n })\n }\n```"}], "func_name": "write_blob_part_stream", "docstring": "Writes part of a blob to disk.\nUpload then needs to be \"completed\"", "repo": "Trow-Registry/trow", "path": "src/registry/storage.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/src/registry/storage.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac12be86f7b1911f49a4033c24fd094575ab8d9020743cc7cb3090826fb5a73d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_stream\n\nDocumentation:\nReturns the number of bytes written\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn write_stream(&mut self, mut stream: S) -> io::Result\n where\n S: Stream> + Unpin,\n E: std::error::Error + Send + Sync + 'static,\n {\n let mut len = 0;\n while let Some(chunk) = stream.next().await {\n let chunk = chunk.map_err(|e| io::Error::new(io::ErrorKind::UnexpectedEof, e))?;\n len += chunk.len();\n self.file.write_all(&chunk).await?;\n }\n self.file.flush().await?;\n Ok(len)\n }\n```"}], "func_name": "write_stream", "docstring": "Returns the number of bytes written", "repo": "Trow-Registry/trow", "path": "src/registry/temporary_file.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/src/registry/temporary_file.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "40cb7966ce7e38a078bd77096bebc500d09992037b38e6f6d380ba4312935d06"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_aws_ecr_password_from_env\n\nDocumentation:\nFetches AWS ECR credentials.\nWe use the [rusoto ChainProvider](https://docs.rs/rusoto_credential/0.48.0/rusoto_credential/struct.ChainProvider.html)\nto fetch AWS credentials.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn get_aws_ecr_password_from_env(ecr_host: &str) -> Result {\n let region = ecr_host\n .split('.')\n .nth(3)\n .ok_or(EcrPasswordError::InvalidRegion)?\n .to_owned();\n let region = aws_types::region::Region::new(region);\n let config = aws_config::defaults(BehaviorVersion::v2025_01_17())\n .region(region)\n .load()\n .await;\n let ecr_clt = aws_sdk_ecr::Client::new(&config);\n let token_response = ecr_clt.get_authorization_token().send().await?;\n let token = token_response\n .authorization_data\n .unwrap()\n .into_iter()\n .next()\n .unwrap()\n .authorization_token\n .unwrap();\n\n // The token is base64(username:password). Here, username is \"AWS\".\n // To get the password, we trim \"AWS:\" from the decoded token.\n let engine = base64::engine::general_purpose::STANDARD;\n let mut auth_str = engine.decode(token)?;\n auth_str.drain(0..4);\n\n Ok(String::from_utf8(auth_str)?)\n}\n```"}], "func_name": "get_aws_ecr_password_from_env", "docstring": "Fetches AWS ECR credentials.\nWe use the [rusoto ChainProvider](https://docs.rs/rusoto_credential/0.48.0/rusoto_credential/struct.ChainProvider.html)\nto fetch AWS credentials.", "repo": "Trow-Registry/trow", "path": "src/registry/proxy/proxy_config.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/src/registry/proxy/proxy_config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be2aed5006c1411061b01713130f2d6ee4dcf194ffef37b992858dccccb5cf78"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_image_ref_regex\n\nDocumentation:\nThe regex validates an image reference.\nIt returns `name`, `tag` and `digest`.\n\nBuilt from:\nhttps://github.com/distribution/reference/blob/727f80d42224f6696b8e1ad16b06aadf2c6b833b/regexp.go\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nconst fn get_image_ref_regex() -> &'static str {\n const SEPARATOR: &str = \"(?:[._]|__|[-]+)\";\n const ALPHANUMERIC: &str = \"[a-z0-9]+\";\n const DOMAIN_COMPONENT: &str = \"(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\";\n const NAME_COMPONENT: &str = formatcp!(\"{ALPHANUMERIC}(?:{SEPARATOR}{ALPHANUMERIC})*\");\n const DOMAIN_NAME: &str = formatcp!(\"{DOMAIN_COMPONENT}(?:[.]{DOMAIN_COMPONENT})*\");\n const IPV6_ADDR: &str = r\"\\[(?:[a-fA-F0-9:]+)\\]\";\n const DOMAIN: &str = formatcp!(\"(?:{DOMAIN_NAME}|{IPV6_ADDR})(?::[0-9]+)?\");\n const DIGEST: &str = \"[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[:xdigit:]]{32,}\";\n const TAG: &str = r\"[\\w][\\w.-]{0,127}\";\n const NAME: &str = formatcp!(\"(?:{DOMAIN}/)?{NAME_COMPONENT}(/{NAME_COMPONENT})*\");\n\n formatcp!(\"^(?P{NAME})(?::(?P{TAG}))?(?:@(?P{DIGEST}))?$\")\n}\n```"}], "func_name": "get_image_ref_regex", "docstring": "The regex validates an image reference.\nIt returns `name`, `tag` and `digest`.\n\nBuilt from:\nhttps://github.com/distribution/reference/blob/727f80d42224f6696b8e1ad16b06aadf2c6b833b/regexp.go", "repo": "Trow-Registry/trow", "path": "src/registry/proxy/remote_image.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/src/registry/proxy/remote_image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "441e4fe329a69a65168b1efefadddac93418f5be1bdf26bb1c8ec6082523ffe0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_base_uri\n\nDocumentation:\nExample return value: `https://registry-1.docker.io/v2/library/nginx`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_base_uri(&self) -> String {\n format!(\"{}://{}/v2/{}\", self.scheme, self.host, self.repo)\n }\n```"}], "func_name": "get_base_uri", "docstring": "Example return value: `https://registry-1.docker.io/v2/library/nginx`", "repo": "Trow-Registry/trow", "path": "src/registry/proxy/remote_image.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/src/registry/proxy/remote_image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e4bdc32e5ef7f8a83dac6e971935e67c8d7668a987c418bba909317a3c4968e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_ref\n\nDocumentation:\nExample return value: `registry-1.docker.io/library/nginx@sha256:12345`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_ref(&self) -> String {\n let (sep, ref_) = match &self.reference {\n ManifestReference::Digest(d) => (\"@\", Cow::Owned(d.to_string())),\n ManifestReference::Tag(t) => (\":\", Cow::Borrowed(t)),\n };\n format!(\"{}/{}{sep}{ref_}\", self.host, self.repo)\n }\n```"}], "func_name": "get_ref", "docstring": "Example return value: `registry-1.docker.io/library/nginx@sha256:12345`", "repo": "Trow-Registry/trow", "path": "src/registry/proxy/remote_image.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/src/registry/proxy/remote_image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a0d9d1b9d90b42e9ea2faa6b4ceb028b4593b5ae914ef8d0193034c58b6bff6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_from_str\n\nDocumentation:\nNote: this uses the same validation rules as the Docker engine.\nSchemes (`http`, `https`) are not supported here.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_from_str(image_ref: &str) -> Result {\n lazy_static! {\n static ref RE: regex::Regex = regex::RegexBuilder::new(get_image_ref_regex())\n .size_limit(1024*1024) // 1MB limit (complex regex can explode in size)\n .unicode(false) // unicode is not allowed in image references\n .build().unwrap();\n };\n\n let captures = RE\n .captures(image_ref)\n .ok_or_else(|| RemoteImageError::InvalidImageReference(image_ref.to_string()))?;\n\n let name = captures.name(\"name\").unwrap().as_str();\n\n let host;\n let repo;\n // https://github.com/distribution/distribution/blob/6affafd1f030087d88f88841bf66a8abe2bf4d24/reference/normalize.go#L90\n let i = name.find('/').unwrap_or(0);\n if i == 0\n || (!name[..i].contains(['.', ':'])\n && &name[..i] != \"localhost\"\n && name[..i].to_lowercase() == name[..i])\n {\n host = \"registry-1.docker.io\";\n repo = name.to_string();\n } else {\n host = &name[..i];\n repo = name[i + 1..].to_string();\n }\n\n let ref_ = if let Some(match_digest) = captures.name(\"digest\") {\n let digest = Digest::try_from_raw(match_digest.as_str())?;\n ManifestReference::Digest(digest)\n } else if let Some(match_tag) = captures.name(\"tag\") {\n ManifestReference::Tag(match_tag.as_str().to_owned())\n } else {\n ManifestReference::Tag(\"latest\".to_string())\n };\n\n Ok(Self::new(host, repo, ref_))\n }\n```"}], "func_name": "try_from_str", "docstring": "Note: this uses the same validation rules as the Docker engine.\nSchemes (`http`, `https`) are not supported here.", "repo": "Trow-Registry/trow", "path": "src/registry/proxy/remote_image.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/src/registry/proxy/remote_image.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "52a57ee29ef0019a06497aae619519de40ee381c8cf6d95d32b8c46c09d24313"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_raw\n\nDocumentation:\nTo work around the fact that manifests cannot be serialized/deserialized\nor their digest might not match\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_raw(content: Bytes) -> Self {\n let content_length = content.len();\n let response = Response::new(Body::from(content));\n Self {\n response,\n content_length,\n content_type: PhantomData,\n }\n }\n```"}], "func_name": "new_raw", "docstring": "To work around the fact that manifests cannot be serialized/deserialized\nor their digest might not match", "repo": "Trow-Registry/trow", "path": "src/routes/response/mod.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/src/routes/response/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b7ed29af9374fddbdb3cd43ba4656267aef407442047c46cd3a88a8e580f7924"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_content_type\n\nDocumentation:\nOverwrites the default content type of `application/json`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_content_type(mut self, content_type: &str) -> Self {\n self.response.headers_mut().insert(\n header::CONTENT_TYPE,\n HeaderValue::from_str(content_type).unwrap(),\n );\n self\n }\n```"}], "func_name": "set_content_type", "docstring": "Overwrites the default content type of `application/json`", "repo": "Trow-Registry/trow", "path": "src/routes/response/mod.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/src/routes/response/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6c8d13211f1b7a031d79aaddc9bdf14ecd97e12d1ac01f415e867d31fb10c988"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_trow\n\nDocumentation:\nCall out to cargo to start trow.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn start_trow(temp_dir: &Path, ipv6: bool) -> TrowInstance {\n let localhost = if ipv6 { \"[::1]\" } else { \"127.0.0.1\" };\n let listener = TcpListener::bind(format!(\"{localhost}:0\")).unwrap();\n let port = listener.local_addr().unwrap().port();\n drop(listener);\n\n let mut child = Command::new(\"./target/debug/trow\")\n .arg(format!(\n \"--bind={ip}:{port}\",\n ip = if ipv6 { \"[::]\" } else { \"0.0.0.0\" }\n ))\n .arg(format!(\"--data-dir={}\", temp_dir.display()))\n .env_clear()\n .envs(Environment::inherit().compile())\n .spawn()\n .expect(\"failed to start\");\n\n let uri = format!(\"http://{localhost}:{port}\");\n let mut timeout = 50;\n let client = reqwest::Client::new();\n let mut response = client.get(&uri).send().await;\n while timeout > 0 && (response.is_err() || (response.unwrap().status() != StatusCode::OK)) {\n thread::sleep(Duration::from_millis(500));\n response = client.get(&uri).send().await;\n timeout -= 1;\n }\n if timeout == 0 {\n child.kill().unwrap();\n panic!(\n \"Failed to start Trow:\\n{:?}\\n---\\n{:?}\",\n child.stdout.unwrap(),\n child.stderr.unwrap()\n );\n }\n TrowInstance { pid: child, port }\n }\n```"}], "func_name": "start_trow", "docstring": "Call out to cargo to start trow.", "repo": "Trow-Registry/trow", "path": "tests/smoke_test.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/tests/smoke_test.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b45ce2d579fb0d9112d07b3ada1798f4e1dbf345dd2e9e25e0ef0014204c6b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_file\n\nDocumentation:\nReturns a temporary file filled with `contents`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_file(dir: &Path, contents: T) -> PathBuf {\n let rnum: u16 = fastrand::u16(0..=u16::MAX);\n let path = dir.join(rnum.to_string());\n let mut file = File::create(&path).unwrap();\n file.write_all(serde_yaml_ng::to_string(&contents).unwrap().as_bytes())\n .unwrap();\n file.flush().unwrap();\n\n path\n}\n```"}], "func_name": "get_file", "docstring": "Returns a temporary file filled with `contents`", "repo": "Trow-Registry/trow", "path": "tests/common/mod.rs", "url": "https://github.com/Trow-Registry/trow/blob/master/tests/common/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81930cdb957d8f0e8a2769062c1ddc6f0af86f09d54673ed7e6bcd44f114a39c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: initialize_logger\n\nDocumentation:\nInitialize the logger with the given [LevelFilter]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn initialize_logger(filter: LevelFilter) {\n Builder::from_env(Env::default().default_filter_or(filter.as_str()))\n .format_target(false)\n .init();\n }\n```"}], "func_name": "initialize_logger", "docstring": "Initialize the logger with the given [LevelFilter]", "repo": "esp-rs/espflash", "path": "espflash/src/lib.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ac3cb20b6405412360e0b944b562836346c1401c7e284bec429c8c6a487b778"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: matches\n\nDocumentation:\nCheck if the given USB port matches this device\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn matches(&self, port: &UsbPortInfo) -> bool {\n self.vid == port.vid && self.pid == port.pid\n }\n```"}], "func_name": "matches", "docstring": "Check if the given USB port matches this device", "repo": "esp-rs/espflash", "path": "espflash/src/cli/config.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c62a649540b3a79642c990931f1a76951d8147f91fed4c668b273b938ef766ac"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load\n\nDocumentation:\nLoad configuration from the configuration files\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load() -> Result {\n let project_config_file = Self::project_config_path()?;\n let port_config_file = Self::port_config_path()?;\n\n let project_config = if let Ok(data) = read_to_string(&project_config_file) {\n toml::from_str(&data).into_diagnostic()?\n } else {\n ProjectConfig::default()\n };\n\n if let Some(table) = &project_config.esp_idf_format_args.partition_table {\n match table.extension() {\n Some(ext) if ext == \"bin\" || ext == \"csv\" => {}\n _ => return Err(Error::InvalidPartitionTablePath.into()),\n }\n }\n\n if let Some(bootloader) = &project_config.esp_idf_format_args.bootloader {\n if bootloader.extension() != Some(OsStr::new(\"bin\")) {\n return Err(Error::InvalidBootloaderPath.into());\n }\n }\n\n debug!(\"Config: {:#?}\", &project_config);\n\n let mut port_config = if let Ok(data) = read_to_string(&port_config_file) {\n toml::from_str(&data).into_diagnostic()?\n } else {\n PortConfig::default()\n };\n port_config.save_path = port_config_file;\n debug!(\"Port Config: {:#?}\", &port_config);\n\n Ok(Config {\n project_config,\n port_config,\n })\n }\n```"}], "func_name": "load", "docstring": "Load configuration from the configuration files", "repo": "esp-rs/espflash", "path": "espflash/src/cli/config.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f45318b5a4ef6aaa351e04c05837635fffbc96226b2041f37084dfc0d32716a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: save_with\n\nDocumentation:\nSave port configuration to the configuration file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn save_with(&self, modify_fn: F) -> Result<()> {\n let mut copy = self.clone();\n modify_fn(&mut copy);\n\n let serialized = toml::to_string(©.port_config)\n .into_diagnostic()\n .wrap_err(\"Failed to serialize config\")?;\n\n create_dir_all(self.port_config.save_path.parent().unwrap())\n .into_diagnostic()\n .wrap_err(\"Failed to create config directory\")?;\n write(&self.port_config.save_path, serialized)\n .into_diagnostic()\n .wrap_err_with(|| {\n format!(\n \"Failed to write config to {}\",\n self.port_config.save_path.display()\n )\n })\n }\n```"}], "func_name": "save_with", "docstring": "Save port configuration to the configuration file", "repo": "esp-rs/espflash", "path": "espflash/src/cli/config.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e05855328c23068bac769f2a9ee721a5340145b721998874ec8fdb6d14c2da7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_u32\n\nDocumentation:\nParses an integer, in base-10 or hexadecimal format, into a [u32]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_u32(input: &str) -> Result {\n let input: &str = &input.replace('_', \"\");\n let (s, radix) = if input.len() > 2 && matches!(&input[0..2], \"0x\" | \"0X\") {\n (&input[2..], 16)\n } else {\n (input, 10)\n };\n\n u32::from_str_radix(s, radix)\n}\n```"}], "func_name": "parse_u32", "docstring": "Parses an integer, in base-10 or hexadecimal format, into a [u32]", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1611b5d9f667f232819c8d98d7b3eac99472fe60f6e2ed690e575f3ccbb8a3fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nSelect a serial port and establish a connection with a target device\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connect(\n args: &ConnectArgs,\n config: &Config,\n no_verify: bool,\n no_skip: bool,\n) -> Result {\n if args.before == ResetBeforeOperation::NoReset\n || args.before == ResetBeforeOperation::NoResetNoSync\n {\n warn!(\n \"Pre-connection option '{:#?}' was selected. Connection may fail if the chip is not in bootloader or flasher stub mode.\",\n args.before\n );\n }\n\n let port_info = serial::serial_port_info(args, config)?;\n\n // Attempt to open the serial port and set its initial baud rate.\n info!(\"Serial port: '{}'\", port_info.port_name);\n info!(\"Connecting...\");\n\n let serial_port = serialport::new(&port_info.port_name, 115_200)\n .flow_control(FlowControl::None)\n .open_native()\n .map_err(Error::from)\n .wrap_err_with(|| format!(\"Failed to open serial port {}\", port_info.port_name))?;\n\n // NOTE: since `get_serial_port_info` filters out all PCI Port and Bluetooth\n // serial ports, we can just pretend these types don't exist here.\n let port_info = match port_info.port_type {\n SerialPortType::UsbPort(info) => info,\n SerialPortType::PciPort | SerialPortType::Unknown => {\n debug!(\"Matched `SerialPortType::PciPort or ::Unknown`\");\n UsbPortInfo {\n vid: 0,\n pid: 0,\n serial_number: None,\n manufacturer: None,\n product: None,\n }\n }\n _ => unreachable!(),\n };\n\n let connection = Connection::new(\n *Box::new(serial_port),\n port_info,\n args.after,\n args.before,\n args.baud\n .or(config.project_config.baudrate)\n .unwrap_or(115_200),\n );\n Ok(Flasher::connect(\n connection,\n !args.no_stub,\n !no_verify,\n !no_skip,\n args.chip,\n )?)\n}\n```"}], "func_name": "connect", "docstring": "Select a serial port and establish a connection with a target device", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c0a24ea1e78a84c86238c0d0897670b06fb6eee3f3222ceaa8d9cb1fdad70f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: board_info\n\nDocumentation:\nConnect to a target device and print information about its chip\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn board_info(args: &ConnectArgs, config: &Config) -> Result<()> {\n let mut flasher = connect(args, config, true, true)?;\n print_board_info(&mut flasher)?;\n\n let chip = flasher.chip();\n if chip != Chip::Esp32 {\n let security_info = flasher.security_info()?;\n println!(\"{security_info}\");\n } else {\n println!(\"Security features: None\");\n }\n\n flasher.connection().reset_after(!args.no_stub, chip)?;\n\n Ok(())\n}\n```"}], "func_name": "board_info", "docstring": "Connect to a target device and print information about its chip", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b8cfc3b724ddf83640df2b6ab600949271d89fc5339885116ceb7cf48ba4e6d9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: checksum_md5\n\nDocumentation:\nConnect to a target device and calculate the checksum of the given region\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn checksum_md5(args: &ChecksumMd5Args, config: &Config) -> Result<()> {\n let mut flasher = connect(&args.connect_args, config, true, true)?;\n\n let checksum = flasher.checksum_md5(args.address, args.size)?;\n println!(\"0x{:x}\", checksum);\n\n let chip = flasher.chip();\n flasher\n .connection()\n .reset_after(!args.connect_args.no_stub, chip)?;\n\n Ok(())\n}\n```"}], "func_name": "checksum_md5", "docstring": "Connect to a target device and calculate the checksum of the given region", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3d8853ac7b3d688bd668519d39bfb59747793afaede63cce3fae0506fb8fdf06"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: completions\n\nDocumentation:\nGenerate shell completions for the given shell\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn completions(args: &CompletionsArgs, app: &mut clap::Command, bin_name: &str) -> Result<()> {\n clap_complete::generate(args.shell, app, bin_name, &mut std::io::stdout());\n\n Ok(())\n}\n```"}], "func_name": "completions", "docstring": "Generate shell completions for the given shell", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e57d8bf5338d1036f0361e88118109e6f3100f7495a13015e1a36f85b4ca1b5e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_chip_rev\n\nDocumentation:\nParses chip revision from string to major * 100 + minor format\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_chip_rev(chip_rev: &str) -> Result {\n let mut split = chip_rev.split('.');\n\n let parse_or_error = |value: Option<&str>| {\n value\n .ok_or_else(|| Error::ParseChipRevError {\n chip_rev: chip_rev.to_string(),\n })\n .and_then(|v| {\n v.parse::().map_err(|_| Error::ParseChipRevError {\n chip_rev: chip_rev.to_string(),\n })\n })\n .into_diagnostic()\n };\n\n let major = parse_or_error(split.next())?;\n let minor = parse_or_error(split.next())?;\n\n if split.next().is_some() {\n return Err(Error::ParseChipRevError {\n chip_rev: chip_rev.to_string(),\n })\n .into_diagnostic();\n }\n\n Ok(major * 100 + minor)\n}\n```"}], "func_name": "parse_chip_rev", "docstring": "Parses chip revision from string to major * 100 + minor format", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f908335f19deb61314262750ce2ddea6ab7729b6e7270aef24371deee1c5aec9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: save_elf_as_image\n\nDocumentation:\nConvert the provided firmware image from ELF to binary\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn save_elf_as_image<'a>(\n image_path: PathBuf,\n flash_size: Option,\n merge: bool,\n skip_padding: bool,\n image_format: ImageFormat<'a>,\n) -> Result<()> {\n let metadata = image_format.metadata();\n if metadata.contains_key(\"app_size\") && metadata.contains_key(\"part_size\") {\n let app_size = metadata[\"app_size\"].parse::().unwrap();\n let part_size = metadata[\"part_size\"].parse::().unwrap();\n\n display_image_size(app_size, Some(part_size));\n }\n\n if merge {\n let mut file = fs::OpenOptions::new()\n .write(true)\n .truncate(true)\n .create(true)\n .open(image_path)\n .into_diagnostic()?;\n\n for segment in image_format.flash_segments() {\n let padding_bytes = vec![\n 0xffu8;\n segment.addr as usize\n - file.metadata().into_diagnostic()?.len() as usize\n ];\n file.write_all(&padding_bytes).into_diagnostic()?;\n file.write_all(&segment.data).into_diagnostic()?;\n }\n\n if !skip_padding {\n // Take flash_size as input parameter, if None, use default value of 4Mb\n let padding_bytes = vec![\n 0xffu8;\n flash_size.unwrap_or_default().size() as usize\n - file.metadata().into_diagnostic()?.len() as usize\n ];\n file.write_all(&padding_bytes).into_diagnostic()?;\n }\n } else {\n match image_format.ota_segments().as_slice() {\n [single] => fs::write(&image_path, &single.data).into_diagnostic()?,\n parts => {\n for part in parts {\n let part_path = format!(\"{:#x}_{}\", part.addr, image_path.display());\n fs::write(part_path, &part.data).into_diagnostic()?\n }\n }\n }\n }\n\n info!(\"Image successfully saved!\");\n\n Ok(())\n}\n```"}], "func_name": "save_elf_as_image", "docstring": "Convert the provided firmware image from ELF to binary", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "35026217980d48d06d76e303cbc4af5b3cd0bbec55279ace5471e14971fe7879"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: display_image_size\n\nDocumentation:\nDisplays the image or app size\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn display_image_size(app_size: u32, part_size: Option) {\n if let Some(part_size) = part_size {\n let percent = app_size as f32 / part_size as f32 * 100.0;\n println!(\n \"App/part. size: {}/{} bytes, {:.2}%\",\n HumanCount(app_size as u64),\n HumanCount(part_size as u64),\n percent\n );\n } else {\n println!(\"App size: {} bytes\", HumanCount(app_size as u64));\n }\n}\n```"}], "func_name": "display_image_size", "docstring": "Displays the image or app size", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0cd2d582f62d64e91207151cf1cff331cbb234f11358450ebc9057eb8693bb11"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: erase_flash\n\nDocumentation:\nErase the entire flash memory of a target device\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn erase_flash(args: EraseFlashArgs, config: &Config) -> Result<()> {\n if args.connect_args.no_stub {\n return Err(Error::StubRequired.into());\n }\n\n let mut flasher = connect(&args.connect_args, config, true, true)?;\n info!(\"Erasing Flash...\");\n\n let chip = flasher.chip();\n\n flasher.erase_flash()?;\n flasher\n .connection()\n .reset_after(!args.connect_args.no_stub, chip)?;\n\n info!(\"Flash has been erased!\");\n\n Ok(())\n}\n```"}], "func_name": "erase_flash", "docstring": "Erase the entire flash memory of a target device", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "72db594d7dca1ea376f02b91e9e6f47e28da641de1b8dbcfb6a71bdd9cfe6618"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: erase_region\n\nDocumentation:\nErase a specified region of flash memory\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn erase_region(args: EraseRegionArgs, config: &Config) -> Result<()> {\n if args.connect_args.no_stub {\n return Err(Error::StubRequired).into_diagnostic();\n }\n\n if args.address % FLASH_SECTOR_SIZE as u32 != 0 || args.size % FLASH_SECTOR_SIZE as u32 != 0 {\n return Err(Error::InvalidEraseRegionArgument {\n address: args.address,\n size: args.size,\n })\n .into_diagnostic();\n }\n\n let mut flasher = connect(&args.connect_args, config, true, true)?;\n let chip = flasher.chip();\n\n info!(\n \"Erasing region at 0x{:08x} ({} bytes)\",\n args.address, args.size\n );\n\n flasher.erase_region(args.address, args.size)?;\n flasher\n .connection()\n .reset_after(!args.connect_args.no_stub, chip)?;\n\n Ok(())\n}\n```"}], "func_name": "erase_region", "docstring": "Erase a specified region of flash memory", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b80dbcd81f1e670caab8a020b067821d5226088f5e6a41e50f61b96ae3d38e90"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: flash_image\n\nDocumentation:\nWrite an ELF image to a target device's flash\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn flash_image<'a>(flasher: &mut Flasher, image_format: ImageFormat<'a>) -> Result<()> {\n flasher.load_image_to_flash(Some(&mut EspflashProgress::default()), image_format)?;\n info!(\"Flashing has completed!\");\n\n Ok(())\n}\n```"}], "func_name": "flash_image", "docstring": "Write an ELF image to a target device's flash", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf4bc82eaffcb7046dd691797c6e933f846cda20ab22739ab2791ae90d1ab219"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: erase_partitions\n\nDocumentation:\nErase one or more partitions by label or [DataType]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn erase_partitions(\n flasher: &mut Flasher,\n partition_table: Option,\n erase_parts: Option>,\n erase_data_parts: Option>,\n) -> Result<()> {\n let partition_table = match &partition_table {\n Some(partition_table) => partition_table,\n None => return Err(MissingPartitionTable.into()),\n };\n\n // Using a hashmap to deduplicate entries\n let mut parts_to_erase = None;\n\n // Look for any partitions with specific labels\n if let Some(part_labels) = erase_parts {\n for label in part_labels {\n let part = partition_table\n .find(label.as_str())\n .ok_or_else(|| MissingPartition::from(label))?;\n\n parts_to_erase\n .get_or_insert(HashMap::new())\n .insert(part.offset(), part);\n }\n }\n\n // Look for any data partitions with specific data subtype\n // There might be multiple partition of the same subtype, e.g. when using\n // multiple FAT partitions\n if let Some(partition_types) = erase_data_parts {\n for ty in partition_types {\n for part in partition_table.partitions() {\n if part.ty() == esp_idf_part::Type::Data\n && part.subtype() == esp_idf_part::SubType::Data(ty)\n {\n parts_to_erase\n .get_or_insert(HashMap::new())\n .insert(part.offset(), part);\n }\n }\n }\n }\n\n if let Some(parts) = parts_to_erase {\n parts\n .iter()\n .try_for_each(|(_, p)| erase_partition(flasher, p))?;\n }\n\n Ok(())\n}\n```"}], "func_name": "erase_partitions", "docstring": "Erase one or more partitions by label or [DataType]", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f416e3995eb71e6711e60afbd582ae6cbb5e686cc51e272da1234a45cb1ddbde"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_flash\n\nDocumentation:\nRead flash content and write it to a file\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_flash(args: ReadFlashArgs, config: &Config) -> Result<()> {\n let mut flasher = connect(&args.connect_args, config, false, false)?;\n print_board_info(&mut flasher)?;\n\n if args.connect_args.no_stub {\n flasher.read_flash_rom(\n args.address,\n args.size,\n args.block_size,\n args.max_in_flight,\n args.file,\n )?;\n } else {\n flasher.read_flash(\n args.address,\n args.size,\n args.block_size,\n args.max_in_flight,\n args.file,\n )?;\n }\n\n let chip = flasher.chip();\n flasher\n .connection()\n .reset_after(!args.connect_args.no_stub, chip)?;\n\n Ok(())\n}\n```"}], "func_name": "read_flash", "docstring": "Read flash content and write it to a file", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b3ed814a8b182033ceab8bb062a3b015588158aedc46467468b93d622712567b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: partition_table\n\nDocumentation:\nConvert and display CSV and binary partition tables\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn partition_table(args: PartitionTableArgs) -> Result<()> {\n if args.to_binary {\n let table = parse_partition_table(&args.partition_table)?;\n\n // Use either stdout or a file if provided for the output.\n let mut writer: Box = if let Some(output) = args.output {\n Box::new(fs::File::create(output).into_diagnostic()?)\n } else {\n Box::new(std::io::stdout())\n };\n\n writer\n .write_all(&table.to_bin().into_diagnostic()?)\n .into_diagnostic()?;\n } else if args.to_csv {\n let input = fs::read(&args.partition_table).into_diagnostic()?;\n let table = PartitionTable::try_from_bytes(input).into_diagnostic()?;\n\n // Use either stdout or a file if provided for the output.\n let mut writer: Box = if let Some(output) = args.output {\n Box::new(fs::File::create(output).into_diagnostic()?)\n } else {\n Box::new(std::io::stdout())\n };\n\n writer\n .write_all(table.to_csv().into_diagnostic()?.as_bytes())\n .into_diagnostic()?;\n } else {\n let input = fs::read(&args.partition_table).into_diagnostic()?;\n let table = PartitionTable::try_from(input).into_diagnostic()?;\n\n pretty_print(table);\n }\n\n Ok(())\n}\n```"}], "func_name": "partition_table", "docstring": "Convert and display CSV and binary partition tables", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ab5a7649bc89bc6d7f8ed32ae4270d632d59b325b32f742a22ca75b406d448eb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_image_format\n\nDocumentation:\nMake an image format from the given arguments\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn make_image_format<'a>(\n elf_data: &'a [u8],\n flash_data: &FlashData,\n image_format_kind: ImageFormatKind,\n config: &Config,\n esp_idf_format_args: Option,\n build_ctx_bootloader: Option,\n build_ctx_partition_table: Option,\n) -> Result, Error> {\n let image_format = match image_format_kind {\n ImageFormatKind::EspIdf => {\n let mut args = esp_idf_format_args.unwrap_or_default();\n // Set bootloader path with precedence\n if args.bootloader.is_none() {\n args.bootloader = config\n .project_config\n .esp_idf_format_args\n .bootloader\n .clone()\n .or(build_ctx_bootloader);\n }\n\n // Set partition table path with precedence\n if args.partition_table.is_none() {\n args.partition_table = config\n .project_config\n .esp_idf_format_args\n .partition_table\n .clone()\n .or(build_ctx_partition_table);\n }\n IdfBootloaderFormat::new(\n elf_data,\n flash_data,\n args.partition_table.as_deref(),\n args.bootloader.as_deref(),\n args.partition_table_offset,\n args.target_app_partition.as_deref(),\n )?\n }\n };\n\n Ok(image_format.into())\n}\n```"}], "func_name": "make_image_format", "docstring": "Make an image format from the given arguments", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cdb5e8f9864771644be1febd5eebabb7c22e5e3150e4a1439d671f637702e8e3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_flash_data\n\nDocumentation:\nMake flash data from the given arguments\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn make_flash_data(\n image_args: ImageArgs,\n flash_config_args: &FlashConfigArgs,\n config: &Config,\n chip: Chip,\n xtal_freq: XtalFrequency,\n) -> FlashData {\n // Create flash settings with precedence\n let mode = flash_config_args\n .flash_mode\n .or(config.project_config.flash.mode);\n let size = flash_config_args\n .flash_size\n .or(config.project_config.flash.size)\n .or_else(|| Some(FlashSize::default()));\n let freq = flash_config_args\n .flash_freq\n .or(config.project_config.flash.freq);\n\n let flash_settings = FlashSettings::new(mode, size, freq);\n\n FlashData::new(\n flash_settings,\n image_args.min_chip_rev,\n image_args.mmu_page_size,\n chip,\n xtal_freq,\n )\n}\n```"}], "func_name": "make_flash_data", "docstring": "Make flash data from the given arguments", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "669030bc96bc06e5d6da8d99db783a92fb08d74ca6e9823fcacb30030b11aaa8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_bin\n\nDocumentation:\nWrite a binary to the flash memory of a target device\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_bin(args: WriteBinArgs, config: &Config) -> Result<()> {\n // Check monitor arguments\n check_monitor_args(&args.monitor, &args.monitor_args)?;\n\n // Load the file to be flashed\n let mut f = File::open(&args.file).into_diagnostic()?;\n\n // If the file size is not divisible by 4, we need to pad `FF` bytes to the end\n let size = f.metadata().into_diagnostic()?.len();\n let mut padded_bytes = 0;\n if size % 4 != 0 {\n padded_bytes = 4 - (size % 4);\n }\n let mut buffer = Vec::with_capacity(size.try_into().into_diagnostic()?);\n f.read_to_end(&mut buffer).into_diagnostic()?;\n buffer.extend(std::iter::repeat_n(0xFF, padded_bytes as usize));\n\n let mut flasher = connect(&args.connect_args, config, false, false)?;\n print_board_info(&mut flasher)?;\n\n let chip = flasher.chip();\n let target = chip.into_target();\n let target_xtal_freq = target.crystal_freq(flasher.connection())?;\n\n flasher.write_bin_to_flash(\n args.address,\n &buffer,\n Some(&mut EspflashProgress::default()),\n )?;\n\n if args.monitor {\n let pid = flasher.connection().usb_pid();\n let mut monitor_args = args.monitor_args;\n if chip == Chip::Esp32c2\n && target_xtal_freq == XtalFrequency::_26Mhz\n && monitor_args.monitor_baud == 115_200\n {\n monitor_args.monitor_baud = 74_880;\n }\n monitor(\n flasher.into_connection().into_serial(),\n None,\n pid,\n monitor_args,\n )?;\n }\n\n Ok(())\n}\n```"}], "func_name": "write_bin", "docstring": "Write a binary to the flash memory of a target device", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "87da0b322d5ef5de15a06033e9c25563e00a7390b285ded83a265f5474ff81e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_esp_idf_args\n\nDocumentation:\nCheck if the given arguments are valid for the ESP-IDF format\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check_esp_idf_args(\n format: ImageFormatKind,\n erase_parts: &Option>,\n erase_data_parts: &Option>,\n) -> Result<()> {\n if format != ImageFormatKind::EspIdf && (erase_parts.is_some() || erase_data_parts.is_some()) {\n return Err(miette::miette!(\n \"`erase-parts` and `erase-data` parts are only supported when using the `esp-idf` format.\"\n ));\n }\n\n Ok(())\n}\n```"}], "func_name": "check_esp_idf_args", "docstring": "Check if the given arguments are valid for the ESP-IDF format", "repo": "esp-rs/espflash", "path": "espflash/src/cli/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a7f2145c10f6632b0603acde0cdbd21f330220517f23685faaba9c0e0dee697"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: serial_port_info\n\nDocumentation:\nReturn the information of a serial port taking into account the different\nways of choosing a port.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn serial_port_info(matches: &ConnectArgs, config: &Config) -> Result {\n // A serial port should be specified either as a command-line argument or in a\n // configuration file. In the case that both have been provided the command-line\n // argument takes precedence.\n //\n // Users may optionally specify the device's VID and PID in the configuration\n // file. If no VID/PID has been provided, the user will always be prompted to\n // select a serial port. If some VID and PID were provided then the user will\n // also be prompted to select a port, unless there is only one found whose VID\n // and PID match the configured values.\n //\n // The call to canonicalize() was originally added to resolve\n // https://github.com/esp-rs/espflash/issues/177, however, canonicalize\n // doesn't work (on Windows) with \"dummy\" device paths like `COM4`. That's\n // the reason we need to handle Windows/Posix differently.\n\n if let Some(serial) = &matches.port {\n let ports = detect_usb_serial_ports(true).unwrap_or_default();\n find_serial_port(&ports, serial)\n } else if let Some(serial) = &config.port_config.connection.serial {\n let ports = detect_usb_serial_ports(true).unwrap_or_default();\n find_serial_port(&ports, serial)\n } else {\n let ports = detect_usb_serial_ports(matches.list_all_ports).unwrap_or_default();\n let (port, matches) = select_serial_port(ports, &config.port_config, matches.confirm_port)?;\n match &port.port_type {\n SerialPortType::UsbPort(usb_info) if !matches => {\n let remember = Confirm::with_theme(&ColorfulTheme::default())\n .with_prompt(\"Remember this serial port for future use?\")\n .interact_opt()?\n .unwrap_or_default();\n\n if remember {\n // Allow this operation to fail without terminating the\n // application, but inform the user if something goes wrong.\n if let Err(e) = config.save_with(|config| {\n config.port_config.usb_device.push(UsbDevice {\n vid: usb_info.vid,\n pid: usb_info.pid,\n })\n }) {\n error!(\"Failed to save config {:#}\", e);\n }\n }\n }\n _ => {}\n }\n\n Ok(port)\n }\n}\n```"}], "func_name": "serial_port_info", "docstring": "Return the information of a serial port taking into account the different\nways of choosing a port.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/serial.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/serial.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "079136fda8ca5dd89e4d19261746ddb1c52110e0fc953cad78567cbc988342f2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: find_serial_port\n\nDocumentation:\nGiven a vector of `SerialPortInfo` structs, attempt to find and return one\nwhose `port_name` field matches the provided `name` argument.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn find_serial_port(ports: &[SerialPortInfo], name: &str) -> Result {\n #[cfg(not(target_os = \"windows\"))]\n let name = fs::canonicalize(name)?;\n #[cfg(not(target_os = \"windows\"))]\n let name = name.to_string_lossy();\n\n // The case in device paths matters in BSD!\n #[cfg(any(\n target_os = \"freebsd\",\n target_os = \"dragonfly\",\n target_os = \"openbsd\",\n target_os = \"netbsd\"\n ))]\n let port_info = ports.iter().find(|port| port.port_name == name);\n\n // On Windows and other *nix systems, the case is not important.\n #[cfg(not(any(\n target_os = \"freebsd\",\n target_os = \"dragonfly\",\n target_os = \"openbsd\",\n target_os = \"netbsd\"\n )))]\n let port_info = ports\n .iter()\n .find(|port| port.port_name.eq_ignore_ascii_case(name.as_ref()));\n\n if let Some(port) = port_info {\n Ok(port.to_owned())\n } else {\n Err(Error::SerialNotFound(name.to_string()))\n }\n}\n```"}], "func_name": "find_serial_port", "docstring": "Given a vector of `SerialPortInfo` structs, attempt to find and return one\nwhose `port_name` field matches the provided `name` argument.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/serial.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/serial.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c440a48dda911d68821d57c39bb771df965864c7d853bb7cb14f06e346bd7254"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: detect_usb_serial_ports\n\nDocumentation:\nReturns a vector with available USB serial ports.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn detect_usb_serial_ports(list_all_ports: bool) -> Result> {\n let ports = available_ports().into_diagnostic()?;\n let ports = ports\n .into_iter()\n .filter(|port_info| {\n if list_all_ports {\n matches!(\n &port_info.port_type,\n SerialPortType::UsbPort(..) |\n // Allow PciPort. The user may want to use it.\n // The port might have been misdetected by the system as PCI.\n SerialPortType::PciPort |\n // Good luck.\n SerialPortType::Unknown\n )\n } else {\n matches!(&port_info.port_type, SerialPortType::UsbPort(..))\n }\n })\n .collect::>();\n\n Ok(ports)\n}\n```"}], "func_name": "detect_usb_serial_ports", "docstring": "Returns a vector with available USB serial ports.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/serial.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/serial.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e37888cf78feb05c0f9bba6e00ceac759c8ef00117057e69f3b57a05f03c9175"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: select_serial_port\n\nDocumentation:\nAsk the user to select a serial port from a list of detected serial ports.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn select_serial_port(\n mut ports: Vec,\n config: &PortConfig,\n force_confirm_port: bool,\n) -> Result<(SerialPortInfo, bool), Error> {\n if let [port] = ports\n .iter()\n .filter(|&p| known_ports_filter(p, config))\n .collect::>()\n .as_slice()\n {\n // There is a unique recognized device.\n if !force_confirm_port {\n return Ok(((*port).to_owned(), true));\n }\n }\n\n if ports.len() > 1 {\n // Multiple serial ports detected.\n info!(\"Detected {} serial ports\", ports.len());\n info!(\"Ports which match a known common dev board are highlighted\");\n info!(\"Please select a port\");\n\n ports.sort_by_key(|a| !known_ports_filter(a, config));\n\n let port_names = ports\n .iter()\n .map(|port_info| {\n let formatted = if known_ports_filter(port_info, config) {\n port_info.port_name.as_str().bold()\n } else {\n port_info.port_name.as_str().reset()\n };\n match &port_info.port_type {\n SerialPortType::UsbPort(info) => {\n if let Some(product) = &info.product {\n format!(\"{} - {}\", formatted, product)\n } else {\n formatted.to_string()\n }\n }\n _ => formatted.to_string(),\n }\n })\n .collect::>();\n\n // https://github.com/console-rs/dialoguer/issues/77\n ctrlc::set_handler(move || {\n let term = dialoguer::console::Term::stdout();\n let _ = term.show_cursor();\n })\n .expect(\"Error setting Ctrl-C handler\");\n\n let index = Select::with_theme(&ColorfulTheme::default())\n .items(&port_names)\n .default(0)\n .interact_opt()?\n .ok_or(Error::Cancelled)?;\n\n match ports.get(index) {\n Some(port_info) => Ok((port_info.to_owned(), known_ports_filter(port_info, config))),\n None => Err(Error::SerialNotFound(\n port_names.get(index).unwrap().to_string(),\n )),\n }\n } else if let [port] = ports.as_slice() {\n // A single port, but we didn't recognize it. Prompt for confirmation.\n let port_name = port.port_name.clone();\n let product = match &port.port_type {\n SerialPortType::UsbPort(info) => info.product.as_ref(),\n _ => None,\n };\n if confirm_port(&port_name, product)? {\n Ok((port.to_owned(), false))\n } else {\n Err(Error::SerialNotFound(port_name))\n }\n } else {\n // No serial ports detected\n Err(Error::NoSerial)\n }\n}\n```"}], "func_name": "select_serial_port", "docstring": "Ask the user to select a serial port from a list of detected serial ports.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/serial.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/serial.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "97fde335a8a7ea5afdd69cb38de04dbcc431256a595451e673e0bd4ee486e026"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: confirm_port\n\nDocumentation:\nAsk the user to confirm the use of a serial port.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn confirm_port(port_name: &str, product: Option<&String>) -> Result {\n Confirm::with_theme(&ColorfulTheme::default())\n .with_prompt({\n if let Some(product) = product {\n format!(\"Use serial port '{}' - {}?\", port_name, product)\n } else {\n format!(\"Use serial port '{}'?\", port_name)\n }\n })\n .interact_opt()?\n .ok_or(Error::Cancelled)\n}\n```"}], "func_name": "confirm_port", "docstring": "Ask the user to confirm the use of a serial port.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/serial.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/serial.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0bb4ab41e5e6f989ebf95afd796933d88e2e850e943ea11e7a370831b34f9314"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new processor from a child process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(child: Child) -> Self {\n let mut child = child;\n let (tx, rx) = mpsc::channel::();\n\n let mut stdout = child.stdout.take().unwrap();\n let stdin = child.stdin.take().unwrap();\n\n std::thread::spawn(move || {\n let mut buffer = [0u8; 1024];\n loop {\n if let Ok(len) = stdout.read(&mut buffer) {\n for b in &buffer[..len] {\n if tx.send(*b).is_err() {\n break;\n }\n }\n }\n }\n });\n\n Self { rx, stdin, child }\n }\n```"}], "func_name": "new", "docstring": "Creates a new processor from a child process.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/monitor/external_processors.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/monitor/external_processors.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a65eb1a6075ce18c9c27f6b8c2023d9f97a569d4237dcc0bdc54325de9c79c30"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_receive\n\nDocumentation:\nTries to receive data from the processor.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_receive(&mut self) -> Vec {\n let mut res = Vec::new();\n while let Ok(b) = self.rx.try_recv() {\n res.push(b);\n }\n res\n }\n```"}], "func_name": "try_receive", "docstring": "Tries to receive data from the processor.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/monitor/external_processors.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/monitor/external_processors.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e42558eafb1ee2705b78547edc7ca62b7a5e7858199e34b5a865404b4efdbaa8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new collection of external processors.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(processors: Option, elf: Option) -> Result {\n let mut args = Vec::new();\n\n if let Some(elf) = elf {\n args.push(elf.as_os_str().to_str().unwrap().to_string());\n };\n\n let mut spawned = Vec::new();\n if let Some(processors) = processors {\n for processor in processors.split(\",\") {\n let processor = std::process::Command::new(processor)\n .args(args.clone())\n .stdin(Stdio::piped())\n .stdout(Stdio::piped())\n .stderr(Stdio::inherit())\n .spawn()\n .map_err(|_| Error {\n executable: processor.to_string(),\n })?;\n spawned.push(Processor::new(processor));\n }\n }\n\n Ok(Self {\n processors: spawned,\n })\n }\n```"}], "func_name": "new", "docstring": "Creates a new collection of external processors.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/monitor/external_processors.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/monitor/external_processors.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf85545d3586982c848238bb3454fd6811ee131b6bc6379eb302e7a768ab32c2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process\n\nDocumentation:\nProcesses input bytes through a series of processors, returning the\nfinal output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn process(&mut self, read: &[u8]) -> Vec {\n let mut buffer = Vec::new();\n buffer.extend_from_slice(read);\n\n for processor in &mut self.processors {\n processor.send(buffer);\n buffer = processor.try_receive();\n }\n\n buffer\n }\n```"}], "func_name": "process", "docstring": "Processes input bytes through a series of processors, returning the\nfinal output.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/monitor/external_processors.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/monitor/external_processors.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "60040a26145bad1664afa394e916efff06eb567f23ddeb46757a8f1e396eb229"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nEnable raw mode and return a guard that will disable it when dropped.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new() -> Result {\n enable_raw_mode().into_diagnostic()?;\n Ok(RawModeGuard)\n }\n```"}], "func_name": "new", "docstring": "Enable raw mode and return a guard that will disable it when dropped.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/monitor/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/monitor/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d9b90675a3e07711eb18d987925e5cba8c9e66345d7e83c78fe90573949e4c09"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: monitor\n\nDocumentation:\nOpen a serial monitor on the given serial port, using the given input\nparser.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn monitor(\n mut serial: Port,\n elf: Option<&[u8]>,\n pid: u16,\n monitor_args: MonitorConfigArgs,\n) -> miette::Result<()> {\n println!(\"Commands:\");\n println!(\" CTRL+R Reset chip\");\n println!(\" CTRL+C Exit\");\n println!();\n\n if monitor_args.non_interactive && !monitor_args.no_reset {\n reset_after_flash(&mut serial, pid).into_diagnostic()?;\n }\n\n let baud = monitor_args.monitor_baud;\n debug!(\"Opening serial monitor with baudrate: {}\", baud);\n\n // Explicitly set the baud rate when starting the serial monitor, to allow using\n // different rates for flashing.\n serial.set_baud_rate(baud).into_diagnostic()?;\n serial\n .set_timeout(Duration::from_millis(5))\n .into_diagnostic()?;\n\n // We are in raw mode until `_raw_mode` is dropped (ie. this function returns).\n let _raw_mode = RawModeGuard::new();\n\n let stdout = stdout();\n let mut stdout = ResolvingPrinter::new(elf, stdout.lock());\n\n let mut parser: Box = match monitor_args\n .log_format\n .unwrap_or_else(|| deduce_log_format(elf))\n {\n LogFormat::Defmt => Box::new(parser::esp_defmt::EspDefmt::new(\n elf,\n monitor_args.output_format,\n )?),\n LogFormat::Serial => {\n if monitor_args.output_format.is_some() {\n warn!(\"Output format specified but log format is serial. Ignoring output format.\");\n }\n Box::new(parser::serial::Serial)\n }\n };\n\n let mut external_processors =\n ExternalProcessors::new(monitor_args.processors, monitor_args.elf)?;\n\n let mut buff = [0; 1024];\n loop {\n let read_count = match serial.read(&mut buff) {\n Ok(count) => Ok(count),\n Err(e) if e.kind() == ErrorKind::TimedOut => Ok(0),\n Err(e) if e.kind() == ErrorKind::Interrupted => continue,\n err => err.into_diagnostic(),\n }?;\n\n let processed = external_processors.process(&buff[0..read_count]);\n parser.feed(&processed, &mut stdout);\n\n // Don't forget to flush the writer!\n stdout.flush().ok();\n\n if !handle_user_input(&mut serial, pid, monitor_args.non_interactive)? {\n break;\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "monitor", "docstring": "Open a serial monitor on the given serial port, using the given input\nparser.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/monitor/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/monitor/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b3f033c9f607984e50f020928b118a106181ad071ff7534699a872da1a07f31b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_user_input\n\nDocumentation:\nHandle user input from the terminal.\n\nReturns `true` if the program should continue running, `false` if it should\nexit.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_user_input(serial: &mut Port, pid: u16, non_interactive: bool) -> Result {\n let key = match key_event().into_diagnostic() {\n Ok(Some(event)) => event,\n Ok(None) => return Ok(true),\n Err(_) if non_interactive => return Ok(true),\n Err(err) => return Err(err),\n };\n\n if key.kind == KeyEventKind::Press {\n if key.modifiers.contains(KeyModifiers::CONTROL) {\n match key.code {\n KeyCode::Char('c') => return Ok(false),\n KeyCode::Char('r') => {\n reset_after_flash(serial, pid).into_diagnostic()?;\n return Ok(true);\n }\n _ => {}\n }\n }\n\n if let Some(bytes) = handle_key_event(key) {\n serial.write_all(&bytes).into_diagnostic()?;\n serial.flush().into_diagnostic()?;\n }\n }\n\n Ok(true)\n}\n```"}], "func_name": "handle_user_input", "docstring": "Handle user input from the terminal.\n\nReturns `true` if the program should continue running, `false` if it should\nexit.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/monitor/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/monitor/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "34a6ed16ed61e5292d89897dac3357a0cc25035d28eee336152d0e96c4db1da2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_from\n\nDocumentation:\nTries to create a new `Symbols` instance from the given ELF file bytes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_from(bytes: &'sym [u8]) -> Result> {\n let object = File::parse(bytes)?;\n let dwarf = Dwarf::load(\n |id: SectionId| -> Result, gimli::Error> {\n let data = object\n .section_by_name(id.name())\n .and_then(|section| section.data().ok())\n .unwrap_or(&[][..]);\n Ok(EndianSlice::new(data, LittleEndian))\n },\n )?;\n\n let ctx = Context::from_dwarf(dwarf)?;\n\n Ok(Self { object, ctx })\n }\n```"}], "func_name": "try_from", "docstring": "Tries to create a new `Symbols` instance from the given ELF file bytes.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/monitor/symbols.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/monitor/symbols.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f6fbd049ba6f4a4cbc9425da95aab9857a36c075f7fc4b12aa770a53ccfea593"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: name\n\nDocumentation:\nReturns the name of the function at the given address, if one can be\nfound.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn name(&self, addr: u64) -> Option {\n // No need to try an address not contained in any segment:\n if !self.object.segments().any(|segment| {\n (segment.address()..(segment.address() + segment.size())).contains(&addr)\n }) {\n return None;\n }\n\n // The basic steps here are:\n // 1. Find which frame `addr` is in\n // 2. Look up and demangle the function name\n // 3. If no function name is found, try to look it up in the object file\n // directly\n // 4. Return a demangled function name, if one was found\n let mut frames = match self.ctx.find_frames(addr) {\n LookupResult::Output(result) => result.unwrap(),\n LookupResult::Load { .. } => unimplemented!(),\n };\n\n frames\n .next()\n .ok()\n .flatten()\n .and_then(|frame| {\n frame\n .function\n .and_then(|name| name.demangle().map(|s| s.into_owned()).ok())\n })\n .or_else(|| {\n // Don't use `symbol_map().get(addr)` - it's documentation says \"Get the symbol\n // before the given address.\" which might be totally wrong\n let symbol = self.object.symbols().find(|symbol| {\n (symbol.address()..=(symbol.address() + symbol.size())).contains(&addr)\n });\n\n if let Some(symbol) = symbol {\n match symbol.name() {\n Ok(name) if !name.is_empty() => Some(\n addr2line::demangle_auto(std::borrow::Cow::Borrowed(name), None)\n .to_string(),\n ),\n _ => None,\n }\n } else {\n None\n }\n })\n }\n```"}], "func_name": "name", "docstring": "Returns the name of the function at the given address, if one can be\nfound.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/monitor/symbols.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/monitor/symbols.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3e8a7f75a0b145f051f1928a6ecf9a74abece69c69c0cd6ce6413e974535b3b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: location\n\nDocumentation:\nReturns the file name and line number of the function at the given\naddress, if one can be.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn location(&self, addr: u64) -> Option<(String, u32)> {\n // Find the location which `addr` is in. If we can dedetermine a file name and\n // line number for this function we will return them both in a tuple.\n self.ctx.find_location(addr).ok()?.map(|location| {\n let file = location.file.map(|f| f.to_string());\n let line = location.line;\n\n match (file, line) {\n (Some(file), Some(line)) => Some((file, line)),\n _ => None,\n }\n })?\n }\n```"}], "func_name": "location", "docstring": "Returns the file name and line number of the function at the given\naddress, if one can be.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/monitor/symbols.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/monitor/symbols.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f895c2e61680f54e741dad2171239adcb0a44436ba396a1f00d2425622c70de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: feed\n\nDocumentation:\nFeeds data into the parser, extracting and processing framed or raw\ndata.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn feed(&mut self, buffer: &[u8], mut process: impl FnMut(FrameKind<'_>)) {\n self.buffer.extend_from_slice(buffer);\n\n while let Some((frame, consumed)) = Self::search(&self.buffer, self.in_frame) {\n if self.in_frame {\n process(FrameKind::Defmt(frame));\n } else if !frame.is_empty() {\n process(FrameKind::Raw(frame));\n }\n self.in_frame = !self.in_frame;\n\n self.buffer.drain(..consumed);\n }\n\n if !self.in_frame {\n // If we have a 0xFF byte at the end, we should assume it's the start of a new\n // frame.\n let consume = if self.buffer.ends_with(&[0xFF]) {\n &self.buffer[..self.buffer.len() - 1]\n } else {\n self.buffer.as_slice()\n };\n\n if !consume.is_empty() {\n process(FrameKind::Raw(consume));\n self.buffer.drain(..consume.len());\n }\n }\n }\n```"}], "func_name": "feed", "docstring": "Feeds data into the parser, extracting and processing framed or raw\ndata.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/monitor/parser/esp_defmt.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/monitor/parser/esp_defmt.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c00fefb0adac0b143eb96f2cc405586a816b564a38813ceb04efab260f063b9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load\n\nDocumentation:\nLoads symbols from the ELF file (if provided) and initializes the\ncontext.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn load(elf: Option<&[u8]>, output_format: Option) -> Result {\n let Some(elf) = elf else {\n bail!(DefmtError::NoElf);\n };\n\n let table = match Table::parse(elf) {\n Ok(Some(table)) => table,\n Ok(None) => bail!(DefmtError::NoDefmtData),\n Err(e) => return Err(DefmtError::TableParseFailed).with_context(|| e),\n };\n\n let encoding = table.encoding();\n\n // We only support rzcobs encoding because it is the only way to multiplex\n // a defmt stream and an ASCII log stream over the same serial port.\n ensure!(\n encoding == defmt_decoder::Encoding::Rzcobs,\n DefmtError::UnsupportedEncoding(encoding)\n );\n\n let locs = table\n .get_locations(elf)\n .map_err(|_e| DefmtError::LocationDataParseFailed)?;\n\n let locs = if !table.is_empty() && locs.is_empty() {\n warn!(\n \"Insufficient DWARF info; compile your program with `debug = 2` to enable location info.\"\n );\n None\n } else if table.indices().all(|idx| locs.contains_key(&(idx as u64))) {\n Some(locs)\n } else {\n warn!(\"Location info is incomplete; it will be omitted from the output.\");\n None\n };\n\n let show_location = locs.is_some();\n let has_timestamp = table.has_timestamp();\n\n let format = match output_format.as_deref() {\n None | Some(\"oneline\") => FormatterFormat::OneLine {\n with_location: show_location,\n },\n Some(\"full\") => FormatterFormat::Default {\n with_location: show_location,\n },\n Some(format) => FormatterFormat::Custom(format),\n };\n\n Ok(Self {\n table,\n locs,\n formatter: Formatter::new(FormatterConfig {\n format,\n is_timestamp_available: has_timestamp,\n }),\n })\n }\n```"}], "func_name": "load", "docstring": "Loads symbols from the ELF file (if provided) and initializes the\ncontext.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/monitor/parser/esp_defmt.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/monitor/parser/esp_defmt.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "75546461d0168d1a0683f91dd0f7b45af8f42e3d6dfa433980cd1e8405b23bc2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `ResolvingPrinter` with the given ELF file and writer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(elf: Option<&'ctx [u8]>, writer: W) -> Self {\n Self {\n writer,\n symbols: elf.and_then(|elf| Symbols::try_from(elf).ok()),\n merger: Utf8Merger::new(),\n line_fragment: String::new(),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `ResolvingPrinter` with the given ELF file and writer.", "repo": "esp-rs/espflash", "path": "espflash/src/cli/monitor/parser/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/cli/monitor/parser/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7d31d25060b4edc2d77f63d5e2ce4ddad79186a62b1fd31aec718dde3549a8b9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: timeout\n\nDocumentation:\nReturn a timeout based on the command type\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn timeout(&self) -> Duration {\n match self {\n CommandType::MemEnd => MEM_END_TIMEOUT,\n CommandType::Sync => SYNC_TIMEOUT,\n CommandType::EraseFlash => ERASE_CHIP_TIMEOUT,\n CommandType::FlashDeflEnd => FLASH_DEFLATE_END_TIMEOUT,\n CommandType::FlashMd5 => FLASH_MD5_TIMEOUT,\n _ => DEFAULT_TIMEOUT,\n }\n }\n```"}], "func_name": "timeout", "docstring": "Return a timeout based on the command type", "repo": "esp-rs/espflash", "path": "espflash/src/connection/command.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4efabc909cf8c3f8bc08c9c5e95e74d92e0cf8917e4ed6a41bc9ab9815382931"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: timeout_for_size\n\nDocumentation:\nReturn a timeout based on the size\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn timeout_for_size(&self, size: u32) -> Duration {\n fn calc_timeout(timeout_per_mb: Duration, size: u32) -> Duration {\n let mb = size as f64 / 1_000_000.0;\n std::cmp::max(\n FLASH_DEFLATE_END_TIMEOUT,\n Duration::from_millis((timeout_per_mb.as_millis() as f64 * mb) as u64),\n )\n }\n match self {\n CommandType::FlashBegin | CommandType::FlashDeflBegin | CommandType::EraseRegion => {\n calc_timeout(ERASE_REGION_TIMEOUT_PER_MB, size)\n }\n CommandType::FlashData | CommandType::FlashDeflData => {\n calc_timeout(ERASE_WRITE_TIMEOUT_PER_MB, size)\n }\n _ => self.timeout(),\n }\n }\n```"}], "func_name": "timeout_for_size", "docstring": "Return a timeout based on the size", "repo": "esp-rs/espflash", "path": "espflash/src/connection/command.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e2891bb7790acae682684047464cbc10d05292294b2f73be2e132dd7e7aaac7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_basic\n\nDocumentation:\nWrite a data array and its checksum to a writer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_basic(mut writer: W, data: &[u8], checksum: u32) -> std::io::Result<()> {\n writer.write_all(&((data.len() as u16).to_le_bytes()))?;\n writer.write_all(&(checksum.to_le_bytes()))?;\n writer.write_all(data)?;\n Ok(())\n}\n```"}], "func_name": "write_basic", "docstring": "Write a data array and its checksum to a writer", "repo": "esp-rs/espflash", "path": "espflash/src/connection/command.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/command.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a146eb1d8c92956bab0877e53459386c6abed55e02edefbfedea4795ba8d8a00"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new connection with a target device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n serial: Port,\n port_info: UsbPortInfo,\n after_operation: ResetAfterOperation,\n before_operation: ResetBeforeOperation,\n baud: u32,\n ) -> Self {\n Connection {\n serial,\n port_info,\n decoder: SlipDecoder::new(),\n after_operation,\n before_operation,\n secure_download_mode: false,\n baud,\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new connection with a target device.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4b5b4f33314658f085bd0c339162f078b4b1827f3aa507d2ddba3c81684a6cb4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sync\n\nDocumentation:\nTry to sync with the device for a given timeout.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn sync(&mut self) -> Result<(), Error> {\n self.with_timeout(CommandType::Sync.timeout(), |connection| {\n connection.command(Command::Sync)?;\n connection.flush()?;\n\n sleep(Duration::from_millis(10));\n\n for _ in 0..MAX_CONNECT_ATTEMPTS {\n match connection.read_response()? {\n Some(response) if response.return_op == CommandType::Sync as u8 => {\n if response.status == 1 {\n connection.flush().ok();\n return Err(Error::RomError(RomError::new(\n CommandType::Sync,\n RomErrorKind::from(response.error),\n )));\n }\n }\n _ => {\n return Err(Error::RomError(RomError::new(\n CommandType::Sync,\n RomErrorKind::InvalidMessage,\n )));\n }\n }\n }\n\n Ok(())\n })?;\n\n Ok(())\n }\n```"}], "func_name": "sync", "docstring": "Try to sync with the device for a given timeout.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5142b90de8aefe4093838bd791f9e42993974b85308c785eaaf629d0c3e78077"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_after\n\nDocumentation:\nReset the device taking into account the reset after argument.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reset_after(&mut self, is_stub: bool, chip: Chip) -> Result<(), Error> {\n let pid = self.usb_pid();\n\n match self.after_operation {\n ResetAfterOperation::HardReset => hard_reset(&mut self.serial, pid),\n ResetAfterOperation::NoReset => {\n info!(\"Staying in bootloader\");\n soft_reset(self, true, is_stub)?;\n\n Ok(())\n }\n ResetAfterOperation::NoResetNoStub => {\n info!(\"Staying in flasher stub\");\n Ok(())\n }\n ResetAfterOperation::WatchdogReset => {\n info!(\"Resetting device with watchdog\");\n\n match chip {\n Chip::Esp32c3 => {\n if self.is_using_usb_serial_jtag() {\n chip.into_rtc_wdt_reset()?.rtc_wdt_reset(self)?;\n }\n }\n Chip::Esp32p4 => {\n // Check if the connection is USB OTG\n if chip.into_usb_otg()?.is_using_usb_otg(self)? {\n chip.into_rtc_wdt_reset()?.rtc_wdt_reset(self)?;\n }\n }\n Chip::Esp32s2 => {\n // Check if the connection is USB OTG\n if chip.into_usb_otg()?.is_using_usb_otg(self)? {\n let target = chip.into_rtc_wdt_reset()?;\n\n // Check the strapping register to see if we can perform RTC WDT\n // reset\n if target.can_rtc_wdt_reset(self)? {\n target.rtc_wdt_reset(self)?;\n }\n }\n }\n Chip::Esp32s3 => {\n if self.is_using_usb_serial_jtag()\n || chip.into_usb_otg()?.is_using_usb_otg(self)?\n {\n let target = chip.into_rtc_wdt_reset()?;\n\n // Check the strapping register to see if we can perform RTC WDT\n // reset\n if target.can_rtc_wdt_reset(self)? {\n target.rtc_wdt_reset(self)?;\n }\n }\n }\n _ => {\n return Err(Error::UnsupportedFeature {\n chip,\n feature: \"watchdog reset\".into(),\n });\n }\n }\n\n Ok(())\n }\n }\n }\n```"}], "func_name": "reset_after", "docstring": "Reset the device taking into account the reset after argument.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51bdbe85dc32e0828e1c128c4c384dbb2d55f42267897f24923774db2678b72d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reset_to_flash\n\nDocumentation:\nReset the device to flash mode.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reset_to_flash(&mut self, extra_delay: bool) -> Result<(), Error> {\n if self.is_using_usb_serial_jtag() {\n UsbJtagSerialReset.reset(&mut self.serial)\n } else {\n #[cfg(unix)]\n if UnixTightReset::new(extra_delay)\n .reset(&mut self.serial)\n .is_ok()\n {\n return Ok(());\n }\n\n ClassicReset::new(extra_delay).reset(&mut self.serial)\n }\n }\n```"}], "func_name": "reset_to_flash", "docstring": "Reset the device to flash mode.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "514e966d4850aaf139d4a87c42b498299c767ef57590c246eab2980f7d057c9a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_timeout\n\nDocumentation:\nSet timeout for the serial port.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_timeout(&mut self, timeout: Duration) -> Result<(), Error> {\n self.serial.set_timeout(timeout)?;\n Ok(())\n }\n```"}], "func_name": "set_timeout", "docstring": "Set timeout for the serial port.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bff44407df54cb77b7042600154fe711699da5b0aa2631bd6d65fb664ab5161a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_baud\n\nDocumentation:\nSet baud rate for the serial port.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_baud(&mut self, baud: u32) -> Result<(), Error> {\n self.serial.set_baud_rate(baud)?;\n self.baud = baud;\n Ok(())\n }\n```"}], "func_name": "set_baud", "docstring": "Set baud rate for the serial port.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "84bb9adcd974201f3f4cc507774cf0969be1598d26a72fa4758d4485f34efa21"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_timeout\n\nDocumentation:\nRun a command with a timeout defined by the command type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_timeout(&mut self, timeout: Duration, mut f: F) -> Result\n where\n F: FnMut(&mut Connection) -> Result,\n {\n let old_timeout = {\n let mut binding = Box::new(&mut self.serial);\n let serial = binding.as_mut();\n let old_timeout = serial.timeout();\n serial.set_timeout(timeout)?;\n old_timeout\n };\n\n let result = f(self);\n\n self.serial.set_timeout(old_timeout)?;\n\n result\n }\n```"}], "func_name": "with_timeout", "docstring": "Run a command with a timeout defined by the command type.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c1370f377966c9b26eb616f3c19f0ac3b4ca13b1ff4429b0c6fd6c57b8c1568"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_flash_response\n\nDocumentation:\nRead the response from a serial port.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_flash_response(&mut self) -> Result, Error> {\n let mut response = Vec::new();\n\n self.decoder.decode(&mut self.serial, &mut response)?;\n\n if response.is_empty() {\n return Ok(None);\n }\n let value = CommandResponseValue::Vector(response.clone());\n\n let header = CommandResponse {\n resp: 1_u8,\n return_op: CommandType::ReadFlash as u8,\n return_length: response.len() as u16,\n value,\n error: 0_u8,\n status: 0_u8,\n };\n\n Ok(Some(header))\n }\n```"}], "func_name": "read_flash_response", "docstring": "Read the response from a serial port.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a234cda751176dfc32c6b391bdc46975ef312ea2e3f7c057baa887c9f98ae432"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_raw\n\nDocumentation:\nWrite raw data to the serial port.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_raw(&mut self, data: u32) -> Result<(), Error> {\n let mut binding = Box::new(&mut self.serial);\n let serial = binding.as_mut();\n serial.clear(serialport::ClearBuffer::Input)?;\n let mut writer = BufWriter::new(serial);\n let mut encoder = SlipEncoder::new(&mut writer)?;\n encoder.write_all(&data.to_le_bytes())?;\n encoder.finish()?;\n writer.flush()?;\n Ok(())\n }\n```"}], "func_name": "write_raw", "docstring": "Write raw data to the serial port.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8683f74a94df5a0221e9b3981f36a9fc66cd42e0e69f49d7bf481ebde3c0d834"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_command\n\nDocumentation:\nWrite a command to the serial port.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_command(&mut self, command: Command<'_>) -> Result<(), Error> {\n debug!(\"Writing command: {:02x?}\", command);\n let mut binding = Box::new(&mut self.serial);\n let serial = binding.as_mut();\n\n serial.clear(serialport::ClearBuffer::Input)?;\n let mut writer = BufWriter::new(serial);\n let mut encoder = SlipEncoder::new(&mut writer)?;\n command.write(&mut encoder)?;\n encoder.finish()?;\n writer.flush()?;\n Ok(())\n }\n```"}], "func_name": "write_command", "docstring": "Write a command to the serial port.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a4aebecd5879b1344fb5da9a725e02ee7b1efb54dbd92d2acb8a6ad64f3dc92f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: command\n\nDocumentation:\nWrite a command and reads the response.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn command(&mut self, command: Command<'_>) -> Result {\n let ty = command.command_type();\n self.write_command(command).for_command(ty)?;\n for _ in 0..100 {\n match self.read_response().for_command(ty)? {\n Some(response) if response.return_op == ty as u8 => {\n return if response.status != 0 {\n let _error = self.flush();\n Err(Error::RomError(RomError::new(\n command.command_type(),\n RomErrorKind::from(response.error),\n )))\n } else {\n // Check if the response is a Vector and strip header (first 8 bytes)\n // https://github.com/espressif/esptool/blob/749d1ad/esptool/loader.py#L481\n let modified_value = match response.value {\n CommandResponseValue::Vector(mut vec) if vec.len() >= 8 => {\n vec = vec[8..][..response.return_length as usize].to_vec();\n CommandResponseValue::Vector(vec)\n }\n _ => response.value, // If not Vector, return as is\n };\n\n Ok(modified_value)\n };\n }\n _ => continue,\n }\n }\n Err(Error::Connection(ConnectionError::ConnectionFailed))\n }\n```"}], "func_name": "command", "docstring": "Write a command and reads the response.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e0c1ead4a8bcb8abe3b95d64c67c1c9f77ec1d3860bd39d9f4d156d27c77da06"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: detect_chip\n\nDocumentation:\nDetect which chip is connected to this connection\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn detect_chip(\n &mut self,\n use_stub: bool,\n ) -> Result {\n // Try to read the magic value from the chip\n let magic = if use_stub {\n self.with_timeout(CommandType::ReadReg.timeout(), |connection| {\n connection.command(Command::ReadReg {\n address: CHIP_DETECT_MAGIC_REG_ADDR,\n })\n })?\n .try_into()?\n } else {\n self.read_reg(CHIP_DETECT_MAGIC_REG_ADDR)?\n };\n debug!(\"Read chip magic value: 0x{:08x}\", magic);\n Chip::from_magic(magic)\n }\n```"}], "func_name": "detect_chip", "docstring": "Detect which chip is connected to this connection", "repo": "esp-rs/espflash", "path": "espflash/src/connection/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "169a5510d559c369b68b0d71ffea49e81a09aa6b668b2eb50f910391d567ac7b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write\n\nDocumentation:\nWrites the given buffer replacing the END and ESC bytes.\n\nSee https://docs.espressif.com/projects/esptool/en/latest/esp32c3/advanced-topics/serial-protocol.html#low-level-protocol\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write(&mut self, buf: &[u8]) -> std::io::Result {\n for value in buf.iter() {\n match *value {\n END => {\n self.len += self.writer.write(&[ESC, ESC_END])?;\n }\n ESC => {\n self.len += self.writer.write(&[ESC, ESC_ESC])?;\n }\n _ => {\n self.len += self.writer.write(&[*value])?;\n }\n }\n }\n\n Ok(buf.len())\n }\n```"}], "func_name": "write", "docstring": "Writes the given buffer replacing the END and ESC bytes.\n\nSee https://docs.espressif.com/projects/esptool/en/latest/esp32c3/advanced-topics/serial-protocol.html#low-level-protocol", "repo": "esp-rs/espflash", "path": "espflash/src/connection/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a6d60757f3b2995f5410cedc43e77bb8fbc047239758e086cc9603673b9ff792"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new `ClassicReset` strategy with the given delay.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(extra_delay: bool) -> Self {\n let delay = if extra_delay {\n EXTRA_RESET_DELAY\n } else {\n DEFAULT_RESET_DELAY\n };\n\n Self { delay }\n }\n```"}], "func_name": "new", "docstring": "Create a new `ClassicReset` strategy with the given delay.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/reset.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/reset.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2e0346b6f2b5d024d225e596b78dc28089550b0b390cac7ad91012e26e8727a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: hard_reset\n\nDocumentation:\nReset sequence for hard resetting the chip.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn hard_reset(serial_port: &mut Port, pid: u16) -> Result<(), Error> {\n debug!(\"Using HardReset reset strategy\");\n\n // Using esptool HardReset strategy (https://github.com/espressif/esptool/blob/3301d0ff4638d4db1760a22540dbd9d07c55ec37/esptool/reset.py#L132-L153)\n // leads to https://github.com/esp-rs/espflash/issues/592 in Windows, using `reset_after_flash` instead works fine for all platforms.\n // We had similar issues in the past: https://github.com/esp-rs/espflash/pull/157\n reset_after_flash(serial_port, pid)?;\n\n Ok(())\n}\n```"}], "func_name": "hard_reset", "docstring": "Reset sequence for hard resetting the chip.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/reset.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/reset.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5fd0c6867c64ebb59caf2d9997606bcb87a9a591a1e9efa39858ed4479403d80"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: soft_reset\n\nDocumentation:\nPerform a soft reset of the device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn soft_reset(\n connection: &mut Connection,\n stay_in_bootloader: bool,\n is_stub: bool,\n) -> Result<(), Error> {\n debug!(\"Using SoftReset reset strategy\");\n if !is_stub {\n if stay_in_bootloader {\n // ROM bootloader is already in bootloader\n return Ok(());\n } else {\n // 'run user code' is as close to a soft reset as we can do\n connection.with_timeout(CommandType::FlashBegin.timeout(), |connection| {\n let size: u32 = 0;\n let offset: u32 = 0;\n let blocks: u32 = size.div_ceil(FLASH_WRITE_SIZE as u32);\n connection.command(Command::FlashBegin {\n size,\n blocks,\n block_size: FLASH_WRITE_SIZE.try_into().unwrap(),\n offset,\n supports_encryption: false,\n })\n })?;\n connection.with_timeout(CommandType::FlashEnd.timeout(), |connection| {\n connection.write_command(Command::FlashEnd { reboot: false })\n })?;\n }\n } else if stay_in_bootloader {\n // Soft resetting from the stub loader will re-load the ROM bootloader\n connection.with_timeout(CommandType::FlashBegin.timeout(), |connection| {\n let size: u32 = 0;\n let offset: u32 = 0;\n let blocks: u32 = size.div_ceil(FLASH_WRITE_SIZE as u32);\n connection.command(Command::FlashBegin {\n size,\n blocks,\n block_size: FLASH_WRITE_SIZE.try_into().unwrap(),\n offset,\n supports_encryption: false,\n })\n })?;\n connection.with_timeout(CommandType::FlashEnd.timeout(), |connection| {\n connection.write_command(Command::FlashEnd { reboot: true })\n })?;\n } else {\n // Running user code from stub loader requires some hacks in the stub loader\n connection.with_timeout(CommandType::RunUserCode.timeout(), |connection| {\n connection.command(Command::RunUserCode)\n })?;\n }\n\n Ok(())\n}\n```"}], "func_name": "soft_reset", "docstring": "Perform a soft reset of the device.", "repo": "esp-rs/espflash", "path": "espflash/src/connection/reset.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/connection/reset.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "75cc99d92a0963a885e4a840cb7c0f476e0a8668666ae5213a8bb67565a5fa91"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode_flash_frequency\n\nDocumentation:\nEncodes flash frequency into the format used by the bootloader.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn encode_flash_frequency(self: FlashFrequency, chip: Chip) -> Result {\n let encodings = chip.into_target().flash_frequency_encodings();\n if let Some(&f) = encodings.get(&self) {\n Ok(f)\n } else {\n Err(Error::UnsupportedFlashFrequency {\n chip,\n frequency: self,\n })\n }\n }\n```"}], "func_name": "encode_flash_frequency", "docstring": "Encodes flash frequency into the format used by the bootloader.", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "26907c96978627ae589fcfbf197d4983499234d5f90bd18f1de3bb161efcb0af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode_flash_size\n\nDocumentation:\nEncodes flash size into the format used by the bootloader.\n\n## Values:\n\n* \n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn encode_flash_size(self: FlashSize) -> Result {\n use FlashSize::*;\n\n let encoded = match self {\n _1Mb => 0,\n _2Mb => 1,\n _4Mb => 2,\n _8Mb => 3,\n _16Mb => 4,\n _32Mb => 5,\n _64Mb => 6,\n _128Mb => 7,\n _256Mb => 8,\n _ => return Err(Error::UnsupportedFlash(self as u8)),\n };\n\n Ok(encoded)\n }\n```"}], "func_name": "encode_flash_size", "docstring": "Encodes flash size into the format used by the bootloader.\n\n## Values:\n\n* ", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca7fc3cdbb00e43044884362223e403c72c317e981b76fd42ae6b78193bfcf58"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_detected\n\nDocumentation:\nCreate a [FlashSize] from an [u8]\n\n[source](https://github.com/espressif/esptool/blob/f4d2510/esptool/cmds.py#L42)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn from_detected(value: u8) -> Result {\n match value {\n 0x12 | 0x32 => Ok(FlashSize::_256Kb),\n 0x13 | 0x33 => Ok(FlashSize::_512Kb),\n 0x14 | 0x34 => Ok(FlashSize::_1Mb),\n 0x15 | 0x35 => Ok(FlashSize::_2Mb),\n 0x16 | 0x36 => Ok(FlashSize::_4Mb),\n 0x17 | 0x37 => Ok(FlashSize::_8Mb),\n 0x18 | 0x38 => Ok(FlashSize::_16Mb),\n 0x19 | 0x39 => Ok(FlashSize::_32Mb),\n 0x20 | 0x1A | 0x3A => Ok(FlashSize::_64Mb),\n 0x21 | 0x1B => Ok(FlashSize::_128Mb),\n 0x22 | 0x1C => Ok(FlashSize::_256Mb),\n _ => Err(Error::UnsupportedFlash(value)),\n }\n }\n```"}], "func_name": "from_detected", "docstring": "Create a [FlashSize] from an [u8]\n\n[source](https://github.com/espressif/esptool/blob/f4d2510/esptool/cmds.py#L42)", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "35b8f2f11d9b3b87d23c1fbeddb2db4c74ac6f197fb072bb5e46e0486b4a4a24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: size\n\nDocumentation:\nReturns the flash size in bytes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn size(self) -> u32 {\n match self {\n FlashSize::_256Kb => 0x0040000,\n FlashSize::_512Kb => 0x0080000,\n FlashSize::_1Mb => 0x0100000,\n FlashSize::_2Mb => 0x0200000,\n FlashSize::_4Mb => 0x0400000,\n FlashSize::_8Mb => 0x0800000,\n FlashSize::_16Mb => 0x1000000,\n FlashSize::_32Mb => 0x2000000,\n FlashSize::_64Mb => 0x4000000,\n FlashSize::_128Mb => 0x8000000,\n FlashSize::_256Mb => 0x10000000,\n }\n }\n```"}], "func_name": "size", "docstring": "Returns the flash size in bytes", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3e5ff61d1456f968d8285f6dc36bc537675af57ed38a2ff1ece263f3d61adca5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default\n\nDocumentation:\nReturns the default [FlashSettings] with all fields set to `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn default() -> Self {\n FlashSettings {\n mode: None,\n size: None,\n freq: None,\n }\n }\n```"}], "func_name": "default", "docstring": "Returns the default [FlashSettings] with all fields set to `None`.", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "29721f46e0fd375dbeb7d0ba19314cf1f018c36c111a80e45fd3c8033c135fb1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new [FlashSettings] with the specified mode, size, and\nfrequency.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n mode: Option,\n size: Option,\n freq: Option,\n ) -> Self {\n FlashSettings { mode, size, freq }\n }\n```"}], "func_name": "new", "docstring": "Creates a new [FlashSettings] with the specified mode, size, and\nfrequency.", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a288a587bdfc107301c1988a08581ca4bbb9f02a47f4c1b572a13f9ebea56107"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default\n\nDocumentation:\nCreate a new [SpiSetParams] with the specified size.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn default(size: u32) -> Self {\n SpiSetParams {\n fl_id: 0,\n total_size: size,\n block_size: 64 * 1024,\n sector_size: 4 * 1024,\n page_size: 256,\n status_mask: 0xFFFF,\n }\n }\n```"}], "func_name": "default", "docstring": "Create a new [SpiSetParams] with the specified size.", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9898f3ad50c2486002fb5c60a5c14adc22e784fe4047bf31d88c70b0d96f2a99"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode\n\nDocumentation:\nEncode the parameters into a byte array\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn encode(&self) -> Vec {\n let mut encoded: Vec = Vec::new();\n encoded.extend_from_slice(&self.fl_id.to_le_bytes());\n encoded.extend_from_slice(&self.total_size.to_le_bytes());\n encoded.extend_from_slice(&self.block_size.to_le_bytes());\n encoded.extend_from_slice(&self.sector_size.to_le_bytes());\n encoded.extend_from_slice(&self.page_size.to_le_bytes());\n encoded.extend_from_slice(&self.status_mask.to_le_bytes());\n encoded\n }\n```"}], "func_name": "encode", "docstring": "Encode the parameters into a byte array", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c71d3ed47cdc6c7b8be82a0e92629623bf3053288ad33e3e37af85575d15392"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default\n\nDocumentation:\nCreate a new [SpiAttachParams] with default values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn default() -> Self {\n SpiAttachParams {\n clk: 0,\n q: 0,\n d: 0,\n hd: 0,\n cs: 0,\n }\n }\n```"}], "func_name": "default", "docstring": "Create a new [SpiAttachParams] with default values.", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "60b7751f20722c8747ecbf4b5d7c340816b95cc77470ce20e4d8123249e9da7a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nThe serial port's baud rate should be 115_200 to connect. After\nconnecting, Flasher will change the baud rate to the `baud`\nparameter.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connect(\n mut connection: Connection,\n use_stub: bool,\n verify: bool,\n skip: bool,\n chip: Option,\n ) -> Result {\n // The connection should already be established with the device using the\n // default baud rate of 115,200 and timeout of 3 seconds.\n connection.begin()?;\n connection.set_timeout(DEFAULT_TIMEOUT)?;\n\n detect_sdm(&mut connection);\n\n let detected_chip = if connection.before_operation() != ResetBeforeOperation::NoResetNoSync\n {\n // Detect which chip we are connected to.\n let detected_chip = connection.detect_chip(use_stub)?;\n if let Some(chip) = chip {\n if chip != detected_chip {\n return Err(Error::ChipMismatch(\n chip.to_string(),\n detected_chip.to_string(),\n ));\n }\n }\n detected_chip\n } else if connection.before_operation() == ResetBeforeOperation::NoResetNoSync\n && chip.is_some()\n {\n chip.unwrap()\n } else {\n return Err(Error::ChipNotProvided);\n };\n\n let mut flasher = Flasher {\n connection,\n chip: detected_chip,\n flash_size: FlashSize::_4Mb,\n spi_params: SpiAttachParams::default(),\n use_stub,\n verify,\n skip,\n };\n\n if flasher.connection.before_operation() == ResetBeforeOperation::NoResetNoSync {\n return Ok(flasher);\n }\n\n if !flasher.connection.secure_download_mode {\n // Load flash stub if enabled.\n if use_stub {\n info!(\"Using flash stub\");\n flasher.load_stub()?;\n }\n // Flash size autodetection doesn't work in Secure Download Mode.\n flasher.spi_autodetect()?;\n } else if use_stub {\n warn!(\"Stub is not supported in Secure Download Mode, setting --no-stub\");\n flasher.use_stub = false;\n }\n\n // Now that we have established a connection and detected the chip and flash\n // size, we can set the baud rate of the connection to the configured value.\n if flasher.connection.baud() > 115_200 {\n warn!(\"Setting baud rate higher than 115,200 can cause issues\");\n flasher.change_baud(flasher.connection.baud())?;\n }\n\n Ok(flasher)\n }\n```"}], "func_name": "connect", "docstring": "The serial port's baud rate should be 115_200 to connect. After\nconnecting, Flasher will change the baud rate to the `baud`\nparameter.", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "43f0390cf3acfbe19d217ef4b3b58d61ddf4bad1177cf08aeed4a1792248b7c3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: flash_detect\n\nDocumentation:\nDetect the flash size of the connected device.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn flash_detect(&mut self) -> Result, Error> {\n const FLASH_RETRY: u8 = 0xFF;\n\n let flash_id = self.spi_command(CommandType::FlashDetect, &[], 24)?;\n let size_id = (flash_id >> 16) as u8;\n\n // This value indicates that an alternate detection method should be tried.\n if size_id == FLASH_RETRY {\n return Ok(None);\n }\n\n let flash_size = match FlashSize::from_detected(size_id) {\n Ok(size) => size,\n Err(_) => {\n warn!(\n \"Could not detect flash size (FlashID=0x{:02X}, SizeID=0x{:02X}), defaulting to 4MB\",\n flash_id, size_id\n );\n FlashSize::default()\n }\n };\n\n Ok(Some(flash_size))\n }\n```"}], "func_name": "flash_detect", "docstring": "Detect the flash size of the connected device.", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "abe862fe832515ef9eace4e85fc7f4cb4cf591a78bf8d0af62b3347fa52b7c9c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connection\n\nDocumentation:\nThe active serial connection being used by the flasher\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connection(&mut self) -> &mut Connection {\n &mut self.connection\n }\n```"}], "func_name": "connection", "docstring": "The active serial connection being used by the flasher", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8f5e3453b09c9dca11422c66f2391c1e4391df585cebb1badceeafd8f0e47001"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: device_info\n\nDocumentation:\nRead and print any information we can about the connected device\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn device_info(&mut self) -> Result {\n let chip = self.chip();\n let target = chip.into_target();\n\n // chip_revision reads from efuse, which is not possible in Secure Download Mode\n let revision = (!self.connection.secure_download_mode)\n .then(|| target.chip_revision(self.connection()))\n .transpose()?;\n\n let crystal_frequency = target.crystal_freq(self.connection())?;\n let features = target\n .chip_features(self.connection())?\n .iter()\n .map(|s| s.to_string())\n .collect::>();\n\n let mac_address = (!self.connection.secure_download_mode)\n .then(|| target.mac_address(self.connection()))\n .transpose()?;\n\n let info = DeviceInfo {\n chip,\n revision,\n crystal_frequency,\n flash_size: self.flash_size,\n features,\n mac_address,\n };\n\n Ok(info)\n }\n```"}], "func_name": "device_info", "docstring": "Read and print any information we can about the connected device", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "776a8cc3b39c5d06f4c24bf197ebb54b6bdfebe30c2a0d0962e3a7b3229181e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_elf_to_ram\n\nDocumentation:\nLoad an ELF image to RAM and execute it\n\nNote that this will not touch the flash on the device\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load_elf_to_ram(\n &mut self,\n elf_data: &[u8],\n mut progress: Option<&mut dyn ProgressCallbacks>,\n ) -> Result<(), Error> {\n let elf = ElfFile::parse(elf_data)?;\n if rom_segments(self.chip, &elf).next().is_some() {\n return Err(Error::ElfNotRamLoadable);\n }\n\n let mut target = self.chip.ram_target(\n Some(elf.elf_header().e_entry.get(Endianness::Little)),\n self.chip\n .into_target()\n .max_ram_block_size(&mut self.connection)?,\n );\n target.begin(&mut self.connection).flashing()?;\n\n for segment in ram_segments(self.chip, &elf) {\n target\n .write_segment(&mut self.connection, segment, &mut progress)\n .flashing()?;\n }\n\n target.finish(&mut self.connection, true).flashing()\n }\n```"}], "func_name": "load_elf_to_ram", "docstring": "Load an ELF image to RAM and execute it\n\nNote that this will not touch the flash on the device", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c3111a71685b3540e21db5e10b815dfe7e9dbb657eb304c880c702cc3a833d42"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_image_to_flash\n\nDocumentation:\nLoad an ELF image to flash and execute it\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load_image_to_flash<'a>(\n &mut self,\n mut progress: Option<&mut dyn ProgressCallbacks>,\n image_format: ImageFormat<'a>,\n ) -> Result<(), Error> {\n let mut target =\n self.chip\n .flash_target(self.spi_params, self.use_stub, self.verify, self.skip);\n target.begin(&mut self.connection).flashing()?;\n\n // When the `cli` feature is enabled, display the image size information.\n #[cfg(feature = \"cli\")]\n {\n let metadata = image_format.metadata();\n if metadata.contains_key(\"app_size\") && metadata.contains_key(\"part_size\") {\n let app_size = metadata[\"app_size\"].parse::().unwrap();\n let part_size = metadata[\"part_size\"].parse::().unwrap();\n\n crate::cli::display_image_size(app_size, Some(part_size));\n }\n }\n\n for segment in image_format.flash_segments() {\n target\n .write_segment(&mut self.connection, segment, &mut progress)\n .flashing()?;\n }\n\n target.finish(&mut self.connection, true).flashing()?;\n\n Ok(())\n }\n```"}], "func_name": "load_image_to_flash", "docstring": "Load an ELF image to flash and execute it", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "29fcf10323ffb185e75f59b79ac18b3d0b1f180fa95ca2b764e90a05ed66b5e3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_bin_to_flash\n\nDocumentation:\nLoad an bin image to flash at a specific address\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_bin_to_flash(\n &mut self,\n addr: u32,\n data: &[u8],\n progress: Option<&mut dyn ProgressCallbacks>,\n ) -> Result<(), Error> {\n let segment = Segment {\n addr,\n data: Cow::from(data),\n };\n self.write_bins_to_flash(&[segment], progress)?;\n\n info!(\"Binary successfully written to flash!\");\n\n Ok(())\n }\n```"}], "func_name": "write_bin_to_flash", "docstring": "Load an bin image to flash at a specific address", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a587b0f96a8a4311fc84f836977d4c04bb8752e48784f0772715e20ff35b133e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_bins_to_flash\n\nDocumentation:\nLoad multiple bin images to flash at specific addresses\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_bins_to_flash(\n &mut self,\n segments: &[Segment<'_>],\n mut progress: Option<&mut dyn ProgressCallbacks>,\n ) -> Result<(), Error> {\n if self.connection.secure_download_mode {\n return Err(Error::UnsupportedFeature {\n chip: self.chip,\n feature: \"writing binaries in Secure Download Mode currently\".into(),\n });\n }\n\n let mut target = self\n .chip\n .flash_target(self.spi_params, self.use_stub, false, false);\n\n target.begin(&mut self.connection).flashing()?;\n\n for segment in segments {\n target.write_segment(&mut self.connection, segment.borrow(), &mut progress)?;\n }\n\n target.finish(&mut self.connection, true).flashing()?;\n\n Ok(())\n }\n```"}], "func_name": "write_bins_to_flash", "docstring": "Load multiple bin images to flash at specific addresses", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f1363b4ea30dc56638e2024e3794d154a0d1edbe2e589ea27e2cb40d04da1b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: change_baud\n\nDocumentation:\nChange the baud rate of the connection.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn change_baud(&mut self, baud: u32) -> Result<(), Error> {\n debug!(\"Change baud to: {}\", baud);\n\n let prior_baud = match self.use_stub {\n true => self.connection.baud(),\n false => 0,\n };\n\n let target = self.chip.into_target();\n let xtal_freq = target.crystal_freq(&mut self.connection)?;\n\n // Probably this is just a temporary solution until the next chip revision.\n //\n // The ROM code thinks it uses a 40 MHz XTAL. Recompute the baud rate in order\n // to trick the ROM code to set the correct baud rate for a 26 MHz XTAL.\n let mut new_baud = baud;\n if self.chip == Chip::Esp32c2 && !self.use_stub && xtal_freq == XtalFrequency::_26Mhz {\n new_baud = new_baud * 40 / 26;\n }\n\n self.connection\n .with_timeout(CommandType::ChangeBaudrate.timeout(), |connection| {\n connection.command(Command::ChangeBaudrate {\n new_baud,\n prior_baud,\n })\n })?;\n self.connection.set_baud(baud)?;\n sleep(Duration::from_secs_f32(0.05));\n self.connection.flush()?;\n\n Ok(())\n }\n```"}], "func_name": "change_baud", "docstring": "Change the baud rate of the connection.", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "817f2d8265e96f0701f6f2f4023139ba8ca5bd84dbacdbcba4a7cf3e9e94b96c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_flash_rom\n\nDocumentation:\nRead the flash ROM and write it to a file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_flash_rom(\n &mut self,\n offset: u32,\n size: u32,\n block_size: u32,\n max_in_flight: u32,\n file_path: PathBuf,\n ) -> Result<(), Error> {\n // ROM read limit per command\n const BLOCK_LEN: usize = 64;\n\n let mut data: Vec = Vec::new();\n\n let mut file = OpenOptions::new()\n .write(true)\n .truncate(true)\n .create(true)\n .open(&file_path)?;\n\n let mut correct_offset = offset;\n\n while data.len() < size as usize {\n let block_len = std::cmp::min(BLOCK_LEN, size as usize - data.len());\n\n correct_offset += data.len() as u32;\n\n let response = self.connection.with_timeout(\n CommandType::ReadFlashSlow.timeout(),\n |connection| {\n connection.command(Command::ReadFlashSlow {\n offset: correct_offset,\n size: block_len as u32,\n block_size,\n max_in_flight,\n })\n },\n )?;\n\n let payload: Vec = response.try_into()?;\n\n assert!(payload.len() >= block_len);\n\n // command always returns 64 byte buffer,\n // regardless of how many bytes were actually read from flash\n data.append(&mut payload[..block_len].to_vec());\n }\n\n file.write_all(&data)?;\n\n info!(\n \"Flash content successfully read and written to '{}'!\",\n file_path.display()\n );\n\n Ok(())\n }\n```"}], "func_name": "read_flash_rom", "docstring": "Read the flash ROM and write it to a file.", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b633409445a7855b5818772365669ed502fa4e213099e29f140310ba46d6e8f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_flash\n\nDocumentation:\nRead the flash and write it to a file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_flash(\n &mut self,\n offset: u32,\n size: u32,\n block_size: u32,\n max_in_flight: u32,\n file_path: PathBuf,\n ) -> Result<(), Error> {\n debug!(\"Reading 0x{:x}B from 0x{:08x}\", size, offset);\n\n let mut data = Vec::new();\n\n let mut file = OpenOptions::new()\n .write(true)\n .truncate(true)\n .create(true)\n .open(&file_path)?;\n\n self.connection\n .with_timeout(CommandType::ReadFlash.timeout(), |connection| {\n connection.command(Command::ReadFlash {\n offset,\n size,\n block_size,\n max_in_flight,\n })\n })?;\n\n while data.len() < size as usize {\n let response = self.connection.read_flash_response()?;\n let chunk: Vec = if let Some(response) = response {\n response.value.try_into()?\n } else {\n return Err(Error::IncorrectResponse);\n };\n\n data.extend_from_slice(&chunk);\n\n if data.len() < size as usize && chunk.len() < block_size as usize {\n return Err(Error::CorruptData(block_size as usize, chunk.len()));\n }\n\n self.connection.write_raw(data.len() as u32)?;\n }\n\n if data.len() > size as usize {\n return Err(Error::ReadMoreThanExpected);\n }\n\n let response = self.connection.read_flash_response()?;\n let digest: Vec = if let Some(response) = response {\n response.value.try_into()?\n } else {\n return Err(Error::IncorrectResponse);\n };\n\n if digest.len() != 16 {\n return Err(Error::IncorrectDigestLength(digest.len()));\n }\n\n let mut md5_hasher = Md5::new();\n md5_hasher.update(&data);\n let checksum_md5 = md5_hasher.finalize();\n\n if digest != checksum_md5.as_slice() {\n return Err(Error::DigestMismatch(\n digest,\n checksum_md5.as_slice().to_vec(),\n ));\n }\n\n file.write_all(&data)?;\n\n info!(\n \"Flash content successfully read and written to '{}'!\",\n file_path.display()\n );\n\n Ok(())\n }\n```"}], "func_name": "read_flash", "docstring": "Read the flash and write it to a file.", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0634c9427792e8f51f83f201b32074949c9af640fdac65c9a79de3ecd037d3ef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nFetch flash stub for the provided chip\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(chip: Chip) -> FlashStub {\n let s = match chip {\n Chip::Esp32 => STUB_32,\n Chip::Esp32c2 => STUB_32C2,\n Chip::Esp32c3 => STUB_32C3,\n Chip::Esp32c5 => STUB_32C5,\n Chip::Esp32c6 => STUB_32C6,\n Chip::Esp32h2 => STUB_32H2,\n Chip::Esp32p4 => STUB_32P4,\n Chip::Esp32s2 => STUB_32S2,\n Chip::Esp32s3 => STUB_32S3,\n };\n\n let stub: FlashStub = toml::from_str(s).unwrap();\n\n stub\n }\n```"}], "func_name": "get", "docstring": "Fetch flash stub for the provided chip", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/stubs.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/stubs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f91e73b25a65f1312180676f7b32b27da4ae4782b6a33c806a7d5635f76377e7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: text\n\nDocumentation:\nFetch text start address and bytes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn text(&self) -> (u32, Vec) {\n let v = general_purpose::STANDARD.decode(&self.text).unwrap();\n (self.text_start, v)\n }\n```"}], "func_name": "text", "docstring": "Fetch text start address and bytes", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/stubs.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/stubs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1155b25b53dddc1fc60562da0dbc3c23b7a107b358c5707c089da8cad54f8a66"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: data\n\nDocumentation:\nFetch data start address and bytes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn data(&self) -> (u32, Vec) {\n let v = general_purpose::STANDARD.decode(&self.data).unwrap();\n (self.data_start, v)\n }\n```"}], "func_name": "data", "docstring": "Fetch data start address and bytes", "repo": "esp-rs/espflash", "path": "espflash/src/flasher/stubs.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/flasher/stubs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "33e54b9bf2242cdd4b39ae879c7c0f19018b80d656d43f8758b69ef3aef75f84"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_bootloader\n\nDocumentation:\nGet the default bootloader for the given chip and crystal frequency\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn default_bootloader(\n chip: Chip,\n xtal_freq: XtalFrequency,\n) -> Result<&'static [u8], Error> {\n let error = Error::UnsupportedFeature {\n chip,\n feature: \"the selected crystal frequency\".into(),\n };\n\n match chip {\n Chip::Esp32 => match xtal_freq {\n XtalFrequency::_26Mhz => Ok(BOOTLOADER_ESP32_26MHZ),\n XtalFrequency::_40Mhz => Ok(BOOTLOADER_ESP32_40MHZ),\n _ => Err(error),\n },\n Chip::Esp32c2 => match xtal_freq {\n XtalFrequency::_26Mhz => Ok(BOOTLOADER_ESP32C2_26MHZ),\n XtalFrequency::_40Mhz => Ok(BOOTLOADER_ESP32C2_40MHZ),\n _ => Err(error),\n },\n Chip::Esp32c3 => match xtal_freq {\n XtalFrequency::_40Mhz => Ok(BOOTLOADER_ESP32C3),\n _ => Err(error),\n },\n Chip::Esp32c5 => match xtal_freq {\n XtalFrequency::_40Mhz | XtalFrequency::_48Mhz => Ok(BOOTLOADER_ESP32C5),\n _ => Err(error),\n },\n Chip::Esp32c6 => match xtal_freq {\n XtalFrequency::_40Mhz => Ok(BOOTLOADER_ESP32C6),\n _ => Err(error),\n },\n Chip::Esp32h2 => match xtal_freq {\n XtalFrequency::_32Mhz => Ok(BOOTLOADER_ESP32H2),\n _ => Err(error),\n },\n Chip::Esp32p4 => match xtal_freq {\n XtalFrequency::_40Mhz => Ok(BOOTLOADER_ESP32P4),\n _ => Err(error),\n },\n Chip::Esp32s2 => match xtal_freq {\n XtalFrequency::_40Mhz => Ok(BOOTLOADER_ESP32S2),\n _ => Err(error),\n },\n Chip::Esp32s3 => match xtal_freq {\n XtalFrequency::_40Mhz => Ok(BOOTLOADER_ESP32S3),\n _ => Err(error),\n },\n }\n}\n```"}], "func_name": "default_bootloader", "docstring": "Get the default bootloader for the given chip and crystal frequency", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/esp_idf.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/esp_idf.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0cee92e3661957e28cec8c476bb4401bbf31ef8aeb5ecc7dc987228746d91e5a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_flash_config\n\nDocumentation:\nUpdates flash size and baud filed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_flash_config(\n &mut self,\n size: FlashSize,\n freq: FlashFrequency,\n chip: Chip,\n ) -> Result<(), Error> {\n let flash_size = size.encode_flash_size()?;\n let flash_baud = freq.encode_flash_frequency(chip)?;\n\n // bit field\n self.flash_config = (flash_size << 4) | flash_baud;\n Ok(())\n }\n```"}], "func_name": "write_flash_config", "docstring": "Updates flash size and baud filed.", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/esp_idf.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/esp_idf.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d00cdc5fed7946237bf882d8cb0c7737c382895034b7beb06dbb44e0416e75b1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: flash_segments\n\nDocumentation:\nReturns an iterator over the [RomSegment].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn flash_segments<'b>(self) -> Box> + 'b>\n where\n 'a: 'b,\n {\n let bootloader_segment = Segment {\n addr: self.boot_addr,\n data: self.bootloader,\n };\n\n let partition_table_segment = Segment {\n addr: self.partition_table_offset,\n data: Cow::Owned(self.partition_table.to_bin().unwrap()),\n };\n\n let app_segment = Segment {\n addr: self.flash_segment.addr,\n data: self.flash_segment.data,\n };\n\n Box::new(\n once(bootloader_segment)\n .chain(once(partition_table_segment))\n .chain(once(app_segment)),\n )\n }\n```"}], "func_name": "flash_segments", "docstring": "Returns an iterator over the [RomSegment].", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/esp_idf.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/esp_idf.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a747f5735103fd57ee6272e1b7393dd1ecb3dbffe48e981536a22dd7277dc166"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ota_segments\n\nDocumentation:\nReturns an iterator over the OTA segment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ota_segments<'b>(self) -> Box> + 'b>\n where\n 'a: 'b,\n {\n Box::new(once(self.flash_segment))\n }\n```"}], "func_name": "ota_segments", "docstring": "Returns an iterator over the OTA segment.", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/esp_idf.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/esp_idf.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ffb9b4b60b01d261a67cdb53b488fa29a537f4553f2e189a0d05c20c16673530"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: metadata\n\nDocumentation:\nReturns a map of metadata about the application image.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn metadata(&self) -> HashMap<&str, String> {\n HashMap::from([\n (\"app_size\", self.app_size.to_string()),\n (\"part_size\", self.partition_table_size.to_string()),\n ])\n }\n```"}], "func_name": "metadata", "docstring": "Returns a map of metadata about the application image.", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/esp_idf.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/esp_idf.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e3f2429304a1d23679c996e6e41a401b182299dad1c6ae9812273f249883a8f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_partition_table\n\nDocumentation:\nGenerates a default partition table.\n\n`flash_size` is used to scale app partition when present, otherwise the\nparameter defaults are used.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn default_partition_table(chip: Chip, flash_size: Option) -> PartitionTable {\n const NVS_ADDR: u32 = 0x9000;\n const NVS_SIZE: u32 = 0x6000;\n const PHY_INIT_DATA_ADDR: u32 = 0xf000;\n const PHY_INIT_DATA_SIZE: u32 = 0x1000;\n\n let (app_addr, app_size) = match chip {\n Chip::Esp32 => (0x1_0000, 0x3f_0000),\n Chip::Esp32c2 => (0x1_0000, 0x1f_0000),\n Chip::Esp32c3 => (0x1_0000, 0x3f_0000),\n Chip::Esp32c5 => (0x1_0000, 0x3f_0000),\n Chip::Esp32c6 => (0x1_0000, 0x3f_0000),\n Chip::Esp32h2 => (0x1_0000, 0x3f_0000),\n Chip::Esp32p4 => (0x1_0000, 0x3f_0000),\n Chip::Esp32s2 => (0x1_0000, 0x10_0000),\n Chip::Esp32s3 => (0x1_0000, 0x10_0000),\n };\n\n PartitionTable::new(vec![\n Partition::new(\n String::from(\"nvs\"),\n Type::Data,\n SubType::Data(DataType::Nvs),\n NVS_ADDR,\n NVS_SIZE,\n Flags::empty(),\n ),\n Partition::new(\n String::from(\"phy_init\"),\n Type::Data,\n SubType::Data(DataType::Phy),\n PHY_INIT_DATA_ADDR,\n PHY_INIT_DATA_SIZE,\n Flags::empty(),\n ),\n Partition::new(\n String::from(\"factory\"),\n Type::App,\n SubType::App(AppType::Factory),\n app_addr,\n core::cmp::min(\n flash_size.map_or(app_size, |size| size - app_addr),\n MAX_PARTITION_SIZE,\n ),\n Flags::empty(),\n ),\n ])\n}\n```"}], "func_name": "default_partition_table", "docstring": "Generates a default partition table.\n\n`flash_size` is used to scale app partition when present, otherwise the\nparameter defaults are used.", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/esp_idf.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/esp_idf.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b7cecdbaed212d2904f1b3116790c3294f7a5ef2a12bbd6bfef3e3e7ea01a18"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: segment_padding\n\nDocumentation:\nActual alignment (in data bytes) required for a segment header: positioned\nso that after we write the next 8 byte header, file_offset % IROM_ALIGN ==\nsegment.addr % IROM_ALIGN\n\n(this is because the segment's vaddr may not be IROM_ALIGNed, more likely is\naligned IROM_ALIGN+0x18 to account for the binary file header)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn segment_padding(offset: usize, segment: &Segment<'_>, align_to: u32) -> u32 {\n let align_past = (segment.addr - SEG_HEADER_LEN) % align_to;\n let pad_len = ((align_to - ((offset as u32) % align_to)) + align_past) % align_to;\n\n if pad_len % align_to == 0 {\n 0\n } else if pad_len > SEG_HEADER_LEN {\n pad_len - SEG_HEADER_LEN\n } else {\n pad_len + align_to - SEG_HEADER_LEN\n }\n}\n```"}], "func_name": "segment_padding", "docstring": "Actual alignment (in data bytes) required for a segment header: positioned\nso that after we write the next 8 byte header, file_offset % IROM_ALIGN ==\nsegment.addr % IROM_ALIGN\n\n(this is because the segment's vaddr may not be IROM_ALIGNed, more likely is\naligned IROM_ALIGN+0x18 to account for the binary file header)", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/esp_idf.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/esp_idf.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0aff902dafdef0de1d05cd7d86348d5a8fe01143568506f2c8562e507c3ec24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: save_flash_segment\n\nDocumentation:\nSave a segment to the data buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn save_flash_segment(\n data: &mut Vec,\n mut segment: Segment<'_>,\n checksum: u8,\n mmu_page_size: u32,\n) -> Result {\n let end_pos = (data.len() + segment.data().len()) as u32 + SEG_HEADER_LEN;\n let segment_remainder = end_pos % mmu_page_size;\n\n if segment_remainder < 0x24 {\n // Work around a bug in ESP-IDF 2nd stage bootloader, that it didn't map the\n // last MMU page, if an IROM/DROM segment was < 0x24 bytes over the page\n // boundary.\n static PADDING: [u8; 0x24] = [0; 0x24];\n\n segment += &PADDING[0..(0x24 - segment_remainder as usize)];\n }\n\n let checksum = save_segment(data, &segment, checksum)?;\n\n Ok(checksum)\n}\n```"}], "func_name": "save_flash_segment", "docstring": "Save a segment to the data buffer.", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/esp_idf.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/esp_idf.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b8a0bfd186e02dc9bfe7753b156c39738899fa0dc2da2f060577eeae764cad95"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: save_segment\n\nDocumentation:\nStores a segment header and the segment data in the data buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn save_segment(data: &mut Vec, segment: &Segment<'_>, checksum: u8) -> Result {\n let padding = (4 - segment.size() % 4) % 4;\n let header = SegmentHeader {\n addr: segment.addr,\n length: segment.size() + padding,\n };\n\n data.write_all(bytes_of(&header))?;\n data.write_all(segment.data())?;\n\n let padding = &[0u8; 4][0..padding as usize];\n data.write_all(padding)?;\n\n Ok(update_checksum(segment.data(), checksum))\n}\n```"}], "func_name": "save_segment", "docstring": "Stores a segment header and the segment data in the data buffer.", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/esp_idf.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/esp_idf.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7dce365102660fa1566e6a27686cdb8d537eb7231be9289cf4ccad9c7f539bc9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_checksum\n\nDocumentation:\nUpdate the checksum with the given data\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn update_checksum(data: &[u8], mut checksum: u8) -> u8 {\n for byte in data {\n checksum ^= *byte;\n }\n\n checksum\n}\n```"}], "func_name": "update_checksum", "docstring": "Update the checksum with the given data", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/esp_idf.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/esp_idf.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "af81907c57108c16968b31f77070e496315105dde9da7e33886aaad81b681b04"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_partition_table\n\nDocumentation:\nParse a [PartitionTable] from the provided path\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_partition_table(path: &Path) -> Result {\n let data = fs::read(path).map_err(|e| Error::FileOpenError(path.display().to_string(), e))?;\n\n Ok(PartitionTable::try_from(data)?)\n}\n```"}], "func_name": "parse_partition_table", "docstring": "Parse a [PartitionTable] from the provided path", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/esp_idf.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/esp_idf.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aa44480c61c98c793136de724a11049067d8fa2ead7ab0a4a8caf1a1ddc37750"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_idf_bootloader\n\nDocumentation:\nCheck if the provided ELF contains the app descriptor required by [the IDF bootloader](https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-guides/bootloader.html).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check_idf_bootloader(elf_data: &Vec) -> Result<()> {\n let object = File::parse(elf_data.as_slice()).into_diagnostic()?;\n let section = object.section_by_name(\".rodata_desc\").is_some();\n let symbol = object.symbols().any(|sym| sym.name() == Ok(\"esp_app_desc\"));\n\n if !section || !symbol {\n return Err(Error::AppDescriptorNotPresent).into_diagnostic();\n }\n\n Ok(())\n}\n```"}], "func_name": "check_idf_bootloader", "docstring": "Check if the provided ELF contains the app descriptor required by [the IDF bootloader](https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-guides/bootloader.html).", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/esp_idf.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/esp_idf.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "763d0dc468cfee62c677622ed92c0cd2c8f4d73f85a7d340318d0f28887bb331"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ota_segments\n\nDocumentation:\nReturns all data segments required for OTA updates\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ota_segments(self) -> Vec> {\n match self {\n ImageFormat::EspIdf(idf) => idf.ota_segments().collect(),\n }\n }\n```"}], "func_name": "ota_segments", "docstring": "Returns all data segments required for OTA updates", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "093d65530900fa62df27735f0b81af741c29b7f3737d5804dec6382afb4c3ba3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: metadata\n\nDocumentation:\nReturns metadata about the application image\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn metadata(&self) -> HashMap<&str, String> {\n match self {\n ImageFormat::EspIdf(idf) => idf.metadata(),\n }\n }\n```"}], "func_name": "metadata", "docstring": "Returns metadata about the application image", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6acb2c259b570c1a4ca72d5531857e83f26bfe33bcc44875b697ba3eb90cc897"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: split_off\n\nDocumentation:\nSplit of the first `count` bytes into a new segment, adjusting the\nremaining segment as needed\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn split_off(&mut self, count: usize) -> Self {\n if count < self.data.len() {\n let (head, tail) = match take(&mut self.data) {\n Cow::Borrowed(data) => {\n let (head, tail) = data.split_at(count);\n (Cow::Borrowed(head), Cow::Borrowed(tail))\n }\n Cow::Owned(mut data) => {\n let tail = data.split_off(count);\n (Cow::Owned(data), Cow::Owned(tail))\n }\n };\n let new = Segment {\n addr: self.addr,\n data: head,\n };\n self.addr += count as u32;\n self.data = tail;\n new\n } else {\n let new = self.clone();\n self.addr += self.size();\n self.data = Cow::Borrowed(&[]);\n new\n }\n }\n```"}], "func_name": "split_off", "docstring": "Split of the first `count` bytes into a new segment, adjusting the\nremaining segment as needed", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0293b57b12501460fd69ceb16a5c7ed49569d0fe0ea6756ecb97b2a715de436f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pad_align\n\nDocumentation:\nPad the segment to the given alignment\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pad_align(&mut self, align: usize) {\n let padding = (align - self.data.len() % align) % align;\n if padding > 0 {\n let mut data = take(&mut self.data).into_owned();\n data.extend_from_slice(&[0; 4][0..padding]);\n self.data = Cow::Owned(data);\n }\n }\n```"}], "func_name": "pad_align", "docstring": "Pad the segment to the given alignment", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "68bdebcc736022eef3c19f5153e25b1979620dfcc595567cc87db3c7e49fdf4b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: borrow\n\nDocumentation:\nBorrow the segment for the given lifetime\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn borrow<'b>(&'b self) -> Segment<'b>\n where\n 'a: 'b,\n {\n Segment {\n addr: self.addr,\n data: Cow::Borrowed(self.data.as_ref()),\n }\n }\n```"}], "func_name": "borrow", "docstring": "Borrow the segment for the given lifetime", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "34bf02638fa3f0333655001b29bf1c08ea37fcc628cfa0b0b40e97160d663c57"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ram_segments\n\nDocumentation:\nReturns an iterator over all RAM segments for a given chip and ELF file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn ram_segments<'a>(\n chip: Chip,\n elf: &'a ElfFile<'a>,\n) -> Box> + 'a> {\n Box::new(segments(elf).filter(move |segment| !chip.into_target().addr_is_flash(segment.addr)))\n}\n```"}], "func_name": "ram_segments", "docstring": "Returns an iterator over all RAM segments for a given chip and ELF file.", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d75cf0396ff1142b1cc45bb1122659b70ab88ae55c5ecaa0b47bd19964fca7e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rom_segments\n\nDocumentation:\nReturns an iterator over all ROM segments for a given chip and ELF file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn rom_segments<'a>(\n chip: Chip,\n elf: &'a ElfFile<'a>,\n) -> Box> + 'a> {\n Box::new(segments(elf).filter(move |segment| chip.into_target().addr_is_flash(segment.addr)))\n}\n```"}], "func_name": "rom_segments", "docstring": "Returns an iterator over all ROM segments for a given chip and ELF file.", "repo": "esp-rs/espflash", "path": "espflash/src/image_format/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/image_format/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d48200f481ac6d3f28b5cd8c079f61ce3a6258d8dc89c97773c02ab96557c250"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: blk_version_major\n\nDocumentation:\nReturn the major BLK version based on eFuses\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn blk_version_major(&self, connection: &mut Connection) -> Result {\n self.read_efuse(connection, efuse::BLK_VERSION_MAJOR)\n }\n```"}], "func_name": "blk_version_major", "docstring": "Return the major BLK version based on eFuses", "repo": "esp-rs/espflash", "path": "espflash/src/targets/esp32s3.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/esp32s3.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dba2f6220e708fc2fdd8de380dc671b3af2e60c388181bcfd6f92cd5f52ccbc8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: blk_version_minor\n\nDocumentation:\nReturn the minor BLK version based on eFuses\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn blk_version_minor(&self, connection: &mut Connection) -> Result {\n self.read_efuse(connection, efuse::BLK_VERSION_MINOR)\n }\n```"}], "func_name": "blk_version_minor", "docstring": "Return the minor BLK version based on eFuses", "repo": "esp-rs/espflash", "path": "espflash/src/targets/esp32s3.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/esp32s3.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "baf81da4660581e3c5b0a3eaada46b9a9f68f9edd3aa0536f977b43927381bb5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: id\n\nDocumentation:\nReturns the chip ID for the [Chip]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn id(&self) -> u16 {\n match self {\n Chip::Esp32 => esp32::CHIP_ID,\n Chip::Esp32c2 => esp32c2::CHIP_ID,\n Chip::Esp32c3 => esp32c3::CHIP_ID,\n Chip::Esp32c5 => esp32c5::CHIP_ID,\n Chip::Esp32c6 => esp32c6::CHIP_ID,\n Chip::Esp32h2 => esp32h2::CHIP_ID,\n Chip::Esp32p4 => esp32p4::CHIP_ID,\n Chip::Esp32s2 => esp32s2::CHIP_ID,\n Chip::Esp32s3 => esp32s3::CHIP_ID,\n }\n }\n```"}], "func_name": "id", "docstring": "Returns the chip ID for the [Chip]", "repo": "esp-rs/espflash", "path": "espflash/src/targets/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f8ca9492b061ff2536d9827a031b9f35187ac2909c60cfd9f6b219fb05631db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: valid_mmu_page_sizes\n\nDocumentation:\nReturns the valid MMU page sizes for the [Chip]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn valid_mmu_page_sizes(self) -> Option<&'static [u32]> {\n match self {\n Chip::Esp32c2 => Some(&[16 * 1024, 32 * 1024, 64 * 1024]),\n Chip::Esp32c6 | Chip::Esp32h2 => Some(&[8 * 1024, 16 * 1024, 32 * 1024, 64 * 1024]),\n // TODO: Verify this is correct for Esp32c5\n _ => None,\n }\n }\n```"}], "func_name": "valid_mmu_page_sizes", "docstring": "Returns the valid MMU page sizes for the [Chip]", "repo": "esp-rs/espflash", "path": "espflash/src/targets/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b39d6e7f7902e80a84fe4ae0e96099a5431854978fd65a36c539382a0902d4bf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: boot_address\n\nDocumentation:\nReturns the boot address for the [Chip]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn boot_address(&self) -> u32 {\n match self {\n Chip::Esp32c2 | Chip::Esp32c3 | Chip::Esp32c6 | Chip::Esp32h2 | Chip::Esp32s3 => 0x0,\n Chip::Esp32 | Chip::Esp32s2 => 0x1000,\n Chip::Esp32c5 | Chip::Esp32p4 => 0x2000,\n }\n }\n```"}], "func_name": "boot_address", "docstring": "Returns the boot address for the [Chip]", "repo": "esp-rs/espflash", "path": "espflash/src/targets/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1060b0995a6266dab436889150b5c06a2430ba2648967b596a92a2983dc1a35d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_flash_frequency\n\nDocumentation:\nReturns the default flash frequency for the [Chip]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn default_flash_frequency(&self) -> FlashFrequency {\n match self {\n Chip::Esp32\n | Chip::Esp32c3\n | Chip::Esp32c5\n | Chip::Esp32c6\n | Chip::Esp32p4\n | Chip::Esp32s2\n | Chip::Esp32s3 => FlashFrequency::_40Mhz,\n Chip::Esp32c2 => FlashFrequency::_30Mhz,\n Chip::Esp32h2 => FlashFrequency::_24Mhz,\n }\n }\n```"}], "func_name": "default_flash_frequency", "docstring": "Returns the default flash frequency for the [Chip]", "repo": "esp-rs/espflash", "path": "espflash/src/targets/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b07034c7f4a0f2f3300e1830cea4d1bcd00a6b011e93a0b16aaf31e46df6642d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_crystal_frequency\n\nDocumentation:\nReturns the default crystal frequency for the [Chip]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn default_crystal_frequency(&self) -> XtalFrequency {\n match self {\n Chip::Esp32c5 => XtalFrequency::_48Mhz,\n Chip::Esp32h2 => XtalFrequency::_32Mhz,\n _ => XtalFrequency::_40Mhz,\n }\n }\n```"}], "func_name": "default_crystal_frequency", "docstring": "Returns the default crystal frequency for the [Chip]", "repo": "esp-rs/espflash", "path": "espflash/src/targets/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44c0d8972941031e79043247321c1fea381c7617d8977c68c666e64060665a71"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: usr\n\nDocumentation:\nGet the address of the USR register.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn usr(&self) -> u32 {\n self.base + self.usr_offset\n }\n```"}], "func_name": "usr", "docstring": "Get the address of the USR register.", "repo": "esp-rs/espflash", "path": "espflash/src/targets/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4599bc66136d9bf4fb75df2f355209c1019f392c3317dc069486fce5515428e1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: usr1\n\nDocumentation:\nGet the address of the USR1 register.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn usr1(&self) -> u32 {\n self.base + self.usr1_offset\n }\n```"}], "func_name": "usr1", "docstring": "Get the address of the USR1 register.", "repo": "esp-rs/espflash", "path": "espflash/src/targets/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aaeb3869780ec37b64307fce9d6449afdb2770f261b34349d881e9c2988665e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: usr2\n\nDocumentation:\nGet the address of the USR2 register.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn usr2(&self) -> u32 {\n self.base + self.usr2_offset\n }\n```"}], "func_name": "usr2", "docstring": "Get the address of the USR2 register.", "repo": "esp-rs/espflash", "path": "espflash/src/targets/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2cb63a2cbe7364a8e132e865d6cfafb8bb60e34ed6438edd8c95c45ddad4ba6b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: w0\n\nDocumentation:\nGet the address of the W0 register.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn w0(&self) -> u32 {\n self.base + self.w0_offset\n }\n```"}], "func_name": "w0", "docstring": "Get the address of the W0 register.", "repo": "esp-rs/espflash", "path": "espflash/src/targets/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e4c135f7b93e0d50177a5c1e23a3489a95aa38c4d3a88ec91a3f957caf9e1418"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mosi_length\n\nDocumentation:\nGet the address of the MOSI length register.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn mosi_length(&self) -> Option {\n self.mosi_length_offset.map(|offset| self.base + offset)\n }\n```"}], "func_name": "mosi_length", "docstring": "Get the address of the MOSI length register.", "repo": "esp-rs/espflash", "path": "espflash/src/targets/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27fdd9419d6d5142375a98995c660c83930c228bdf463cf625d251865a495f92"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: miso_length\n\nDocumentation:\nGet the address of the MISO length register.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn miso_length(&self) -> Option {\n self.miso_length_offset.map(|offset| self.base + offset)\n }\n```"}], "func_name": "miso_length", "docstring": "Get the address of the MISO length register.", "repo": "esp-rs/espflash", "path": "espflash/src/targets/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f9128d3a00d57fc1d6e916bd2f714c92127b04fce51256ed0b4e405e14e0d37c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: flash_frequency_encodings\n\nDocumentation:\nNumeric encodings for the flash frequencies supported by a chip\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn flash_frequency_encodings(&self) -> HashMap {\n use FlashFrequency::*;\n\n let encodings = [(_20Mhz, 0x2), (_26Mhz, 0x1), (_40Mhz, 0x0), (_80Mhz, 0xf)];\n\n HashMap::from(encodings)\n }\n```"}], "func_name": "flash_frequency_encodings", "docstring": "Numeric encodings for the flash frequencies supported by a chip", "repo": "esp-rs/espflash", "path": "espflash/src/targets/mod.rs", "url": "https://github.com/esp-rs/espflash/blob/master/espflash/src/targets/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "31531f4a8c7d10e1a8570b626ca69e11199109587e84cf5419b2bb8dc1bc115d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: retry_partition\n\nDocumentation:\nReturns a reference to the retry partition contained in this config, if any.\n\nWARNING: This method is unstable and may be removed at any time. Do not rely on this\nmethod for anything!\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn retry_partition(&self) -> ::std::option::Option<&::aws_smithy_runtime::client::retries::RetryPartition> {\n self.config\n .load::<::aws_smithy_runtime::client::retries::RetryPartition>()\n }\n```"}], "func_name": "retry_partition", "docstring": "Returns a reference to the retry partition contained in this config, if any.\n\nWARNING: This method is unstable and may be removed at any time. Do not rely on this\nmethod for anything!", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e2b1827bc063c163f6fb2e61d4492246ba9ad042d502602615f2608ce6b017ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: retry_classifiers\n\nDocumentation:\nReturns retry classifiers currently registered by the user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn retry_classifiers(\n &self,\n ) -> impl Iterator + '_ {\n self.runtime_components.retry_classifiers()\n }\n```"}], "func_name": "retry_classifiers", "docstring": "Returns retry classifiers currently registered by the user.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f47bdc12b3ce99e795bcc8c85f29f4cefac833e2fee1b447277ad2140601be3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: invocation_id_generator\n\nDocumentation:\nReturns the invocation ID generator if one was given in config.\n\nThe invocation ID generator generates ID values for the `amz-sdk-invocation-id` header. By\ndefault, this will be a random UUID. Overriding it may be useful in tests that examine the\nHTTP request and need to be deterministic.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn invocation_id_generator(\n &self,\n ) -> ::std::option::Option<::aws_runtime::invocation_id::SharedInvocationIdGenerator> {\n self.config\n .load::<::aws_runtime::invocation_id::SharedInvocationIdGenerator>()\n .cloned()\n }\n```"}], "func_name": "invocation_id_generator", "docstring": "Returns the invocation ID generator if one was given in config.\n\nThe invocation ID generator generates ID values for the `amz-sdk-invocation-id` header. By\ndefault, this will be a random UUID. Overriding it may be useful in tests that examine the\nHTTP request and need to be deterministic.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3eac88b08e76d72fc9ad3757a01c160fca5c120da86d7227da687d11a272cad6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stalled_stream_protection\n\nDocumentation:\nSet the [`StalledStreamProtectionConfig`](crate::config::StalledStreamProtectionConfig)\nto configure protection for stalled streams.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stalled_stream_protection(\n mut self,\n stalled_stream_protection_config: crate::config::StalledStreamProtectionConfig,\n ) -> Self {\n self.set_stalled_stream_protection(::std::option::Option::Some(stalled_stream_protection_config));\n self\n }\n```"}], "func_name": "stalled_stream_protection", "docstring": "Set the [`StalledStreamProtectionConfig`](crate::config::StalledStreamProtectionConfig)\nto configure protection for stalled streams.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d49846c0f6dc1f789ca93ddd98e1e54c255e89eae9b3a4163548dca091cb25a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bearer_token_resolver\n\nDocumentation:\nSets a bearer token provider that will be used for HTTP bearer auth.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bearer_token_resolver(\n mut self,\n bearer_token_resolver: impl crate::config::ResolveIdentity + 'static,\n ) -> Self {\n self.runtime_components.set_identity_resolver(\n ::aws_smithy_runtime_api::client::auth::http::HTTP_BEARER_AUTH_SCHEME_ID,\n ::aws_smithy_runtime_api::shared::IntoShared::<\n ::aws_smithy_runtime_api::client::identity::SharedIdentityResolver,\n >::into_shared(bearer_token_resolver),\n );\n self\n }\n```"}], "func_name": "bearer_token_resolver", "docstring": "Sets a bearer token provider that will be used for HTTP bearer auth.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "29ed52b47df938a6f46d9b2df9ae29f3b084812a5eb8312ffc14d532c348ea73"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: endpoint_resolver\n\nDocumentation:\nSets the endpoint resolver to use when making requests.\n\nThis service does not define a default endpoint resolver.\n\nNote: setting an endpoint resolver will replace any endpoint URL that has been set.\nThis method accepts an endpoint resolver [specific to this\nservice](crate::config::endpoint::ResolveEndpoint). If you want to provide a shared\nendpoint resolver, use [`Self::set_endpoint_resolver`].\n\n# Examples\nCreate a custom endpoint resolver that resolves a different endpoing per-stage, e.g. staging\nvs. production. ```no_run\nuse amzn_codewhisperer_client::config::endpoint::{\nEndpoint,\nEndpointFuture,\nParams,\nResolveEndpoint,\n};\n#[derive(Debug)]\nstruct StageResolver {\nstage: String,\n}\nimpl ResolveEndpoint for StageResolver {\nfn resolve_endpoint(&self, params: &Params) -> EndpointFuture<'_> {\nlet stage = &self.stage;\nEndpointFuture::ready(Ok(Endpoint::builder()\n.url(format!(\"{stage}.myservice.com\"))\n.build()))\n}\n}\nlet resolver = StageResolver {\nstage: std::env::var(\"STAGE\").unwrap(),\n};\nlet config = amzn_codewhisperer_client::Config::builder()\n.endpoint_resolver(resolver)\n.build();\nlet client = amzn_codewhisperer_client::Client::from_conf(config);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn endpoint_resolver(\n mut self,\n endpoint_resolver: impl crate::config::endpoint::ResolveEndpoint + 'static,\n ) -> Self {\n self.set_endpoint_resolver(::std::option::Option::Some(endpoint_resolver.into_shared_resolver()));\n self\n }\n```"}], "func_name": "endpoint_resolver", "docstring": "Sets the endpoint resolver to use when making requests.\n\nThis service does not define a default endpoint resolver.\n\nNote: setting an endpoint resolver will replace any endpoint URL that has been set.\nThis method accepts an endpoint resolver [specific to this\nservice](crate::config::endpoint::ResolveEndpoint). If you want to provide a shared\nendpoint resolver, use [`Self::set_endpoint_resolver`].\n\n# Examples\nCreate a custom endpoint resolver that resolves a different endpoing per-stage, e.g. staging\nvs. production. ```no_run\nuse amzn_codewhisperer_client::config::endpoint::{\nEndpoint,\nEndpointFuture,\nParams,\nResolveEndpoint,\n};\n#[derive(Debug)]\nstruct StageResolver {\nstage: String,\n}\nimpl ResolveEndpoint for StageResolver {\nfn resolve_endpoint(&self, params: &Params) -> EndpointFuture<'_> {\nlet stage = &self.stage;\nEndpointFuture::ready(Ok(Endpoint::builder()\n.url(format!(\"{stage}.myservice.com\"))\n.build()))\n}\n}\nlet resolver = StageResolver {\nstage: std::env::var(\"STAGE\").unwrap(),\n};\nlet config = amzn_codewhisperer_client::Config::builder()\n.endpoint_resolver(resolver)\n.build();\nlet client = amzn_codewhisperer_client::Client::from_conf(config);\n```", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ec1cd46e49062507448ac255dae1b1514c062e2c2f311835693720918c08ff50"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_retry_config\n\nDocumentation:\nSet the retry_config for the builder\n\n# Examples\n```no_run\nuse amzn_codewhisperer_client::config::retry::RetryConfig;\nuse amzn_codewhisperer_client::config::{\nBuilder,\nConfig,\n};\n\nfn disable_retries(builder: &mut Builder) {\nlet retry_config = RetryConfig::standard().with_max_attempts(1);\nbuilder.set_retry_config(Some(retry_config));\n}\n\nlet mut builder = Config::builder();\ndisable_retries(&mut builder);\nlet config = builder.build();\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_retry_config(\n &mut self,\n retry_config: ::std::option::Option<::aws_smithy_types::retry::RetryConfig>,\n ) -> &mut Self {\n retry_config.map(|r| self.config.store_put(r));\n self\n }\n```"}], "func_name": "set_retry_config", "docstring": "Set the retry_config for the builder\n\n# Examples\n```no_run\nuse amzn_codewhisperer_client::config::retry::RetryConfig;\nuse amzn_codewhisperer_client::config::{\nBuilder,\nConfig,\n};\n\nfn disable_retries(builder: &mut Builder) {\nlet retry_config = RetryConfig::standard().with_max_attempts(1);\nbuilder.set_retry_config(Some(retry_config));\n}\n\nlet mut builder = Config::builder();\ndisable_retries(&mut builder);\nlet config = builder.build();\n```", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f3aa9384e3b82831dade9d5422bd245e81fa90c3d8be0e737d9cfca3bf102b67"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sleep_impl\n\nDocumentation:\nSet the sleep_impl for the builder\n\n# Examples\n\n```no_run\nuse amzn_codewhisperer_client::config::{\nAsyncSleep,\nConfig,\nSharedAsyncSleep,\nSleep,\n};\n\n#[derive(Debug)]\npub struct ForeverSleep;\n\nimpl AsyncSleep for ForeverSleep {\nfn sleep(&self, duration: std::time::Duration) -> Sleep {\nSleep::new(std::future::pending())\n}\n}\n\nlet sleep_impl = SharedAsyncSleep::new(ForeverSleep);\nlet config = Config::builder().sleep_impl(sleep_impl).build();\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sleep_impl(mut self, sleep_impl: impl crate::config::AsyncSleep + 'static) -> Self {\n self.set_sleep_impl(Some(::aws_smithy_runtime_api::shared::IntoShared::into_shared(\n sleep_impl,\n )));\n self\n }\n```"}], "func_name": "sleep_impl", "docstring": "Set the sleep_impl for the builder\n\n# Examples\n\n```no_run\nuse amzn_codewhisperer_client::config::{\nAsyncSleep,\nConfig,\nSharedAsyncSleep,\nSleep,\n};\n\n#[derive(Debug)]\npub struct ForeverSleep;\n\nimpl AsyncSleep for ForeverSleep {\nfn sleep(&self, duration: std::time::Duration) -> Sleep {\nSleep::new(std::future::pending())\n}\n}\n\nlet sleep_impl = SharedAsyncSleep::new(ForeverSleep);\nlet config = Config::builder().sleep_impl(sleep_impl).build();\n```", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ece97d1553bc3267c91cdafac253b79b20345bd2059aed8ebfcd6f6d281de8bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_interceptors\n\nDocumentation:\nSet [`SharedInterceptor`](crate::config::SharedInterceptor)s for the builder.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_interceptors(\n &mut self,\n interceptors: impl IntoIterator,\n ) -> &mut Self {\n self.runtime_components.set_interceptors(interceptors.into_iter());\n self\n }\n```"}], "func_name": "set_interceptors", "docstring": "Set [`SharedInterceptor`](crate::config::SharedInterceptor)s for the builder.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1614d312053f47b63ee25cc67ac21173c7494555d77239e26e9a587959be03db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: time_source\n\nDocumentation:\nSets the time source used for this service\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn time_source(mut self, time_source: impl ::aws_smithy_async::time::TimeSource + 'static) -> Self {\n self.set_time_source(::std::option::Option::Some(\n ::aws_smithy_runtime_api::shared::IntoShared::into_shared(time_source),\n ));\n self\n }\n```"}], "func_name": "time_source", "docstring": "Sets the time source used for this service", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c3f98fff3a01cf41e8bb9700853d8000e09b0e8f32c8d98e383ea22d77b74217"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: app_name\n\nDocumentation:\nSets the name of the app that is using the client.\n\nThis _optional_ name is used to identify the application in the user agent that\ngets sent along with requests.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn app_name(mut self, app_name: ::aws_types::app_name::AppName) -> Self {\n self.set_app_name(Some(app_name));\n self\n }\n```"}], "func_name": "app_name", "docstring": "Sets the name of the app that is using the client.\n\nThis _optional_ name is used to identify the application in the user agent that\ngets sent along with requests.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a9c531663c7480555844d207aae86b02ab160dd49972b90e4a43dc2299e47c9e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: token_provider\n\nDocumentation:\nSets the access token provider for this service\n\nNote: the [`Self::bearer_token`] and [`Self::bearer_token_resolver`] methods are\nequivalent to this method, but take the [`Token`] and [`ResolveIdentity`] types\nrespectively.\n\n[`Token`]: crate::config::Token\n[`ResolveIdentity`]: crate::config::ResolveIdentity\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn token_provider(mut self, token_provider: impl crate::config::ProvideToken + 'static) -> Self {\n self.set_token_provider(::std::option::Option::Some(\n ::aws_smithy_runtime_api::shared::IntoShared::::into_shared(\n token_provider,\n ),\n ));\n self\n }\n```"}], "func_name": "token_provider", "docstring": "Sets the access token provider for this service\n\nNote: the [`Self::bearer_token`] and [`Self::bearer_token_resolver`] methods are\nequivalent to this method, but take the [`Token`] and [`ResolveIdentity`] types\nrespectively.\n\n[`Token`]: crate::config::Token\n[`ResolveIdentity`]: crate::config::ResolveIdentity", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "15c3a5398718b7d40b1f03a60ed2e47f3edce99aad3aa4af239b09358dc0e183"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: invocation_id_generator\n\nDocumentation:\nOverrides the default invocation ID generator.\n\nThe invocation ID generator generates ID values for the `amz-sdk-invocation-id` header. By\ndefault, this will be a random UUID. Overriding it may be useful in tests that examine the\nHTTP request and need to be deterministic.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn invocation_id_generator(\n mut self,\n gen: impl ::aws_runtime::invocation_id::InvocationIdGenerator + 'static,\n ) -> Self {\n self.set_invocation_id_generator(::std::option::Option::Some(\n ::aws_runtime::invocation_id::SharedInvocationIdGenerator::new(gen),\n ));\n self\n }\n```"}], "func_name": "invocation_id_generator", "docstring": "Overrides the default invocation ID generator.\n\nThe invocation ID generator generates ID values for the `amz-sdk-invocation-id` header. By\ndefault, this will be a random UUID. Overriding it may be useful in tests that examine the\nHTTP request and need to be deterministic.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17cfc54de649dbce45eb1027d30e86e084ced1b9805fffb49179405f10a4a750"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: apply_test_defaults\n\nDocumentation:\nApply test defaults to the builder\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn apply_test_defaults(&mut self) -> &mut Self {\n self.set_idempotency_token_provider(Some(\"00000000-0000-4000-8000-000000000000\".into()));\n self.set_time_source(::std::option::Option::Some(\n ::aws_smithy_async::time::SharedTimeSource::new(::aws_smithy_async::time::StaticTimeSource::new(\n ::std::time::UNIX_EPOCH + ::std::time::Duration::from_secs(1234567890),\n )),\n ));\n self.config\n .store_put(::aws_runtime::user_agent::AwsUserAgent::for_tests());\n self.set_token_provider(Some(crate::config::SharedTokenProvider::new(\n ::aws_credential_types::Token::for_tests(),\n )));\n self.behavior_version = ::std::option::Option::Some(crate::config::BehaviorVersion::latest());\n self\n }\n```"}], "func_name": "apply_test_defaults", "docstring": "Apply test defaults to the builder", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf454ea0445c2f4633173ef259e8a314efdd212b543c710e64f12a22f943bab6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_artifact_upload_url\n\nDocumentation:\nConstructs a fluent builder for the\n[`CreateArtifactUploadUrl`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`content_md5(impl Into)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::content_md5) / [`set_content_md5(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_content_md5):
required: **false**
(undocumented)
\n- [`content_checksum(impl Into)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::content_checksum) / [`set_content_checksum(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_content_checksum):
required: **false**
(undocumented)
\n- [`content_checksum_type(ContentChecksumType)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::content_checksum_type) / [`set_content_checksum_type(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_content_checksum_type):
required: **false**
(undocumented)
\n- [`content_length(i64)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::content_length) / [`set_content_length(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_content_length):
required: **false**
(undocumented)
\n- [`artifact_type(ArtifactType)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::artifact_type) / [`set_artifact_type(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_artifact_type):
required: **false**
(undocumented)
\n- [`upload_intent(UploadIntent)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::upload_intent) / [`set_upload_intent(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_upload_intent):
required: **false**
Upload Intent
\n- [`upload_context(UploadContext)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::upload_context) / [`set_upload_context(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_upload_context):
required: **false**
(undocumented)
\n- [`upload_id(impl Into)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::upload_id) / [`set_upload_id(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_upload_id):
required: **false**
Upload ID returned by CreateUploadUrl API
\n- [`profile_arn(impl Into)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`CreateArtifactUploadUrlOutput`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput)\nwith field(s):\n- [`upload_id(String)`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput::upload_id): Upload ID returned by CreateUploadUrl API\n- [`upload_url(String)`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput::upload_url): (undocumented)\n- [`kms_key_arn(Option)`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput::kms_key_arn): (undocumented)\n- [`request_headers(Option>)`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput::request_headers):\n(undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_artifact_upload_url(\n &self,\n ) -> crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder {\n crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "create_artifact_upload_url", "docstring": "Constructs a fluent builder for the\n[`CreateArtifactUploadUrl`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`content_md5(impl Into)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::content_md5) / [`set_content_md5(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_content_md5):
required: **false**
(undocumented)
\n- [`content_checksum(impl Into)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::content_checksum) / [`set_content_checksum(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_content_checksum):
required: **false**
(undocumented)
\n- [`content_checksum_type(ContentChecksumType)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::content_checksum_type) / [`set_content_checksum_type(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_content_checksum_type):
required: **false**
(undocumented)
\n- [`content_length(i64)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::content_length) / [`set_content_length(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_content_length):
required: **false**
(undocumented)
\n- [`artifact_type(ArtifactType)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::artifact_type) / [`set_artifact_type(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_artifact_type):
required: **false**
(undocumented)
\n- [`upload_intent(UploadIntent)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::upload_intent) / [`set_upload_intent(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_upload_intent):
required: **false**
Upload Intent
\n- [`upload_context(UploadContext)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::upload_context) / [`set_upload_context(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_upload_context):
required: **false**
(undocumented)
\n- [`upload_id(impl Into)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::upload_id) / [`set_upload_id(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_upload_id):
required: **false**
Upload ID returned by CreateUploadUrl API
\n- [`profile_arn(impl Into)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`CreateArtifactUploadUrlOutput`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput)\nwith field(s):\n- [`upload_id(String)`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput::upload_id): Upload ID returned by CreateUploadUrl API\n- [`upload_url(String)`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput::upload_url): (undocumented)\n- [`kms_key_arn(Option)`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput::kms_key_arn): (undocumented)\n- [`request_headers(Option>)`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput::request_headers):\n(undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/create_artifact_upload_url.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/create_artifact_upload_url.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "98cab58aeec024e667edadc18531405dc8ab27a122bcef44785c3e9d19228c7c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_subscription_token\n\nDocumentation:\nConstructs a fluent builder for the\n[`CreateSubscriptionToken`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`account_id(impl Into)`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenFluentBuilder::account_id) / [`set_account_id(Option)`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenFluentBuilder::set_account_id):
required: **true**
Represents the AWS account ID of the customer
\n- [`client_token(impl Into)`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`CreateSubscriptionTokenOutput`](crate::operation::create_subscription_token::CreateSubscriptionTokenOutput)\nwith field(s):\n- [`encoded_verification_url(String)`](crate::operation::create_subscription_token::CreateSubscriptionTokenOutput::encoded_verification_url): (undocumented)\n- [`token(String)`](crate::operation::create_subscription_token::CreateSubscriptionTokenOutput::token): (undocumented)\n- [`status(SubscriptionStatus)`](crate::operation::create_subscription_token::CreateSubscriptionTokenOutput::status): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::create_subscription_token::CreateSubscriptionTokenError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_subscription_token(\n &self,\n ) -> crate::operation::create_subscription_token::builders::CreateSubscriptionTokenFluentBuilder {\n crate::operation::create_subscription_token::builders::CreateSubscriptionTokenFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "create_subscription_token", "docstring": "Constructs a fluent builder for the\n[`CreateSubscriptionToken`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`account_id(impl Into)`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenFluentBuilder::account_id) / [`set_account_id(Option)`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenFluentBuilder::set_account_id):
required: **true**
Represents the AWS account ID of the customer
\n- [`client_token(impl Into)`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`CreateSubscriptionTokenOutput`](crate::operation::create_subscription_token::CreateSubscriptionTokenOutput)\nwith field(s):\n- [`encoded_verification_url(String)`](crate::operation::create_subscription_token::CreateSubscriptionTokenOutput::encoded_verification_url): (undocumented)\n- [`token(String)`](crate::operation::create_subscription_token::CreateSubscriptionTokenOutput::token): (undocumented)\n- [`status(SubscriptionStatus)`](crate::operation::create_subscription_token::CreateSubscriptionTokenOutput::status): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::create_subscription_token::CreateSubscriptionTokenError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/create_subscription_token.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/create_subscription_token.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6df9e5cc4a8594f508aa6c6a6a64ae8b9dc7b8b2f3c559be24b83014e4f55a6a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_task_assist_conversation\n\nDocumentation:\nConstructs a fluent builder for the\n[`CreateTaskAssistConversation`](crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`profile_arn(impl Into)`](crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with [`CreateTaskAssistConversationOutput`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationOutput) with field(s):\n- [`conversation_id(String)`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationOutput::conversation_id): ID which represents a multi-turn conversation\n- On failure, responds with [`SdkError`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_task_assist_conversation(\n &self,\n ) -> crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationFluentBuilder {\n crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "create_task_assist_conversation", "docstring": "Constructs a fluent builder for the\n[`CreateTaskAssistConversation`](crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`profile_arn(impl Into)`](crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with [`CreateTaskAssistConversationOutput`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationOutput) with field(s):\n- [`conversation_id(String)`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationOutput::conversation_id): ID which represents a multi-turn conversation\n- On failure, responds with [`SdkError`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/create_task_assist_conversation.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/create_task_assist_conversation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d07444b202fd946dcb19a6d2e0c8fb122ce51f39858c33a3ef7cc9e601c2e34c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_user_memory_entry\n\nDocumentation:\nConstructs a fluent builder for the\n[`CreateUserMemoryEntry`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`memory_entry_string(impl Into)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::memory_entry_string) / [`set_memory_entry_string(Option)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::set_memory_entry_string):
required: **true**
(undocumented)
\n- [`origin(Origin)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::origin) / [`set_origin(Option)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::set_origin):
required: **true**
Enum to represent the origin application conversing with Sidekick.
\n- [`profile_arn(impl Into)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::set_profile_arn):
required: **false**
ProfileArn for the managing Q Profile
\n- [`client_token(impl Into)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`CreateUserMemoryEntryOutput`](crate::operation::create_user_memory_entry::CreateUserMemoryEntryOutput)\nwith field(s):\n- [`memory_entry(MemoryEntry)`](crate::operation::create_user_memory_entry::CreateUserMemoryEntryOutput::memory_entry): MemoryEntry corresponds to a single user memory\n- On failure, responds with\n[`SdkError`](crate::operation::create_user_memory_entry::CreateUserMemoryEntryError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_user_memory_entry(\n &self,\n ) -> crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder {\n crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "create_user_memory_entry", "docstring": "Constructs a fluent builder for the\n[`CreateUserMemoryEntry`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`memory_entry_string(impl Into)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::memory_entry_string) / [`set_memory_entry_string(Option)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::set_memory_entry_string):
required: **true**
(undocumented)
\n- [`origin(Origin)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::origin) / [`set_origin(Option)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::set_origin):
required: **true**
Enum to represent the origin application conversing with Sidekick.
\n- [`profile_arn(impl Into)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::set_profile_arn):
required: **false**
ProfileArn for the managing Q Profile
\n- [`client_token(impl Into)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`CreateUserMemoryEntryOutput`](crate::operation::create_user_memory_entry::CreateUserMemoryEntryOutput)\nwith field(s):\n- [`memory_entry(MemoryEntry)`](crate::operation::create_user_memory_entry::CreateUserMemoryEntryOutput::memory_entry): MemoryEntry corresponds to a single user memory\n- On failure, responds with\n[`SdkError`](crate::operation::create_user_memory_entry::CreateUserMemoryEntryError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/create_user_memory_entry.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/create_user_memory_entry.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c826e546248dd6707da4fa6d9de69335e67f3604329b0385968007ee82722393"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_task_assist_conversation\n\nDocumentation:\nConstructs a fluent builder for the\n[`DeleteTaskAssistConversation`](crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`conversation_id(impl Into)`](crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationFluentBuilder::conversation_id) / [`set_conversation_id(Option)`](crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationFluentBuilder::set_conversation_id):
required: **true**
ID which represents a multi-turn conversation
\n- [`profile_arn(impl Into)`](crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with [`DeleteTaskAssistConversationOutput`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationOutput) with field(s):\n- [`conversation_id(String)`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationOutput::conversation_id): ID which represents a multi-turn conversation\n- On failure, responds with [`SdkError`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn delete_task_assist_conversation(\n &self,\n ) -> crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationFluentBuilder {\n crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "delete_task_assist_conversation", "docstring": "Constructs a fluent builder for the\n[`DeleteTaskAssistConversation`](crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`conversation_id(impl Into)`](crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationFluentBuilder::conversation_id) / [`set_conversation_id(Option)`](crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationFluentBuilder::set_conversation_id):
required: **true**
ID which represents a multi-turn conversation
\n- [`profile_arn(impl Into)`](crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with [`DeleteTaskAssistConversationOutput`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationOutput) with field(s):\n- [`conversation_id(String)`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationOutput::conversation_id): ID which represents a multi-turn conversation\n- On failure, responds with [`SdkError`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/delete_task_assist_conversation.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/delete_task_assist_conversation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d93360da37d949916dcfa9395adbaeca8bd51dc5069480192fe231519d77f1b5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_user_memory_entry\n\nDocumentation:\nConstructs a fluent builder for the\n[`DeleteUserMemoryEntry`](crate::operation::delete_user_memory_entry::builders::DeleteUserMemoryEntryFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`id(impl Into)`](crate::operation::delete_user_memory_entry::builders::DeleteUserMemoryEntryFluentBuilder::id) / [`set_id(Option)`](crate::operation::delete_user_memory_entry::builders::DeleteUserMemoryEntryFluentBuilder::set_id):
required: **true**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::delete_user_memory_entry::builders::DeleteUserMemoryEntryFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::delete_user_memory_entry::builders::DeleteUserMemoryEntryFluentBuilder::set_profile_arn):
required: **false**
ProfileArn for the managing Q Profile
\n- On success, responds with\n[`DeleteUserMemoryEntryOutput`](crate::operation::delete_user_memory_entry::DeleteUserMemoryEntryOutput)\n- On failure, responds with\n[`SdkError`](crate::operation::delete_user_memory_entry::DeleteUserMemoryEntryError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn delete_user_memory_entry(\n &self,\n ) -> crate::operation::delete_user_memory_entry::builders::DeleteUserMemoryEntryFluentBuilder {\n crate::operation::delete_user_memory_entry::builders::DeleteUserMemoryEntryFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "delete_user_memory_entry", "docstring": "Constructs a fluent builder for the\n[`DeleteUserMemoryEntry`](crate::operation::delete_user_memory_entry::builders::DeleteUserMemoryEntryFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`id(impl Into)`](crate::operation::delete_user_memory_entry::builders::DeleteUserMemoryEntryFluentBuilder::id) / [`set_id(Option)`](crate::operation::delete_user_memory_entry::builders::DeleteUserMemoryEntryFluentBuilder::set_id):
required: **true**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::delete_user_memory_entry::builders::DeleteUserMemoryEntryFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::delete_user_memory_entry::builders::DeleteUserMemoryEntryFluentBuilder::set_profile_arn):
required: **false**
ProfileArn for the managing Q Profile
\n- On success, responds with\n[`DeleteUserMemoryEntryOutput`](crate::operation::delete_user_memory_entry::DeleteUserMemoryEntryOutput)\n- On failure, responds with\n[`SdkError`](crate::operation::delete_user_memory_entry::DeleteUserMemoryEntryError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/delete_user_memory_entry.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/delete_user_memory_entry.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3bf707d70ab6fa5288933ca74b711c4defc7f350af4cca359582ce4960a7f621"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_completions\n\nDocumentation:\nConstructs a fluent builder for the\n[`GenerateCompletions`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`file_context(FileContext)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::file_context) / [`set_file_context(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_file_context):
required: **true**
(undocumented)
\n- [`editor_state(EditorState)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::editor_state) / [`set_editor_state(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_editor_state):
required: **false**
Represents the state of an Editor
\n- [`max_results(i32)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`prediction_types(PredictionType)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::prediction_types) / [`set_prediction_types(Option>)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_prediction_types):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- [`reference_tracker_configuration(ReferenceTrackerConfiguration)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::reference_tracker_configuration) / [`set_reference_tracker_configuration(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_reference_tracker_configuration):
required: **false**
(undocumented)
\n- [`supplemental_contexts(SupplementalContext)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::supplemental_contexts) / [`set_supplemental_contexts(Option>)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_supplemental_contexts):
required: **false**
(undocumented)
\n- [`customization_arn(impl Into)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::customization_arn) / [`set_customization_arn(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_customization_arn):
required: **false**
(undocumented)
\n- [`opt_out_preference(OptOutPreference)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::opt_out_preference) / [`set_opt_out_preference(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_opt_out_preference):
required: **false**
(undocumented)
\n- [`user_context(UserContext)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::user_context) / [`set_user_context(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_user_context):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- [`workspace_id(impl Into)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::workspace_id) / [`set_workspace_id(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_workspace_id):
required: **false**
(undocumented)
\n- [`model_id(impl Into)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::model_id) / [`set_model_id(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_model_id):
required: **false**
Unique identifier for the model
\n- On success, responds with\n[`GenerateCompletionsOutput`](crate::operation::generate_completions::GenerateCompletionsOutput)\nwith field(s):\n- [`predictions(Option>)`](crate::operation::generate_completions::GenerateCompletionsOutput::predictions): (undocumented)\n- [`completions(Option>)`](crate::operation::generate_completions::GenerateCompletionsOutput::completions): (undocumented)\n- [`next_token(Option)`](crate::operation::generate_completions::GenerateCompletionsOutput::next_token): (undocumented)\n- [`model_id(Option)`](crate::operation::generate_completions::GenerateCompletionsOutput::model_id): Unique identifier for the model\n- On failure, responds with\n[`SdkError`](crate::operation::generate_completions::GenerateCompletionsError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate_completions(\n &self,\n ) -> crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder {\n crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "generate_completions", "docstring": "Constructs a fluent builder for the\n[`GenerateCompletions`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`file_context(FileContext)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::file_context) / [`set_file_context(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_file_context):
required: **true**
(undocumented)
\n- [`editor_state(EditorState)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::editor_state) / [`set_editor_state(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_editor_state):
required: **false**
Represents the state of an Editor
\n- [`max_results(i32)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`prediction_types(PredictionType)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::prediction_types) / [`set_prediction_types(Option>)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_prediction_types):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- [`reference_tracker_configuration(ReferenceTrackerConfiguration)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::reference_tracker_configuration) / [`set_reference_tracker_configuration(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_reference_tracker_configuration):
required: **false**
(undocumented)
\n- [`supplemental_contexts(SupplementalContext)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::supplemental_contexts) / [`set_supplemental_contexts(Option>)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_supplemental_contexts):
required: **false**
(undocumented)
\n- [`customization_arn(impl Into)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::customization_arn) / [`set_customization_arn(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_customization_arn):
required: **false**
(undocumented)
\n- [`opt_out_preference(OptOutPreference)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::opt_out_preference) / [`set_opt_out_preference(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_opt_out_preference):
required: **false**
(undocumented)
\n- [`user_context(UserContext)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::user_context) / [`set_user_context(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_user_context):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- [`workspace_id(impl Into)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::workspace_id) / [`set_workspace_id(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_workspace_id):
required: **false**
(undocumented)
\n- [`model_id(impl Into)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::model_id) / [`set_model_id(Option)`](crate::operation::generate_completions::builders::GenerateCompletionsFluentBuilder::set_model_id):
required: **false**
Unique identifier for the model
\n- On success, responds with\n[`GenerateCompletionsOutput`](crate::operation::generate_completions::GenerateCompletionsOutput)\nwith field(s):\n- [`predictions(Option>)`](crate::operation::generate_completions::GenerateCompletionsOutput::predictions): (undocumented)\n- [`completions(Option>)`](crate::operation::generate_completions::GenerateCompletionsOutput::completions): (undocumented)\n- [`next_token(Option)`](crate::operation::generate_completions::GenerateCompletionsOutput::next_token): (undocumented)\n- [`model_id(Option)`](crate::operation::generate_completions::GenerateCompletionsOutput::model_id): Unique identifier for the model\n- On failure, responds with\n[`SdkError`](crate::operation::generate_completions::GenerateCompletionsError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/generate_completions.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/generate_completions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "72b31ee5048cde69aa74e71f75255f3ea9959da64e854bf778b0a050850be0a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_task_assist_code_generation\n\nDocumentation:\nConstructs a fluent builder for the\n[`GetTaskAssistCodeGeneration`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`conversation_id(impl Into)`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder::conversation_id) / [`set_conversation_id(Option)`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder::set_conversation_id):
required: **true**
ID which represents a multi-turn conversation
\n- [`code_generation_id(impl Into)`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder::code_generation_id) / [`set_code_generation_id(Option)`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder::set_code_generation_id):
required: **true**
ID which represents a single code generation in a conversation
\n- [`profile_arn(impl Into)`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with [`GetTaskAssistCodeGenerationOutput`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput) with field(s):\n- [`conversation_id(String)`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput::conversation_id): ID which represents a multi-turn conversation\n- [`code_generation_status(CodeGenerationStatus)`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput::code_generation_status): (undocumented)\n- [`code_generation_status_detail(Option)`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput::code_generation_status_detail): Detailed message about the code generation status\n- [`code_generation_remaining_iteration_count(Option)`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput::code_generation_remaining_iteration_count): (undocumented)\n- [`code_generation_total_iteration_count(Option)`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput::code_generation_total_iteration_count): (undocumented)\n- On failure, responds with [`SdkError`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_task_assist_code_generation(\n &self,\n ) -> crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder {\n crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "get_task_assist_code_generation", "docstring": "Constructs a fluent builder for the\n[`GetTaskAssistCodeGeneration`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`conversation_id(impl Into)`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder::conversation_id) / [`set_conversation_id(Option)`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder::set_conversation_id):
required: **true**
ID which represents a multi-turn conversation
\n- [`code_generation_id(impl Into)`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder::code_generation_id) / [`set_code_generation_id(Option)`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder::set_code_generation_id):
required: **true**
ID which represents a single code generation in a conversation
\n- [`profile_arn(impl Into)`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with [`GetTaskAssistCodeGenerationOutput`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput) with field(s):\n- [`conversation_id(String)`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput::conversation_id): ID which represents a multi-turn conversation\n- [`code_generation_status(CodeGenerationStatus)`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput::code_generation_status): (undocumented)\n- [`code_generation_status_detail(Option)`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput::code_generation_status_detail): Detailed message about the code generation status\n- [`code_generation_remaining_iteration_count(Option)`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput::code_generation_remaining_iteration_count): (undocumented)\n- [`code_generation_total_iteration_count(Option)`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput::code_generation_total_iteration_count): (undocumented)\n- On failure, responds with [`SdkError`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/get_task_assist_code_generation.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/get_task_assist_code_generation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4b98ef5d80be94739106929ea452cf6772d265b125ad334f4e01fa0625db1f9d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_test_generation\n\nDocumentation:\nConstructs a fluent builder for the\n[`GetTestGeneration`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`test_generation_job_group_name(impl Into)`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder::test_generation_job_group_name) / [`set_test_generation_job_group_name(Option)`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder::set_test_generation_job_group_name):
required: **true**
Test generation job group name
\n- [`test_generation_job_id(impl Into)`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder::test_generation_job_id) / [`set_test_generation_job_id(Option)`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder::set_test_generation_job_id):
required: **true**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`GetTestGenerationOutput`](crate::operation::get_test_generation::GetTestGenerationOutput)\nwith field(s):\n- [`test_generation_job(Option)`](crate::operation::get_test_generation::GetTestGenerationOutput::test_generation_job): Represents a test generation job\n- On failure, responds with\n[`SdkError`](crate::operation::get_test_generation::GetTestGenerationError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_test_generation(\n &self,\n ) -> crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder {\n crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "get_test_generation", "docstring": "Constructs a fluent builder for the\n[`GetTestGeneration`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`test_generation_job_group_name(impl Into)`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder::test_generation_job_group_name) / [`set_test_generation_job_group_name(Option)`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder::set_test_generation_job_group_name):
required: **true**
Test generation job group name
\n- [`test_generation_job_id(impl Into)`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder::test_generation_job_id) / [`set_test_generation_job_id(Option)`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder::set_test_generation_job_id):
required: **true**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::get_test_generation::builders::GetTestGenerationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`GetTestGenerationOutput`](crate::operation::get_test_generation::GetTestGenerationOutput)\nwith field(s):\n- [`test_generation_job(Option)`](crate::operation::get_test_generation::GetTestGenerationOutput::test_generation_job): Represents a test generation job\n- On failure, responds with\n[`SdkError`](crate::operation::get_test_generation::GetTestGenerationError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/get_test_generation.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/get_test_generation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "173425b4a46fa44f39fb829af945ef1acb614bf5148bd37b345b0970ab291718"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_transformation_plan\n\nDocumentation:\nConstructs a fluent builder for the\n[`GetTransformationPlan`](crate::operation::get_transformation_plan::builders::GetTransformationPlanFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`transformation_job_id(impl Into)`](crate::operation::get_transformation_plan::builders::GetTransformationPlanFluentBuilder::transformation_job_id) / [`set_transformation_job_id(Option)`](crate::operation::get_transformation_plan::builders::GetTransformationPlanFluentBuilder::set_transformation_job_id):
required: **true**
Identifier for the Transformation Job
\n- [`profile_arn(impl Into)`](crate::operation::get_transformation_plan::builders::GetTransformationPlanFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::get_transformation_plan::builders::GetTransformationPlanFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`GetTransformationPlanOutput`](crate::operation::get_transformation_plan::GetTransformationPlanOutput)\nwith field(s):\n- [`transformation_plan(TransformationPlan)`](crate::operation::get_transformation_plan::GetTransformationPlanOutput::transformation_plan): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::get_transformation_plan::GetTransformationPlanError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_transformation_plan(\n &self,\n ) -> crate::operation::get_transformation_plan::builders::GetTransformationPlanFluentBuilder {\n crate::operation::get_transformation_plan::builders::GetTransformationPlanFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "get_transformation_plan", "docstring": "Constructs a fluent builder for the\n[`GetTransformationPlan`](crate::operation::get_transformation_plan::builders::GetTransformationPlanFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`transformation_job_id(impl Into)`](crate::operation::get_transformation_plan::builders::GetTransformationPlanFluentBuilder::transformation_job_id) / [`set_transformation_job_id(Option)`](crate::operation::get_transformation_plan::builders::GetTransformationPlanFluentBuilder::set_transformation_job_id):
required: **true**
Identifier for the Transformation Job
\n- [`profile_arn(impl Into)`](crate::operation::get_transformation_plan::builders::GetTransformationPlanFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::get_transformation_plan::builders::GetTransformationPlanFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`GetTransformationPlanOutput`](crate::operation::get_transformation_plan::GetTransformationPlanOutput)\nwith field(s):\n- [`transformation_plan(TransformationPlan)`](crate::operation::get_transformation_plan::GetTransformationPlanOutput::transformation_plan): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::get_transformation_plan::GetTransformationPlanError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/get_transformation_plan.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/get_transformation_plan.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fe70f8b0bbb82816eb47ff65d319fece34a21aaefebea985d34634dc7e077a2a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_available_customizations\n\nDocumentation:\nConstructs a fluent builder for the\n[`ListAvailableCustomizations`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`max_results(i32)`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with [`ListAvailableCustomizationsOutput`](crate::operation::list_available_customizations::ListAvailableCustomizationsOutput) with field(s):\n- [`customizations(Vec::)`](crate::operation::list_available_customizations::ListAvailableCustomizationsOutput::customizations): (undocumented)\n- [`next_token(Option)`](crate::operation::list_available_customizations::ListAvailableCustomizationsOutput::next_token): (undocumented)\n- On failure, responds with [`SdkError`](crate::operation::list_available_customizations::ListAvailableCustomizationsError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_available_customizations(\n &self,\n ) -> crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder {\n crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "list_available_customizations", "docstring": "Constructs a fluent builder for the\n[`ListAvailableCustomizations`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`max_results(i32)`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with [`ListAvailableCustomizationsOutput`](crate::operation::list_available_customizations::ListAvailableCustomizationsOutput) with field(s):\n- [`customizations(Vec::)`](crate::operation::list_available_customizations::ListAvailableCustomizationsOutput::customizations): (undocumented)\n- [`next_token(Option)`](crate::operation::list_available_customizations::ListAvailableCustomizationsOutput::next_token): (undocumented)\n- On failure, responds with [`SdkError`](crate::operation::list_available_customizations::ListAvailableCustomizationsError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/list_available_customizations.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/list_available_customizations.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e0013f93ae40cc25b2456e7162d2632683f0d86a6bcdfa6f2b2b0c5da7ce5add"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_available_profiles\n\nDocumentation:\nConstructs a fluent builder for the\n[`ListAvailableProfiles`](crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`max_results(i32)`](crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListAvailableProfilesOutput`](crate::operation::list_available_profiles::ListAvailableProfilesOutput)\nwith field(s):\n- [`profiles(Vec::)`](crate::operation::list_available_profiles::ListAvailableProfilesOutput::profiles): (undocumented)\n- [`next_token(Option)`](crate::operation::list_available_profiles::ListAvailableProfilesOutput::next_token): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::list_available_profiles::ListAvailableProfilesError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_available_profiles(\n &self,\n ) -> crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder {\n crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "list_available_profiles", "docstring": "Constructs a fluent builder for the\n[`ListAvailableProfiles`](crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`max_results(i32)`](crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_available_profiles::builders::ListAvailableProfilesFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListAvailableProfilesOutput`](crate::operation::list_available_profiles::ListAvailableProfilesOutput)\nwith field(s):\n- [`profiles(Vec::)`](crate::operation::list_available_profiles::ListAvailableProfilesOutput::profiles): (undocumented)\n- [`next_token(Option)`](crate::operation::list_available_profiles::ListAvailableProfilesOutput::next_token): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::list_available_profiles::ListAvailableProfilesError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/list_available_profiles.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/list_available_profiles.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "03c661d4ff496b03fd80f726fc6e27b97f61313a6f3dca041f735672d1ea9e2a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_code_analysis_findings\n\nDocumentation:\nConstructs a fluent builder for the\n[`ListCodeAnalysisFindings`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`job_id(impl Into)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::job_id) / [`set_job_id(Option)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::set_job_id):
required: **true**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- [`code_analysis_findings_schema(CodeAnalysisFindingsSchema)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::code_analysis_findings_schema) / [`set_code_analysis_findings_schema(Option)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::set_code_analysis_findings_schema):
required: **true**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListCodeAnalysisFindingsOutput`](crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsOutput)\nwith field(s):\n- [`next_token(Option)`](crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsOutput::next_token): (undocumented)\n- [`code_analysis_findings(String)`](crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsOutput::code_analysis_findings): (undocumented)\n- On failure, responds with [`SdkError`](crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_code_analysis_findings(\n &self,\n ) -> crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder {\n crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "list_code_analysis_findings", "docstring": "Constructs a fluent builder for the\n[`ListCodeAnalysisFindings`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`job_id(impl Into)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::job_id) / [`set_job_id(Option)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::set_job_id):
required: **true**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- [`code_analysis_findings_schema(CodeAnalysisFindingsSchema)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::code_analysis_findings_schema) / [`set_code_analysis_findings_schema(Option)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::set_code_analysis_findings_schema):
required: **true**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListCodeAnalysisFindingsOutput`](crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsOutput)\nwith field(s):\n- [`next_token(Option)`](crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsOutput::next_token): (undocumented)\n- [`code_analysis_findings(String)`](crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsOutput::code_analysis_findings): (undocumented)\n- On failure, responds with [`SdkError`](crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/list_code_analysis_findings.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/list_code_analysis_findings.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ce9c8df20d69acabe87d5c8ea0bc76c84563d9ecaa2c4c48c9cce346191f65c6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_feature_evaluations\n\nDocumentation:\nConstructs a fluent builder for the\n[`ListFeatureEvaluations`](crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`user_context(UserContext)`](crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsFluentBuilder::user_context) / [`set_user_context(Option)`](crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsFluentBuilder::set_user_context):
required: **true**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListFeatureEvaluationsOutput`](crate::operation::list_feature_evaluations::ListFeatureEvaluationsOutput)\nwith field(s):\n- [`feature_evaluations(Vec::)`](crate::operation::list_feature_evaluations::ListFeatureEvaluationsOutput::feature_evaluations): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::list_feature_evaluations::ListFeatureEvaluationsError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_feature_evaluations(\n &self,\n ) -> crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsFluentBuilder {\n crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "list_feature_evaluations", "docstring": "Constructs a fluent builder for the\n[`ListFeatureEvaluations`](crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`user_context(UserContext)`](crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsFluentBuilder::user_context) / [`set_user_context(Option)`](crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsFluentBuilder::set_user_context):
required: **true**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListFeatureEvaluationsOutput`](crate::operation::list_feature_evaluations::ListFeatureEvaluationsOutput)\nwith field(s):\n- [`feature_evaluations(Vec::)`](crate::operation::list_feature_evaluations::ListFeatureEvaluationsOutput::feature_evaluations): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::list_feature_evaluations::ListFeatureEvaluationsError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/list_feature_evaluations.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/list_feature_evaluations.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "78a0c7abec669de7561ae9cbc19b968faa0608cc4a3ff995585ee06d9e208a73"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_user_memory_entries\n\nDocumentation:\nConstructs a fluent builder for the\n[`ListUserMemoryEntries`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`max_results(i32)`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::set_profile_arn):
required: **false**
ProfileArn for the managing Q Profile
\n- [`next_token(impl Into)`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListUserMemoryEntriesOutput`](crate::operation::list_user_memory_entries::ListUserMemoryEntriesOutput)\nwith field(s):\n- [`memory_entries(Vec::)`](crate::operation::list_user_memory_entries::ListUserMemoryEntriesOutput::memory_entries): List of user memories\n- [`next_token(Option)`](crate::operation::list_user_memory_entries::ListUserMemoryEntriesOutput::next_token): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::list_user_memory_entries::ListUserMemoryEntriesError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_user_memory_entries(\n &self,\n ) -> crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder {\n crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "list_user_memory_entries", "docstring": "Constructs a fluent builder for the\n[`ListUserMemoryEntries`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`max_results(i32)`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::set_profile_arn):
required: **false**
ProfileArn for the managing Q Profile
\n- [`next_token(impl Into)`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListUserMemoryEntriesOutput`](crate::operation::list_user_memory_entries::ListUserMemoryEntriesOutput)\nwith field(s):\n- [`memory_entries(Vec::)`](crate::operation::list_user_memory_entries::ListUserMemoryEntriesOutput::memory_entries): List of user memories\n- [`next_token(Option)`](crate::operation::list_user_memory_entries::ListUserMemoryEntriesOutput::next_token): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::list_user_memory_entries::ListUserMemoryEntriesError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/list_user_memory_entries.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/list_user_memory_entries.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c4777872e19b292e189eaac4af5f1f919448ccf05ceba35a582d5e9bed8ebcad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_workspace_metadata\n\nDocumentation:\nConstructs a fluent builder for the\n[`ListWorkspaceMetadata`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`workspace_root(impl Into)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::workspace_root) / [`set_workspace_root(Option)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::set_workspace_root):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- [`max_results(i32)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListWorkspaceMetadataOutput`](crate::operation::list_workspace_metadata::ListWorkspaceMetadataOutput)\nwith field(s):\n- [`workspaces(Vec::)`](crate::operation::list_workspace_metadata::ListWorkspaceMetadataOutput::workspaces): (undocumented)\n- [`next_token(Option)`](crate::operation::list_workspace_metadata::ListWorkspaceMetadataOutput::next_token): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::list_workspace_metadata::ListWorkspaceMetadataError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_workspace_metadata(\n &self,\n ) -> crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder {\n crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "list_workspace_metadata", "docstring": "Constructs a fluent builder for the\n[`ListWorkspaceMetadata`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`workspace_root(impl Into)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::workspace_root) / [`set_workspace_root(Option)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::set_workspace_root):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- [`max_results(i32)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListWorkspaceMetadataOutput`](crate::operation::list_workspace_metadata::ListWorkspaceMetadataOutput)\nwith field(s):\n- [`workspaces(Vec::)`](crate::operation::list_workspace_metadata::ListWorkspaceMetadataOutput::workspaces): (undocumented)\n- [`next_token(Option)`](crate::operation::list_workspace_metadata::ListWorkspaceMetadataOutput::next_token): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::list_workspace_metadata::ListWorkspaceMetadataError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/list_workspace_metadata.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/list_workspace_metadata.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "866ae121a146279344e2128b0cccdd65ae80fc3030e113d89c146d4697a11150"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_telemetry_event\n\nDocumentation:\nConstructs a fluent builder for the\n[`PushTelemetryEvent`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`client_token(impl Into)`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- [`event_type(impl Into)`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder::event_type) / [`set_event_type(Option)`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder::set_event_type):
required: **true**
(undocumented)
\n- [`event(Document)`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder::event) / [`set_event(Option)`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder::set_event):
required: **true**
(undocumented)
\n- On success, responds with\n[`PushTelemetryEventOutput`](crate::operation::push_telemetry_event::PushTelemetryEventOutput)\n- On failure, responds with\n[`SdkError`](crate::operation::push_telemetry_event::PushTelemetryEventError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn push_telemetry_event(\n &self,\n ) -> crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder {\n crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "push_telemetry_event", "docstring": "Constructs a fluent builder for the\n[`PushTelemetryEvent`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`client_token(impl Into)`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- [`event_type(impl Into)`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder::event_type) / [`set_event_type(Option)`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder::set_event_type):
required: **true**
(undocumented)
\n- [`event(Document)`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder::event) / [`set_event(Option)`](crate::operation::push_telemetry_event::builders::PushTelemetryEventFluentBuilder::set_event):
required: **true**
(undocumented)
\n- On success, responds with\n[`PushTelemetryEventOutput`](crate::operation::push_telemetry_event::PushTelemetryEventOutput)\n- On failure, responds with\n[`SdkError`](crate::operation::push_telemetry_event::PushTelemetryEventError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/push_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/push_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "04a5835ee5acc5ad7aad330675e5ccdb3dca71aa2396e11d9afe8c9144971bc1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resume_transformation\n\nDocumentation:\nConstructs a fluent builder for the\n[`ResumeTransformation`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`transformation_job_id(impl Into)`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder::transformation_job_id) / [`set_transformation_job_id(Option)`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder::set_transformation_job_id):
required: **true**
Identifier for the Transformation Job
\n- [`user_action_status(TransformationUserActionStatus)`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder::user_action_status) / [`set_user_action_status(Option)`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder::set_user_action_status):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`ResumeTransformationOutput`](crate::operation::resume_transformation::ResumeTransformationOutput)\nwith field(s):\n- [`transformation_status(TransformationStatus)`](crate::operation::resume_transformation::ResumeTransformationOutput::transformation_status): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::resume_transformation::ResumeTransformationError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn resume_transformation(\n &self,\n ) -> crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder {\n crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "resume_transformation", "docstring": "Constructs a fluent builder for the\n[`ResumeTransformation`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`transformation_job_id(impl Into)`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder::transformation_job_id) / [`set_transformation_job_id(Option)`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder::set_transformation_job_id):
required: **true**
Identifier for the Transformation Job
\n- [`user_action_status(TransformationUserActionStatus)`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder::user_action_status) / [`set_user_action_status(Option)`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder::set_user_action_status):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::resume_transformation::builders::ResumeTransformationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`ResumeTransformationOutput`](crate::operation::resume_transformation::ResumeTransformationOutput)\nwith field(s):\n- [`transformation_status(TransformationStatus)`](crate::operation::resume_transformation::ResumeTransformationOutput::transformation_status): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::resume_transformation::ResumeTransformationError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/resume_transformation.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/resume_transformation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "572ebedd5cfccfff0b307e6120fe42dc490db108131abffcb503c21ea7f2b3f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_telemetry_event\n\nDocumentation:\nConstructs a fluent builder for the\n[`SendTelemetryEvent`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`client_token(impl Into)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- [`telemetry_event(TelemetryEvent)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::telemetry_event) / [`set_telemetry_event(Option)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::set_telemetry_event):
required: **true**
(undocumented)
\n- [`opt_out_preference(OptOutPreference)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::opt_out_preference) / [`set_opt_out_preference(Option)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::set_opt_out_preference):
required: **false**
(undocumented)
\n- [`user_context(UserContext)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::user_context) / [`set_user_context(Option)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::set_user_context):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- [`model_id(impl Into)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::model_id) / [`set_model_id(Option)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::set_model_id):
required: **false**
Unique identifier for the model
\n- On success, responds with\n[`SendTelemetryEventOutput`](crate::operation::send_telemetry_event::SendTelemetryEventOutput)\n- On failure, responds with\n[`SdkError`](crate::operation::send_telemetry_event::SendTelemetryEventError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn send_telemetry_event(\n &self,\n ) -> crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder {\n crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "send_telemetry_event", "docstring": "Constructs a fluent builder for the\n[`SendTelemetryEvent`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`client_token(impl Into)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- [`telemetry_event(TelemetryEvent)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::telemetry_event) / [`set_telemetry_event(Option)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::set_telemetry_event):
required: **true**
(undocumented)
\n- [`opt_out_preference(OptOutPreference)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::opt_out_preference) / [`set_opt_out_preference(Option)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::set_opt_out_preference):
required: **false**
(undocumented)
\n- [`user_context(UserContext)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::user_context) / [`set_user_context(Option)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::set_user_context):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- [`model_id(impl Into)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::model_id) / [`set_model_id(Option)`](crate::operation::send_telemetry_event::builders::SendTelemetryEventFluentBuilder::set_model_id):
required: **false**
Unique identifier for the model
\n- On success, responds with\n[`SendTelemetryEventOutput`](crate::operation::send_telemetry_event::SendTelemetryEventOutput)\n- On failure, responds with\n[`SdkError`](crate::operation::send_telemetry_event::SendTelemetryEventError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/send_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/send_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "00cda100d17e8df81a845475bcb6742f59a1629afdf0b9585df4a57898ae7b05"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_code_analysis\n\nDocumentation:\nConstructs a fluent builder for the\n[`StartCodeAnalysis`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`artifacts(ArtifactType, impl\nInto)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::artifacts)\n/ [`set_artifacts(Option>)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::set_artifacts):\n
required: **true**
(undocumented)
\n- [`programming_language(ProgrammingLanguage)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::programming_language) / [`set_programming_language(Option)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::set_programming_language):
required: **true**
Programming Languages supported by CodeWhisperer
\n- [`client_token(impl Into)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- [`scope(CodeAnalysisScope)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::scope) / [`set_scope(Option)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::set_scope):
required: **false**
(undocumented)
\n- [`code_scan_name(impl Into)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::code_scan_name) / [`set_code_scan_name(Option)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::set_code_scan_name):
required: **false**
Code analysis scan name
\n- [`profile_arn(impl Into)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`StartCodeAnalysisOutput`](crate::operation::start_code_analysis::StartCodeAnalysisOutput)\nwith field(s):\n- [`job_id(String)`](crate::operation::start_code_analysis::StartCodeAnalysisOutput::job_id): (undocumented)\n- [`status(CodeAnalysisStatus)`](crate::operation::start_code_analysis::StartCodeAnalysisOutput::status): (undocumented)\n- [`error_message(Option)`](crate::operation::start_code_analysis::StartCodeAnalysisOutput::error_message): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::start_code_analysis::StartCodeAnalysisError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start_code_analysis(\n &self,\n ) -> crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder {\n crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "start_code_analysis", "docstring": "Constructs a fluent builder for the\n[`StartCodeAnalysis`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`artifacts(ArtifactType, impl\nInto)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::artifacts)\n/ [`set_artifacts(Option>)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::set_artifacts):\n
required: **true**
(undocumented)
\n- [`programming_language(ProgrammingLanguage)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::programming_language) / [`set_programming_language(Option)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::set_programming_language):
required: **true**
Programming Languages supported by CodeWhisperer
\n- [`client_token(impl Into)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- [`scope(CodeAnalysisScope)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::scope) / [`set_scope(Option)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::set_scope):
required: **false**
(undocumented)
\n- [`code_scan_name(impl Into)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::code_scan_name) / [`set_code_scan_name(Option)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::set_code_scan_name):
required: **false**
Code analysis scan name
\n- [`profile_arn(impl Into)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::start_code_analysis::builders::StartCodeAnalysisFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`StartCodeAnalysisOutput`](crate::operation::start_code_analysis::StartCodeAnalysisOutput)\nwith field(s):\n- [`job_id(String)`](crate::operation::start_code_analysis::StartCodeAnalysisOutput::job_id): (undocumented)\n- [`status(CodeAnalysisStatus)`](crate::operation::start_code_analysis::StartCodeAnalysisOutput::status): (undocumented)\n- [`error_message(Option)`](crate::operation::start_code_analysis::StartCodeAnalysisOutput::error_message): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::start_code_analysis::StartCodeAnalysisError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/start_code_analysis.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/start_code_analysis.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0b84f8ef30bd4209dab20b44acaa4fbae3e21fa3dc5206525aa39c1838da6229"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_task_assist_code_generation\n\nDocumentation:\nConstructs a fluent builder for the\n[`StartTaskAssistCodeGeneration`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`conversation_state(ConversationState)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::conversation_state) / [`set_conversation_state(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_conversation_state):
required: **true**
Structure to represent the current state of a chat conversation.
\n- [`workspace_state(WorkspaceState)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::workspace_state) / [`set_workspace_state(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_workspace_state):
required: **true**
Represents a Workspace state uploaded to S3 for Async Code Actions
\n- [`task_assist_plan(TaskAssistPlanStep)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::task_assist_plan) / [`set_task_assist_plan(Option>)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_task_assist_plan):
required: **false**
(undocumented)
\n- [`code_generation_id(impl Into)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::code_generation_id) / [`set_code_generation_id(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_code_generation_id):
required: **false**
ID which represents a single code generation in a conversation
\n- [`current_code_generation_id(impl Into)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::current_code_generation_id) / [`set_current_code_generation_id(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_current_code_generation_id):
required: **false**
ID which represents a single code generation in a conversation
\n- [`intent(Intent)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::intent) / [`set_intent(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_intent):
required: **false**
(undocumented)
\n- [`intent_context(IntentContext)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::intent_context) / [`set_intent_context(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_intent_context):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with [`StartTaskAssistCodeGenerationOutput`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationOutput) with field(s):\n- [`conversation_id(String)`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationOutput::conversation_id): ID which represents a multi-turn conversation\n- [`code_generation_id(String)`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationOutput::code_generation_id): ID which represents a single code generation in a conversation\n- On failure, responds with [`SdkError`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start_task_assist_code_generation(\n &self,\n ) -> crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder {\n crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "start_task_assist_code_generation", "docstring": "Constructs a fluent builder for the\n[`StartTaskAssistCodeGeneration`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`conversation_state(ConversationState)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::conversation_state) / [`set_conversation_state(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_conversation_state):
required: **true**
Structure to represent the current state of a chat conversation.
\n- [`workspace_state(WorkspaceState)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::workspace_state) / [`set_workspace_state(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_workspace_state):
required: **true**
Represents a Workspace state uploaded to S3 for Async Code Actions
\n- [`task_assist_plan(TaskAssistPlanStep)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::task_assist_plan) / [`set_task_assist_plan(Option>)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_task_assist_plan):
required: **false**
(undocumented)
\n- [`code_generation_id(impl Into)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::code_generation_id) / [`set_code_generation_id(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_code_generation_id):
required: **false**
ID which represents a single code generation in a conversation
\n- [`current_code_generation_id(impl Into)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::current_code_generation_id) / [`set_current_code_generation_id(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_current_code_generation_id):
required: **false**
ID which represents a single code generation in a conversation
\n- [`intent(Intent)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::intent) / [`set_intent(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_intent):
required: **false**
(undocumented)
\n- [`intent_context(IntentContext)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::intent_context) / [`set_intent_context(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_intent_context):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with [`StartTaskAssistCodeGenerationOutput`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationOutput) with field(s):\n- [`conversation_id(String)`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationOutput::conversation_id): ID which represents a multi-turn conversation\n- [`code_generation_id(String)`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationOutput::code_generation_id): ID which represents a single code generation in a conversation\n- On failure, responds with [`SdkError`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/start_task_assist_code_generation.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/start_task_assist_code_generation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cac208ef4c3c036d50b407b06cb7f7d3aaf43baf63d4264f7726b11748ec6569"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_test_generation\n\nDocumentation:\nConstructs a fluent builder for the\n[`StartTestGeneration`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`upload_id(impl Into)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::upload_id) / [`set_upload_id(Option)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_upload_id):
required: **true**
Upload ID returned by CreateUploadUrl API
\n- [`target_code_list(TargetCode)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::target_code_list) / [`set_target_code_list(Option>)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_target_code_list):
required: **true**
(undocumented)
\n- [`user_input(impl Into)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::user_input) / [`set_user_input(Option)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_user_input):
required: **true**
The content of user input.
\n- [`test_generation_job_group_name(impl Into)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::test_generation_job_group_name) / [`set_test_generation_job_group_name(Option)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_test_generation_job_group_name):
required: **false**
Test generation job group name
\n- [`client_token(impl Into)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- [`reference_tracker_configuration(ReferenceTrackerConfiguration)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::reference_tracker_configuration) / [`set_reference_tracker_configuration(Option)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_reference_tracker_configuration):
required: **false**
(undocumented)
\n- On success, responds with\n[`StartTestGenerationOutput`](crate::operation::start_test_generation::StartTestGenerationOutput)\nwith field(s):\n- [`test_generation_job(Option)`](crate::operation::start_test_generation::StartTestGenerationOutput::test_generation_job): Represents a test generation job\n- On failure, responds with\n[`SdkError`](crate::operation::start_test_generation::StartTestGenerationError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start_test_generation(\n &self,\n ) -> crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder {\n crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "start_test_generation", "docstring": "Constructs a fluent builder for the\n[`StartTestGeneration`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`upload_id(impl Into)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::upload_id) / [`set_upload_id(Option)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_upload_id):
required: **true**
Upload ID returned by CreateUploadUrl API
\n- [`target_code_list(TargetCode)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::target_code_list) / [`set_target_code_list(Option>)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_target_code_list):
required: **true**
(undocumented)
\n- [`user_input(impl Into)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::user_input) / [`set_user_input(Option)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_user_input):
required: **true**
The content of user input.
\n- [`test_generation_job_group_name(impl Into)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::test_generation_job_group_name) / [`set_test_generation_job_group_name(Option)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_test_generation_job_group_name):
required: **false**
Test generation job group name
\n- [`client_token(impl Into)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- [`reference_tracker_configuration(ReferenceTrackerConfiguration)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::reference_tracker_configuration) / [`set_reference_tracker_configuration(Option)`](crate::operation::start_test_generation::builders::StartTestGenerationFluentBuilder::set_reference_tracker_configuration):
required: **false**
(undocumented)
\n- On success, responds with\n[`StartTestGenerationOutput`](crate::operation::start_test_generation::StartTestGenerationOutput)\nwith field(s):\n- [`test_generation_job(Option)`](crate::operation::start_test_generation::StartTestGenerationOutput::test_generation_job): Represents a test generation job\n- On failure, responds with\n[`SdkError`](crate::operation::start_test_generation::StartTestGenerationError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/start_test_generation.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/start_test_generation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6b48b145f48071cfe4d69b9855c94be9d3c343cf6d133e00af51c5901e2755b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_transformation\n\nDocumentation:\nConstructs a fluent builder for the\n[`StartTransformation`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`workspace_state(WorkspaceState)`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder::workspace_state) / [`set_workspace_state(Option)`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder::set_workspace_state):
required: **true**
Represents a Workspace state uploaded to S3 for Async Code Actions
\n- [`transformation_spec(TransformationSpec)`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder::transformation_spec) / [`set_transformation_spec(Option)`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder::set_transformation_spec):
required: **true**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`StartTransformationOutput`](crate::operation::start_transformation::StartTransformationOutput)\nwith field(s):\n- [`transformation_job_id(String)`](crate::operation::start_transformation::StartTransformationOutput::transformation_job_id): Identifier for the Transformation Job\n- On failure, responds with\n[`SdkError`](crate::operation::start_transformation::StartTransformationError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start_transformation(\n &self,\n ) -> crate::operation::start_transformation::builders::StartTransformationFluentBuilder {\n crate::operation::start_transformation::builders::StartTransformationFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "start_transformation", "docstring": "Constructs a fluent builder for the\n[`StartTransformation`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`workspace_state(WorkspaceState)`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder::workspace_state) / [`set_workspace_state(Option)`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder::set_workspace_state):
required: **true**
Represents a Workspace state uploaded to S3 for Async Code Actions
\n- [`transformation_spec(TransformationSpec)`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder::transformation_spec) / [`set_transformation_spec(Option)`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder::set_transformation_spec):
required: **true**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::start_transformation::builders::StartTransformationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`StartTransformationOutput`](crate::operation::start_transformation::StartTransformationOutput)\nwith field(s):\n- [`transformation_job_id(String)`](crate::operation::start_transformation::StartTransformationOutput::transformation_job_id): Identifier for the Transformation Job\n- On failure, responds with\n[`SdkError`](crate::operation::start_transformation::StartTransformationError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/start_transformation.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/start_transformation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18b1df0e70bb99679bf9092520a6da708a7ff92823b0a68a1dc284178fcf7142"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stop_transformation\n\nDocumentation:\nConstructs a fluent builder for the\n[`StopTransformation`](crate::operation::stop_transformation::builders::StopTransformationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`transformation_job_id(impl Into)`](crate::operation::stop_transformation::builders::StopTransformationFluentBuilder::transformation_job_id) / [`set_transformation_job_id(Option)`](crate::operation::stop_transformation::builders::StopTransformationFluentBuilder::set_transformation_job_id):
required: **true**
Identifier for the Transformation Job
\n- [`profile_arn(impl Into)`](crate::operation::stop_transformation::builders::StopTransformationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::stop_transformation::builders::StopTransformationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`StopTransformationOutput`](crate::operation::stop_transformation::StopTransformationOutput)\nwith field(s):\n- [`transformation_status(TransformationStatus)`](crate::operation::stop_transformation::StopTransformationOutput::transformation_status): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::stop_transformation::StopTransformationError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stop_transformation(\n &self,\n ) -> crate::operation::stop_transformation::builders::StopTransformationFluentBuilder {\n crate::operation::stop_transformation::builders::StopTransformationFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "stop_transformation", "docstring": "Constructs a fluent builder for the\n[`StopTransformation`](crate::operation::stop_transformation::builders::StopTransformationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`transformation_job_id(impl Into)`](crate::operation::stop_transformation::builders::StopTransformationFluentBuilder::transformation_job_id) / [`set_transformation_job_id(Option)`](crate::operation::stop_transformation::builders::StopTransformationFluentBuilder::set_transformation_job_id):
required: **true**
Identifier for the Transformation Job
\n- [`profile_arn(impl Into)`](crate::operation::stop_transformation::builders::StopTransformationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::stop_transformation::builders::StopTransformationFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`StopTransformationOutput`](crate::operation::stop_transformation::StopTransformationOutput)\nwith field(s):\n- [`transformation_status(TransformationStatus)`](crate::operation::stop_transformation::StopTransformationOutput::transformation_status): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::stop_transformation::StopTransformationError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/client/stop_transformation.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/client/stop_transformation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f970cab41be0c0c4a87d6f781d2b82182d819d5a5ec3333b148c54fea3d43b1e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unhandled\n\nDocumentation:\nCreates the `CreateArtifactUploadUrlError::Unhandled` variant from any error type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unhandled(\n err: impl ::std::convert::Into<\n ::std::boxed::Box,\n >,\n ) -> Self {\n Self::Unhandled(crate::error::sealed_unhandled::Unhandled {\n source: err.into(),\n meta: ::std::default::Default::default(),\n })\n }\n```"}], "func_name": "unhandled", "docstring": "Creates the `CreateArtifactUploadUrlError::Unhandled` variant from any error type.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "91ec0e66010a2257bd9d7e8d0b6aafa5d4bdc735e827a5903d2bea20339c0355"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: meta\n\nDocumentation:\nReturns error metadata, which includes the error code, message,\nrequest ID, and potentially additional information.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn meta(&self) -> &::aws_smithy_types::error::ErrorMetadata {\n match self {\n Self::AccessDeniedError(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e),\n Self::ValidationError(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e),\n Self::ThrottlingError(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e),\n Self::InternalServerError(e) => ::aws_smithy_types::error::metadata::ProvideErrorMetadata::meta(e),\n Self::Unhandled(e) => &e.meta,\n }\n }\n```"}], "func_name": "meta", "docstring": "Returns error metadata, which includes the error code, message,\nrequest ID, and potentially additional information.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "187a971ae43d8fbca54fa84a5c7b33e692e96faaa632070980591e85fd5316e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_access_denied_error\n\nDocumentation:\nReturns `true` if the error kind is `CreateArtifactUploadUrlError::AccessDeniedError`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_access_denied_error(&self) -> bool {\n matches!(self, Self::AccessDeniedError(_))\n }\n```"}], "func_name": "is_access_denied_error", "docstring": "Returns `true` if the error kind is `CreateArtifactUploadUrlError::AccessDeniedError`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f7132d20bdca1a98a593a2a17b26eb2d7d044bcbce4df47eb85faf94f9e2ac4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_throttling_error\n\nDocumentation:\nReturns `true` if the error kind is `CreateArtifactUploadUrlError::ThrottlingError`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_throttling_error(&self) -> bool {\n matches!(self, Self::ThrottlingError(_))\n }\n```"}], "func_name": "is_throttling_error", "docstring": "Returns `true` if the error kind is `CreateArtifactUploadUrlError::ThrottlingError`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e83125ec08368f5f3a5ef0af118c4c66a40f65f33adff098455d6d31f1ca793c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_conflict_error\n\nDocumentation:\nReturns `true` if the error kind is `CreateSubscriptionTokenError::ConflictError`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_conflict_error(&self) -> bool {\n matches!(self, Self::ConflictError(_))\n }\n```"}], "func_name": "is_conflict_error", "docstring": "Returns `true` if the error kind is `CreateSubscriptionTokenError::ConflictError`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_subscription_token.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_subscription_token.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b2852fcd50eeb6ede4f6454cb3a059c0dde0191b2e6bc989f3682e9fa651c243"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_service_quota_exceeded_error\n\nDocumentation:\nReturns `true` if the error kind is\n`CreateTaskAssistConversationError::ServiceQuotaExceededError`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_service_quota_exceeded_error(&self) -> bool {\n matches!(self, Self::ServiceQuotaExceededError(_))\n }\n```"}], "func_name": "is_service_quota_exceeded_error", "docstring": "Returns `true` if the error kind is\n`CreateTaskAssistConversationError::ServiceQuotaExceededError`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_task_assist_conversation.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_task_assist_conversation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "684a419791b0302675ab41acdc5471ed92c31dce89b10f415de21a73ac9483fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_resource_not_found_error\n\nDocumentation:\nReturns `true` if the error kind is `CreateUploadUrlError::ResourceNotFoundError`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_resource_not_found_error(&self) -> bool {\n matches!(self, Self::ResourceNotFoundError(_))\n }\n```"}], "func_name": "is_resource_not_found_error", "docstring": "Returns `true` if the error kind is `CreateUploadUrlError::ResourceNotFoundError`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_upload_url.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_upload_url.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a3201fa2f2422109aa6817e839525f407b3053af935a9dcaece81630f1047d1f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_with\n\nDocumentation:\nSends a request with this input using the given client.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn send_with(\n self,\n client: &crate::Client,\n ) -> ::std::result::Result<\n crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput,\n ::aws_smithy_runtime_api::client::result::SdkError<\n crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlError,\n ::aws_smithy_runtime_api::client::orchestrator::HttpResponse,\n >,\n > {\n let mut fluent_builder = client.create_artifact_upload_url();\n fluent_builder.inner = self;\n fluent_builder.send().await\n }\n```"}], "func_name": "send_with", "docstring": "Sends a request with this input using the given client.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url/builders.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url/builders.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be528a39c5b90538fdf2670f2dca156439290100642d98db28059582dcd68bc2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: customize\n\nDocumentation:\nConsumes this builder, creating a customizable operation that can be modified before being\nsent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn customize(\n self,\n ) -> crate::client::customize::CustomizableOperation<\n crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput,\n crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlError,\n Self,\n > {\n crate::client::customize::CustomizableOperation::new(self)\n }\n```"}], "func_name": "customize", "docstring": "Consumes this builder, creating a customizable operation that can be modified before being\nsent.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url/builders.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url/builders.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be952c27e60e4d0bde5c694f886600b19beca5a307b63f463fba857a06ef34ec"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateArtifactUploadUrlInput`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlInput {\n content_md5: self.content_md5,\n content_checksum: self.content_checksum,\n content_checksum_type: self.content_checksum_type,\n content_length: self.content_length,\n artifact_type: self.artifact_type,\n upload_intent: self.upload_intent,\n upload_context: self.upload_context,\n upload_id: self.upload_id,\n profile_arn: self.profile_arn,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateArtifactUploadUrlInput`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url/_create_artifact_upload_url_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url/_create_artifact_upload_url_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d5f52b74ff8aacb050c5bb93f387b2265c36bf142f4212b103b4cd61b12bb7e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateArtifactUploadUrlOutput`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput).\nThis method will fail if any of the following fields are not set:\n- [`upload_id`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlOutputBuilder::upload_id)\n- [`upload_url`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlOutputBuilder::upload_url)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput {\n upload_id: self.upload_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"upload_id\",\n \"upload_id was not specified but it is required when building CreateArtifactUploadUrlOutput\",\n )\n })?,\n upload_url: self.upload_url.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"upload_url\",\n \"upload_url was not specified but it is required when building CreateArtifactUploadUrlOutput\",\n )\n })?,\n kms_key_arn: self.kms_key_arn,\n request_headers: self.request_headers,\n _request_id: self._request_id,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateArtifactUploadUrlOutput`](crate::operation::create_artifact_upload_url::CreateArtifactUploadUrlOutput).\nThis method will fail if any of the following fields are not set:\n- [`upload_id`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlOutputBuilder::upload_id)\n- [`upload_url`](crate::operation::create_artifact_upload_url::builders::CreateArtifactUploadUrlOutputBuilder::upload_url)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url/_create_artifact_upload_url_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_artifact_upload_url/_create_artifact_upload_url_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "23e5e83f69fcdda825a530f697547c60f91a2f06d670c51f24c0269e3fcfb014"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateSubscriptionTokenInput`](crate::operation::create_subscription_token::CreateSubscriptionTokenInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_subscription_token::CreateSubscriptionTokenInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::create_subscription_token::CreateSubscriptionTokenInput {\n account_id: self.account_id,\n client_token: self.client_token,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateSubscriptionTokenInput`](crate::operation::create_subscription_token::CreateSubscriptionTokenInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_subscription_token/_create_subscription_token_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_subscription_token/_create_subscription_token_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a9ff6e293e31f4703d5ec60a33a02b4b328b02d5d0686f796e8820b590aea520"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateSubscriptionTokenOutput`](crate::operation::create_subscription_token::CreateSubscriptionTokenOutput).\nThis method will fail if any of the following fields are not set:\n- [`encoded_verification_url`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenOutputBuilder::encoded_verification_url)\n- [`token`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenOutputBuilder::token)\n- [`status`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenOutputBuilder::status)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_subscription_token::CreateSubscriptionTokenOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::create_subscription_token::CreateSubscriptionTokenOutput {\n encoded_verification_url: self.encoded_verification_url.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"encoded_verification_url\",\n \"encoded_verification_url was not specified but it is required when building CreateSubscriptionTokenOutput\",\n )\n })?,\n token: self.token.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"token\",\n \"token was not specified but it is required when building CreateSubscriptionTokenOutput\",\n )\n })?,\n status: self.status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"status\",\n \"status was not specified but it is required when building CreateSubscriptionTokenOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateSubscriptionTokenOutput`](crate::operation::create_subscription_token::CreateSubscriptionTokenOutput).\nThis method will fail if any of the following fields are not set:\n- [`encoded_verification_url`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenOutputBuilder::encoded_verification_url)\n- [`token`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenOutputBuilder::token)\n- [`status`](crate::operation::create_subscription_token::builders::CreateSubscriptionTokenOutputBuilder::status)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_subscription_token/_create_subscription_token_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_subscription_token/_create_subscription_token_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0611634ef0411c3246ebd2e1fa07e8083149d715ea74792fb1c7c80c52d6971"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`CreateTaskAssistConversationInput`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationInputBuilder {\n crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationInputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`CreateTaskAssistConversationInput`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_task_assist_conversation/_create_task_assist_conversation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_task_assist_conversation/_create_task_assist_conversation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f512f1d6635a1eb4e0c1bf0b17cb7c32ca4dcf8e95753e6e570e344baa01b35"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateTaskAssistConversationInput`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_task_assist_conversation::CreateTaskAssistConversationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::create_task_assist_conversation::CreateTaskAssistConversationInput {\n profile_arn: self.profile_arn,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateTaskAssistConversationInput`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_task_assist_conversation/_create_task_assist_conversation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_task_assist_conversation/_create_task_assist_conversation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6c05d279df4c4e51d770e267b488d72ccfd67eb41bf2b18577eb15ad6cdfa741"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`CreateTaskAssistConversationOutput`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationOutputBuilder {\n crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationOutputBuilder::default(\n )\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`CreateTaskAssistConversationOutput`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_task_assist_conversation/_create_task_assist_conversation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_task_assist_conversation/_create_task_assist_conversation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f1d8fa4e4cdaa26cdc745b449eff550243cd04cea5c59291cfe40f41cfab3cb4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateTaskAssistConversationOutput`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationOutput).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationOutputBuilder::conversation_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_task_assist_conversation::CreateTaskAssistConversationOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::create_task_assist_conversation::CreateTaskAssistConversationOutput {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building CreateTaskAssistConversationOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateTaskAssistConversationOutput`](crate::operation::create_task_assist_conversation::CreateTaskAssistConversationOutput).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::operation::create_task_assist_conversation::builders::CreateTaskAssistConversationOutputBuilder::conversation_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_task_assist_conversation/_create_task_assist_conversation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_task_assist_conversation/_create_task_assist_conversation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7dc111bbf5c1e7ec38a61c8a739182f7410a801691884a7e0e2aa2485d1b17af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateUploadUrlInput`](crate::operation::create_upload_url::CreateUploadUrlInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_upload_url::CreateUploadUrlInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::create_upload_url::CreateUploadUrlInput {\n content_md5: self.content_md5,\n content_checksum: self.content_checksum,\n content_checksum_type: self.content_checksum_type,\n content_length: self.content_length,\n artifact_type: self.artifact_type,\n upload_intent: self.upload_intent,\n upload_context: self.upload_context,\n upload_id: self.upload_id,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateUploadUrlInput`](crate::operation::create_upload_url::CreateUploadUrlInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_upload_url/_create_upload_url_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_upload_url/_create_upload_url_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "06446267cca3a77c7e45c9eef134927615f35def8ae6fed132c5dede35f370df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateUploadUrlOutput`](crate::operation::create_upload_url::CreateUploadUrlOutput).\nThis method will fail if any of the following fields are not set:\n- [`upload_id`](crate::operation::create_upload_url::builders::CreateUploadUrlOutputBuilder::upload_id)\n- [`upload_url`](crate::operation::create_upload_url::builders::CreateUploadUrlOutputBuilder::upload_url)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_upload_url::CreateUploadUrlOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::create_upload_url::CreateUploadUrlOutput {\n upload_id: self.upload_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"upload_id\",\n \"upload_id was not specified but it is required when building CreateUploadUrlOutput\",\n )\n })?,\n upload_url: self.upload_url.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"upload_url\",\n \"upload_url was not specified but it is required when building CreateUploadUrlOutput\",\n )\n })?,\n kms_key_arn: self.kms_key_arn,\n request_headers: self.request_headers,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateUploadUrlOutput`](crate::operation::create_upload_url::CreateUploadUrlOutput).\nThis method will fail if any of the following fields are not set:\n- [`upload_id`](crate::operation::create_upload_url::builders::CreateUploadUrlOutputBuilder::upload_id)\n- [`upload_url`](crate::operation::create_upload_url::builders::CreateUploadUrlOutputBuilder::upload_url)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_upload_url/_create_upload_url_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_upload_url/_create_upload_url_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "41443b411748eb9dfb52d93d149c19c783b77dcf435917ce487ee4b82f67760b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateUserMemoryEntryInput`](crate::operation::create_user_memory_entry::CreateUserMemoryEntryInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_user_memory_entry::CreateUserMemoryEntryInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::create_user_memory_entry::CreateUserMemoryEntryInput {\n memory_entry_string: self.memory_entry_string,\n origin: self.origin,\n profile_arn: self.profile_arn,\n client_token: self.client_token,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateUserMemoryEntryInput`](crate::operation::create_user_memory_entry::CreateUserMemoryEntryInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_user_memory_entry/_create_user_memory_entry_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_user_memory_entry/_create_user_memory_entry_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c06a52ea2cfce47abc0713bedc73feaeb3b4d5539e84e8eed96d20fb833dbc09"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: memory_entry\n\nDocumentation:\nMemoryEntry corresponds to a single user memory\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn memory_entry(mut self, input: crate::types::MemoryEntry) -> Self {\n self.memory_entry = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "memory_entry", "docstring": "MemoryEntry corresponds to a single user memory\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_user_memory_entry/_create_user_memory_entry_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_user_memory_entry/_create_user_memory_entry_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c6243b925512229fbb1848c49a41477f2883ce3699eae79b3ad92c3fdf04851"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_memory_entry\n\nDocumentation:\nMemoryEntry corresponds to a single user memory\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_memory_entry(mut self, input: ::std::option::Option) -> Self {\n self.memory_entry = input;\n self\n }\n```"}], "func_name": "set_memory_entry", "docstring": "MemoryEntry corresponds to a single user memory", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_user_memory_entry/_create_user_memory_entry_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_user_memory_entry/_create_user_memory_entry_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eda02d93667366ff559753b962f7a0181cb2de854f096eafc5e7a939d7e48d1b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateUserMemoryEntryOutput`](crate::operation::create_user_memory_entry::CreateUserMemoryEntryOutput).\nThis method will fail if any of the following fields are not set:\n- [`memory_entry`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryOutputBuilder::memory_entry)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_user_memory_entry::CreateUserMemoryEntryOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::create_user_memory_entry::CreateUserMemoryEntryOutput {\n memory_entry: self.memory_entry.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"memory_entry\",\n \"memory_entry was not specified but it is required when building CreateUserMemoryEntryOutput\",\n )\n })?,\n _request_id: self._request_id,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateUserMemoryEntryOutput`](crate::operation::create_user_memory_entry::CreateUserMemoryEntryOutput).\nThis method will fail if any of the following fields are not set:\n- [`memory_entry`](crate::operation::create_user_memory_entry::builders::CreateUserMemoryEntryOutputBuilder::memory_entry)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_user_memory_entry/_create_user_memory_entry_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_user_memory_entry/_create_user_memory_entry_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d3686662ef3e43e055f530c25fcebe865499b7e56b5189dbd548f46035e1e0a9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateWorkspaceInput`](crate::operation::create_workspace::CreateWorkspaceInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_workspace::CreateWorkspaceInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::create_workspace::CreateWorkspaceInput {\n workspace_root: self.workspace_root,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateWorkspaceInput`](crate::operation::create_workspace::CreateWorkspaceInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_workspace/_create_workspace_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_workspace/_create_workspace_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "285c5e466a1c69a008eb05716085dcdc6ec5324396d73476034aecda926f36c2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateWorkspaceOutput`](crate::operation::create_workspace::CreateWorkspaceOutput).\nThis method will fail if any of the following fields are not set:\n- [`workspace`](crate::operation::create_workspace::builders::CreateWorkspaceOutputBuilder::workspace)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_workspace::CreateWorkspaceOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::create_workspace::CreateWorkspaceOutput {\n workspace: self.workspace.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"workspace\",\n \"workspace was not specified but it is required when building CreateWorkspaceOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateWorkspaceOutput`](crate::operation::create_workspace::CreateWorkspaceOutput).\nThis method will fail if any of the following fields are not set:\n- [`workspace`](crate::operation::create_workspace::builders::CreateWorkspaceOutputBuilder::workspace)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/create_workspace/_create_workspace_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/create_workspace/_create_workspace_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c24f82af9b6617350c864f0a9633240064059dc70749ee1769e430ffad241d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`DeleteTaskAssistConversationInput`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationInputBuilder {\n crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationInputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`DeleteTaskAssistConversationInput`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/delete_task_assist_conversation/_delete_task_assist_conversation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/delete_task_assist_conversation/_delete_task_assist_conversation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8555df4332475f4c706bdec1d03e75f80f9df12c60c5a92ecb7eb3d6765e2593"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DeleteTaskAssistConversationInput`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationInput {\n conversation_id: self.conversation_id,\n profile_arn: self.profile_arn,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DeleteTaskAssistConversationInput`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/delete_task_assist_conversation/_delete_task_assist_conversation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/delete_task_assist_conversation/_delete_task_assist_conversation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dbd0aca460906e37e7de7f4f3c55543fe398171fc9dec777b7a4966a42d08b0e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`DeleteTaskAssistConversationOutput`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationOutputBuilder {\n crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationOutputBuilder::default(\n )\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`DeleteTaskAssistConversationOutput`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/delete_task_assist_conversation/_delete_task_assist_conversation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/delete_task_assist_conversation/_delete_task_assist_conversation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a60ef6247752008128c9be0e96939294bb3070e8853044a10251fe82ca35fccb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DeleteTaskAssistConversationOutput`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationOutput).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationOutputBuilder::conversation_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationOutput {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building DeleteTaskAssistConversationOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DeleteTaskAssistConversationOutput`](crate::operation::delete_task_assist_conversation::DeleteTaskAssistConversationOutput).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::operation::delete_task_assist_conversation::builders::DeleteTaskAssistConversationOutputBuilder::conversation_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/delete_task_assist_conversation/_delete_task_assist_conversation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/delete_task_assist_conversation/_delete_task_assist_conversation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2bcb211469212c72fa327b5df5f04c2dcb4ec8154291f290acf8d354d5d691a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DeleteUserMemoryEntryInput`](crate::operation::delete_user_memory_entry::DeleteUserMemoryEntryInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::delete_user_memory_entry::DeleteUserMemoryEntryInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::delete_user_memory_entry::DeleteUserMemoryEntryInput {\n id: self.id,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DeleteUserMemoryEntryInput`](crate::operation::delete_user_memory_entry::DeleteUserMemoryEntryInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/delete_user_memory_entry/_delete_user_memory_entry_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/delete_user_memory_entry/_delete_user_memory_entry_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6417fdd6d93c57fc24b5c8bb0c546cdcfccf5497aff17edcc0e5e854a9be9f10"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DeleteUserMemoryEntryOutput`](crate::operation::delete_user_memory_entry::DeleteUserMemoryEntryOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::delete_user_memory_entry::DeleteUserMemoryEntryOutput {\n crate::operation::delete_user_memory_entry::DeleteUserMemoryEntryOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DeleteUserMemoryEntryOutput`](crate::operation::delete_user_memory_entry::DeleteUserMemoryEntryOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/delete_user_memory_entry/_delete_user_memory_entry_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/delete_user_memory_entry/_delete_user_memory_entry_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f9a043c5bec9d5bb27db5a99676c6e1231adb4f7b649ec291f9a9840b139796"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DeleteWorkspaceInput`](crate::operation::delete_workspace::DeleteWorkspaceInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::delete_workspace::DeleteWorkspaceInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::delete_workspace::DeleteWorkspaceInput {\n workspace_id: self.workspace_id,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DeleteWorkspaceInput`](crate::operation::delete_workspace::DeleteWorkspaceInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/delete_workspace/_delete_workspace_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/delete_workspace/_delete_workspace_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27a78e31b7a80ebd00a4a3278313242edabc381dac7ab7e80353b77fbff2510c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DeleteWorkspaceOutput`](crate::operation::delete_workspace::DeleteWorkspaceOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::delete_workspace::DeleteWorkspaceOutput {\n crate::operation::delete_workspace::DeleteWorkspaceOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DeleteWorkspaceOutput`](crate::operation::delete_workspace::DeleteWorkspaceOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/delete_workspace/_delete_workspace_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/delete_workspace/_delete_workspace_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "96ea14d1eaf2c82c9521c64fc6233b4cab6fce41ce9595f696646c6f5e57687d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: editor_state\n\nDocumentation:\nRepresents the state of an Editor\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn editor_state(mut self, input: crate::types::EditorState) -> Self {\n self.inner = self.inner.editor_state(input);\n self\n }\n```"}], "func_name": "editor_state", "docstring": "Represents the state of an Editor", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/generate_completions/builders.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/generate_completions/builders.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d03ffeb87f1a2ec1128cae422a4e54a1b5a2b78c93d03fd029b94f9ca8bad9b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prediction_types\n\nDocumentation:\nAppends an item to `prediction_types`.\n\nTo override the contents of this collection use\n[`set_prediction_types`](Self::set_prediction_types).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn prediction_types(mut self, input: crate::types::PredictionType) -> Self {\n let mut v = self.prediction_types.unwrap_or_default();\n v.push(input);\n self.prediction_types = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "prediction_types", "docstring": "Appends an item to `prediction_types`.\n\nTo override the contents of this collection use\n[`set_prediction_types`](Self::set_prediction_types).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/generate_completions/_generate_completions_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/generate_completions/_generate_completions_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17821421763ba3bb0bff720ecabdf7454a26a2d2a7816695c63308f54b266329"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: supplemental_contexts\n\nDocumentation:\nAppends an item to `supplemental_contexts`.\n\nTo override the contents of this collection use\n[`set_supplemental_contexts`](Self::set_supplemental_contexts).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn supplemental_contexts(mut self, input: crate::types::SupplementalContext) -> Self {\n let mut v = self.supplemental_contexts.unwrap_or_default();\n v.push(input);\n self.supplemental_contexts = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "supplemental_contexts", "docstring": "Appends an item to `supplemental_contexts`.\n\nTo override the contents of this collection use\n[`set_supplemental_contexts`](Self::set_supplemental_contexts).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/generate_completions/_generate_completions_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/generate_completions/_generate_completions_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7445a20e15dc5ab230bef1a89dc4349779b3513b88cc9978ca0b3805e2bffe64"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GenerateCompletionsInput`](crate::operation::generate_completions::GenerateCompletionsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::generate_completions::GenerateCompletionsInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::generate_completions::GenerateCompletionsInput {\n file_context: self.file_context,\n editor_state: self.editor_state,\n max_results: self.max_results,\n prediction_types: self.prediction_types,\n next_token: self.next_token,\n reference_tracker_configuration: self.reference_tracker_configuration,\n supplemental_contexts: self.supplemental_contexts,\n customization_arn: self.customization_arn,\n opt_out_preference: self.opt_out_preference,\n user_context: self.user_context,\n profile_arn: self.profile_arn,\n workspace_id: self.workspace_id,\n model_id: self.model_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GenerateCompletionsInput`](crate::operation::generate_completions::GenerateCompletionsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/generate_completions/_generate_completions_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/generate_completions/_generate_completions_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9c2625fad7d1dbd2130c0f1a84ddf8dd2f57f9367d2df11eece686f4291f189b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: predictions\n\nDocumentation:\nAppends an item to `predictions`.\n\nTo override the contents of this collection use [`set_predictions`](Self::set_predictions).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn predictions(mut self, input: crate::types::Prediction) -> Self {\n let mut v = self.predictions.unwrap_or_default();\n v.push(input);\n self.predictions = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "predictions", "docstring": "Appends an item to `predictions`.\n\nTo override the contents of this collection use [`set_predictions`](Self::set_predictions).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/generate_completions/_generate_completions_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/generate_completions/_generate_completions_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f24c44a316ce8d3b360ae74770862a9d010af196edc5c22694d555bee89dd62"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: completions\n\nDocumentation:\nAppends an item to `completions`.\n\nTo override the contents of this collection use [`set_completions`](Self::set_completions).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn completions(mut self, input: crate::types::Completion) -> Self {\n let mut v = self.completions.unwrap_or_default();\n v.push(input);\n self.completions = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "completions", "docstring": "Appends an item to `completions`.\n\nTo override the contents of this collection use [`set_completions`](Self::set_completions).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/generate_completions/_generate_completions_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/generate_completions/_generate_completions_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "52e49f35a67083028bb8cecb0a90eb29127187b355ace46946a7a3216eac20e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GenerateCompletionsOutput`](crate::operation::generate_completions::GenerateCompletionsOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::generate_completions::GenerateCompletionsOutput {\n crate::operation::generate_completions::GenerateCompletionsOutput {\n predictions: self.predictions,\n completions: self.completions,\n next_token: self.next_token,\n model_id: self.model_id,\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GenerateCompletionsOutput`](crate::operation::generate_completions::GenerateCompletionsOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/generate_completions/_generate_completions_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/generate_completions/_generate_completions_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ae3d418837c7994a6d3f6ee86578a92215a8a8f37e8d7507a699e8698d56f0e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetCodeAnalysisInput`](crate::operation::get_code_analysis::GetCodeAnalysisInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::get_code_analysis::GetCodeAnalysisInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::get_code_analysis::GetCodeAnalysisInput {\n job_id: self.job_id,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetCodeAnalysisInput`](crate::operation::get_code_analysis::GetCodeAnalysisInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_code_analysis/_get_code_analysis_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_code_analysis/_get_code_analysis_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8b0bbe2af8cebfd8d133093901b9d08c30399ea5a4ae59e824f0f57fca3ceace"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetCodeAnalysisOutput`](crate::operation::get_code_analysis::GetCodeAnalysisOutput).\nThis method will fail if any of the following fields are not set:\n- [`status`](crate::operation::get_code_analysis::builders::GetCodeAnalysisOutputBuilder::status)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::get_code_analysis::GetCodeAnalysisOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::get_code_analysis::GetCodeAnalysisOutput {\n status: self.status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"status\",\n \"status was not specified but it is required when building GetCodeAnalysisOutput\",\n )\n })?,\n error_message: self.error_message,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetCodeAnalysisOutput`](crate::operation::get_code_analysis::GetCodeAnalysisOutput).\nThis method will fail if any of the following fields are not set:\n- [`status`](crate::operation::get_code_analysis::builders::GetCodeAnalysisOutputBuilder::status)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_code_analysis/_get_code_analysis_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_code_analysis/_get_code_analysis_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "703be6dcc347b5bd19d539dd45daa593263efc720a557999ee60dc18b6328964"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetCodeFixJobInput`](crate::operation::get_code_fix_job::GetCodeFixJobInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::get_code_fix_job::GetCodeFixJobInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::get_code_fix_job::GetCodeFixJobInput {\n job_id: self.job_id,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetCodeFixJobInput`](crate::operation::get_code_fix_job::GetCodeFixJobInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_code_fix_job/_get_code_fix_job_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_code_fix_job/_get_code_fix_job_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "083b65a6433077aca54bd0ed88d1f498459423207bfeb1134f1d04e8e9f23aa4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetCodeFixJobOutput`](crate::operation::get_code_fix_job::GetCodeFixJobOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::get_code_fix_job::GetCodeFixJobOutput {\n crate::operation::get_code_fix_job::GetCodeFixJobOutput {\n job_status: self.job_status,\n suggested_fix: self.suggested_fix,\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetCodeFixJobOutput`](crate::operation::get_code_fix_job::GetCodeFixJobOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_code_fix_job/_get_code_fix_job_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_code_fix_job/_get_code_fix_job_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "11477e0e799a7badc147e9a4bf421ac85042c3f2dd2e4a7ee7661ce95aa563c8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: code_generation_id\n\nDocumentation:\nID which represents a single code generation in a conversation\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn code_generation_id(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.inner = self.inner.code_generation_id(input.into());\n self\n }\n```"}], "func_name": "code_generation_id", "docstring": "ID which represents a single code generation in a conversation", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/builders.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/builders.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "91ce6aa1f1b11f6119b83d76dda0e6727e6ea6ece8804163588c0aba4736d2df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`GetTaskAssistCodeGenerationInput`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationInputBuilder {\n crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationInputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`GetTaskAssistCodeGenerationInput`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/_get_task_assist_code_generation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/_get_task_assist_code_generation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9398452a653358210113ade4b010037846934186b55d90123ce2f60b8a616671"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: code_generation_id\n\nDocumentation:\nID which represents a single code generation in a conversation\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn code_generation_id(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.code_generation_id = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "code_generation_id", "docstring": "ID which represents a single code generation in a conversation\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/_get_task_assist_code_generation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/_get_task_assist_code_generation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "21f1d0f9551bd78f02a2e8e25ac70d1507d2cb4e6ef68b6d4509fe537de37d85"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetTaskAssistCodeGenerationInput`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationInput {\n conversation_id: self.conversation_id,\n code_generation_id: self.code_generation_id,\n profile_arn: self.profile_arn,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetTaskAssistCodeGenerationInput`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/_get_task_assist_code_generation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/_get_task_assist_code_generation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cce4ffea8d64a883e43ce55d99d225ae76cb98963cfc2da040eb77bf058433e1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`GetTaskAssistCodeGenerationOutput`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationOutputBuilder {\n crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationOutputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`GetTaskAssistCodeGenerationOutput`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/_get_task_assist_code_generation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/_get_task_assist_code_generation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f1eec8967c13f4dc394864f38be7343c578cd04d4de0fc7d19f69a5b2bae27cc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: code_generation_status_detail\n\nDocumentation:\nDetailed message about the code generation status\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn code_generation_status_detail(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.code_generation_status_detail = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "code_generation_status_detail", "docstring": "Detailed message about the code generation status", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/_get_task_assist_code_generation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/_get_task_assist_code_generation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b5529e77b26be00cf6ea6e12eb5527ee6634e271729cdb7e16db56b9fd0de5af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetTaskAssistCodeGenerationOutput`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationOutputBuilder::conversation_id)\n- [`code_generation_status`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationOutputBuilder::code_generation_status)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building GetTaskAssistCodeGenerationOutput\",\n )\n })?,\n code_generation_status: self.code_generation_status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"code_generation_status\",\n \"code_generation_status was not specified but it is required when building GetTaskAssistCodeGenerationOutput\",\n )\n })?,\n code_generation_status_detail: self.code_generation_status_detail,\n code_generation_remaining_iteration_count: self.code_generation_remaining_iteration_count,\n code_generation_total_iteration_count: self.code_generation_total_iteration_count,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetTaskAssistCodeGenerationOutput`](crate::operation::get_task_assist_code_generation::GetTaskAssistCodeGenerationOutput).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationOutputBuilder::conversation_id)\n- [`code_generation_status`](crate::operation::get_task_assist_code_generation::builders::GetTaskAssistCodeGenerationOutputBuilder::code_generation_status)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/_get_task_assist_code_generation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_task_assist_code_generation/_get_task_assist_code_generation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f2ddf28ca849be8831cea048446a4b1a68e1e2111a25ace1b8a4ab1631f1c893"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: test_generation_job_group_name\n\nDocumentation:\nTest generation job group name\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn test_generation_job_group_name(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.test_generation_job_group_name = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "test_generation_job_group_name", "docstring": "Test generation job group name\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_test_generation/_get_test_generation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_test_generation/_get_test_generation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c29751a85f90eb2285f53f6e5ad2723aa5bf9c78963f1e445bf0975400f3c01"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetTestGenerationInput`](crate::operation::get_test_generation::GetTestGenerationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::get_test_generation::GetTestGenerationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::get_test_generation::GetTestGenerationInput {\n test_generation_job_group_name: self.test_generation_job_group_name,\n test_generation_job_id: self.test_generation_job_id,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetTestGenerationInput`](crate::operation::get_test_generation::GetTestGenerationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_test_generation/_get_test_generation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_test_generation/_get_test_generation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad858b5ef0bc4bacfaf5fc70a2d069c3a9dd7fd0b008aa5f8e52f8564c761cb8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetTestGenerationOutput`](crate::operation::get_test_generation::GetTestGenerationOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::get_test_generation::GetTestGenerationOutput {\n crate::operation::get_test_generation::GetTestGenerationOutput {\n test_generation_job: self.test_generation_job,\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetTestGenerationOutput`](crate::operation::get_test_generation::GetTestGenerationOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_test_generation/_get_test_generation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_test_generation/_get_test_generation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb7ab9ee14d85d2eb363b269e7774374040412132fcdd237f219b52ed5ed40c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: transformation_job_id\n\nDocumentation:\nIdentifier for the Transformation Job\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn transformation_job_id(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.transformation_job_id = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "transformation_job_id", "docstring": "Identifier for the Transformation Job\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_transformation/_get_transformation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_transformation/_get_transformation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "699153cc940d0fbb298cc7afe4f6dc66a2d4a1195c2c68972e5cf69fd8a96ac5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetTransformationInput`](crate::operation::get_transformation::GetTransformationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::get_transformation::GetTransformationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::get_transformation::GetTransformationInput {\n transformation_job_id: self.transformation_job_id,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetTransformationInput`](crate::operation::get_transformation::GetTransformationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_transformation/_get_transformation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_transformation/_get_transformation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e82ac19a3d5666ef559847031e5d447c2c2bb3401fa23bcf292069a00488ff4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: transformation_job\n\nDocumentation:\nRepresent a Transformation Job\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn transformation_job(mut self, input: crate::types::TransformationJob) -> Self {\n self.transformation_job = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "transformation_job", "docstring": "Represent a Transformation Job\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_transformation/_get_transformation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_transformation/_get_transformation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "359d6f1c4770835b2e1db89133f77c6b40e6e5d772af9e1adc54693dad530a5a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetTransformationOutput`](crate::operation::get_transformation::GetTransformationOutput).\nThis method will fail if any of the following fields are not set:\n- [`transformation_job`](crate::operation::get_transformation::builders::GetTransformationOutputBuilder::transformation_job)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::get_transformation::GetTransformationOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::get_transformation::GetTransformationOutput {\n transformation_job: self.transformation_job.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"transformation_job\",\n \"transformation_job was not specified but it is required when building GetTransformationOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetTransformationOutput`](crate::operation::get_transformation::GetTransformationOutput).\nThis method will fail if any of the following fields are not set:\n- [`transformation_job`](crate::operation::get_transformation::builders::GetTransformationOutputBuilder::transformation_job)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_transformation/_get_transformation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_transformation/_get_transformation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f297246c5b919e8cebb75b5e9a59db653a1f79466b0c9bc0225d101451958d10"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetTransformationPlanInput`](crate::operation::get_transformation_plan::GetTransformationPlanInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::get_transformation_plan::GetTransformationPlanInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::get_transformation_plan::GetTransformationPlanInput {\n transformation_job_id: self.transformation_job_id,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetTransformationPlanInput`](crate::operation::get_transformation_plan::GetTransformationPlanInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_transformation_plan/_get_transformation_plan_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_transformation_plan/_get_transformation_plan_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09a75ba5e143147846ccb70829d27f6515f430067438154625ebfbeec069b71f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetTransformationPlanOutput`](crate::operation::get_transformation_plan::GetTransformationPlanOutput).\nThis method will fail if any of the following fields are not set:\n- [`transformation_plan`](crate::operation::get_transformation_plan::builders::GetTransformationPlanOutputBuilder::transformation_plan)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::get_transformation_plan::GetTransformationPlanOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::get_transformation_plan::GetTransformationPlanOutput {\n transformation_plan: self.transformation_plan.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"transformation_plan\",\n \"transformation_plan was not specified but it is required when building GetTransformationPlanOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetTransformationPlanOutput`](crate::operation::get_transformation_plan::GetTransformationPlanOutput).\nThis method will fail if any of the following fields are not set:\n- [`transformation_plan`](crate::operation::get_transformation_plan::builders::GetTransformationPlanOutputBuilder::transformation_plan)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_transformation_plan/_get_transformation_plan_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_transformation_plan/_get_transformation_plan_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "92316d23aa2acd6ff62edbe464a5b2ba7476aa53ba8e916e6ab224d3deba4df4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: profile_arn\n\nDocumentation:\nThe ARN of the Q Developer profile. Required for enterprise customers, optional for Builder\nID users.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn profile_arn(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.inner = self.inner.profile_arn(input.into());\n self\n }\n```"}], "func_name": "profile_arn", "docstring": "The ARN of the Q Developer profile. Required for enterprise customers, optional for Builder\nID users.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_usage_limits/builders.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_usage_limits/builders.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ae2b8ee1c9dac20c4550a419285d1d7d00931308ad8ffe6a42f6a3d892bc357"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: days_until_reset\n\nDocumentation:\nNumber of days remaining until the usage metrics reset\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn days_until_reset(mut self, input: i32) -> Self {\n self.days_until_reset = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "days_until_reset", "docstring": "Number of days remaining until the usage metrics reset\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_usage_limits/_get_usage_limits_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_usage_limits/_get_usage_limits_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb79bcb9ae083b878715fc09fadaae394768bc5acfa035bf7a610a42b6ff54f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_days_until_reset\n\nDocumentation:\nNumber of days remaining until the usage metrics reset\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_days_until_reset(mut self, input: ::std::option::Option) -> Self {\n self.days_until_reset = input;\n self\n }\n```"}], "func_name": "set_days_until_reset", "docstring": "Number of days remaining until the usage metrics reset", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/get_usage_limits/_get_usage_limits_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/get_usage_limits/_get_usage_limits_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d90310e33273a401bc6591034f2976f04bc35c14a1e064434f4b159a64adf94f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: items\n\nDocumentation:\nCreate a flattened paginator\n\nThis paginator automatically flattens results using `customizations`. Queries to the\nunderlying service are dispatched lazily.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn items(\n self,\n ) -> crate::operation::list_available_customizations::paginator::ListAvailableCustomizationsPaginatorItems {\n crate::operation::list_available_customizations::paginator::ListAvailableCustomizationsPaginatorItems(self)\n }\n```"}], "func_name": "items", "docstring": "Create a flattened paginator\n\nThis paginator automatically flattens results using `customizations`. Queries to the\nunderlying service are dispatched lazily.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_available_customizations/paginator.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_available_customizations/paginator.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "62ae49a5582b7d6e654b5e98ee2604eee32e301c9577b2ff1a90e5e2c02cb40c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`ListAvailableCustomizationsInput`](crate::operation::list_available_customizations::ListAvailableCustomizationsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::list_available_customizations::builders::ListAvailableCustomizationsInputBuilder {\n crate::operation::list_available_customizations::builders::ListAvailableCustomizationsInputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`ListAvailableCustomizationsInput`](crate::operation::list_available_customizations::ListAvailableCustomizationsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_available_customizations/_list_available_customizations_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_available_customizations/_list_available_customizations_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b627b9836fbf2ee9463137829a08e7037356a6b751d3024052597e03732e3ede"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListAvailableCustomizationsInput`](crate::operation::list_available_customizations::ListAvailableCustomizationsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_available_customizations::ListAvailableCustomizationsInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::list_available_customizations::ListAvailableCustomizationsInput {\n max_results: self.max_results,\n next_token: self.next_token,\n profile_arn: self.profile_arn,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListAvailableCustomizationsInput`](crate::operation::list_available_customizations::ListAvailableCustomizationsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_available_customizations/_list_available_customizations_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_available_customizations/_list_available_customizations_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "185255a79e63443324d97d6e91536e62435f7a5e1b8d3f52aa97fa694bc8fcbe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`ListAvailableCustomizationsOutput`](crate::operation::list_available_customizations::ListAvailableCustomizationsOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::list_available_customizations::builders::ListAvailableCustomizationsOutputBuilder {\n crate::operation::list_available_customizations::builders::ListAvailableCustomizationsOutputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`ListAvailableCustomizationsOutput`](crate::operation::list_available_customizations::ListAvailableCustomizationsOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_available_customizations/_list_available_customizations_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_available_customizations/_list_available_customizations_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c6648fa0f39ca1ef48639e7990dd611877acf2210d1f6dce327444c152654eec"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: customizations\n\nDocumentation:\nAppends an item to `customizations`.\n\nTo override the contents of this collection use\n[`set_customizations`](Self::set_customizations).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn customizations(mut self, input: crate::types::Customization) -> Self {\n let mut v = self.customizations.unwrap_or_default();\n v.push(input);\n self.customizations = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "customizations", "docstring": "Appends an item to `customizations`.\n\nTo override the contents of this collection use\n[`set_customizations`](Self::set_customizations).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_available_customizations/_list_available_customizations_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_available_customizations/_list_available_customizations_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8444511b796fe0ae7a95293d4c05b1e60b82971b946fb91f78f9827957ebcc66"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListAvailableCustomizationsOutput`](crate::operation::list_available_customizations::ListAvailableCustomizationsOutput).\nThis method will fail if any of the following fields are not set:\n- [`customizations`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsOutputBuilder::customizations)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_available_customizations::ListAvailableCustomizationsOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_available_customizations::ListAvailableCustomizationsOutput {\n customizations: self.customizations.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"customizations\",\n \"customizations was not specified but it is required when building ListAvailableCustomizationsOutput\",\n )\n })?,\n next_token: self.next_token,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListAvailableCustomizationsOutput`](crate::operation::list_available_customizations::ListAvailableCustomizationsOutput).\nThis method will fail if any of the following fields are not set:\n- [`customizations`](crate::operation::list_available_customizations::builders::ListAvailableCustomizationsOutputBuilder::customizations)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_available_customizations/_list_available_customizations_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_available_customizations/_list_available_customizations_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94c02fc9c9241d58ac2246444df93af2324645557be354d8380b4d2214fa93ac"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListAvailableProfilesInput`](crate::operation::list_available_profiles::ListAvailableProfilesInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_available_profiles::ListAvailableProfilesInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_available_profiles::ListAvailableProfilesInput {\n max_results: self.max_results,\n next_token: self.next_token,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListAvailableProfilesInput`](crate::operation::list_available_profiles::ListAvailableProfilesInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_available_profiles/_list_available_profiles_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_available_profiles/_list_available_profiles_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea3ddf93ecdaf2718112747168dcbffd202a0bc8a4e7e50c5f051d54a209dbc9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: profiles\n\nDocumentation:\nAppends an item to `profiles`.\n\nTo override the contents of this collection use [`set_profiles`](Self::set_profiles).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn profiles(mut self, input: crate::types::Profile) -> Self {\n let mut v = self.profiles.unwrap_or_default();\n v.push(input);\n self.profiles = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "profiles", "docstring": "Appends an item to `profiles`.\n\nTo override the contents of this collection use [`set_profiles`](Self::set_profiles).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_available_profiles/_list_available_profiles_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_available_profiles/_list_available_profiles_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c5ba0015ae0646c80002498336e17d3a1683973c58086ee53cb1b332258e17af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListAvailableProfilesOutput`](crate::operation::list_available_profiles::ListAvailableProfilesOutput).\nThis method will fail if any of the following fields are not set:\n- [`profiles`](crate::operation::list_available_profiles::builders::ListAvailableProfilesOutputBuilder::profiles)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_available_profiles::ListAvailableProfilesOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_available_profiles::ListAvailableProfilesOutput {\n profiles: self.profiles.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"profiles\",\n \"profiles was not specified but it is required when building ListAvailableProfilesOutput\",\n )\n })?,\n next_token: self.next_token,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListAvailableProfilesOutput`](crate::operation::list_available_profiles::ListAvailableProfilesOutput).\nThis method will fail if any of the following fields are not set:\n- [`profiles`](crate::operation::list_available_profiles::builders::ListAvailableProfilesOutputBuilder::profiles)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_available_profiles/_list_available_profiles_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_available_profiles/_list_available_profiles_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5974fd6f2e11f70dff1c73673b1dd4fcbf738d5e6f23c9513fb3677bd627e449"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListCodeAnalysisFindingsInput`](crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsInput {\n job_id: self.job_id,\n next_token: self.next_token,\n code_analysis_findings_schema: self.code_analysis_findings_schema,\n profile_arn: self.profile_arn,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListCodeAnalysisFindingsInput`](crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_code_analysis_findings/_list_code_analysis_findings_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_code_analysis_findings/_list_code_analysis_findings_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f75450e41cb93e450cb356097d8e653ffd3e8a81de0cde9f5ae47883b7f2ebbe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListCodeAnalysisFindingsOutput`](crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsOutput).\nThis method will fail if any of the following fields are not set:\n- [`code_analysis_findings`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsOutputBuilder::code_analysis_findings)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsOutput {\n next_token: self.next_token,\n code_analysis_findings: self.code_analysis_findings.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"code_analysis_findings\",\n \"code_analysis_findings was not specified but it is required when building ListCodeAnalysisFindingsOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListCodeAnalysisFindingsOutput`](crate::operation::list_code_analysis_findings::ListCodeAnalysisFindingsOutput).\nThis method will fail if any of the following fields are not set:\n- [`code_analysis_findings`](crate::operation::list_code_analysis_findings::builders::ListCodeAnalysisFindingsOutputBuilder::code_analysis_findings)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_code_analysis_findings/_list_code_analysis_findings_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_code_analysis_findings/_list_code_analysis_findings_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd7162339498a120898919b019e57eefe59e9afbe6e38947a013cebb110cac2b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListEventsInput`](crate::operation::list_events::ListEventsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_events::ListEventsInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_events::ListEventsInput {\n conversation_id: self.conversation_id,\n max_results: self.max_results,\n next_token: self.next_token,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListEventsInput`](crate::operation::list_events::ListEventsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_events/_list_events_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_events/_list_events_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a20742c4c18c3150785daca46455de8c9d28d0915bb2f323af77e1bd67ed6e5d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListEventsOutput`](crate::operation::list_events::ListEventsOutput). This method will\nfail if any of the following fields are not set:\n- [`conversation_id`](crate::operation::list_events::builders::ListEventsOutputBuilder::conversation_id)\n- [`events`](crate::operation::list_events::builders::ListEventsOutputBuilder::events)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_events::ListEventsOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_events::ListEventsOutput {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building ListEventsOutput\",\n )\n })?,\n events: self.events.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"events\",\n \"events was not specified but it is required when building ListEventsOutput\",\n )\n })?,\n next_token: self.next_token,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListEventsOutput`](crate::operation::list_events::ListEventsOutput). This method will\nfail if any of the following fields are not set:\n- [`conversation_id`](crate::operation::list_events::builders::ListEventsOutputBuilder::conversation_id)\n- [`events`](crate::operation::list_events::builders::ListEventsOutputBuilder::events)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_events/_list_events_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_events/_list_events_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "475f3ab127e8d2b701cf398e6436e9e170edb3c2198fc7fd46881cc0c79fd09b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListFeatureEvaluationsInput`](crate::operation::list_feature_evaluations::ListFeatureEvaluationsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_feature_evaluations::ListFeatureEvaluationsInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::list_feature_evaluations::ListFeatureEvaluationsInput {\n user_context: self.user_context,\n profile_arn: self.profile_arn,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListFeatureEvaluationsInput`](crate::operation::list_feature_evaluations::ListFeatureEvaluationsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_feature_evaluations/_list_feature_evaluations_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_feature_evaluations/_list_feature_evaluations_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81f991c1ed171c394c8d9223fcfe7358917cc5f6327478196d0d36ad47cb4407"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: feature_evaluations\n\nDocumentation:\nAppends an item to `feature_evaluations`.\n\nTo override the contents of this collection use\n[`set_feature_evaluations`](Self::set_feature_evaluations).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn feature_evaluations(mut self, input: crate::types::FeatureEvaluation) -> Self {\n let mut v = self.feature_evaluations.unwrap_or_default();\n v.push(input);\n self.feature_evaluations = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "feature_evaluations", "docstring": "Appends an item to `feature_evaluations`.\n\nTo override the contents of this collection use\n[`set_feature_evaluations`](Self::set_feature_evaluations).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_feature_evaluations/_list_feature_evaluations_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_feature_evaluations/_list_feature_evaluations_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69a382adb9244225a63f497100d5c080dbf4b88e57cb37f462af0ec19a224257"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListFeatureEvaluationsOutput`](crate::operation::list_feature_evaluations::ListFeatureEvaluationsOutput).\nThis method will fail if any of the following fields are not set:\n- [`feature_evaluations`](crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsOutputBuilder::feature_evaluations)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_feature_evaluations::ListFeatureEvaluationsOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_feature_evaluations::ListFeatureEvaluationsOutput {\n feature_evaluations: self.feature_evaluations.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"feature_evaluations\",\n \"feature_evaluations was not specified but it is required when building ListFeatureEvaluationsOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListFeatureEvaluationsOutput`](crate::operation::list_feature_evaluations::ListFeatureEvaluationsOutput).\nThis method will fail if any of the following fields are not set:\n- [`feature_evaluations`](crate::operation::list_feature_evaluations::builders::ListFeatureEvaluationsOutputBuilder::feature_evaluations)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_feature_evaluations/_list_feature_evaluations_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_feature_evaluations/_list_feature_evaluations_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d87237fd070d85ed809c986a96eac2cc884a0e8338b9370aa16947f404bd75bb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListUserMemoryEntriesInput`](crate::operation::list_user_memory_entries::ListUserMemoryEntriesInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_user_memory_entries::ListUserMemoryEntriesInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_user_memory_entries::ListUserMemoryEntriesInput {\n max_results: self.max_results,\n profile_arn: self.profile_arn,\n next_token: self.next_token,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListUserMemoryEntriesInput`](crate::operation::list_user_memory_entries::ListUserMemoryEntriesInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_user_memory_entries/_list_user_memory_entries_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_user_memory_entries/_list_user_memory_entries_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c55d62fb5491c33f429b844d952810397d0b067fce5cee971d0fd091d7f65b7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: memory_entries\n\nDocumentation:\nAppends an item to `memory_entries`.\n\nTo override the contents of this collection use\n[`set_memory_entries`](Self::set_memory_entries).\n\nList of user memories\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn memory_entries(mut self, input: crate::types::MemoryEntry) -> Self {\n let mut v = self.memory_entries.unwrap_or_default();\n v.push(input);\n self.memory_entries = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "memory_entries", "docstring": "Appends an item to `memory_entries`.\n\nTo override the contents of this collection use\n[`set_memory_entries`](Self::set_memory_entries).\n\nList of user memories", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_user_memory_entries/_list_user_memory_entries_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_user_memory_entries/_list_user_memory_entries_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0241051fc2074a8b7efeeaba3dca1571ca34484c25f35a7490babcfdbf55d489"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListUserMemoryEntriesOutput`](crate::operation::list_user_memory_entries::ListUserMemoryEntriesOutput).\nThis method will fail if any of the following fields are not set:\n- [`memory_entries`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesOutputBuilder::memory_entries)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_user_memory_entries::ListUserMemoryEntriesOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::list_user_memory_entries::ListUserMemoryEntriesOutput {\n memory_entries: self.memory_entries.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"memory_entries\",\n \"memory_entries was not specified but it is required when building ListUserMemoryEntriesOutput\",\n )\n })?,\n next_token: self.next_token,\n _request_id: self._request_id,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListUserMemoryEntriesOutput`](crate::operation::list_user_memory_entries::ListUserMemoryEntriesOutput).\nThis method will fail if any of the following fields are not set:\n- [`memory_entries`](crate::operation::list_user_memory_entries::builders::ListUserMemoryEntriesOutputBuilder::memory_entries)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_user_memory_entries/_list_user_memory_entries_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_user_memory_entries/_list_user_memory_entries_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "57a3504d5a3b29e7849bac42f0c9a1cb3afb39b374466357d9175d3920cf54f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListWorkspaceMetadataInput`](crate::operation::list_workspace_metadata::ListWorkspaceMetadataInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_workspace_metadata::ListWorkspaceMetadataInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_workspace_metadata::ListWorkspaceMetadataInput {\n workspace_root: self.workspace_root,\n next_token: self.next_token,\n max_results: self.max_results,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListWorkspaceMetadataInput`](crate::operation::list_workspace_metadata::ListWorkspaceMetadataInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_workspace_metadata/_list_workspace_metadata_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_workspace_metadata/_list_workspace_metadata_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "af946304ea12b208673d006fca18ad1c211652e5adda0eab4f037ae3795e5475"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: workspaces\n\nDocumentation:\nAppends an item to `workspaces`.\n\nTo override the contents of this collection use [`set_workspaces`](Self::set_workspaces).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn workspaces(mut self, input: crate::types::WorkspaceMetadata) -> Self {\n let mut v = self.workspaces.unwrap_or_default();\n v.push(input);\n self.workspaces = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "workspaces", "docstring": "Appends an item to `workspaces`.\n\nTo override the contents of this collection use [`set_workspaces`](Self::set_workspaces).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_workspace_metadata/_list_workspace_metadata_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_workspace_metadata/_list_workspace_metadata_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "41960dc8941069aefba1618ddc47d1fd33a569de65702989cbefdea35294d3b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListWorkspaceMetadataOutput`](crate::operation::list_workspace_metadata::ListWorkspaceMetadataOutput).\nThis method will fail if any of the following fields are not set:\n- [`workspaces`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataOutputBuilder::workspaces)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_workspace_metadata::ListWorkspaceMetadataOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_workspace_metadata::ListWorkspaceMetadataOutput {\n workspaces: self.workspaces.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"workspaces\",\n \"workspaces was not specified but it is required when building ListWorkspaceMetadataOutput\",\n )\n })?,\n next_token: self.next_token,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListWorkspaceMetadataOutput`](crate::operation::list_workspace_metadata::ListWorkspaceMetadataOutput).\nThis method will fail if any of the following fields are not set:\n- [`workspaces`](crate::operation::list_workspace_metadata::builders::ListWorkspaceMetadataOutputBuilder::workspaces)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/list_workspace_metadata/_list_workspace_metadata_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/list_workspace_metadata/_list_workspace_metadata_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "22493aa76b60998b04ebe4f65587b04cd3483d3201c8dc1e9f74d93ac0ad682d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`PushTelemetryEventInput`](crate::operation::push_telemetry_event::PushTelemetryEventInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::push_telemetry_event::PushTelemetryEventInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::push_telemetry_event::PushTelemetryEventInput {\n client_token: self.client_token,\n event_type: self.event_type,\n event: self.event,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`PushTelemetryEventInput`](crate::operation::push_telemetry_event::PushTelemetryEventInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/push_telemetry_event/_push_telemetry_event_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/push_telemetry_event/_push_telemetry_event_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "40100732b24f4c36ec2b185234b0e204ceeab4360b273b065f52f0f1b38cbb6c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`PushTelemetryEventOutput`](crate::operation::push_telemetry_event::PushTelemetryEventOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::push_telemetry_event::PushTelemetryEventOutput {\n crate::operation::push_telemetry_event::PushTelemetryEventOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`PushTelemetryEventOutput`](crate::operation::push_telemetry_event::PushTelemetryEventOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/push_telemetry_event/_push_telemetry_event_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/push_telemetry_event/_push_telemetry_event_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ea59aa8c055f1a9d10cae9032ce9df47bb8bb30758d60b40d39faa4f3e04d10"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ResumeTransformationInput`](crate::operation::resume_transformation::ResumeTransformationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::resume_transformation::ResumeTransformationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::resume_transformation::ResumeTransformationInput {\n transformation_job_id: self.transformation_job_id,\n user_action_status: self.user_action_status,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ResumeTransformationInput`](crate::operation::resume_transformation::ResumeTransformationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/resume_transformation/_resume_transformation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/resume_transformation/_resume_transformation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "26f02bbe082370508f6c709e8aea43d03773cf4b0be530fb53f1d663ec70f7b5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ResumeTransformationOutput`](crate::operation::resume_transformation::ResumeTransformationOutput).\nThis method will fail if any of the following fields are not set:\n- [`transformation_status`](crate::operation::resume_transformation::builders::ResumeTransformationOutputBuilder::transformation_status)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::resume_transformation::ResumeTransformationOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::resume_transformation::ResumeTransformationOutput {\n transformation_status: self.transformation_status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"transformation_status\",\n \"transformation_status was not specified but it is required when building ResumeTransformationOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ResumeTransformationOutput`](crate::operation::resume_transformation::ResumeTransformationOutput).\nThis method will fail if any of the following fields are not set:\n- [`transformation_status`](crate::operation::resume_transformation::builders::ResumeTransformationOutputBuilder::transformation_status)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/resume_transformation/_resume_transformation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/resume_transformation/_resume_transformation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "408e6ab0986730787a4209db4d06b69311aaa587199546920d51706342e3d018"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`SendTelemetryEventInput`](crate::operation::send_telemetry_event::SendTelemetryEventInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::send_telemetry_event::SendTelemetryEventInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::send_telemetry_event::SendTelemetryEventInput {\n client_token: self.client_token,\n telemetry_event: self.telemetry_event,\n opt_out_preference: self.opt_out_preference,\n user_context: self.user_context,\n profile_arn: self.profile_arn,\n model_id: self.model_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`SendTelemetryEventInput`](crate::operation::send_telemetry_event::SendTelemetryEventInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/send_telemetry_event/_send_telemetry_event_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/send_telemetry_event/_send_telemetry_event_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "20a6ec8ab80889a47310fa28cf5772e2dd630bcec6bf12cbafcf40d80f893409"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`SendTelemetryEventOutput`](crate::operation::send_telemetry_event::SendTelemetryEventOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::send_telemetry_event::SendTelemetryEventOutput {\n crate::operation::send_telemetry_event::SendTelemetryEventOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`SendTelemetryEventOutput`](crate::operation::send_telemetry_event::SendTelemetryEventOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/send_telemetry_event/_send_telemetry_event_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/send_telemetry_event/_send_telemetry_event_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "55ad6f9c731a4450c4d2500b1b99192910b68be77bffd35e6f948048aa25ee54"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: artifacts\n\nDocumentation:\nAdds a key-value pair to `artifacts`.\n\nTo override the contents of this collection use [`set_artifacts`](Self::set_artifacts).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn artifacts(\n mut self,\n k: crate::types::ArtifactType,\n v: impl ::std::convert::Into<::std::string::String>,\n ) -> Self {\n let mut hash_map = self.artifacts.unwrap_or_default();\n hash_map.insert(k, v.into());\n self.artifacts = ::std::option::Option::Some(hash_map);\n self\n }\n```"}], "func_name": "artifacts", "docstring": "Adds a key-value pair to `artifacts`.\n\nTo override the contents of this collection use [`set_artifacts`](Self::set_artifacts).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_code_analysis/_start_code_analysis_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_code_analysis/_start_code_analysis_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6aa3fa9217077d1bacc4f7a0f3a49bcd80fa90bce53f0a2a0e5572ad257d174a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: programming_language\n\nDocumentation:\nProgramming Languages supported by CodeWhisperer\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn programming_language(mut self, input: crate::types::ProgrammingLanguage) -> Self {\n self.programming_language = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "programming_language", "docstring": "Programming Languages supported by CodeWhisperer\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_code_analysis/_start_code_analysis_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_code_analysis/_start_code_analysis_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "395f64395e2012283f43c9c38a3b641a836f9521cddb10db25d5bb6e8aaa8d48"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`StartCodeAnalysisInput`](crate::operation::start_code_analysis::StartCodeAnalysisInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::start_code_analysis::StartCodeAnalysisInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::start_code_analysis::StartCodeAnalysisInput {\n artifacts: self.artifacts,\n programming_language: self.programming_language,\n client_token: self.client_token,\n scope: self.scope,\n code_scan_name: self.code_scan_name,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`StartCodeAnalysisInput`](crate::operation::start_code_analysis::StartCodeAnalysisInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_code_analysis/_start_code_analysis_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_code_analysis/_start_code_analysis_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5a6215590512f80780674b1a04a14c545079dd557b11e364e09abc808cfb016"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`StartCodeAnalysisOutput`](crate::operation::start_code_analysis::StartCodeAnalysisOutput).\nThis method will fail if any of the following fields are not set:\n- [`job_id`](crate::operation::start_code_analysis::builders::StartCodeAnalysisOutputBuilder::job_id)\n- [`status`](crate::operation::start_code_analysis::builders::StartCodeAnalysisOutputBuilder::status)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::start_code_analysis::StartCodeAnalysisOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::start_code_analysis::StartCodeAnalysisOutput {\n job_id: self.job_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"job_id\",\n \"job_id was not specified but it is required when building StartCodeAnalysisOutput\",\n )\n })?,\n status: self.status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"status\",\n \"status was not specified but it is required when building StartCodeAnalysisOutput\",\n )\n })?,\n error_message: self.error_message,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`StartCodeAnalysisOutput`](crate::operation::start_code_analysis::StartCodeAnalysisOutput).\nThis method will fail if any of the following fields are not set:\n- [`job_id`](crate::operation::start_code_analysis::builders::StartCodeAnalysisOutputBuilder::job_id)\n- [`status`](crate::operation::start_code_analysis::builders::StartCodeAnalysisOutputBuilder::status)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_code_analysis/_start_code_analysis_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_code_analysis/_start_code_analysis_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "68f8bea900b7d5b2b205c9b066858506293b5191cbd4a0dec1e3651d27ed71e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: snippet_range\n\nDocumentation:\nIndicates Range / Span in a Text Document\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn snippet_range(mut self, input: crate::types::Range) -> Self {\n self.inner = self.inner.snippet_range(input);\n self\n }\n```"}], "func_name": "snippet_range", "docstring": "Indicates Range / Span in a Text Document", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_code_fix_job/builders.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_code_fix_job/builders.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "10b04ed4ab51c7ba1cedeb75ea0b897e0fe9fff0bf623471e6cd04f9badf5e2c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: snippet_range\n\nDocumentation:\nIndicates Range / Span in a Text Document\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn snippet_range(mut self, input: crate::types::Range) -> Self {\n self.snippet_range = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "snippet_range", "docstring": "Indicates Range / Span in a Text Document\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_code_fix_job/_start_code_fix_job_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_code_fix_job/_start_code_fix_job_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6530b9eb7e93c148a722416f60f107aa28b9f7048f5adaec87c72f08aaee184"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`StartCodeFixJobInput`](crate::operation::start_code_fix_job::StartCodeFixJobInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::start_code_fix_job::StartCodeFixJobInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::start_code_fix_job::StartCodeFixJobInput {\n snippet_range: self.snippet_range,\n upload_id: self.upload_id,\n description: self.description,\n rule_id: self.rule_id,\n code_fix_name: self.code_fix_name,\n reference_tracker_configuration: self.reference_tracker_configuration,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`StartCodeFixJobInput`](crate::operation::start_code_fix_job::StartCodeFixJobInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_code_fix_job/_start_code_fix_job_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_code_fix_job/_start_code_fix_job_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f88b1c1acc1579470e63b8af316f3ec21920bf248709fc81e786fc0ccc008a1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`StartCodeFixJobOutput`](crate::operation::start_code_fix_job::StartCodeFixJobOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::start_code_fix_job::StartCodeFixJobOutput {\n crate::operation::start_code_fix_job::StartCodeFixJobOutput {\n job_id: self.job_id,\n status: self.status,\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`StartCodeFixJobOutput`](crate::operation::start_code_fix_job::StartCodeFixJobOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_code_fix_job/_start_code_fix_job_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_code_fix_job/_start_code_fix_job_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d5a8caac80b211b6b5bf674424d08b04e4d267770724e44a969c4daecc8d427"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: conversation_state\n\nDocumentation:\nStructure to represent the current state of a chat conversation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn conversation_state(mut self, input: crate::types::ConversationState) -> Self {\n self.inner = self.inner.conversation_state(input);\n self\n }\n```"}], "func_name": "conversation_state", "docstring": "Structure to represent the current state of a chat conversation.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/builders.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/builders.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "92ed4fd207a70283e5f75717e8e971135d232110029d260c7e72630b6e87494c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: workspace_state\n\nDocumentation:\nRepresents a Workspace state uploaded to S3 for Async Code Actions\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn workspace_state(mut self, input: crate::types::WorkspaceState) -> Self {\n self.inner = self.inner.workspace_state(input);\n self\n }\n```"}], "func_name": "workspace_state", "docstring": "Represents a Workspace state uploaded to S3 for Async Code Actions", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/builders.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/builders.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "de6d8b53b31f08bf567c97788e9510e066ab626125d2bdf5583c29bdefda4d74"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`StartTaskAssistCodeGenerationInput`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationInputBuilder {\n crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationInputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`StartTaskAssistCodeGenerationInput`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/_start_task_assist_code_generation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/_start_task_assist_code_generation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d9ffa95243c4d6910fc5416185a56a4e29059bb07067bec50c9919c8b014463"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: workspace_state\n\nDocumentation:\nRepresents a Workspace state uploaded to S3 for Async Code Actions\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn workspace_state(mut self, input: crate::types::WorkspaceState) -> Self {\n self.workspace_state = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "workspace_state", "docstring": "Represents a Workspace state uploaded to S3 for Async Code Actions\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/_start_task_assist_code_generation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/_start_task_assist_code_generation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fb7eb9064c278ca2c72bc1bf15cfb773f490cf6c02729e552c5938a3a6dcfae7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: task_assist_plan\n\nDocumentation:\nAppends an item to `task_assist_plan`.\n\nTo override the contents of this collection use\n[`set_task_assist_plan`](Self::set_task_assist_plan).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn task_assist_plan(mut self, input: crate::types::TaskAssistPlanStep) -> Self {\n let mut v = self.task_assist_plan.unwrap_or_default();\n v.push(input);\n self.task_assist_plan = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "task_assist_plan", "docstring": "Appends an item to `task_assist_plan`.\n\nTo override the contents of this collection use\n[`set_task_assist_plan`](Self::set_task_assist_plan).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/_start_task_assist_code_generation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/_start_task_assist_code_generation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e8efe84d037bdec160459829f9a3d690ad1fd8dc6971a05861933b26f002101b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`StartTaskAssistCodeGenerationInput`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationInput {\n conversation_state: self.conversation_state,\n workspace_state: self.workspace_state,\n task_assist_plan: self.task_assist_plan,\n code_generation_id: self.code_generation_id,\n current_code_generation_id: self.current_code_generation_id,\n intent: self.intent,\n intent_context: self.intent_context,\n profile_arn: self.profile_arn,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`StartTaskAssistCodeGenerationInput`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/_start_task_assist_code_generation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/_start_task_assist_code_generation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1fde7dd5de87ad0e41947b1e14012c636ed4e7c1a6f92e36b9776bfdc9ae7c52"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`StartTaskAssistCodeGenerationOutput`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationOutputBuilder {\n crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationOutputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`StartTaskAssistCodeGenerationOutput`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/_start_task_assist_code_generation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/_start_task_assist_code_generation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c57a164bac9024c8671ed3693fe9d6bf09fd38a7f143facc22e8be95cce99f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`StartTaskAssistCodeGenerationOutput`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationOutput).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationOutputBuilder::conversation_id)\n- [`code_generation_id`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationOutputBuilder::code_generation_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationOutput {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building StartTaskAssistCodeGenerationOutput\",\n )\n })?,\n code_generation_id: self.code_generation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"code_generation_id\",\n \"code_generation_id was not specified but it is required when building StartTaskAssistCodeGenerationOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`StartTaskAssistCodeGenerationOutput`](crate::operation::start_task_assist_code_generation::StartTaskAssistCodeGenerationOutput).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationOutputBuilder::conversation_id)\n- [`code_generation_id`](crate::operation::start_task_assist_code_generation::builders::StartTaskAssistCodeGenerationOutputBuilder::code_generation_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/_start_task_assist_code_generation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_task_assist_code_generation/_start_task_assist_code_generation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4973535257e19a0f5327c822330ebc74553224be8eceb1bf83f91f58bffbb7c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: target_code_list\n\nDocumentation:\nAppends an item to `target_code_list`.\n\nTo override the contents of this collection use\n[`set_target_code_list`](Self::set_target_code_list).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn target_code_list(mut self, input: crate::types::TargetCode) -> Self {\n let mut v = self.target_code_list.unwrap_or_default();\n v.push(input);\n self.target_code_list = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "target_code_list", "docstring": "Appends an item to `target_code_list`.\n\nTo override the contents of this collection use\n[`set_target_code_list`](Self::set_target_code_list).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_test_generation/_start_test_generation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_test_generation/_start_test_generation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aa63af2d30ed7bb450480bfd15bdd18d331587af88f2c8878e042036fab49e42"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: user_input\n\nDocumentation:\nThe content of user input.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn user_input(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.user_input = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "user_input", "docstring": "The content of user input.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_test_generation/_start_test_generation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_test_generation/_start_test_generation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "89966107d3385f3123945a985986e55beaff5b9f4807975954e7b5e5632a9158"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`StartTestGenerationInput`](crate::operation::start_test_generation::StartTestGenerationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::start_test_generation::StartTestGenerationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::start_test_generation::StartTestGenerationInput {\n upload_id: self.upload_id,\n target_code_list: self.target_code_list,\n user_input: self.user_input,\n test_generation_job_group_name: self.test_generation_job_group_name,\n client_token: self.client_token,\n profile_arn: self.profile_arn,\n reference_tracker_configuration: self.reference_tracker_configuration,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`StartTestGenerationInput`](crate::operation::start_test_generation::StartTestGenerationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_test_generation/_start_test_generation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_test_generation/_start_test_generation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eacc979c16d8d03a9ea7563a6b0afde70cdeef37caeb37529a4016fe45490fca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`StartTestGenerationOutput`](crate::operation::start_test_generation::StartTestGenerationOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::start_test_generation::StartTestGenerationOutput {\n crate::operation::start_test_generation::StartTestGenerationOutput {\n test_generation_job: self.test_generation_job,\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`StartTestGenerationOutput`](crate::operation::start_test_generation::StartTestGenerationOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_test_generation/_start_test_generation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_test_generation/_start_test_generation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "edcfb2bbda72165c4b66ac2968540fefbaf60173f260a15917153ea3d206c7d2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`StartTransformationInput`](crate::operation::start_transformation::StartTransformationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::start_transformation::StartTransformationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::start_transformation::StartTransformationInput {\n workspace_state: self.workspace_state,\n transformation_spec: self.transformation_spec,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`StartTransformationInput`](crate::operation::start_transformation::StartTransformationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_transformation/_start_transformation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_transformation/_start_transformation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b19c6f593fe35cd6c9e47a14f1c8876aec20dc382ff89cb633dd11a974df3c8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`StartTransformationOutput`](crate::operation::start_transformation::StartTransformationOutput).\nThis method will fail if any of the following fields are not set:\n- [`transformation_job_id`](crate::operation::start_transformation::builders::StartTransformationOutputBuilder::transformation_job_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::start_transformation::StartTransformationOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::start_transformation::StartTransformationOutput {\n transformation_job_id: self.transformation_job_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"transformation_job_id\",\n \"transformation_job_id was not specified but it is required when building StartTransformationOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`StartTransformationOutput`](crate::operation::start_transformation::StartTransformationOutput).\nThis method will fail if any of the following fields are not set:\n- [`transformation_job_id`](crate::operation::start_transformation::builders::StartTransformationOutputBuilder::transformation_job_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/start_transformation/_start_transformation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/start_transformation/_start_transformation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eaa7d8fe4ad800c4dbe497ce32ce8188ae1dcc35df8914efcda9e4a080cab894"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`StopTransformationInput`](crate::operation::stop_transformation::StopTransformationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::stop_transformation::StopTransformationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::stop_transformation::StopTransformationInput {\n transformation_job_id: self.transformation_job_id,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`StopTransformationInput`](crate::operation::stop_transformation::StopTransformationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/stop_transformation/_stop_transformation_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/stop_transformation/_stop_transformation_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e7f00ca85186ea2ae2d29c521c88a1577b2f39333f4d3c83fdbe1237853a40d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`StopTransformationOutput`](crate::operation::stop_transformation::StopTransformationOutput).\nThis method will fail if any of the following fields are not set:\n- [`transformation_status`](crate::operation::stop_transformation::builders::StopTransformationOutputBuilder::transformation_status)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::stop_transformation::StopTransformationOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::stop_transformation::StopTransformationOutput {\n transformation_status: self.transformation_status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"transformation_status\",\n \"transformation_status was not specified but it is required when building StopTransformationOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`StopTransformationOutput`](crate::operation::stop_transformation::StopTransformationOutput).\nThis method will fail if any of the following fields are not set:\n- [`transformation_status`](crate::operation::stop_transformation::builders::StopTransformationOutputBuilder::transformation_status)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/operation/stop_transformation/_stop_transformation_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/operation/stop_transformation/_stop_transformation_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e10064f303636523878345770abcfe001d4d90fd2bd6d3d5286d8c01df1f1886"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_str\n\nDocumentation:\nReturns the `&str` value of the enum member.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_str(&self) -> &str {\n match self {\n AccessDeniedExceptionReason::UnauthorizedCustomizationResourceAccess => {\n \"UNAUTHORIZED_CUSTOMIZATION_RESOURCE_ACCESS\"\n },\n AccessDeniedExceptionReason::UnauthorizedWorkspaceContextFeatureAccess => {\n \"UNAUTHORIZED_WORKSPACE_CONTEXT_FEATURE_ACCESS\"\n },\n AccessDeniedExceptionReason::Unknown(value) => value.as_str(),\n }\n }\n```"}], "func_name": "as_str", "docstring": "Returns the `&str` value of the enum member.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_access_denied_exception_reason.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_access_denied_exception_reason.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8aa49ebe0033a7e81bf66566fd8a918af423ead2d75cb35d089ff48caf9ebc99"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: values\n\nDocumentation:\nReturns all the `&str` representations of the enum members.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn values() -> &'static [&'static str] {\n &[\n \"UNAUTHORIZED_CUSTOMIZATION_RESOURCE_ACCESS\",\n \"UNAUTHORIZED_WORKSPACE_CONTEXT_FEATURE_ACCESS\",\n ]\n }\n```"}], "func_name": "values", "docstring": "Returns all the `&str` representations of the enum members.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_access_denied_exception_reason.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_access_denied_exception_reason.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e243945ba89a13eba78069f1d6d7d5f0864d7539ae1bbeea29824144e9fda36"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`AdditionalContentEntry`](crate::types::AdditionalContentEntry). This method will fail\nif any of the following fields are not set:\n- [`name`](crate::types::builders::AdditionalContentEntryBuilder::name)\n- [`description`](crate::types::builders::AdditionalContentEntryBuilder::description)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::AdditionalContentEntry {\n name: self.name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"name\",\n \"name was not specified but it is required when building AdditionalContentEntry\",\n )\n })?,\n description: self.description.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"description\",\n \"description was not specified but it is required when building AdditionalContentEntry\",\n )\n })?,\n inner_context: self.inner_context,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`AdditionalContentEntry`](crate::types::AdditionalContentEntry). This method will fail\nif any of the following fields are not set:\n- [`name`](crate::types::builders::AdditionalContentEntryBuilder::name)\n- [`description`](crate::types::builders::AdditionalContentEntryBuilder::description)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_additional_content_entry.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_additional_content_entry.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7fda7b6919724518e7c340e7f976697a5438d3d1543bb90fe6d54afdf58388a9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ApplicationProperties`](crate::types::ApplicationProperties). This method will fail if\nany of the following fields are not set:\n- [`tenant_id`](crate::types::builders::ApplicationPropertiesBuilder::tenant_id)\n- [`application_arn`](crate::types::builders::ApplicationPropertiesBuilder::application_arn)\n- [`tenant_url`](crate::types::builders::ApplicationPropertiesBuilder::tenant_url)\n- [`application_type`](crate::types::builders::ApplicationPropertiesBuilder::application_type)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::ApplicationProperties {\n tenant_id: self.tenant_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"tenant_id\",\n \"tenant_id was not specified but it is required when building ApplicationProperties\",\n )\n })?,\n application_arn: self.application_arn.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"application_arn\",\n \"application_arn was not specified but it is required when building ApplicationProperties\",\n )\n })?,\n tenant_url: self.tenant_url.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"tenant_url\",\n \"tenant_url was not specified but it is required when building ApplicationProperties\",\n )\n })?,\n application_type: self.application_type.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"application_type\",\n \"application_type was not specified but it is required when building ApplicationProperties\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ApplicationProperties`](crate::types::ApplicationProperties). This method will fail if\nany of the following fields are not set:\n- [`tenant_id`](crate::types::builders::ApplicationPropertiesBuilder::tenant_id)\n- [`application_arn`](crate::types::builders::ApplicationPropertiesBuilder::application_arn)\n- [`tenant_url`](crate::types::builders::ApplicationPropertiesBuilder::tenant_url)\n- [`application_type`](crate::types::builders::ApplicationPropertiesBuilder::application_type)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_application_properties.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_application_properties.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "42a784d934d413d4235b76df8eb5bdf9901ed5dc44946cb1ac22e3b550cd0ab4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: property_context\n\nDocumentation:\nContext about how the property is used\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn property_context(&self) -> &str {\n use std::ops::Deref;\n self.property_context.deref()\n }\n```"}], "func_name": "property_context", "docstring": "Context about how the property is used", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_app_studio_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_app_studio_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3ee067b38df6a33b2c48ad1a4eb72df57ed1c2da96c4a67dc3d792e2f71b5466"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: property_context\n\nDocumentation:\nContext about how the property is used\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn property_context(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.property_context = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "property_context", "docstring": "Context about how the property is used\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_app_studio_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_app_studio_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51aa3113a4d559ded0e901fca57bec0b9b6cced1b9b5ab2b4d4edafa25906696"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`AppStudioState`](crate::types::AppStudioState).\nThis method will fail if any of the following fields are not set:\n- [`namespace`](crate::types::builders::AppStudioStateBuilder::namespace)\n- [`property_name`](crate::types::builders::AppStudioStateBuilder::property_name)\n- [`property_context`](crate::types::builders::AppStudioStateBuilder::property_context)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::AppStudioState {\n namespace: self.namespace.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"namespace\",\n \"namespace was not specified but it is required when building AppStudioState\",\n )\n })?,\n property_name: self.property_name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"property_name\",\n \"property_name was not specified but it is required when building AppStudioState\",\n )\n })?,\n property_value: self.property_value,\n property_context: self.property_context.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"property_context\",\n \"property_context was not specified but it is required when building AppStudioState\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`AppStudioState`](crate::types::AppStudioState).\nThis method will fail if any of the following fields are not set:\n- [`namespace`](crate::types::builders::AppStudioStateBuilder::namespace)\n- [`property_name`](crate::types::builders::AppStudioStateBuilder::property_name)\n- [`property_context`](crate::types::builders::AppStudioStateBuilder::property_context)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_app_studio_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_app_studio_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f88e9d6f683a94edf0d70ab303d5f0e1290cebea8778042dfc6b7a6da68afac2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: supplementary_web_links\n\nDocumentation:\nAppends an item to `supplementary_web_links`.\n\nTo override the contents of this collection use\n[`set_supplementary_web_links`](Self::set_supplementary_web_links).\n\nWeb References\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn supplementary_web_links(mut self, input: crate::types::SupplementaryWebLink) -> Self {\n let mut v = self.supplementary_web_links.unwrap_or_default();\n v.push(input);\n self.supplementary_web_links = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "supplementary_web_links", "docstring": "Appends an item to `supplementary_web_links`.\n\nTo override the contents of this collection use\n[`set_supplementary_web_links`](Self::set_supplementary_web_links).\n\nWeb References", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_assistant_response_message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_assistant_response_message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb2722d2bfebf435250ff94b3296a955b8f5bf2e4df30a06f21ccb5fb2cabbfb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: references\n\nDocumentation:\nAppends an item to `references`.\n\nTo override the contents of this collection use [`set_references`](Self::set_references).\n\nCode References\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn references(mut self, input: crate::types::Reference) -> Self {\n let mut v = self.references.unwrap_or_default();\n v.push(input);\n self.references = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "references", "docstring": "Appends an item to `references`.\n\nTo override the contents of this collection use [`set_references`](Self::set_references).\n\nCode References", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_assistant_response_message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_assistant_response_message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "435b80888a623d71b26eee63bd5d3e7f2ecf6c8dbfbbec3b82a990afcba1a569"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tool_uses\n\nDocumentation:\nAppends an item to `tool_uses`.\n\nTo override the contents of this collection use [`set_tool_uses`](Self::set_tool_uses).\n\nToolUse Request\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn tool_uses(mut self, input: crate::types::ToolUse) -> Self {\n let mut v = self.tool_uses.unwrap_or_default();\n v.push(input);\n self.tool_uses = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "tool_uses", "docstring": "Appends an item to `tool_uses`.\n\nTo override the contents of this collection use [`set_tool_uses`](Self::set_tool_uses).\n\nToolUse Request", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_assistant_response_message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_assistant_response_message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e8c871fd5e8ed12253c1952eaa0c7cd3110fd608b21640ee5e2ee44b5a8dd45a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`AssistantResponseMessage`](crate::types::AssistantResponseMessage). This method will\nfail if any of the following fields are not set:\n- [`content`](crate::types::builders::AssistantResponseMessageBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::AssistantResponseMessage {\n message_id: self.message_id,\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building AssistantResponseMessage\",\n )\n })?,\n supplementary_web_links: self.supplementary_web_links,\n references: self.references,\n followup_prompt: self.followup_prompt,\n tool_uses: self.tool_uses,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`AssistantResponseMessage`](crate::types::AssistantResponseMessage). This method will\nfail if any of the following fields are not set:\n- [`content`](crate::types::builders::AssistantResponseMessageBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_assistant_response_message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_assistant_response_message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "98324c80d058b5e22447e510697ac781737161df91fdc9b98a949f5e2d685428"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ByUserAnalytics`](crate::types::ByUserAnalytics).\nThis method will fail if any of the following fields are not set:\n- [`toggle`](crate::types::builders::ByUserAnalyticsBuilder::toggle)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::ByUserAnalytics {\n s3_uri: self.s3_uri,\n toggle: self.toggle.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"toggle\",\n \"toggle was not specified but it is required when building ByUserAnalytics\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ByUserAnalytics`](crate::types::ByUserAnalytics).\nThis method will fail if any of the following fields are not set:\n- [`toggle`](crate::types::builders::ByUserAnalyticsBuilder::toggle)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_by_user_analytics.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_by_user_analytics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25905f1a48ff0c25a6f5e552e239439a99612dce55c23be0d27bafc3ad83d926"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ChangeLogOptions`](crate::types::ChangeLogOptions).\nThis method will fail if any of the following fields are not set:\n- [`granularity`](crate::types::builders::ChangeLogOptionsBuilder::granularity)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::ChangeLogOptions {\n granularity: self.granularity.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"granularity\",\n \"granularity was not specified but it is required when building ChangeLogOptions\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ChangeLogOptions`](crate::types::ChangeLogOptions).\nThis method will fail if any of the following fields are not set:\n- [`granularity`](crate::types::builders::ChangeLogOptionsBuilder::granularity)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_change_log_options.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_change_log_options.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b9d2fa9bb7dce16559348701ec6a9ccfecbf2cc1e29f5f1efc330005ef36403e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: time_between_chunks\n\nDocumentation:\nAppends an item to `time_between_chunks`.\n\nTo override the contents of this collection use\n[`set_time_between_chunks`](Self::set_time_between_chunks).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn time_between_chunks(mut self, input: f64) -> Self {\n let mut v = self.time_between_chunks.unwrap_or_default();\n v.push(input);\n self.time_between_chunks = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "time_between_chunks", "docstring": "Appends an item to `time_between_chunks`.\n\nTo override the contents of this collection use\n[`set_time_between_chunks`](Self::set_time_between_chunks).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_chat_add_message_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_chat_add_message_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c3036a21e3200bac7dde93b79414f160b3b9d923a1ba3ea745bd333bedb47b9c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ChatAddMessageEvent`](crate::types::ChatAddMessageEvent). This method will fail if any\nof the following fields are not set:\n- [`conversation_id`](crate::types::builders::ChatAddMessageEventBuilder::conversation_id)\n- [`message_id`](crate::types::builders::ChatAddMessageEventBuilder::message_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::ChatAddMessageEvent {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building ChatAddMessageEvent\",\n )\n })?,\n message_id: self.message_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message_id\",\n \"message_id was not specified but it is required when building ChatAddMessageEvent\",\n )\n })?,\n customization_arn: self.customization_arn,\n user_intent: self.user_intent,\n has_code_snippet: self.has_code_snippet,\n programming_language: self.programming_language,\n active_editor_total_characters: self.active_editor_total_characters,\n time_to_first_chunk_milliseconds: self.time_to_first_chunk_milliseconds,\n time_between_chunks: self.time_between_chunks,\n full_responselatency: self.full_responselatency,\n request_length: self.request_length,\n response_length: self.response_length,\n number_of_code_blocks: self.number_of_code_blocks,\n has_project_level_context: self.has_project_level_context,\n result: self.result,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ChatAddMessageEvent`](crate::types::ChatAddMessageEvent). This method will fail if any\nof the following fields are not set:\n- [`conversation_id`](crate::types::builders::ChatAddMessageEventBuilder::conversation_id)\n- [`message_id`](crate::types::builders::ChatAddMessageEventBuilder::message_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_chat_add_message_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_chat_add_message_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1662ba968bb695c21c763ac0afed935ada04c7b0e87bd49da211ffcc6f72c622"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: added_ide_diagnostics\n\nDocumentation:\nAppends an item to `added_ide_diagnostics`.\n\nTo override the contents of this collection use\n[`set_added_ide_diagnostics`](Self::set_added_ide_diagnostics).\n\nList of IDE Diagnostics\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn added_ide_diagnostics(mut self, input: crate::types::IdeDiagnostic) -> Self {\n let mut v = self.added_ide_diagnostics.unwrap_or_default();\n v.push(input);\n self.added_ide_diagnostics = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "added_ide_diagnostics", "docstring": "Appends an item to `added_ide_diagnostics`.\n\nTo override the contents of this collection use\n[`set_added_ide_diagnostics`](Self::set_added_ide_diagnostics).\n\nList of IDE Diagnostics", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_chat_interact_with_message_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_chat_interact_with_message_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f4c188ecea9fa3de4a77ce102ded65753e0444fa28b15f7787a046d7b7e41158"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: removed_ide_diagnostics\n\nDocumentation:\nAppends an item to `removed_ide_diagnostics`.\n\nTo override the contents of this collection use\n[`set_removed_ide_diagnostics`](Self::set_removed_ide_diagnostics).\n\nList of IDE Diagnostics\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn removed_ide_diagnostics(mut self, input: crate::types::IdeDiagnostic) -> Self {\n let mut v = self.removed_ide_diagnostics.unwrap_or_default();\n v.push(input);\n self.removed_ide_diagnostics = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "removed_ide_diagnostics", "docstring": "Appends an item to `removed_ide_diagnostics`.\n\nTo override the contents of this collection use\n[`set_removed_ide_diagnostics`](Self::set_removed_ide_diagnostics).\n\nList of IDE Diagnostics", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_chat_interact_with_message_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_chat_interact_with_message_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c2351e28ccbf83b591b5edb107a3924f13cbd0a5766447f4b4f6deed9ae49ecc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ChatInteractWithMessageEvent`](crate::types::ChatInteractWithMessageEvent).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::types::builders::ChatInteractWithMessageEventBuilder::conversation_id)\n- [`message_id`](crate::types::builders::ChatInteractWithMessageEventBuilder::message_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::ChatInteractWithMessageEvent,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::ChatInteractWithMessageEvent {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building ChatInteractWithMessageEvent\",\n )\n })?,\n message_id: self.message_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message_id\",\n \"message_id was not specified but it is required when building ChatInteractWithMessageEvent\",\n )\n })?,\n customization_arn: self.customization_arn,\n interaction_type: self.interaction_type,\n interaction_target: self.interaction_target,\n accepted_character_count: self.accepted_character_count,\n accepted_line_count: self.accepted_line_count,\n accepted_snippet_has_reference: self.accepted_snippet_has_reference,\n has_project_level_context: self.has_project_level_context,\n user_intent: self.user_intent,\n added_ide_diagnostics: self.added_ide_diagnostics,\n removed_ide_diagnostics: self.removed_ide_diagnostics,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ChatInteractWithMessageEvent`](crate::types::ChatInteractWithMessageEvent).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::types::builders::ChatInteractWithMessageEventBuilder::conversation_id)\n- [`message_id`](crate::types::builders::ChatInteractWithMessageEventBuilder::message_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_chat_interact_with_message_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_chat_interact_with_message_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "77a522b5baebc28b05eb9bbb490d92b95836647f7c060b243977a6f738fbbbf7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_assistant_response_message\n\nDocumentation:\nTries to convert the enum instance into\n[`AssistantResponseMessage`](crate::types::ChatMessage::AssistantResponseMessage),\nextracting the inner [`AssistantResponseMessage`](crate::types::AssistantResponseMessage).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_assistant_response_message(\n &self,\n ) -> ::std::result::Result<&crate::types::AssistantResponseMessage, &Self> {\n if let ChatMessage::AssistantResponseMessage(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_assistant_response_message", "docstring": "Tries to convert the enum instance into\n[`AssistantResponseMessage`](crate::types::ChatMessage::AssistantResponseMessage),\nextracting the inner [`AssistantResponseMessage`](crate::types::AssistantResponseMessage).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_chat_message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_chat_message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3feae92d1aab5fb51905056840f7db4ad660b9259304d79d58db2197ba0ef0f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_user_input_message\n\nDocumentation:\nTries to convert the enum instance into\n[`UserInputMessage`](crate::types::ChatMessage::UserInputMessage), extracting the inner\n[`UserInputMessage`](crate::types::UserInputMessage). Returns `Err(&Self)` if it can't\nbe converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_user_input_message(&self) -> ::std::result::Result<&crate::types::UserInputMessage, &Self> {\n if let ChatMessage::UserInputMessage(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_user_input_message", "docstring": "Tries to convert the enum instance into\n[`UserInputMessage`](crate::types::ChatMessage::UserInputMessage), extracting the inner\n[`UserInputMessage`](crate::types::UserInputMessage). Returns `Err(&Self)` if it can't\nbe converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_chat_message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_chat_message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e90b98342aa4aeb2541f25e1e7653898d01e9cbaa345b37ce8255ef6d274b75d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ChatUserModificationEvent`](crate::types::ChatUserModificationEvent). This method will\nfail if any of the following fields are not set:\n- [`conversation_id`](crate::types::builders::ChatUserModificationEventBuilder::conversation_id)\n- [`message_id`](crate::types::builders::ChatUserModificationEventBuilder::message_id)\n- [`modification_percentage`](crate::types::builders::ChatUserModificationEventBuilder::modification_percentage)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::ChatUserModificationEvent {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building ChatUserModificationEvent\",\n )\n })?,\n customization_arn: self.customization_arn,\n message_id: self.message_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message_id\",\n \"message_id was not specified but it is required when building ChatUserModificationEvent\",\n )\n })?,\n programming_language: self.programming_language,\n modification_percentage: self.modification_percentage.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"modification_percentage\",\n \"modification_percentage was not specified but it is required when building ChatUserModificationEvent\",\n )\n })?,\n has_project_level_context: self.has_project_level_context,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ChatUserModificationEvent`](crate::types::ChatUserModificationEvent). This method will\nfail if any of the following fields are not set:\n- [`conversation_id`](crate::types::builders::ChatUserModificationEventBuilder::conversation_id)\n- [`message_id`](crate::types::builders::ChatUserModificationEventBuilder::message_id)\n- [`modification_percentage`](crate::types::builders::ChatUserModificationEventBuilder::modification_percentage)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_chat_user_modification_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_chat_user_modification_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c06b70a7d8ed2cf814f30e1277956689f9fe233780c8887bb669a92496360a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: code_scan_name\n\nDocumentation:\nCode analysis scan name\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn code_scan_name(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.code_scan_name = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "code_scan_name", "docstring": "Code analysis scan name\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_analysis_upload_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_analysis_upload_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7705928a117de5e6b8a50144953f4a4f1b3dfecd5133e0ccfb58752349a94561"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CodeAnalysisUploadContext`](crate::types::CodeAnalysisUploadContext). This method will\nfail if any of the following fields are not set:\n- [`code_scan_name`](crate::types::builders::CodeAnalysisUploadContextBuilder::code_scan_name)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::CodeAnalysisUploadContext {\n code_scan_name: self.code_scan_name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"code_scan_name\",\n \"code_scan_name was not specified but it is required when building CodeAnalysisUploadContext\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CodeAnalysisUploadContext`](crate::types::CodeAnalysisUploadContext). This method will\nfail if any of the following fields are not set:\n- [`code_scan_name`](crate::types::builders::CodeAnalysisUploadContextBuilder::code_scan_name)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_analysis_upload_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_analysis_upload_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d8a4129fb184b75608443a30ed4c8f18f25f248e9e834cbd959b344bc03cfd6e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CodeCoverageEvent`](crate::types::CodeCoverageEvent). This method will fail if any of\nthe following fields are not set:\n- [`programming_language`](crate::types::builders::CodeCoverageEventBuilder::programming_language)\n- [`timestamp`](crate::types::builders::CodeCoverageEventBuilder::timestamp)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::CodeCoverageEvent {\n customization_arn: self.customization_arn,\n programming_language: self.programming_language.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"programming_language\",\n \"programming_language was not specified but it is required when building CodeCoverageEvent\",\n )\n })?,\n accepted_character_count: self.accepted_character_count.unwrap_or_default(),\n total_character_count: self.total_character_count.unwrap_or_default(),\n timestamp: self.timestamp.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"timestamp\",\n \"timestamp was not specified but it is required when building CodeCoverageEvent\",\n )\n })?,\n unmodified_accepted_character_count: self.unmodified_accepted_character_count.unwrap_or_default(),\n total_new_code_character_count: self.total_new_code_character_count.unwrap_or_default(),\n total_new_code_line_count: self.total_new_code_line_count.unwrap_or_default(),\n user_written_code_character_count: self.user_written_code_character_count.unwrap_or_default(),\n user_written_code_line_count: self.user_written_code_line_count.unwrap_or_default(),\n added_character_count: self.added_character_count.unwrap_or_default(),\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CodeCoverageEvent`](crate::types::CodeCoverageEvent). This method will fail if any of\nthe following fields are not set:\n- [`programming_language`](crate::types::builders::CodeCoverageEventBuilder::programming_language)\n- [`timestamp`](crate::types::builders::CodeCoverageEventBuilder::timestamp)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_coverage_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_coverage_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e5f5a8f8eb03bbb6275ed44d3ec1429c44ce5b67ca0741a1fb50c063bc84d261"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: href\n\nDocumentation:\nAn URI to open with more information about the diagnostic error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn href(&self) -> &str {\n use std::ops::Deref;\n self.href.deref()\n }\n```"}], "func_name": "href", "docstring": "An URI to open with more information about the diagnostic error.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_description.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_description.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4746947d30c937bc38fff30abd9083abb9f613376bccba157f870b7e31dab13d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: href\n\nDocumentation:\nAn URI to open with more information about the diagnostic error.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn href(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.href = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "href", "docstring": "An URI to open with more information about the diagnostic error.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_description.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_description.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "36466401f008a36276afb6409d0416c0c4ff3c251c1f358d4407653e56a985a4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`CodeDescription`](crate::types::CodeDescription).\nThis method will fail if any of the following fields are not set:\n- [`href`](crate::types::builders::CodeDescriptionBuilder::href)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::CodeDescription {\n href: self.href.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"href\",\n \"href was not specified but it is required when building CodeDescription\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`CodeDescription`](crate::types::CodeDescription).\nThis method will fail if any of the following fields are not set:\n- [`href`](crate::types::builders::CodeDescriptionBuilder::href)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_description.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_description.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a83d1c4bf43fa8ca693436609ee78dc86d198131c2a910e7b0752cfb7dc2b014"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CodeFixAcceptanceEvent`](crate::types::CodeFixAcceptanceEvent). This method will fail\nif any of the following fields are not set:\n- [`job_id`](crate::types::builders::CodeFixAcceptanceEventBuilder::job_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::CodeFixAcceptanceEvent {\n job_id: self.job_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"job_id\",\n \"job_id was not specified but it is required when building CodeFixAcceptanceEvent\",\n )\n })?,\n rule_id: self.rule_id,\n detector_id: self.detector_id,\n finding_id: self.finding_id,\n programming_language: self.programming_language,\n lines_of_code_accepted: self.lines_of_code_accepted,\n chars_of_code_accepted: self.chars_of_code_accepted,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CodeFixAcceptanceEvent`](crate::types::CodeFixAcceptanceEvent). This method will fail\nif any of the following fields are not set:\n- [`job_id`](crate::types::builders::CodeFixAcceptanceEventBuilder::job_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_fix_acceptance_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_fix_acceptance_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93ef0cf3053ab917bc33a09df980389d0dd6e8506b3542e83fce7d0a7b3a64ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CodeFixGenerationEvent`](crate::types::CodeFixGenerationEvent). This method will fail\nif any of the following fields are not set:\n- [`job_id`](crate::types::builders::CodeFixGenerationEventBuilder::job_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::CodeFixGenerationEvent {\n job_id: self.job_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"job_id\",\n \"job_id was not specified but it is required when building CodeFixGenerationEvent\",\n )\n })?,\n rule_id: self.rule_id,\n detector_id: self.detector_id,\n finding_id: self.finding_id,\n programming_language: self.programming_language,\n lines_of_code_generated: self.lines_of_code_generated,\n chars_of_code_generated: self.chars_of_code_generated,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CodeFixGenerationEvent`](crate::types::CodeFixGenerationEvent). This method will fail\nif any of the following fields are not set:\n- [`job_id`](crate::types::builders::CodeFixGenerationEventBuilder::job_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_fix_generation_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_fix_generation_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "352d27357e8e7f204e95c34bba3c4d953572ad475afbcdafa39edbdcaf207a7c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: code_fix_name\n\nDocumentation:\nCode fix name\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn code_fix_name(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.code_fix_name = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "code_fix_name", "docstring": "Code fix name\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_fix_upload_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_fix_upload_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2e93e8bbed77ed793bde733f1498c09b4bab33ee961a818bdf94d70f62202fcb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CodeFixUploadContext`](crate::types::CodeFixUploadContext). This method will fail if\nany of the following fields are not set:\n- [`code_fix_name`](crate::types::builders::CodeFixUploadContextBuilder::code_fix_name)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::CodeFixUploadContext {\n code_fix_name: self.code_fix_name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"code_fix_name\",\n \"code_fix_name was not specified but it is required when building CodeFixUploadContext\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CodeFixUploadContext`](crate::types::CodeFixUploadContext). This method will fail if\nany of the following fields are not set:\n- [`code_fix_name`](crate::types::builders::CodeFixUploadContextBuilder::code_fix_name)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_fix_upload_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_fix_upload_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a45f2edbb087af6b6fe7ff8eef5677d6753b4f9e66988f1dff9caa54fa31c40e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CodeGenerationStatus`](crate::types::CodeGenerationStatus). This method will fail if\nany of the following fields are not set:\n- [`status`](crate::types::builders::CodeGenerationStatusBuilder::status)\n- [`current_stage`](crate::types::builders::CodeGenerationStatusBuilder::current_stage)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::CodeGenerationStatus {\n status: self.status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"status\",\n \"status was not specified but it is required when building CodeGenerationStatus\",\n )\n })?,\n current_stage: self.current_stage.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"current_stage\",\n \"current_stage was not specified but it is required when building CodeGenerationStatus\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CodeGenerationStatus`](crate::types::CodeGenerationStatus). This method will fail if\nany of the following fields are not set:\n- [`status`](crate::types::builders::CodeGenerationStatusBuilder::status)\n- [`current_stage`](crate::types::builders::CodeGenerationStatusBuilder::current_stage)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_generation_status.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_generation_status.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "66cb1dc6c0013d27f2040a5ab8ad27f8eda11f2e2916c88cc72195a255cc6b61"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`CodeScanEvent`](crate::types::CodeScanEvent).\nThis method will fail if any of the following fields are not set:\n- [`programming_language`](crate::types::builders::CodeScanEventBuilder::programming_language)\n- [`code_scan_job_id`](crate::types::builders::CodeScanEventBuilder::code_scan_job_id)\n- [`timestamp`](crate::types::builders::CodeScanEventBuilder::timestamp)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::CodeScanEvent {\n programming_language: self.programming_language.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"programming_language\",\n \"programming_language was not specified but it is required when building CodeScanEvent\",\n )\n })?,\n code_scan_job_id: self.code_scan_job_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"code_scan_job_id\",\n \"code_scan_job_id was not specified but it is required when building CodeScanEvent\",\n )\n })?,\n timestamp: self.timestamp.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"timestamp\",\n \"timestamp was not specified but it is required when building CodeScanEvent\",\n )\n })?,\n code_analysis_scope: self.code_analysis_scope,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`CodeScanEvent`](crate::types::CodeScanEvent).\nThis method will fail if any of the following fields are not set:\n- [`programming_language`](crate::types::builders::CodeScanEventBuilder::programming_language)\n- [`code_scan_job_id`](crate::types::builders::CodeScanEventBuilder::code_scan_job_id)\n- [`timestamp`](crate::types::builders::CodeScanEventBuilder::timestamp)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_scan_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_scan_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0a9ead44a71565e94d2558837aa9659403d5a7c9b277977858fea6b58a742752"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CodeScanFailedEvent`](crate::types::CodeScanFailedEvent). This method will fail if any\nof the following fields are not set:\n- [`programming_language`](crate::types::builders::CodeScanFailedEventBuilder::programming_language)\n- [`code_scan_job_id`](crate::types::builders::CodeScanFailedEventBuilder::code_scan_job_id)\n- [`timestamp`](crate::types::builders::CodeScanFailedEventBuilder::timestamp)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::CodeScanFailedEvent {\n programming_language: self.programming_language.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"programming_language\",\n \"programming_language was not specified but it is required when building CodeScanFailedEvent\",\n )\n })?,\n code_scan_job_id: self.code_scan_job_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"code_scan_job_id\",\n \"code_scan_job_id was not specified but it is required when building CodeScanFailedEvent\",\n )\n })?,\n timestamp: self.timestamp.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"timestamp\",\n \"timestamp was not specified but it is required when building CodeScanFailedEvent\",\n )\n })?,\n code_analysis_scope: self.code_analysis_scope,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CodeScanFailedEvent`](crate::types::CodeScanFailedEvent). This method will fail if any\nof the following fields are not set:\n- [`programming_language`](crate::types::builders::CodeScanFailedEventBuilder::programming_language)\n- [`code_scan_job_id`](crate::types::builders::CodeScanFailedEventBuilder::code_scan_job_id)\n- [`timestamp`](crate::types::builders::CodeScanFailedEventBuilder::timestamp)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_scan_failed_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_scan_failed_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bcb495325a9f758baaa36018bc86e0d49bbe7285678eb27aa935d3d61188576b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CodeScanRemediationsEvent`](crate::types::CodeScanRemediationsEvent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::CodeScanRemediationsEvent {\n crate::types::CodeScanRemediationsEvent {\n programming_language: self.programming_language,\n code_scan_remediations_event_type: self.code_scan_remediations_event_type,\n timestamp: self.timestamp,\n detector_id: self.detector_id,\n finding_id: self.finding_id,\n rule_id: self.rule_id,\n component: self.component,\n reason: self.reason,\n result: self.result,\n includes_fix: self.includes_fix,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CodeScanRemediationsEvent`](crate::types::CodeScanRemediationsEvent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_scan_remediations_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_scan_remediations_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5cd3dc1d20aa6aa3e35e1d8af2217f650208189fa0eb74a3302d1f2051cd9a44"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CodeScanSucceededEvent`](crate::types::CodeScanSucceededEvent). This method will fail\nif any of the following fields are not set:\n- [`programming_language`](crate::types::builders::CodeScanSucceededEventBuilder::programming_language)\n- [`code_scan_job_id`](crate::types::builders::CodeScanSucceededEventBuilder::code_scan_job_id)\n- [`timestamp`](crate::types::builders::CodeScanSucceededEventBuilder::timestamp)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::CodeScanSucceededEvent {\n programming_language: self.programming_language.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"programming_language\",\n \"programming_language was not specified but it is required when building CodeScanSucceededEvent\",\n )\n })?,\n code_scan_job_id: self.code_scan_job_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"code_scan_job_id\",\n \"code_scan_job_id was not specified but it is required when building CodeScanSucceededEvent\",\n )\n })?,\n timestamp: self.timestamp.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"timestamp\",\n \"timestamp was not specified but it is required when building CodeScanSucceededEvent\",\n )\n })?,\n number_of_findings: self.number_of_findings.unwrap_or_default(),\n code_analysis_scope: self.code_analysis_scope,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CodeScanSucceededEvent`](crate::types::CodeScanSucceededEvent). This method will fail\nif any of the following fields are not set:\n- [`programming_language`](crate::types::builders::CodeScanSucceededEventBuilder::programming_language)\n- [`code_scan_job_id`](crate::types::builders::CodeScanSucceededEventBuilder::code_scan_job_id)\n- [`timestamp`](crate::types::builders::CodeScanSucceededEventBuilder::timestamp)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_code_scan_succeeded_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_code_scan_succeeded_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ad6d14465f24b38a167433b85629793dcfa110d1591a8d60a7e91a267d61322"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: most_relevant_missing_imports\n\nDocumentation:\nAppends an item to `most_relevant_missing_imports`.\n\nTo override the contents of this collection use\n[`set_most_relevant_missing_imports`](Self::set_most_relevant_missing_imports).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn most_relevant_missing_imports(mut self, input: crate::types::Import) -> Self {\n let mut v = self.most_relevant_missing_imports.unwrap_or_default();\n v.push(input);\n self.most_relevant_missing_imports = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "most_relevant_missing_imports", "docstring": "Appends an item to `most_relevant_missing_imports`.\n\nTo override the contents of this collection use\n[`set_most_relevant_missing_imports`](Self::set_most_relevant_missing_imports).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_completion.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_completion.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dbe1e70853dc3d48db533bc99f3220fc62bc678c949b7b0193ac2c5c2ff701f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Completion`](crate::types::Completion).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::CompletionBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Completion {\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building Completion\",\n )\n })?,\n references: self.references,\n most_relevant_missing_imports: self.most_relevant_missing_imports,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Completion`](crate::types::Completion).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::CompletionBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_completion.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_completion.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fad160fa1804ad6ffb419a75e4d759b13bfd4a544d6c9e5be96a68b504851b70"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ConsoleState`](crate::types::ConsoleState).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::ConsoleState {\n crate::types::ConsoleState {\n region: self.region,\n console_url: self.console_url,\n service_id: self.service_id,\n service_console_page: self.service_console_page,\n service_subconsole_page: self.service_subconsole_page,\n task_name: self.task_name,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ConsoleState`](crate::types::ConsoleState).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_console_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_console_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "31e602b2cc5adb92c5872c297b4542ea6866ad464b2473480e855344e2912f1a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: history\n\nDocumentation:\nAppends an item to `history`.\n\nTo override the contents of this collection use [`set_history`](Self::set_history).\n\nHolds the history of chat messages.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn history(mut self, input: crate::types::ChatMessage) -> Self {\n let mut v = self.history.unwrap_or_default();\n v.push(input);\n self.history = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "history", "docstring": "Appends an item to `history`.\n\nTo override the contents of this collection use [`set_history`](Self::set_history).\n\nHolds the history of chat messages.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "368eaccfde2466d5f571685faf256eaceae3c403dbfe1c3248820ea267e0a37b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_history\n\nDocumentation:\nHolds the history of chat messages.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_history(mut self, input: ::std::option::Option<::std::vec::Vec>) -> Self {\n self.history = input;\n self\n }\n```"}], "func_name": "set_history", "docstring": "Holds the history of chat messages.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "432efb3cc945aff91182c261ac43e8ffdb20829f740d7771839d29757dd3e9b2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: current_message\n\nDocumentation:\nHolds the current message being processed or displayed.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn current_message(mut self, input: crate::types::ChatMessage) -> Self {\n self.current_message = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "current_message", "docstring": "Holds the current message being processed or displayed.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d6fd5a365dfc654f520dbacfcd5a359139d5c6284453d02fc3fa9e37b1732b5a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_current_message\n\nDocumentation:\nHolds the current message being processed or displayed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_current_message(mut self, input: ::std::option::Option) -> Self {\n self.current_message = input;\n self\n }\n```"}], "func_name": "set_current_message", "docstring": "Holds the current message being processed or displayed.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "941182ea46901e4a5b27922496001229fa3d199f9783ec14761b4882d130c5ef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: chat_trigger_type\n\nDocumentation:\nTrigger Reason for Chat\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn chat_trigger_type(mut self, input: crate::types::ChatTriggerType) -> Self {\n self.chat_trigger_type = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "chat_trigger_type", "docstring": "Trigger Reason for Chat\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5088d5437c34f449370cf3330bdb3191d8d753a5c29ea66ef52687518c2488e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ConversationState`](crate::types::ConversationState). This method will fail if any of\nthe following fields are not set:\n- [`current_message`](crate::types::builders::ConversationStateBuilder::current_message)\n- [`chat_trigger_type`](crate::types::builders::ConversationStateBuilder::chat_trigger_type)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::ConversationState {\n conversation_id: self.conversation_id,\n history: self.history,\n current_message: self.current_message.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"current_message\",\n \"current_message was not specified but it is required when building ConversationState\",\n )\n })?,\n chat_trigger_type: self.chat_trigger_type.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"chat_trigger_type\",\n \"chat_trigger_type was not specified but it is required when building ConversationState\",\n )\n })?,\n customization_arn: self.customization_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ConversationState`](crate::types::ConversationState). This method will fail if any of\nthe following fields are not set:\n- [`current_message`](crate::types::builders::ConversationStateBuilder::current_message)\n- [`chat_trigger_type`](crate::types::builders::ConversationStateBuilder::chat_trigger_type)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82148ccddfc2c11f17255df7ae1d33b6ac944e03bc936eb70b0bc4933555c6e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_position\n\nDocumentation:\nTries to convert the enum instance into [`Position`](crate::types::CursorState::Position),\nextracting the inner [`Position`](crate::types::Position). Returns `Err(&Self)` if it\ncan't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_position(&self) -> ::std::result::Result<&crate::types::Position, &Self> {\n if let CursorState::Position(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_position", "docstring": "Tries to convert the enum instance into [`Position`](crate::types::CursorState::Position),\nextracting the inner [`Position`](crate::types::Position). Returns `Err(&Self)` if it\ncan't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_cursor_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_cursor_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1140fd9eda1d79d91a5f3df50304360c760775e6a719b94514fed5c4d2fe4d59"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_range\n\nDocumentation:\nTries to convert the enum instance into [`Range`](crate::types::CursorState::Range),\nextracting the inner [`Range`](crate::types::Range). Returns `Err(&Self)` if it can't be\nconverted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_range(&self) -> ::std::result::Result<&crate::types::Range, &Self> {\n if let CursorState::Range(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_range", "docstring": "Tries to convert the enum instance into [`Range`](crate::types::CursorState::Range),\nextracting the inner [`Range`](crate::types::Range). Returns `Err(&Self)` if it can't be\nconverted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_cursor_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_cursor_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b6bce94d4868607de63957d7295969ab6eb6f96a5523b9a95dcb033a615b04c8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Customization`](crate::types::Customization).\nThis method will fail if any of the following fields are not set:\n- [`arn`](crate::types::builders::CustomizationBuilder::arn)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Customization {\n arn: self.arn.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"arn\",\n \"arn was not specified but it is required when building Customization\",\n )\n })?,\n name: self.name,\n description: self.description,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Customization`](crate::types::Customization).\nThis method will fail if any of the following fields are not set:\n- [`arn`](crate::types::builders::CustomizationBuilder::arn)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_customization.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_customization.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d5a90956bda67378d543c6c5c3a75b3b27a8268a164ee41742abe6256f5f9f9e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DashboardAnalytics`](crate::types::DashboardAnalytics). This method will fail if any\nof the following fields are not set:\n- [`toggle`](crate::types::builders::DashboardAnalyticsBuilder::toggle)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::DashboardAnalytics {\n toggle: self.toggle.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"toggle\",\n \"toggle was not specified but it is required when building DashboardAnalytics\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DashboardAnalytics`](crate::types::DashboardAnalytics). This method will fail if any\nof the following fields are not set:\n- [`toggle`](crate::types::builders::DashboardAnalyticsBuilder::toggle)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_dashboard_analytics.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_dashboard_analytics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c03087f9d0c7f5f6386474b0092bcc2e4c388478d9047a140509e6ffa5254e7f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_runtime_diagnostic\n\nDocumentation:\nTries to convert the enum instance into\n[`RuntimeDiagnostic`](crate::types::Diagnostic::RuntimeDiagnostic), extracting the inner\n[`RuntimeDiagnostic`](crate::types::RuntimeDiagnostic). Returns `Err(&Self)` if it can't\nbe converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_runtime_diagnostic(&self) -> ::std::result::Result<&crate::types::RuntimeDiagnostic, &Self> {\n if let Diagnostic::RuntimeDiagnostic(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_runtime_diagnostic", "docstring": "Tries to convert the enum instance into\n[`RuntimeDiagnostic`](crate::types::Diagnostic::RuntimeDiagnostic), extracting the inner\n[`RuntimeDiagnostic`](crate::types::RuntimeDiagnostic). Returns `Err(&Self)` if it can't\nbe converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "23de81f248544a9fa43d258b610203dfc8323d7341bc808859707e587c22894f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_text_document_diagnostic\n\nDocumentation:\nTries to convert the enum instance into\n[`TextDocumentDiagnostic`](crate::types::Diagnostic::TextDocumentDiagnostic), extracting the\ninner [`TextDocumentDiagnostic`](crate::types::TextDocumentDiagnostic). Returns `Err(&\nSelf)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_text_document_diagnostic(&self) -> ::std::result::Result<&crate::types::TextDocumentDiagnostic, &Self> {\n if let Diagnostic::TextDocumentDiagnostic(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_text_document_diagnostic", "docstring": "Tries to convert the enum instance into\n[`TextDocumentDiagnostic`](crate::types::Diagnostic::TextDocumentDiagnostic), extracting the\ninner [`TextDocumentDiagnostic`](crate::types::TextDocumentDiagnostic). Returns `Err(&\nSelf)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "70404165c984c95eb16892dd6b3089d5fa651d9163dc93179c1f9b47f2cd710c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DiagnosticLocation`](crate::types::DiagnosticLocation). This method will fail if any\nof the following fields are not set:\n- [`uri`](crate::types::builders::DiagnosticLocationBuilder::uri)\n- [`range`](crate::types::builders::DiagnosticLocationBuilder::range)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::DiagnosticLocation {\n uri: self.uri.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"uri\",\n \"uri was not specified but it is required when building DiagnosticLocation\",\n )\n })?,\n range: self.range.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"range\",\n \"range was not specified but it is required when building DiagnosticLocation\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DiagnosticLocation`](crate::types::DiagnosticLocation). This method will fail if any\nof the following fields are not set:\n- [`uri`](crate::types::builders::DiagnosticLocationBuilder::uri)\n- [`range`](crate::types::builders::DiagnosticLocationBuilder::range)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_diagnostic_location.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_diagnostic_location.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "74465c40a3be4cdf63162633009a0ce66dfc4a0a807a7e6ba3f5b0ef8be75eeb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: location\n\nDocumentation:\nThe location of this related diagnostic information.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn location(mut self, input: crate::types::DiagnosticLocation) -> Self {\n self.location = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "location", "docstring": "The location of this related diagnostic information.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_diagnostic_related_information.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_diagnostic_related_information.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "60d5c77cedd7f318e598a38d2bc0dbe36c4d4686668f434b7bf3778b000e1d61"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_location\n\nDocumentation:\nThe location of this related diagnostic information.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_location(mut self, input: ::std::option::Option) -> Self {\n self.location = input;\n self\n }\n```"}], "func_name": "set_location", "docstring": "The location of this related diagnostic information.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_diagnostic_related_information.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_diagnostic_related_information.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "185594c0212742cb382590dc26f5fee853408fbda8447482e7a649cc47d69383"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DiagnosticRelatedInformation`](crate::types::DiagnosticRelatedInformation).\nThis method will fail if any of the following fields are not set:\n- [`location`](crate::types::builders::DiagnosticRelatedInformationBuilder::location)\n- [`message`](crate::types::builders::DiagnosticRelatedInformationBuilder::message)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::DiagnosticRelatedInformation,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::DiagnosticRelatedInformation {\n location: self.location.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"location\",\n \"location was not specified but it is required when building DiagnosticRelatedInformation\",\n )\n })?,\n message: self.message.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message\",\n \"message was not specified but it is required when building DiagnosticRelatedInformation\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DiagnosticRelatedInformation`](crate::types::DiagnosticRelatedInformation).\nThis method will fail if any of the following fields are not set:\n- [`location`](crate::types::builders::DiagnosticRelatedInformationBuilder::location)\n- [`message`](crate::types::builders::DiagnosticRelatedInformationBuilder::message)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_diagnostic_related_information.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_diagnostic_related_information.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "484e265da935ba700119864f46509cd2118e881ae040309dba1b706c866b9494"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DocumentationIntentContext`](crate::types::DocumentationIntentContext). This method\nwill fail if any of the following fields are not set:\n- [`r#type`](crate::types::builders::DocumentationIntentContextBuilder::type)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::DocumentationIntentContext {\n scope: self.scope,\n r#type: self.r#type.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"r#type\",\n \"r#type was not specified but it is required when building DocumentationIntentContext\",\n )\n })?,\n change_log_options: self.change_log_options,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DocumentationIntentContext`](crate::types::DocumentationIntentContext). This method\nwill fail if any of the following fields are not set:\n- [`r#type`](crate::types::builders::DocumentationIntentContextBuilder::type)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_documentation_intent_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_documentation_intent_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ed69449287697dab60072b916f5530333b44dbd7f8b9e7d0c28b3268bb4ebc85"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: r#type\n\nDocumentation:\nSymbol type - DECLARATION / USAGE\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn r#type(mut self, input: crate::types::SymbolType) -> Self {\n self.r#type = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "r#type", "docstring": "Symbol type - DECLARATION / USAGE\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_document_symbol.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_document_symbol.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "33acd0db02ffbc0478ede96ed73986023a692afb8848aea3f8e56e06a821c8f7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`DocumentSymbol`](crate::types::DocumentSymbol).\nThis method will fail if any of the following fields are not set:\n- [`name`](crate::types::builders::DocumentSymbolBuilder::name)\n- [`r#type`](crate::types::builders::DocumentSymbolBuilder::type)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::DocumentSymbol {\n name: self.name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"name\",\n \"name was not specified but it is required when building DocumentSymbol\",\n )\n })?,\n r#type: self.r#type.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"r#type\",\n \"r#type was not specified but it is required when building DocumentSymbol\",\n )\n })?,\n source: self.source,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`DocumentSymbol`](crate::types::DocumentSymbol).\nThis method will fail if any of the following fields are not set:\n- [`name`](crate::types::builders::DocumentSymbolBuilder::name)\n- [`r#type`](crate::types::builders::DocumentSymbolBuilder::type)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_document_symbol.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_document_symbol.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "749e664bbb41eae1ffd78300cee6fb122fd6463a8a83053f2a30272eb53e24e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: interaction_type\n\nDocumentation:\nTracks whether user chose to generate a new document, update an existing one, or edit\ndocument\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn interaction_type(mut self, input: crate::types::DocInteractionType) -> Self {\n self.interaction_type = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "interaction_type", "docstring": "Tracks whether user chose to generate a new document, update an existing one, or edit\ndocument", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_doc_generation_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_doc_generation_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c7ad2308933dfe5cc5baadf1be6b08658394b6ba5ed1045cd75ffad68b931865"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: folder_level\n\nDocumentation:\nSpecifies the folder depth level where the document should be generated\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn folder_level(mut self, input: crate::types::DocFolderLevel) -> Self {\n self.folder_level = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "folder_level", "docstring": "Specifies the folder depth level where the document should be generated", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_doc_generation_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_doc_generation_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "790831c0f52b3dd96712edc926fc12a4ba7a184f65f45709cf54575bb6a46919"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DocGenerationEvent`](crate::types::DocGenerationEvent). This method will fail if any\nof the following fields are not set:\n- [`conversation_id`](crate::types::builders::DocGenerationEventBuilder::conversation_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::DocGenerationEvent {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building DocGenerationEvent\",\n )\n })?,\n number_of_add_chars: self.number_of_add_chars.unwrap_or_default(),\n number_of_add_lines: self.number_of_add_lines.unwrap_or_default(),\n number_of_add_files: self.number_of_add_files.unwrap_or_default(),\n user_decision: self.user_decision,\n interaction_type: self.interaction_type,\n user_identity: self.user_identity,\n number_of_navigation: self.number_of_navigation.unwrap_or_default(),\n folder_level: self.folder_level,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DocGenerationEvent`](crate::types::DocGenerationEvent). This method will fail if any\nof the following fields are not set:\n- [`conversation_id`](crate::types::builders::DocGenerationEventBuilder::conversation_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_doc_generation_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_doc_generation_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "875e0ce4078abe3a0e8d9f467411992a4a08673d7573e11a975ab8e9520af8fd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DocV2AcceptanceEvent`](crate::types::DocV2AcceptanceEvent). This method will fail if\nany of the following fields are not set:\n- [`conversation_id`](crate::types::builders::DocV2AcceptanceEventBuilder::conversation_id)\n- [`user_decision`](crate::types::builders::DocV2AcceptanceEventBuilder::user_decision)\n- [`interaction_type`](crate::types::builders::DocV2AcceptanceEventBuilder::interaction_type)\n- [`folder_level`](crate::types::builders::DocV2AcceptanceEventBuilder::folder_level)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::DocV2AcceptanceEvent {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building DocV2AcceptanceEvent\",\n )\n })?,\n number_of_added_chars: self.number_of_added_chars.unwrap_or_default(),\n number_of_added_lines: self.number_of_added_lines.unwrap_or_default(),\n number_of_added_files: self.number_of_added_files.unwrap_or_default(),\n user_decision: self.user_decision.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"user_decision\",\n \"user_decision was not specified but it is required when building DocV2AcceptanceEvent\",\n )\n })?,\n interaction_type: self.interaction_type.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"interaction_type\",\n \"interaction_type was not specified but it is required when building DocV2AcceptanceEvent\",\n )\n })?,\n number_of_navigations: self.number_of_navigations.unwrap_or_default(),\n folder_level: self.folder_level.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"folder_level\",\n \"folder_level was not specified but it is required when building DocV2AcceptanceEvent\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DocV2AcceptanceEvent`](crate::types::DocV2AcceptanceEvent). This method will fail if\nany of the following fields are not set:\n- [`conversation_id`](crate::types::builders::DocV2AcceptanceEventBuilder::conversation_id)\n- [`user_decision`](crate::types::builders::DocV2AcceptanceEventBuilder::user_decision)\n- [`interaction_type`](crate::types::builders::DocV2AcceptanceEventBuilder::interaction_type)\n- [`folder_level`](crate::types::builders::DocV2AcceptanceEventBuilder::folder_level)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_doc_v2_acceptance_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_doc_v2_acceptance_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6609b159ba53cf213bfd05759bdc1be04b2d1ff4524e0404df1a94eb25680a8d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DocV2GenerationEvent`](crate::types::DocV2GenerationEvent). This method will fail if\nany of the following fields are not set:\n- [`conversation_id`](crate::types::builders::DocV2GenerationEventBuilder::conversation_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::DocV2GenerationEvent {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building DocV2GenerationEvent\",\n )\n })?,\n number_of_generated_chars: self.number_of_generated_chars.unwrap_or_default(),\n number_of_generated_lines: self.number_of_generated_lines.unwrap_or_default(),\n number_of_generated_files: self.number_of_generated_files.unwrap_or_default(),\n interaction_type: self.interaction_type,\n number_of_navigations: self.number_of_navigations.unwrap_or_default(),\n folder_level: self.folder_level,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DocV2GenerationEvent`](crate::types::DocV2GenerationEvent). This method will fail if\nany of the following fields are not set:\n- [`conversation_id`](crate::types::builders::DocV2GenerationEventBuilder::conversation_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_doc_v2_generation_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_doc_v2_generation_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1bb121d0f6f8e81d75dcce866aec3d1a7f0a447147a463becab64acb6f91628d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Edit`](crate::types::Edit).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::EditBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Edit {\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building Edit\",\n )\n })?,\n references: self.references,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Edit`](crate::types::Edit).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::EditBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_edit.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_edit.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "66d63f9ed037ebdd654f11cfc6d49edfcf107c7d1695f0fd727c0804355bbc8a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: relevant_documents\n\nDocumentation:\nAppends an item to `relevant_documents`.\n\nTo override the contents of this collection use\n[`set_relevant_documents`](Self::set_relevant_documents).\n\nRepresents IDE provided relevant files\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn relevant_documents(mut self, input: crate::types::RelevantTextDocument) -> Self {\n let mut v = self.relevant_documents.unwrap_or_default();\n v.push(input);\n self.relevant_documents = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "relevant_documents", "docstring": "Appends an item to `relevant_documents`.\n\nTo override the contents of this collection use\n[`set_relevant_documents`](Self::set_relevant_documents).\n\nRepresents IDE provided relevant files", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_editor_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_editor_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d7aa13d1f10afc0d3073d0d36f238c60a00b0f3ba4fcbdc5ef26a5ef641f82f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: use_relevant_documents\n\nDocumentation:\nWhether service should use relevant document in prompt\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn use_relevant_documents(mut self, input: bool) -> Self {\n self.use_relevant_documents = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "use_relevant_documents", "docstring": "Whether service should use relevant document in prompt", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_editor_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_editor_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "26e02a460b7f28ffbb1e2ee11a4ab3725552511c89cd1ebd6ebfd1a466ca5ac0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: workspace_folders\n\nDocumentation:\nAppends an item to `workspace_folders`.\n\nTo override the contents of this collection use\n[`set_workspace_folders`](Self::set_workspace_folders).\n\nRepresents IDE provided list of workspace folders\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn workspace_folders(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n let mut v = self.workspace_folders.unwrap_or_default();\n v.push(input.into());\n self.workspace_folders = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "workspace_folders", "docstring": "Appends an item to `workspace_folders`.\n\nTo override the contents of this collection use\n[`set_workspace_folders`](Self::set_workspace_folders).\n\nRepresents IDE provided list of workspace folders", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_editor_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_editor_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "13b970d14930982fe74ee57fb20c9b309939cb9ce8e1f62d0854741c670968dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_workspace_folders\n\nDocumentation:\nRepresents IDE provided list of workspace folders\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_workspace_folders(\n mut self,\n input: ::std::option::Option<::std::vec::Vec<::std::string::String>>,\n ) -> Self {\n self.workspace_folders = input;\n self\n }\n```"}], "func_name": "set_workspace_folders", "docstring": "Represents IDE provided list of workspace folders", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_editor_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_editor_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e855303d3c4dce893623c2d602c45872505357ae3a823382ebc6d57d250bcb54"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`EditorState`](crate::types::EditorState).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::EditorState {\n crate::types::EditorState {\n document: self.document,\n cursor_state: self.cursor_state,\n relevant_documents: self.relevant_documents,\n use_relevant_documents: self.use_relevant_documents,\n workspace_folders: self.workspace_folders,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`EditorState`](crate::types::EditorState).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_editor_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_editor_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ce9363c06f5688e459755dfaa98baadad5a07c849648d73e12f78bfcd11f5f2d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`EnvironmentVariable`](crate::types::EnvironmentVariable).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::EnvironmentVariable {\n crate::types::EnvironmentVariable {\n key: self.key,\n value: self.value,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`EnvironmentVariable`](crate::types::EnvironmentVariable).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_environment_variable.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_environment_variable.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80717682c329cc3c697d71df0f083822ae824e56ff2968355fe5f4b658596917"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: current_working_directory\n\nDocumentation:\nThe current working directory of the environment\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn current_working_directory(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.current_working_directory = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "current_working_directory", "docstring": "The current working directory of the environment", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_env_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_env_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e62d658949957addb945f8353db2bb5f4f0bf049259eab621b9cc809c910d723"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: environment_variables\n\nDocumentation:\nAppends an item to `environment_variables`.\n\nTo override the contents of this collection use\n[`set_environment_variables`](Self::set_environment_variables).\n\nThe environment variables set in the current environment\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn environment_variables(mut self, input: crate::types::EnvironmentVariable) -> Self {\n let mut v = self.environment_variables.unwrap_or_default();\n v.push(input);\n self.environment_variables = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "environment_variables", "docstring": "Appends an item to `environment_variables`.\n\nTo override the contents of this collection use\n[`set_environment_variables`](Self::set_environment_variables).\n\nThe environment variables set in the current environment", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_env_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_env_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d386d635e01dea03fc559d15d5aa7aae32a664a7767b069aabcf973ea29f86f1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_environment_variables\n\nDocumentation:\nThe environment variables set in the current environment\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_environment_variables(\n mut self,\n input: ::std::option::Option<::std::vec::Vec>,\n ) -> Self {\n self.environment_variables = input;\n self\n }\n```"}], "func_name": "set_environment_variables", "docstring": "The environment variables set in the current environment", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_env_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_env_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa7293e8e3f2da24de6c613d8921cb9c5217f10bce871c2c72fbe1708d23107a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`EnvState`](crate::types::EnvState).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::EnvState {\n crate::types::EnvState {\n operating_system: self.operating_system,\n current_working_directory: self.current_working_directory,\n environment_variables: self.environment_variables,\n timezone_offset: self.timezone_offset,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`EnvState`](crate::types::EnvState).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_env_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_env_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f84ee15e22dbf450cbfa6ca572666bb408eb5f7df54169f22aa52d44db7ff1be"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Event`](crate::types::Event).\nThis method will fail if any of the following fields are not set:\n- [`event_id`](crate::types::builders::EventBuilder::event_id)\n- [`generation_id`](crate::types::builders::EventBuilder::generation_id)\n- [`event_timestamp`](crate::types::builders::EventBuilder::event_timestamp)\n- [`event_type`](crate::types::builders::EventBuilder::event_type)\n- [`event_blob`](crate::types::builders::EventBuilder::event_blob)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Event {\n event_id: self.event_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"event_id\",\n \"event_id was not specified but it is required when building Event\",\n )\n })?,\n generation_id: self.generation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"generation_id\",\n \"generation_id was not specified but it is required when building Event\",\n )\n })?,\n event_timestamp: self.event_timestamp.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"event_timestamp\",\n \"event_timestamp was not specified but it is required when building Event\",\n )\n })?,\n event_type: self.event_type.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"event_type\",\n \"event_type was not specified but it is required when building Event\",\n )\n })?,\n event_blob: self.event_blob.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"event_blob\",\n \"event_blob was not specified but it is required when building Event\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Event`](crate::types::Event).\nThis method will fail if any of the following fields are not set:\n- [`event_id`](crate::types::builders::EventBuilder::event_id)\n- [`generation_id`](crate::types::builders::EventBuilder::generation_id)\n- [`event_timestamp`](crate::types::builders::EventBuilder::event_timestamp)\n- [`event_type`](crate::types::builders::EventBuilder::event_type)\n- [`event_blob`](crate::types::builders::EventBuilder::event_blob)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0935cc626d357264e6177f79847017ed8ae756b3901d7b217b32cb9fac4d8e39"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ExternalIdentityDetails`](crate::types::ExternalIdentityDetails).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::ExternalIdentityDetails {\n crate::types::ExternalIdentityDetails {\n issuer_url: self.issuer_url,\n client_id: self.client_id,\n scim_endpoint: self.scim_endpoint,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ExternalIdentityDetails`](crate::types::ExternalIdentityDetails).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_external_identity_details.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_external_identity_details.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "22cb0c8c343dd44e40a4171a94dc6c7e6bdcef29010780273d6f0587c108b94c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`FeatureDevCodeAcceptanceEvent`](crate::types::FeatureDevCodeAcceptanceEvent).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::types::builders::FeatureDevCodeAcceptanceEventBuilder::conversation_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::FeatureDevCodeAcceptanceEvent,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::FeatureDevCodeAcceptanceEvent {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building FeatureDevCodeAcceptanceEvent\",\n )\n })?,\n lines_of_code_accepted: self.lines_of_code_accepted.unwrap_or_default(),\n characters_of_code_accepted: self.characters_of_code_accepted.unwrap_or_default(),\n programming_language: self.programming_language,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`FeatureDevCodeAcceptanceEvent`](crate::types::FeatureDevCodeAcceptanceEvent).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::types::builders::FeatureDevCodeAcceptanceEventBuilder::conversation_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_feature_dev_code_acceptance_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_feature_dev_code_acceptance_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9ff355b1b015ad725d1e280e4bddb3f072bcb10cafc6407b13821aa29533dedb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`FeatureDevCodeGenerationEvent`](crate::types::FeatureDevCodeGenerationEvent).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::types::builders::FeatureDevCodeGenerationEventBuilder::conversation_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::FeatureDevCodeGenerationEvent,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::FeatureDevCodeGenerationEvent {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building FeatureDevCodeGenerationEvent\",\n )\n })?,\n lines_of_code_generated: self.lines_of_code_generated.unwrap_or_default(),\n characters_of_code_generated: self.characters_of_code_generated.unwrap_or_default(),\n programming_language: self.programming_language,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`FeatureDevCodeGenerationEvent`](crate::types::FeatureDevCodeGenerationEvent).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::types::builders::FeatureDevCodeGenerationEventBuilder::conversation_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_feature_dev_code_generation_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_feature_dev_code_generation_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2382e23c7168dbe0790843272ea2ea966f1bbca9eb8850e1599d3ba9fa18e9fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`FeatureDevEvent`](crate::types::FeatureDevEvent).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::types::builders::FeatureDevEventBuilder::conversation_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::FeatureDevEvent {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building FeatureDevEvent\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`FeatureDevEvent`](crate::types::FeatureDevEvent).\nThis method will fail if any of the following fields are not set:\n- [`conversation_id`](crate::types::builders::FeatureDevEventBuilder::conversation_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_feature_dev_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_feature_dev_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "baf12494cea05edd5a443d1501512ecbebe2a25555dc3d486bda93acafd106f2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`FeatureEvaluation`](crate::types::FeatureEvaluation). This method will fail if any of\nthe following fields are not set:\n- [`feature`](crate::types::builders::FeatureEvaluationBuilder::feature)\n- [`variation`](crate::types::builders::FeatureEvaluationBuilder::variation)\n- [`value`](crate::types::builders::FeatureEvaluationBuilder::value)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::FeatureEvaluation {\n feature: self.feature.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"feature\",\n \"feature was not specified but it is required when building FeatureEvaluation\",\n )\n })?,\n variation: self.variation.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"variation\",\n \"variation was not specified but it is required when building FeatureEvaluation\",\n )\n })?,\n value: self.value.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"value\",\n \"value was not specified but it is required when building FeatureEvaluation\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`FeatureEvaluation`](crate::types::FeatureEvaluation). This method will fail if any of\nthe following fields are not set:\n- [`feature`](crate::types::builders::FeatureEvaluationBuilder::feature)\n- [`variation`](crate::types::builders::FeatureEvaluationBuilder::variation)\n- [`value`](crate::types::builders::FeatureEvaluationBuilder::value)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_feature_evaluation.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_feature_evaluation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f3511a9c8d81813c8ace9ad82b455aa868b2750034850730c0702df9f70359f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_bool_value\n\nDocumentation:\nTries to convert the enum instance into\n[`BoolValue`](crate::types::FeatureValue::BoolValue), extracting the inner [`bool`](bool).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_bool_value(&self) -> ::std::result::Result<&bool, &Self> {\n if let FeatureValue::BoolValue(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_bool_value", "docstring": "Tries to convert the enum instance into\n[`BoolValue`](crate::types::FeatureValue::BoolValue), extracting the inner [`bool`](bool).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_feature_value.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_feature_value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "62dd8421f60f3212c1f9df20e98a506d97c4705a7bf0de67d569a98741e6c716"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_double_value\n\nDocumentation:\nTries to convert the enum instance into\n[`DoubleValue`](crate::types::FeatureValue::DoubleValue), extracting the inner [`f64`](f64).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_double_value(&self) -> ::std::result::Result<&f64, &Self> {\n if let FeatureValue::DoubleValue(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_double_value", "docstring": "Tries to convert the enum instance into\n[`DoubleValue`](crate::types::FeatureValue::DoubleValue), extracting the inner [`f64`](f64).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_feature_value.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_feature_value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "76b5455404d5f9d0169798a838610f44d6a883d87c32cdd486191125b2aab8c0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_long_value\n\nDocumentation:\nTries to convert the enum instance into\n[`LongValue`](crate::types::FeatureValue::LongValue), extracting the inner [`i64`](i64).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_long_value(&self) -> ::std::result::Result<&i64, &Self> {\n if let FeatureValue::LongValue(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_long_value", "docstring": "Tries to convert the enum instance into\n[`LongValue`](crate::types::FeatureValue::LongValue), extracting the inner [`i64`](i64).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_feature_value.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_feature_value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "efae8dde6b3a28e26f5a6f490af3a3cb9f358521a60624ddb0ff01f4ee450618"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_string_value\n\nDocumentation:\nTries to convert the enum instance into\n[`StringValue`](crate::types::FeatureValue::StringValue), extracting the inner\n[`String`](::std::string::String). Returns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_string_value(&self) -> ::std::result::Result<&::std::string::String, &Self> {\n if let FeatureValue::StringValue(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_string_value", "docstring": "Tries to convert the enum instance into\n[`StringValue`](crate::types::FeatureValue::StringValue), extracting the inner\n[`String`](::std::string::String). Returns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_feature_value.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_feature_value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8cf93ddf6dc54f69ecac3383c424b2e506d64c806e7770223ce9b5b002da335e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`FileContext`](crate::types::FileContext).\nThis method will fail if any of the following fields are not set:\n- [`left_file_content`](crate::types::builders::FileContextBuilder::left_file_content)\n- [`right_file_content`](crate::types::builders::FileContextBuilder::right_file_content)\n- [`filename`](crate::types::builders::FileContextBuilder::filename)\n- [`programming_language`](crate::types::builders::FileContextBuilder::programming_language)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::FileContext {\n left_file_content: self.left_file_content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"left_file_content\",\n \"left_file_content was not specified but it is required when building FileContext\",\n )\n })?,\n right_file_content: self.right_file_content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"right_file_content\",\n \"right_file_content was not specified but it is required when building FileContext\",\n )\n })?,\n filename: self.filename.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"filename\",\n \"filename was not specified but it is required when building FileContext\",\n )\n })?,\n file_uri: self.file_uri,\n programming_language: self.programming_language.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"programming_language\",\n \"programming_language was not specified but it is required when building FileContext\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`FileContext`](crate::types::FileContext).\nThis method will fail if any of the following fields are not set:\n- [`left_file_content`](crate::types::builders::FileContextBuilder::left_file_content)\n- [`right_file_content`](crate::types::builders::FileContextBuilder::right_file_content)\n- [`filename`](crate::types::builders::FileContextBuilder::filename)\n- [`programming_language`](crate::types::builders::FileContextBuilder::programming_language)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_file_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_file_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3db189c58e339d47a607e29f3bc93ce78b9df6a075c9620bf00edbcf32ecc330"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`FollowupPrompt`](crate::types::FollowupPrompt).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::FollowupPromptBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::FollowupPrompt {\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building FollowupPrompt\",\n )\n })?,\n user_intent: self.user_intent,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`FollowupPrompt`](crate::types::FollowupPrompt).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::FollowupPromptBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_followup_prompt.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_followup_prompt.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "241dd829f44fbe4dd7c74150f233eb3284b24977fcef194f7429448938619c7f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`GitState`](crate::types::GitState).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::GitState {\n crate::types::GitState { status: self.status }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`GitState`](crate::types::GitState).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_git_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_git_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f1f5f0565460421d9f3e61f5ed46f28c9f34c2792d8b0daae48ac3ec9ca3760"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_external_identity_details\n\nDocumentation:\nTries to convert the enum instance into\n[`ExternalIdentityDetails`](crate::types::IdentityDetails::ExternalIdentityDetails),\nextracting the inner [`ExternalIdentityDetails`](crate::types::ExternalIdentityDetails).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_external_identity_details(&self) -> ::std::result::Result<&crate::types::ExternalIdentityDetails, &Self> {\n if let IdentityDetails::ExternalIdentityDetails(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_external_identity_details", "docstring": "Tries to convert the enum instance into\n[`ExternalIdentityDetails`](crate::types::IdentityDetails::ExternalIdentityDetails),\nextracting the inner [`ExternalIdentityDetails`](crate::types::ExternalIdentityDetails).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_identity_details.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_identity_details.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e5cb7cc3d328fc9d7f39622d9d70cf24d9a3c95dabb4af7562560b128cbbade"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_sso_identity_details\n\nDocumentation:\nTries to convert the enum instance into\n[`SsoIdentityDetails`](crate::types::IdentityDetails::SsoIdentityDetails), extracting the\ninner [`SsoIdentityDetails`](crate::types::SsoIdentityDetails). Returns `Err(&Self)` if\nit can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_sso_identity_details(&self) -> ::std::result::Result<&crate::types::SsoIdentityDetails, &Self> {\n if let IdentityDetails::SsoIdentityDetails(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_sso_identity_details", "docstring": "Tries to convert the enum instance into\n[`SsoIdentityDetails`](crate::types::IdentityDetails::SsoIdentityDetails), extracting the\ninner [`SsoIdentityDetails`](crate::types::SsoIdentityDetails). Returns `Err(&Self)` if\nit can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_identity_details.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_identity_details.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c2a9bc9d480c675c47dd63e4c507b489703096fc181204801bb98723ec3b90b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: range\n\nDocumentation:\nThe range at which the message applies.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn range(mut self, input: crate::types::Range) -> Self {\n self.range = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "range", "docstring": "The range at which the message applies.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_ide_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_ide_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "880a08c1d9196ecc20c9975c3ae1504203dc1e5063d2bb2c43a520c0a4963bfa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ide_diagnostic_type\n\nDocumentation:\nType of the diagnostic\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ide_diagnostic_type(mut self, input: crate::types::IdeDiagnosticType) -> Self {\n self.ide_diagnostic_type = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "ide_diagnostic_type", "docstring": "Type of the diagnostic\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_ide_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_ide_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "369c6c1c277ba602f4b9b4a932a43005e1607a2e7cdc4a247272c0e13035a083"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`IdeDiagnostic`](crate::types::IdeDiagnostic).\nThis method will fail if any of the following fields are not set:\n- [`ide_diagnostic_type`](crate::types::builders::IdeDiagnosticBuilder::ide_diagnostic_type)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::IdeDiagnostic {\n range: self.range,\n source: self.source,\n severity: self.severity,\n ide_diagnostic_type: self.ide_diagnostic_type.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"ide_diagnostic_type\",\n \"ide_diagnostic_type was not specified but it is required when building IdeDiagnostic\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`IdeDiagnostic`](crate::types::IdeDiagnostic).\nThis method will fail if any of the following fields are not set:\n- [`ide_diagnostic_type`](crate::types::builders::IdeDiagnosticBuilder::ide_diagnostic_type)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_ide_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_ide_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09b9a4612f6d656ffeabae3744881e112b8b286e0b888eb184cc4060fa1855ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ImageBlock`](crate::types::ImageBlock).\nThis method will fail if any of the following fields are not set:\n- [`format`](crate::types::builders::ImageBlockBuilder::format)\n- [`source`](crate::types::builders::ImageBlockBuilder::source)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::ImageBlock {\n format: self.format.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"format\",\n \"format was not specified but it is required when building ImageBlock\",\n )\n })?,\n source: self.source.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"source\",\n \"source was not specified but it is required when building ImageBlock\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ImageBlock`](crate::types::ImageBlock).\nThis method will fail if any of the following fields are not set:\n- [`format`](crate::types::builders::ImageBlockBuilder::format)\n- [`source`](crate::types::builders::ImageBlockBuilder::source)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_image_block.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_image_block.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d86794073f180925728a065982470e3c602907fe9ee57f17f7b5d87529349b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Import`](crate::types::Import).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::Import {\n crate::types::Import {\n statement: self.statement,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Import`](crate::types::Import).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_import.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_import.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "29643661c4d5540a9550025870ec06c2eca5887b581cd90e158ab10c45b66357"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`InlineChatEvent`](crate::types::InlineChatEvent).\nThis method will fail if any of the following fields are not set:\n- [`request_id`](crate::types::builders::InlineChatEventBuilder::request_id)\n- [`timestamp`](crate::types::builders::InlineChatEventBuilder::timestamp)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::InlineChatEvent {\n request_id: self.request_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"request_id\",\n \"request_id was not specified but it is required when building InlineChatEvent\",\n )\n })?,\n timestamp: self.timestamp.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"timestamp\",\n \"timestamp was not specified but it is required when building InlineChatEvent\",\n )\n })?,\n input_length: self.input_length.unwrap_or_default(),\n num_selected_lines: self.num_selected_lines.unwrap_or_default(),\n num_suggestion_add_chars: self.num_suggestion_add_chars.unwrap_or_default(),\n num_suggestion_add_lines: self.num_suggestion_add_lines.unwrap_or_default(),\n num_suggestion_del_chars: self.num_suggestion_del_chars.unwrap_or_default(),\n num_suggestion_del_lines: self.num_suggestion_del_lines.unwrap_or_default(),\n code_intent: self.code_intent,\n user_decision: self.user_decision,\n response_start_latency: self.response_start_latency,\n response_end_latency: self.response_end_latency,\n programming_language: self.programming_language,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`InlineChatEvent`](crate::types::InlineChatEvent).\nThis method will fail if any of the following fields are not set:\n- [`request_id`](crate::types::builders::InlineChatEventBuilder::request_id)\n- [`timestamp`](crate::types::builders::InlineChatEventBuilder::timestamp)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_inline_chat_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_inline_chat_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8373dd8b8ba4f4f88a235e692b8395fdc4830f636f4e322a6a68d7e5972ae381"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_documentation\n\nDocumentation:\nTries to convert the enum instance into\n[`Documentation`](crate::types::IntentContext::Documentation), extracting the inner\n[`DocumentationIntentContext`](crate::types::DocumentationIntentContext). Returns `Err(&\nSelf)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_documentation(&self) -> ::std::result::Result<&crate::types::DocumentationIntentContext, &Self> {\n if let IntentContext::Documentation(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_documentation", "docstring": "Tries to convert the enum instance into\n[`Documentation`](crate::types::IntentContext::Documentation), extracting the inner\n[`DocumentationIntentContext`](crate::types::DocumentationIntentContext). Returns `Err(&\nSelf)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_intent_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_intent_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b297f5a09db3872ceeee961c1add4fcf37b51502b6932d8ce2d0d13a43f762d5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: metadata\n\nDocumentation:\nMetadata for a single memory entry\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn metadata(mut self, input: crate::types::MemoryEntryMetadata) -> Self {\n self.metadata = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "metadata", "docstring": "Metadata for a single memory entry\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_memory_entry.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_memory_entry.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d2e4dd611b639b1b661ae4ba44a606b86de28b02c6c7dbe41ea6d23f245daaad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`MemoryEntry`](crate::types::MemoryEntry).\nThis method will fail if any of the following fields are not set:\n- [`id`](crate::types::builders::MemoryEntryBuilder::id)\n- [`memory_entry_string`](crate::types::builders::MemoryEntryBuilder::memory_entry_string)\n- [`metadata`](crate::types::builders::MemoryEntryBuilder::metadata)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::MemoryEntry {\n id: self.id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"id\",\n \"id was not specified but it is required when building MemoryEntry\",\n )\n })?,\n memory_entry_string: self.memory_entry_string.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"memory_entry_string\",\n \"memory_entry_string was not specified but it is required when building MemoryEntry\",\n )\n })?,\n metadata: self.metadata.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"metadata\",\n \"metadata was not specified but it is required when building MemoryEntry\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`MemoryEntry`](crate::types::MemoryEntry).\nThis method will fail if any of the following fields are not set:\n- [`id`](crate::types::builders::MemoryEntryBuilder::id)\n- [`memory_entry_string`](crate::types::builders::MemoryEntryBuilder::memory_entry_string)\n- [`metadata`](crate::types::builders::MemoryEntryBuilder::metadata)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_memory_entry.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_memory_entry.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d72ca27d4bde0f7908d3244ab4dbdf194c3543deea52016758ceb80161313bde"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: attributes\n\nDocumentation:\nAttributes is a map of key-value pairs\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn attributes(\n &self,\n ) -> ::std::option::Option<\n &::std::collections::HashMap<::std::string::String, ::std::vec::Vec<::std::string::String>>,\n > {\n self.attributes.as_ref()\n }\n```"}], "func_name": "attributes", "docstring": "Attributes is a map of key-value pairs", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_memory_entry_metadata.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_memory_entry_metadata.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1543f365c42f89ba642dc63e477cf2be7872011690628635b45d5724949b474f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: attributes\n\nDocumentation:\nAdds a key-value pair to `attributes`.\n\nTo override the contents of this collection use [`set_attributes`](Self::set_attributes).\n\nAttributes is a map of key-value pairs\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn attributes(\n mut self,\n k: impl ::std::convert::Into<::std::string::String>,\n v: ::std::vec::Vec<::std::string::String>,\n ) -> Self {\n let mut hash_map = self.attributes.unwrap_or_default();\n hash_map.insert(k.into(), v);\n self.attributes = ::std::option::Option::Some(hash_map);\n self\n }\n```"}], "func_name": "attributes", "docstring": "Adds a key-value pair to `attributes`.\n\nTo override the contents of this collection use [`set_attributes`](Self::set_attributes).\n\nAttributes is a map of key-value pairs", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_memory_entry_metadata.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_memory_entry_metadata.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e97220174c8ec60006df9ec2331d0b1f9ed6c341ac98abef957e5e605cfdd65"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`MemoryEntryMetadata`](crate::types::MemoryEntryMetadata). This method will fail if any\nof the following fields are not set:\n- [`origin`](crate::types::builders::MemoryEntryMetadataBuilder::origin)\n- [`created_at`](crate::types::builders::MemoryEntryMetadataBuilder::created_at)\n- [`updated_at`](crate::types::builders::MemoryEntryMetadataBuilder::updated_at)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::MemoryEntryMetadata {\n origin: self.origin.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"origin\",\n \"origin was not specified but it is required when building MemoryEntryMetadata\",\n )\n })?,\n attributes: self.attributes,\n created_at: self.created_at.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"created_at\",\n \"created_at was not specified but it is required when building MemoryEntryMetadata\",\n )\n })?,\n updated_at: self.updated_at.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"updated_at\",\n \"updated_at was not specified but it is required when building MemoryEntryMetadata\",\n )\n })?,\n memory_status: self.memory_status,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`MemoryEntryMetadata`](crate::types::MemoryEntryMetadata). This method will fail if any\nof the following fields are not set:\n- [`origin`](crate::types::builders::MemoryEntryMetadataBuilder::origin)\n- [`created_at`](crate::types::builders::MemoryEntryMetadataBuilder::created_at)\n- [`updated_at`](crate::types::builders::MemoryEntryMetadataBuilder::updated_at)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_memory_entry_metadata.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_memory_entry_metadata.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2adb331586cb81995f32d237f5095f4fec0d1b6035a63dd19666ab793bc249a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`MetricData`](crate::types::MetricData).\nThis method will fail if any of the following fields are not set:\n- [`metric_name`](crate::types::builders::MetricDataBuilder::metric_name)\n- [`metric_value`](crate::types::builders::MetricDataBuilder::metric_value)\n- [`timestamp`](crate::types::builders::MetricDataBuilder::timestamp)\n- [`product`](crate::types::builders::MetricDataBuilder::product)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::MetricData {\n metric_name: self.metric_name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"metric_name\",\n \"metric_name was not specified but it is required when building MetricData\",\n )\n })?,\n metric_value: self.metric_value.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"metric_value\",\n \"metric_value was not specified but it is required when building MetricData\",\n )\n })?,\n timestamp: self.timestamp.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"timestamp\",\n \"timestamp was not specified but it is required when building MetricData\",\n )\n })?,\n product: self.product.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"product\",\n \"product was not specified but it is required when building MetricData\",\n )\n })?,\n dimensions: self.dimensions,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`MetricData`](crate::types::MetricData).\nThis method will fail if any of the following fields are not set:\n- [`metric_name`](crate::types::builders::MetricDataBuilder::metric_name)\n- [`metric_value`](crate::types::builders::MetricDataBuilder::metric_value)\n- [`timestamp`](crate::types::builders::MetricDataBuilder::timestamp)\n- [`product`](crate::types::builders::MetricDataBuilder::product)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_metric_data.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_metric_data.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aa4f19b0e6260a48271f77fc08687fcff26f2e11e460fbbfaa4b0a7de115de08"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`NotificationsFeature`](crate::types::NotificationsFeature). This method will fail if\nany of the following fields are not set:\n- [`feature`](crate::types::builders::NotificationsFeatureBuilder::feature)\n- [`toggle`](crate::types::builders::NotificationsFeatureBuilder::toggle)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::NotificationsFeature {\n feature: self.feature.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"feature\",\n \"feature was not specified but it is required when building NotificationsFeature\",\n )\n })?,\n toggle: self.toggle.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"toggle\",\n \"toggle was not specified but it is required when building NotificationsFeature\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`NotificationsFeature`](crate::types::NotificationsFeature). This method will fail if\nany of the following fields are not set:\n- [`feature`](crate::types::builders::NotificationsFeatureBuilder::feature)\n- [`toggle`](crate::types::builders::NotificationsFeatureBuilder::toggle)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_notifications_feature.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_notifications_feature.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6164cb530bc88fe809a34890ce69f5472ae247dcbc08cba458e8904f48868065"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: notifications\n\nDocumentation:\nAppends an item to `notifications`.\n\nTo override the contents of this collection use\n[`set_notifications`](Self::set_notifications).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn notifications(mut self, input: crate::types::NotificationsFeature) -> Self {\n let mut v = self.notifications.unwrap_or_default();\n v.push(input);\n self.notifications = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "notifications", "docstring": "Appends an item to `notifications`.\n\nTo override the contents of this collection use\n[`set_notifications`](Self::set_notifications).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_opt_in_features.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_opt_in_features.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6c3feb6eb22a365dadb020393093a7a3ca4d616b787844455a8cded23ce3b7d7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`OptInFeatures`](crate::types::OptInFeatures).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::OptInFeatures {\n crate::types::OptInFeatures {\n prompt_logging: self.prompt_logging,\n by_user_analytics: self.by_user_analytics,\n dashboard_analytics: self.dashboard_analytics,\n notifications: self.notifications,\n workspace_context: self.workspace_context,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`OptInFeatures`](crate::types::OptInFeatures).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_opt_in_features.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_opt_in_features.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d26ea6a048d5768099a7f9bf157cb0a2a0f5478015ee251c845ea5d77577c619"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: target_file_info_list\n\nDocumentation:\nAppends an item to `target_file_info_list`.\n\nTo override the contents of this collection use\n[`set_target_file_info_list`](Self::set_target_file_info_list).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn target_file_info_list(mut self, input: crate::types::TargetFileInfo) -> Self {\n let mut v = self.target_file_info_list.unwrap_or_default();\n v.push(input);\n self.target_file_info_list = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "target_file_info_list", "docstring": "Appends an item to `target_file_info_list`.\n\nTo override the contents of this collection use\n[`set_target_file_info_list`](Self::set_target_file_info_list).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_package_info.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_package_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8f26e0adf6554075af0f86af0a495aad09d84f3e9d7ce05ac1cf89724b72815e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`PackageInfo`](crate::types::PackageInfo).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::PackageInfo {\n crate::types::PackageInfo {\n execution_command: self.execution_command,\n build_command: self.build_command,\n build_order: self.build_order,\n test_framework: self.test_framework,\n package_summary: self.package_summary,\n package_plan: self.package_plan,\n target_file_info_list: self.target_file_info_list,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`PackageInfo`](crate::types::PackageInfo).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_package_info.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_package_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d25e4f553fb146a23e584c72cf93efb71c5f9cbaf4fe65069f1aa46c99e8165"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: line\n\nDocumentation:\nLine position in a document.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn line(mut self, input: i32) -> Self {\n self.line = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "line", "docstring": "Line position in a document.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_position.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_position.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e45db7fe86e13408a8f37ca92c2c491a720bdcb63b23db031fc3081cbdc1433"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: character\n\nDocumentation:\nCharacter offset on a line in a document (zero-based)\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn character(mut self, input: i32) -> Self {\n self.character = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "character", "docstring": "Character offset on a line in a document (zero-based)\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_position.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_position.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3d511e74a3d6c2bdc0ee5c920dc0802c87429b2d63ddd92b42153eef904c63e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_character\n\nDocumentation:\nCharacter offset on a line in a document (zero-based)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_character(mut self, input: ::std::option::Option) -> Self {\n self.character = input;\n self\n }\n```"}], "func_name": "set_character", "docstring": "Character offset on a line in a document (zero-based)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_position.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_position.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b1946624b16eb32d9b8c8b6dc6577cedd940a522ccf7957ba535809084b4c534"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Position`](crate::types::Position).\nThis method will fail if any of the following fields are not set:\n- [`line`](crate::types::builders::PositionBuilder::line)\n- [`character`](crate::types::builders::PositionBuilder::character)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Position {\n line: self.line.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"line\",\n \"line was not specified but it is required when building Position\",\n )\n })?,\n character: self.character.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"character\",\n \"character was not specified but it is required when building Position\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Position`](crate::types::Position).\nThis method will fail if any of the following fields are not set:\n- [`line`](crate::types::builders::PositionBuilder::line)\n- [`character`](crate::types::builders::PositionBuilder::character)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_position.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_position.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4b0eb0c841565277a4ac1da0d0309decca84c96f3a3cb977acc76b23cd960e4b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_completion\n\nDocumentation:\nTries to convert the enum instance into\n[`Completion`](crate::types::Prediction::Completion), extracting the inner\n[`Completion`](crate::types::Completion). Returns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_completion(&self) -> ::std::result::Result<&crate::types::Completion, &Self> {\n if let Prediction::Completion(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_completion", "docstring": "Tries to convert the enum instance into\n[`Completion`](crate::types::Prediction::Completion), extracting the inner\n[`Completion`](crate::types::Completion). Returns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_prediction.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_prediction.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a99b8db80d0a963c3bab4d2d5b1a18a025e863d9dc272e806045e9ce57c1fc44"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_edit\n\nDocumentation:\nTries to convert the enum instance into [`Edit`](crate::types::Prediction::Edit), extracting\nthe inner [`Edit`](crate::types::Edit). Returns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_edit(&self) -> ::std::result::Result<&crate::types::Edit, &Self> {\n if let Prediction::Edit(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_edit", "docstring": "Tries to convert the enum instance into [`Edit`](crate::types::Prediction::Edit), extracting\nthe inner [`Edit`](crate::types::Edit). Returns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_prediction.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_prediction.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4256bc41e5312067c215433761047e641e0ef25af3ef43d69e8a2167248a22e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`PreviousEditorStateMetadata`](crate::types::PreviousEditorStateMetadata). This method\nwill fail if any of the following fields are not set:\n- [`time_offset`](crate::types::builders::PreviousEditorStateMetadataBuilder::time_offset)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::PreviousEditorStateMetadata,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::PreviousEditorStateMetadata {\n time_offset: self.time_offset.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"time_offset\",\n \"time_offset was not specified but it is required when building PreviousEditorStateMetadata\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`PreviousEditorStateMetadata`](crate::types::PreviousEditorStateMetadata). This method\nwill fail if any of the following fields are not set:\n- [`time_offset`](crate::types::builders::PreviousEditorStateMetadataBuilder::time_offset)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_previous_editor_state_metadata.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_previous_editor_state_metadata.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dedc2b46f4a7cd369286a6a356fc76a2719f0fa8a36c4555c488a58e23c1b973"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: active_functionalities\n\nDocumentation:\nAppends an item to `active_functionalities`.\n\nTo override the contents of this collection use\n[`set_active_functionalities`](Self::set_active_functionalities).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn active_functionalities(mut self, input: crate::types::FunctionalityName) -> Self {\n let mut v = self.active_functionalities.unwrap_or_default();\n v.push(input);\n self.active_functionalities = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "active_functionalities", "docstring": "Appends an item to `active_functionalities`.\n\nTo override the contents of this collection use\n[`set_active_functionalities`](Self::set_active_functionalities).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_profile.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_profile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "99734e30444d5abe004019573656eec2f583f49e82050dcb8571f23176e3f9c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: application_properties\n\nDocumentation:\nAppends an item to `application_properties`.\n\nTo override the contents of this collection use\n[`set_application_properties`](Self::set_application_properties).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn application_properties(mut self, input: crate::types::ApplicationProperties) -> Self {\n let mut v = self.application_properties.unwrap_or_default();\n v.push(input);\n self.application_properties = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "application_properties", "docstring": "Appends an item to `application_properties`.\n\nTo override the contents of this collection use\n[`set_application_properties`](Self::set_application_properties).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_profile.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_profile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ee7f041ff64462268e561d3220d990b99a1885653dda929c5e170f397d2aa15"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Profile`](crate::types::Profile).\nThis method will fail if any of the following fields are not set:\n- [`arn`](crate::types::builders::ProfileBuilder::arn)\n- [`profile_name`](crate::types::builders::ProfileBuilder::profile_name)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Profile {\n arn: self.arn.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"arn\",\n \"arn was not specified but it is required when building Profile\",\n )\n })?,\n identity_details: self.identity_details,\n profile_name: self.profile_name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"profile_name\",\n \"profile_name was not specified but it is required when building Profile\",\n )\n })?,\n description: self.description,\n reference_tracker_configuration: self.reference_tracker_configuration,\n kms_key_arn: self.kms_key_arn,\n active_functionalities: self.active_functionalities,\n status: self.status,\n error_details: self.error_details,\n resource_policy: self.resource_policy,\n profile_type: self.profile_type,\n opt_in_features: self.opt_in_features,\n permission_update_required: self.permission_update_required,\n application_properties: self.application_properties,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Profile`](crate::types::Profile).\nThis method will fail if any of the following fields are not set:\n- [`arn`](crate::types::builders::ProfileBuilder::arn)\n- [`profile_name`](crate::types::builders::ProfileBuilder::profile_name)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_profile.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_profile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6dc29dd9854ce51c7293ed947bdc0ca8bc1c94c0fcacaec1a2b60d583617ae27"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ProgrammingLanguage`](crate::types::ProgrammingLanguage). This method will fail if any\nof the following fields are not set:\n- [`language_name`](crate::types::builders::ProgrammingLanguageBuilder::language_name)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::ProgrammingLanguage {\n language_name: self.language_name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"language_name\",\n \"language_name was not specified but it is required when building ProgrammingLanguage\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ProgrammingLanguage`](crate::types::ProgrammingLanguage). This method will fail if any\nof the following fields are not set:\n- [`language_name`](crate::types::builders::ProgrammingLanguageBuilder::language_name)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_programming_language.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_programming_language.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "46d3b8c9b87033a4c1e2883982214ba94c0948ae48acf25ca22acfd2ea78f53f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`PromptLogging`](crate::types::PromptLogging).\nThis method will fail if any of the following fields are not set:\n- [`s3_uri`](crate::types::builders::PromptLoggingBuilder::s3_uri)\n- [`toggle`](crate::types::builders::PromptLoggingBuilder::toggle)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::PromptLogging {\n s3_uri: self.s3_uri.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"s3_uri\",\n \"s3_uri was not specified but it is required when building PromptLogging\",\n )\n })?,\n toggle: self.toggle.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"toggle\",\n \"toggle was not specified but it is required when building PromptLogging\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`PromptLogging`](crate::types::PromptLogging).\nThis method will fail if any of the following fields are not set:\n- [`s3_uri`](crate::types::builders::PromptLoggingBuilder::s3_uri)\n- [`toggle`](crate::types::builders::PromptLoggingBuilder::toggle)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_prompt_logging.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_prompt_logging.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "738d2c100e0bddc55866688e20adec367334655bc9378abe7e4d36c488deaaa5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start\n\nDocumentation:\nThe range's start position.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start(mut self, input: crate::types::Position) -> Self {\n self.start = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "start", "docstring": "The range's start position.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_range.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_range.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d387e37c000deae542406c45d599af022dcca159678f079cb2be43856f11221a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: end\n\nDocumentation:\nThe range's end position.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn end(mut self, input: crate::types::Position) -> Self {\n self.end = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "end", "docstring": "The range's end position.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_range.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_range.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a91057bb2fba610dced12f4a23646954b80ec803d91aec3d87a6cd57205e8433"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Range`](crate::types::Range).\nThis method will fail if any of the following fields are not set:\n- [`start`](crate::types::builders::RangeBuilder::start)\n- [`end`](crate::types::builders::RangeBuilder::end)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Range {\n start: self.start.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"start\",\n \"start was not specified but it is required when building Range\",\n )\n })?,\n end: self.end.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"end\",\n \"end was not specified but it is required when building Range\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Range`](crate::types::Range).\nThis method will fail if any of the following fields are not set:\n- [`start`](crate::types::builders::RangeBuilder::start)\n- [`end`](crate::types::builders::RangeBuilder::end)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_range.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_range.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "67c2f3c68f5b1e63e10ce6511cd5fe68603bdec5dd51e12b5128423ed2387c85"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Reference`](crate::types::Reference).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::Reference {\n crate::types::Reference {\n license_name: self.license_name,\n repository: self.repository,\n url: self.url,\n recommendation_content_span: self.recommendation_content_span,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Reference`](crate::types::Reference).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_reference.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_reference.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac63dcd58253c542b6aef4a4e927044ef5a3fb3b2b1350bff9abd8ac5a2cdea7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: recommendations_with_references\n\nDocumentation:\nRecommendations with references setting for CodeWhisperer\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn recommendations_with_references(\n mut self,\n input: crate::types::RecommendationsWithReferencesPreference,\n ) -> Self {\n self.recommendations_with_references = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "recommendations_with_references", "docstring": "Recommendations with references setting for CodeWhisperer\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_reference_tracker_configuration.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_reference_tracker_configuration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "13b504bf7d64c902da3f664f8810f0ce720784075f7b5ef0ed1b1d45ae782365"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_recommendations_with_references\n\nDocumentation:\nRecommendations with references setting for CodeWhisperer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_recommendations_with_references(\n mut self,\n input: ::std::option::Option,\n ) -> Self {\n self.recommendations_with_references = input;\n self\n }\n```"}], "func_name": "set_recommendations_with_references", "docstring": "Recommendations with references setting for CodeWhisperer", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_reference_tracker_configuration.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_reference_tracker_configuration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "29a67b1e844cf002bf69bbb4aebfb1cad952c812922aba7351fbd833a0eb68d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ReferenceTrackerConfiguration`](crate::types::ReferenceTrackerConfiguration).\nThis method will fail if any of the following fields are not set:\n- [`recommendations_with_references`](crate::types::builders::ReferenceTrackerConfigurationBuilder::recommendations_with_references)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::ReferenceTrackerConfiguration,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::ReferenceTrackerConfiguration {\n recommendations_with_references: self.recommendations_with_references.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"recommendations_with_references\",\n \"recommendations_with_references was not specified but it is required when building ReferenceTrackerConfiguration\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ReferenceTrackerConfiguration`](crate::types::ReferenceTrackerConfiguration).\nThis method will fail if any of the following fields are not set:\n- [`recommendations_with_references`](crate::types::builders::ReferenceTrackerConfigurationBuilder::recommendations_with_references)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_reference_tracker_configuration.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_reference_tracker_configuration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1cb8cf3c7aa12abc82abbc4ea38d2756a0fe57416dd41e464385ef01702958fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: relative_file_path\n\nDocumentation:\nFilepath relative to the root of the workspace\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn relative_file_path(&self) -> &str {\n use std::ops::Deref;\n self.relative_file_path.deref()\n }\n```"}], "func_name": "relative_file_path", "docstring": "Filepath relative to the root of the workspace", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_relevant_text_document.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_relevant_text_document.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "654ec463fe45e8e5625e170da68ae170b3c5fc72264addd737d217b8572c2a50"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: relative_file_path\n\nDocumentation:\nFilepath relative to the root of the workspace\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn relative_file_path(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.relative_file_path = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "relative_file_path", "docstring": "Filepath relative to the root of the workspace\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_relevant_text_document.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_relevant_text_document.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7d17311d3000b325d30ad29adfdd7cd37741daa8bd23ad80a256d3119455b57e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: document_symbols\n\nDocumentation:\nAppends an item to `document_symbols`.\n\nTo override the contents of this collection use\n[`set_document_symbols`](Self::set_document_symbols).\n\nDocumentSymbols parsed from a text document\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn document_symbols(mut self, input: crate::types::DocumentSymbol) -> Self {\n let mut v = self.document_symbols.unwrap_or_default();\n v.push(input);\n self.document_symbols = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "document_symbols", "docstring": "Appends an item to `document_symbols`.\n\nTo override the contents of this collection use\n[`set_document_symbols`](Self::set_document_symbols).\n\nDocumentSymbols parsed from a text document", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_relevant_text_document.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_relevant_text_document.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ab062e71130dc79462fce7229d057506c474cf94f7ec5562edad371fd5f9b6f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: r#type\n\nDocumentation:\nThe type of content(file, prompt, symbol, or workspace)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn r#type(mut self, input: crate::types::ContentType) -> Self {\n self.r#type = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "r#type", "docstring": "The type of content(file, prompt, symbol, or workspace)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_relevant_text_document.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_relevant_text_document.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb21c24eda046dee1fbba0831d418cee3067cdd2515a2762d06b01dbfc12585c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`RelevantTextDocument`](crate::types::RelevantTextDocument). This method will fail if\nany of the following fields are not set:\n- [`relative_file_path`](crate::types::builders::RelevantTextDocumentBuilder::relative_file_path)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::RelevantTextDocument {\n relative_file_path: self.relative_file_path.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"relative_file_path\",\n \"relative_file_path was not specified but it is required when building RelevantTextDocument\",\n )\n })?,\n programming_language: self.programming_language,\n text: self.text,\n document_symbols: self.document_symbols,\n r#type: self.r#type,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`RelevantTextDocument`](crate::types::RelevantTextDocument). This method will fail if\nany of the following fields are not set:\n- [`relative_file_path`](crate::types::builders::RelevantTextDocumentBuilder::relative_file_path)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_relevant_text_document.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_relevant_text_document.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "41939d0f5d727dae84d7f2bdf46cc02b95644e8d025a3254fee5b8168f4dc087"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ResourcePolicy`](crate::types::ResourcePolicy).\nThis method will fail if any of the following fields are not set:\n- [`effect`](crate::types::builders::ResourcePolicyBuilder::effect)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::ResourcePolicy {\n effect: self.effect.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"effect\",\n \"effect was not specified but it is required when building ResourcePolicy\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ResourcePolicy`](crate::types::ResourcePolicy).\nThis method will fail if any of the following fields are not set:\n- [`effect`](crate::types::builders::ResourcePolicyBuilder::effect)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_resource_policy.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_resource_policy.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f704155816180623823cd24b2de81ffcb0769ef1236830b57d944d00eb33bea3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: severity\n\nDocumentation:\nDiagnostic Error type\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn severity(mut self, input: crate::types::DiagnosticSeverity) -> Self {\n self.severity = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "severity", "docstring": "Diagnostic Error type\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_runtime_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_runtime_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a38ef450b34605f7a2c8552850a15e63a3a9b665f1c3c2733e03c80641e68e85"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`RuntimeDiagnostic`](crate::types::RuntimeDiagnostic). This method will fail if any of\nthe following fields are not set:\n- [`source`](crate::types::builders::RuntimeDiagnosticBuilder::source)\n- [`severity`](crate::types::builders::RuntimeDiagnosticBuilder::severity)\n- [`message`](crate::types::builders::RuntimeDiagnosticBuilder::message)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::RuntimeDiagnostic {\n source: self.source.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"source\",\n \"source was not specified but it is required when building RuntimeDiagnostic\",\n )\n })?,\n severity: self.severity.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"severity\",\n \"severity was not specified but it is required when building RuntimeDiagnostic\",\n )\n })?,\n message: self.message.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message\",\n \"message was not specified but it is required when building RuntimeDiagnostic\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`RuntimeDiagnostic`](crate::types::RuntimeDiagnostic). This method will fail if any of\nthe following fields are not set:\n- [`source`](crate::types::builders::RuntimeDiagnosticBuilder::source)\n- [`severity`](crate::types::builders::RuntimeDiagnosticBuilder::severity)\n- [`message`](crate::types::builders::RuntimeDiagnosticBuilder::message)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_runtime_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_runtime_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f686abf7225cd2623dea8142804b38338226d9fe263a8059323d6b4d59c5130"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ShellHistoryEntry`](crate::types::ShellHistoryEntry). This method will fail if any of\nthe following fields are not set:\n- [`command`](crate::types::builders::ShellHistoryEntryBuilder::command)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::ShellHistoryEntry {\n command: self.command.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"command\",\n \"command was not specified but it is required when building ShellHistoryEntry\",\n )\n })?,\n directory: self.directory,\n exit_code: self.exit_code,\n stdout: self.stdout,\n stderr: self.stderr,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ShellHistoryEntry`](crate::types::ShellHistoryEntry). This method will fail if any of\nthe following fields are not set:\n- [`command`](crate::types::builders::ShellHistoryEntryBuilder::command)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_shell_history_entry.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_shell_history_entry.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "70ab55f8463ee6c3d39e01eda0925bbdd9203e1af91f142a7274501f99d0c086"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shell_name\n\nDocumentation:\nThe name of the current shell\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn shell_name(&self) -> &str {\n use std::ops::Deref;\n self.shell_name.deref()\n }\n```"}], "func_name": "shell_name", "docstring": "The name of the current shell", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_shell_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_shell_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7dd3ef97a3cc5704653bc2e19d8a99033359a786034add00cd86e00d792793c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shell_name\n\nDocumentation:\nThe name of the current shell\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn shell_name(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.shell_name = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "shell_name", "docstring": "The name of the current shell\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_shell_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_shell_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c40e4e1c9fbcf028a94225a5cc8081c2af6604982e0d4ca1a5e8b1be70bd2c6e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shell_history\n\nDocumentation:\nAppends an item to `shell_history`.\n\nTo override the contents of this collection use\n[`set_shell_history`](Self::set_shell_history).\n\nThe history previous shell commands for the current shell\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn shell_history(mut self, input: crate::types::ShellHistoryEntry) -> Self {\n let mut v = self.shell_history.unwrap_or_default();\n v.push(input);\n self.shell_history = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "shell_history", "docstring": "Appends an item to `shell_history`.\n\nTo override the contents of this collection use\n[`set_shell_history`](Self::set_shell_history).\n\nThe history previous shell commands for the current shell", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_shell_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_shell_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c960087c75772e9c517e359b7a090aeca7ac1fed6509af7d0eb1d3b46964bb8f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_shell_history\n\nDocumentation:\nThe history previous shell commands for the current shell\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_shell_history(\n mut self,\n input: ::std::option::Option<::std::vec::Vec>,\n ) -> Self {\n self.shell_history = input;\n self\n }\n```"}], "func_name": "set_shell_history", "docstring": "The history previous shell commands for the current shell", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_shell_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_shell_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3676fb88cd7e18eaef5d28e495198f3a13c01ba0152898af0281c6e1bac82bf1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ShellState`](crate::types::ShellState).\nThis method will fail if any of the following fields are not set:\n- [`shell_name`](crate::types::builders::ShellStateBuilder::shell_name)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::ShellState {\n shell_name: self.shell_name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"shell_name\",\n \"shell_name was not specified but it is required when building ShellState\",\n )\n })?,\n shell_history: self.shell_history,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ShellState`](crate::types::ShellState).\nThis method will fail if any of the following fields are not set:\n- [`shell_name`](crate::types::builders::ShellStateBuilder::shell_name)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_shell_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_shell_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63ff461fc929d632c6b63513be6f41a7d0218434cda15f0d6fbbab65e1af63f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Span`](crate::types::Span).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::Span {\n crate::types::Span {\n start: self.start,\n end: self.end,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Span`](crate::types::Span).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_span.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_span.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "03fbb8ca49b4835411cb642d4ae5bf4e08c5d37af9a6e2f566c8a60e8a6ef728"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`SsoIdentityDetails`](crate::types::SsoIdentityDetails). This method will fail if any\nof the following fields are not set:\n- [`instance_arn`](crate::types::builders::SsoIdentityDetailsBuilder::instance_arn)\n- [`oidc_client_id`](crate::types::builders::SsoIdentityDetailsBuilder::oidc_client_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::SsoIdentityDetails {\n instance_arn: self.instance_arn.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"instance_arn\",\n \"instance_arn was not specified but it is required when building SsoIdentityDetails\",\n )\n })?,\n oidc_client_id: self.oidc_client_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"oidc_client_id\",\n \"oidc_client_id was not specified but it is required when building SsoIdentityDetails\",\n )\n })?,\n sso_region: self.sso_region,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`SsoIdentityDetails`](crate::types::SsoIdentityDetails). This method will fail if any\nof the following fields are not set:\n- [`instance_arn`](crate::types::builders::SsoIdentityDetailsBuilder::instance_arn)\n- [`oidc_client_id`](crate::types::builders::SsoIdentityDetailsBuilder::oidc_client_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_sso_identity_details.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_sso_identity_details.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82a55691b14dcfc08a06ea208b8a5c110850ac1f99f7238ae2fc4c3218de760a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`SuggestedFix`](crate::types::SuggestedFix).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::SuggestedFix {\n crate::types::SuggestedFix {\n code_diff: self.code_diff,\n description: self.description,\n references: self.references,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`SuggestedFix`](crate::types::SuggestedFix).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_suggested_fix.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_suggested_fix.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f978f192bfaf38e32d4a7c89f23828702f817400a3f81b7a5197490493d67cbc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`SupplementalContext`](crate::types::SupplementalContext). This method will fail if any\nof the following fields are not set:\n- [`file_path`](crate::types::builders::SupplementalContextBuilder::file_path)\n- [`content`](crate::types::builders::SupplementalContextBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::SupplementalContext {\n file_path: self.file_path.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"file_path\",\n \"file_path was not specified but it is required when building SupplementalContext\",\n )\n })?,\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building SupplementalContext\",\n )\n })?,\n r#type: self.r#type,\n metadata: self.metadata,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`SupplementalContext`](crate::types::SupplementalContext). This method will fail if any\nof the following fields are not set:\n- [`file_path`](crate::types::builders::SupplementalContextBuilder::file_path)\n- [`content`](crate::types::builders::SupplementalContextBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_supplemental_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_supplemental_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e408c9c2d069f3486796fc2ce66dcdfd931910c0f287460cc6c7b945728bfc2e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_previous_editor_state_metadata\n\nDocumentation:\nTries to convert the enum instance into\n[`PreviousEditorStateMetadata`](crate::types::SupplementalContextMetadata::PreviousEditorStateMetadata),\nextracting the inner\n[`PreviousEditorStateMetadata`](crate::types::PreviousEditorStateMetadata).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_previous_editor_state_metadata(\n &self,\n ) -> ::std::result::Result<&crate::types::PreviousEditorStateMetadata, &Self> {\n if let SupplementalContextMetadata::PreviousEditorStateMetadata(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_previous_editor_state_metadata", "docstring": "Tries to convert the enum instance into\n[`PreviousEditorStateMetadata`](crate::types::SupplementalContextMetadata::PreviousEditorStateMetadata),\nextracting the inner\n[`PreviousEditorStateMetadata`](crate::types::PreviousEditorStateMetadata).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_supplemental_context_metadata.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_supplemental_context_metadata.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "86519327bb486b1b2f54def77b10699e41f9c692ff0bc49273fe52298ed9293f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`SupplementaryWebLink`](crate::types::SupplementaryWebLink). This method will fail if\nany of the following fields are not set:\n- [`url`](crate::types::builders::SupplementaryWebLinkBuilder::url)\n- [`title`](crate::types::builders::SupplementaryWebLinkBuilder::title)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::SupplementaryWebLink {\n url: self.url.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"url\",\n \"url was not specified but it is required when building SupplementaryWebLink\",\n )\n })?,\n title: self.title.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"title\",\n \"title was not specified but it is required when building SupplementaryWebLink\",\n )\n })?,\n snippet: self.snippet,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`SupplementaryWebLink`](crate::types::SupplementaryWebLink). This method will fail if\nany of the following fields are not set:\n- [`url`](crate::types::builders::SupplementaryWebLinkBuilder::url)\n- [`title`](crate::types::builders::SupplementaryWebLinkBuilder::title)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_supplementary_web_link.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_supplementary_web_link.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bed15b1c8fa98d0ac92d665b315d829fc18c6ad0aa9096cb9750151d25368421"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: relative_target_path\n\nDocumentation:\nThe file path relative to the root of the workspace, could be a single file or a folder.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn relative_target_path(&self) -> &str {\n use std::ops::Deref;\n self.relative_target_path.deref()\n }\n```"}], "func_name": "relative_target_path", "docstring": "The file path relative to the root of the workspace, could be a single file or a folder.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_target_code.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_target_code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18b8111535c175300d95964f4dd9dfb8da253b42d7a3e3f603d8b73812f495ed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: relative_target_path\n\nDocumentation:\nThe file path relative to the root of the workspace, could be a single file or a folder.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn relative_target_path(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.relative_target_path = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "relative_target_path", "docstring": "The file path relative to the root of the workspace, could be a single file or a folder.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_target_code.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_target_code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "15bca3e92fca3b44984a9eca0a9806c2172fb51b08d98af6d5d2e198252db737"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: target_line_range_list\n\nDocumentation:\nAppends an item to `target_line_range_list`.\n\nTo override the contents of this collection use\n[`set_target_line_range_list`](Self::set_target_line_range_list).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn target_line_range_list(mut self, input: crate::types::Range) -> Self {\n let mut v = self.target_line_range_list.unwrap_or_default();\n v.push(input);\n self.target_line_range_list = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "target_line_range_list", "docstring": "Appends an item to `target_line_range_list`.\n\nTo override the contents of this collection use\n[`set_target_line_range_list`](Self::set_target_line_range_list).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_target_code.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_target_code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b5bfff59aadf8146e65cb4f9a8a4072c969dcdb2a199ca6eaea72f46de1e0425"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`TargetCode`](crate::types::TargetCode).\nThis method will fail if any of the following fields are not set:\n- [`relative_target_path`](crate::types::builders::TargetCodeBuilder::relative_target_path)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::TargetCode {\n relative_target_path: self.relative_target_path.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"relative_target_path\",\n \"relative_target_path was not specified but it is required when building TargetCode\",\n )\n })?,\n target_line_range_list: self.target_line_range_list,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`TargetCode`](crate::types::TargetCode).\nThis method will fail if any of the following fields are not set:\n- [`relative_target_path`](crate::types::builders::TargetCodeBuilder::relative_target_path)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_target_code.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_target_code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ab4b67765785a3c3d6fcc6c44c2c8d0722c815c17d4bc168b375bcc1dfa82d5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: code_references\n\nDocumentation:\nAppends an item to `code_references`.\n\nTo override the contents of this collection use\n[`set_code_references`](Self::set_code_references).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn code_references(mut self, input: crate::types::Reference) -> Self {\n let mut v = self.code_references.unwrap_or_default();\n v.push(input);\n self.code_references = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "code_references", "docstring": "Appends an item to `code_references`.\n\nTo override the contents of this collection use\n[`set_code_references`](Self::set_code_references).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_target_file_info.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_target_file_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a1a3e247026d396a7fe3d0107726875126714bde09395ec6256f508a71be6db1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`TargetFileInfo`](crate::types::TargetFileInfo).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::TargetFileInfo {\n crate::types::TargetFileInfo {\n file_path: self.file_path,\n test_file_path: self.test_file_path,\n test_coverage: self.test_coverage,\n file_summary: self.file_summary,\n file_plan: self.file_plan,\n code_references: self.code_references,\n number_of_test_methods: self.number_of_test_methods,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`TargetFileInfo`](crate::types::TargetFileInfo).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_target_file_info.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_target_file_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "42af5814211607c8939b45eb2fe67c05c2d57531922fbf0c9fdf3ba38da113d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TaskAssistPlanningUploadContext`](crate::types::TaskAssistPlanningUploadContext). This\nmethod will fail if any of the following fields are not set:\n- [`conversation_id`](crate::types::builders::TaskAssistPlanningUploadContextBuilder::conversation_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::TaskAssistPlanningUploadContext,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::TaskAssistPlanningUploadContext {\n conversation_id: self.conversation_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"conversation_id\",\n \"conversation_id was not specified but it is required when building TaskAssistPlanningUploadContext\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TaskAssistPlanningUploadContext`](crate::types::TaskAssistPlanningUploadContext). This\nmethod will fail if any of the following fields are not set:\n- [`conversation_id`](crate::types::builders::TaskAssistPlanningUploadContextBuilder::conversation_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_task_assist_planning_upload_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_task_assist_planning_upload_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "967bfa9486da08753e917f55369ef8a045d95d097fee71b83faf39ec1a226652"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TaskAssistPlanStep`](crate::types::TaskAssistPlanStep). This method will fail if any\nof the following fields are not set:\n- [`file_path`](crate::types::builders::TaskAssistPlanStepBuilder::file_path)\n- [`description`](crate::types::builders::TaskAssistPlanStepBuilder::description)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::TaskAssistPlanStep {\n file_path: self.file_path.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"file_path\",\n \"file_path was not specified but it is required when building TaskAssistPlanStep\",\n )\n })?,\n description: self.description.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"description\",\n \"description was not specified but it is required when building TaskAssistPlanStep\",\n )\n })?,\n start_line: self.start_line,\n end_line: self.end_line,\n action: self.action,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TaskAssistPlanStep`](crate::types::TaskAssistPlanStep). This method will fail if any\nof the following fields are not set:\n- [`file_path`](crate::types::builders::TaskAssistPlanStepBuilder::file_path)\n- [`description`](crate::types::builders::TaskAssistPlanStepBuilder::description)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_task_assist_plan_step.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_task_assist_plan_step.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d4fb0aa4d36e47d238e27aebadae1021e3f981dacc5befa8c0972c6d0a6f3b9b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_chat_add_message_event\n\nDocumentation:\nTries to convert the enum instance into\n[`ChatAddMessageEvent`](crate::types::TelemetryEvent::ChatAddMessageEvent), extracting the\ninner [`ChatAddMessageEvent`](crate::types::ChatAddMessageEvent). Returns `Err(&Self)`\nif it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_chat_add_message_event(&self) -> ::std::result::Result<&crate::types::ChatAddMessageEvent, &Self> {\n if let TelemetryEvent::ChatAddMessageEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_chat_add_message_event", "docstring": "Tries to convert the enum instance into\n[`ChatAddMessageEvent`](crate::types::TelemetryEvent::ChatAddMessageEvent), extracting the\ninner [`ChatAddMessageEvent`](crate::types::ChatAddMessageEvent). Returns `Err(&Self)`\nif it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e360868cb035fef33afadc559356e46f89737fcda291666096836a09c9102ee3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_chat_interact_with_message_event\n\nDocumentation:\nTries to convert the enum instance into\n[`ChatInteractWithMessageEvent`](crate::types::TelemetryEvent::ChatInteractWithMessageEvent),\nextracting the inner\n[`ChatInteractWithMessageEvent`](crate::types::ChatInteractWithMessageEvent).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_chat_interact_with_message_event(\n &self,\n ) -> ::std::result::Result<&crate::types::ChatInteractWithMessageEvent, &Self> {\n if let TelemetryEvent::ChatInteractWithMessageEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_chat_interact_with_message_event", "docstring": "Tries to convert the enum instance into\n[`ChatInteractWithMessageEvent`](crate::types::TelemetryEvent::ChatInteractWithMessageEvent),\nextracting the inner\n[`ChatInteractWithMessageEvent`](crate::types::ChatInteractWithMessageEvent).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5a42a7489dffdc5a6ca51d1cd226b6c66ad70439f2ef473aae704e7def5b363a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_chat_user_modification_event\n\nDocumentation:\nTries to convert the enum instance into\n[`ChatUserModificationEvent`](crate::types::TelemetryEvent::ChatUserModificationEvent),\nextracting the inner [`ChatUserModificationEvent`](crate::types::ChatUserModificationEvent).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_chat_user_modification_event(\n &self,\n ) -> ::std::result::Result<&crate::types::ChatUserModificationEvent, &Self> {\n if let TelemetryEvent::ChatUserModificationEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_chat_user_modification_event", "docstring": "Tries to convert the enum instance into\n[`ChatUserModificationEvent`](crate::types::TelemetryEvent::ChatUserModificationEvent),\nextracting the inner [`ChatUserModificationEvent`](crate::types::ChatUserModificationEvent).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f8a8bef6e984ab7a5c41a52593e87ca8b0e479c82214b5ca2d5e3e0eb59d2636"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_code_coverage_event\n\nDocumentation:\nTries to convert the enum instance into\n[`CodeCoverageEvent`](crate::types::TelemetryEvent::CodeCoverageEvent), extracting the inner\n[`CodeCoverageEvent`](crate::types::CodeCoverageEvent). Returns `Err(&Self)` if it can't\nbe converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_code_coverage_event(&self) -> ::std::result::Result<&crate::types::CodeCoverageEvent, &Self> {\n if let TelemetryEvent::CodeCoverageEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_code_coverage_event", "docstring": "Tries to convert the enum instance into\n[`CodeCoverageEvent`](crate::types::TelemetryEvent::CodeCoverageEvent), extracting the inner\n[`CodeCoverageEvent`](crate::types::CodeCoverageEvent). Returns `Err(&Self)` if it can't\nbe converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "276ec99f379567aa2614b6ecd7197f3c54ddb1ee1c21685cf1b15be126efcdb9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_code_fix_acceptance_event\n\nDocumentation:\nTries to convert the enum instance into\n[`CodeFixAcceptanceEvent`](crate::types::TelemetryEvent::CodeFixAcceptanceEvent), extracting\nthe inner [`CodeFixAcceptanceEvent`](crate::types::CodeFixAcceptanceEvent).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_code_fix_acceptance_event(&self) -> ::std::result::Result<&crate::types::CodeFixAcceptanceEvent, &Self> {\n if let TelemetryEvent::CodeFixAcceptanceEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_code_fix_acceptance_event", "docstring": "Tries to convert the enum instance into\n[`CodeFixAcceptanceEvent`](crate::types::TelemetryEvent::CodeFixAcceptanceEvent), extracting\nthe inner [`CodeFixAcceptanceEvent`](crate::types::CodeFixAcceptanceEvent).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "04e52e8f42e070bfd693fa107f9719cc706f70b9d49aa1b6bb3b693d2904cdb2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_code_fix_generation_event\n\nDocumentation:\nTries to convert the enum instance into\n[`CodeFixGenerationEvent`](crate::types::TelemetryEvent::CodeFixGenerationEvent), extracting\nthe inner [`CodeFixGenerationEvent`](crate::types::CodeFixGenerationEvent).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_code_fix_generation_event(&self) -> ::std::result::Result<&crate::types::CodeFixGenerationEvent, &Self> {\n if let TelemetryEvent::CodeFixGenerationEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_code_fix_generation_event", "docstring": "Tries to convert the enum instance into\n[`CodeFixGenerationEvent`](crate::types::TelemetryEvent::CodeFixGenerationEvent), extracting\nthe inner [`CodeFixGenerationEvent`](crate::types::CodeFixGenerationEvent).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "50d0cff61ed2d97d2e4acc332314720ece01feebe6694701cb7adc81cf15ca51"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_code_scan_event\n\nDocumentation:\nTries to convert the enum instance into\n[`CodeScanEvent`](crate::types::TelemetryEvent::CodeScanEvent), extracting the inner\n[`CodeScanEvent`](crate::types::CodeScanEvent). Returns `Err(&Self)` if it can't be\nconverted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_code_scan_event(&self) -> ::std::result::Result<&crate::types::CodeScanEvent, &Self> {\n if let TelemetryEvent::CodeScanEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_code_scan_event", "docstring": "Tries to convert the enum instance into\n[`CodeScanEvent`](crate::types::TelemetryEvent::CodeScanEvent), extracting the inner\n[`CodeScanEvent`](crate::types::CodeScanEvent). Returns `Err(&Self)` if it can't be\nconverted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "91a4ec9903103edae08ce805cff377dc67167a265d647c4789068b7503559250"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_code_scan_failed_event\n\nDocumentation:\nTries to convert the enum instance into\n[`CodeScanFailedEvent`](crate::types::TelemetryEvent::CodeScanFailedEvent), extracting the\ninner [`CodeScanFailedEvent`](crate::types::CodeScanFailedEvent). Returns `Err(&Self)`\nif it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_code_scan_failed_event(&self) -> ::std::result::Result<&crate::types::CodeScanFailedEvent, &Self> {\n if let TelemetryEvent::CodeScanFailedEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_code_scan_failed_event", "docstring": "Tries to convert the enum instance into\n[`CodeScanFailedEvent`](crate::types::TelemetryEvent::CodeScanFailedEvent), extracting the\ninner [`CodeScanFailedEvent`](crate::types::CodeScanFailedEvent). Returns `Err(&Self)`\nif it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "24391c656ccc419dba42484285bfdf80364ac2c5a8a653dce6232218fffe2f33"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_code_scan_remediations_event\n\nDocumentation:\nTries to convert the enum instance into\n[`CodeScanRemediationsEvent`](crate::types::TelemetryEvent::CodeScanRemediationsEvent),\nextracting the inner [`CodeScanRemediationsEvent`](crate::types::CodeScanRemediationsEvent).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_code_scan_remediations_event(\n &self,\n ) -> ::std::result::Result<&crate::types::CodeScanRemediationsEvent, &Self> {\n if let TelemetryEvent::CodeScanRemediationsEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_code_scan_remediations_event", "docstring": "Tries to convert the enum instance into\n[`CodeScanRemediationsEvent`](crate::types::TelemetryEvent::CodeScanRemediationsEvent),\nextracting the inner [`CodeScanRemediationsEvent`](crate::types::CodeScanRemediationsEvent).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "436e408fc819fc53bd6187f76e98ef0a2dce1604153996cae1b938cf5eefdc91"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_code_scan_succeeded_event\n\nDocumentation:\nTries to convert the enum instance into\n[`CodeScanSucceededEvent`](crate::types::TelemetryEvent::CodeScanSucceededEvent), extracting\nthe inner [`CodeScanSucceededEvent`](crate::types::CodeScanSucceededEvent).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_code_scan_succeeded_event(&self) -> ::std::result::Result<&crate::types::CodeScanSucceededEvent, &Self> {\n if let TelemetryEvent::CodeScanSucceededEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_code_scan_succeeded_event", "docstring": "Tries to convert the enum instance into\n[`CodeScanSucceededEvent`](crate::types::TelemetryEvent::CodeScanSucceededEvent), extracting\nthe inner [`CodeScanSucceededEvent`](crate::types::CodeScanSucceededEvent).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "56416a0e1354c4aa61dcc396c437898fb71e7d680cf59e55f661679c701ca751"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_doc_generation_event\n\nDocumentation:\nTries to convert the enum instance into\n[`DocGenerationEvent`](crate::types::TelemetryEvent::DocGenerationEvent), extracting the\ninner [`DocGenerationEvent`](crate::types::DocGenerationEvent). Returns `Err(&Self)` if\nit can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_doc_generation_event(&self) -> ::std::result::Result<&crate::types::DocGenerationEvent, &Self> {\n if let TelemetryEvent::DocGenerationEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_doc_generation_event", "docstring": "Tries to convert the enum instance into\n[`DocGenerationEvent`](crate::types::TelemetryEvent::DocGenerationEvent), extracting the\ninner [`DocGenerationEvent`](crate::types::DocGenerationEvent). Returns `Err(&Self)` if\nit can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69672e6cf92b42d1a71b1aae2f1edba811c085f7151fa91f2a64c76704f33b8f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_doc_v2_acceptance_event\n\nDocumentation:\nTries to convert the enum instance into\n[`DocV2AcceptanceEvent`](crate::types::TelemetryEvent::DocV2AcceptanceEvent), extracting the\ninner [`DocV2AcceptanceEvent`](crate::types::DocV2AcceptanceEvent). Returns `Err(&Self)`\nif it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_doc_v2_acceptance_event(&self) -> ::std::result::Result<&crate::types::DocV2AcceptanceEvent, &Self> {\n if let TelemetryEvent::DocV2AcceptanceEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_doc_v2_acceptance_event", "docstring": "Tries to convert the enum instance into\n[`DocV2AcceptanceEvent`](crate::types::TelemetryEvent::DocV2AcceptanceEvent), extracting the\ninner [`DocV2AcceptanceEvent`](crate::types::DocV2AcceptanceEvent). Returns `Err(&Self)`\nif it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "49585da6460e55e854285c7f8535c953e2f4d026bea94b9a239d13deb89c7423"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_doc_v2_generation_event\n\nDocumentation:\nTries to convert the enum instance into\n[`DocV2GenerationEvent`](crate::types::TelemetryEvent::DocV2GenerationEvent), extracting the\ninner [`DocV2GenerationEvent`](crate::types::DocV2GenerationEvent). Returns `Err(&Self)`\nif it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_doc_v2_generation_event(&self) -> ::std::result::Result<&crate::types::DocV2GenerationEvent, &Self> {\n if let TelemetryEvent::DocV2GenerationEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_doc_v2_generation_event", "docstring": "Tries to convert the enum instance into\n[`DocV2GenerationEvent`](crate::types::TelemetryEvent::DocV2GenerationEvent), extracting the\ninner [`DocV2GenerationEvent`](crate::types::DocV2GenerationEvent). Returns `Err(&Self)`\nif it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c6ec796b1fe937f8a11aa49a89449d71bea5058cbb31a82ed6b177b7041752b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_feature_dev_code_acceptance_event\n\nDocumentation:\nTries to convert the enum instance into\n[`FeatureDevCodeAcceptanceEvent`](crate::types::TelemetryEvent::FeatureDevCodeAcceptanceEvent),\nextracting the inner\n[`FeatureDevCodeAcceptanceEvent`](crate::types::FeatureDevCodeAcceptanceEvent).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_feature_dev_code_acceptance_event(\n &self,\n ) -> ::std::result::Result<&crate::types::FeatureDevCodeAcceptanceEvent, &Self> {\n if let TelemetryEvent::FeatureDevCodeAcceptanceEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_feature_dev_code_acceptance_event", "docstring": "Tries to convert the enum instance into\n[`FeatureDevCodeAcceptanceEvent`](crate::types::TelemetryEvent::FeatureDevCodeAcceptanceEvent),\nextracting the inner\n[`FeatureDevCodeAcceptanceEvent`](crate::types::FeatureDevCodeAcceptanceEvent).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0bdae693d78a83865c3508efe9e284cd23e3d05ca47375901db7ac0fb40e3d8e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_feature_dev_code_generation_event\n\nDocumentation:\nTries to convert the enum instance into\n[`FeatureDevCodeGenerationEvent`](crate::types::TelemetryEvent::FeatureDevCodeGenerationEvent),\nextracting the inner\n[`FeatureDevCodeGenerationEvent`](crate::types::FeatureDevCodeGenerationEvent).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_feature_dev_code_generation_event(\n &self,\n ) -> ::std::result::Result<&crate::types::FeatureDevCodeGenerationEvent, &Self> {\n if let TelemetryEvent::FeatureDevCodeGenerationEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_feature_dev_code_generation_event", "docstring": "Tries to convert the enum instance into\n[`FeatureDevCodeGenerationEvent`](crate::types::TelemetryEvent::FeatureDevCodeGenerationEvent),\nextracting the inner\n[`FeatureDevCodeGenerationEvent`](crate::types::FeatureDevCodeGenerationEvent).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ab1d604d7c2c650b27bfa84b8492a25ca3e54de748a906acb0667e9bc09d32be"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_feature_dev_event\n\nDocumentation:\nTries to convert the enum instance into\n[`FeatureDevEvent`](crate::types::TelemetryEvent::FeatureDevEvent), extracting the inner\n[`FeatureDevEvent`](crate::types::FeatureDevEvent). Returns `Err(&Self)` if it can't be\nconverted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_feature_dev_event(&self) -> ::std::result::Result<&crate::types::FeatureDevEvent, &Self> {\n if let TelemetryEvent::FeatureDevEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_feature_dev_event", "docstring": "Tries to convert the enum instance into\n[`FeatureDevEvent`](crate::types::TelemetryEvent::FeatureDevEvent), extracting the inner\n[`FeatureDevEvent`](crate::types::FeatureDevEvent). Returns `Err(&Self)` if it can't be\nconverted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7191891d4368c83047300256122c3a849fc694bebd06de1e48d7b43a633363de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_inline_chat_event\n\nDocumentation:\nTries to convert the enum instance into\n[`InlineChatEvent`](crate::types::TelemetryEvent::InlineChatEvent), extracting the inner\n[`InlineChatEvent`](crate::types::InlineChatEvent). Returns `Err(&Self)` if it can't be\nconverted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_inline_chat_event(&self) -> ::std::result::Result<&crate::types::InlineChatEvent, &Self> {\n if let TelemetryEvent::InlineChatEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_inline_chat_event", "docstring": "Tries to convert the enum instance into\n[`InlineChatEvent`](crate::types::TelemetryEvent::InlineChatEvent), extracting the inner\n[`InlineChatEvent`](crate::types::InlineChatEvent). Returns `Err(&Self)` if it can't be\nconverted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9300f7394784c86a62f9e11ffe33a2ba9b82ab1f773e61e4181d5d0e86c630e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_metric_data\n\nDocumentation:\nTries to convert the enum instance into\n[`MetricData`](crate::types::TelemetryEvent::MetricData), extracting the inner\n[`MetricData`](crate::types::MetricData). Returns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_metric_data(&self) -> ::std::result::Result<&crate::types::MetricData, &Self> {\n if let TelemetryEvent::MetricData(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_metric_data", "docstring": "Tries to convert the enum instance into\n[`MetricData`](crate::types::TelemetryEvent::MetricData), extracting the inner\n[`MetricData`](crate::types::MetricData). Returns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b9779514138ff8edc960c8dfec588a0c31f62035f9ea59f5a347a87c467018b1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_terminal_user_interaction_event\n\nDocumentation:\nTries to convert the enum instance into\n[`TerminalUserInteractionEvent`](crate::types::TelemetryEvent::TerminalUserInteractionEvent),\nextracting the inner\n[`TerminalUserInteractionEvent`](crate::types::TerminalUserInteractionEvent).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_terminal_user_interaction_event(\n &self,\n ) -> ::std::result::Result<&crate::types::TerminalUserInteractionEvent, &Self> {\n if let TelemetryEvent::TerminalUserInteractionEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_terminal_user_interaction_event", "docstring": "Tries to convert the enum instance into\n[`TerminalUserInteractionEvent`](crate::types::TelemetryEvent::TerminalUserInteractionEvent),\nextracting the inner\n[`TerminalUserInteractionEvent`](crate::types::TerminalUserInteractionEvent).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e12aff5bc9b3974b6644acec357c101de84d1e3b9c77c16b536c994deaa3b9d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_test_generation_event\n\nDocumentation:\nTries to convert the enum instance into\n[`TestGenerationEvent`](crate::types::TelemetryEvent::TestGenerationEvent), extracting the\ninner [`TestGenerationEvent`](crate::types::TestGenerationEvent). Returns `Err(&Self)`\nif it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_test_generation_event(&self) -> ::std::result::Result<&crate::types::TestGenerationEvent, &Self> {\n if let TelemetryEvent::TestGenerationEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_test_generation_event", "docstring": "Tries to convert the enum instance into\n[`TestGenerationEvent`](crate::types::TelemetryEvent::TestGenerationEvent), extracting the\ninner [`TestGenerationEvent`](crate::types::TestGenerationEvent). Returns `Err(&Self)`\nif it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd06c429444ef28b62b173cba59e247899e1533635f93441da8e250dab306145"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_transform_event\n\nDocumentation:\nTries to convert the enum instance into\n[`TransformEvent`](crate::types::TelemetryEvent::TransformEvent), extracting the inner\n[`TransformEvent`](crate::types::TransformEvent). Returns `Err(&Self)` if it can't be\nconverted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_transform_event(&self) -> ::std::result::Result<&crate::types::TransformEvent, &Self> {\n if let TelemetryEvent::TransformEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_transform_event", "docstring": "Tries to convert the enum instance into\n[`TransformEvent`](crate::types::TelemetryEvent::TransformEvent), extracting the inner\n[`TransformEvent`](crate::types::TransformEvent). Returns `Err(&Self)` if it can't be\nconverted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4cfcc14b36a51a3dce35512b640b44af16c438018f2be8ca5fc1a6602be38cda"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_user_modification_event\n\nDocumentation:\nTries to convert the enum instance into\n[`UserModificationEvent`](crate::types::TelemetryEvent::UserModificationEvent), extracting\nthe inner [`UserModificationEvent`](crate::types::UserModificationEvent). Returns `Err(&\nSelf)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_user_modification_event(&self) -> ::std::result::Result<&crate::types::UserModificationEvent, &Self> {\n if let TelemetryEvent::UserModificationEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_user_modification_event", "docstring": "Tries to convert the enum instance into\n[`UserModificationEvent`](crate::types::TelemetryEvent::UserModificationEvent), extracting\nthe inner [`UserModificationEvent`](crate::types::UserModificationEvent). Returns `Err(&\nSelf)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b4eeb7c5e5442d139ed0fd75ed5509b710bf6765b250b248dd6e664b599617f1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_user_trigger_decision_event\n\nDocumentation:\nTries to convert the enum instance into\n[`UserTriggerDecisionEvent`](crate::types::TelemetryEvent::UserTriggerDecisionEvent),\nextracting the inner [`UserTriggerDecisionEvent`](crate::types::UserTriggerDecisionEvent).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_user_trigger_decision_event(\n &self,\n ) -> ::std::result::Result<&crate::types::UserTriggerDecisionEvent, &Self> {\n if let TelemetryEvent::UserTriggerDecisionEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_user_trigger_decision_event", "docstring": "Tries to convert the enum instance into\n[`UserTriggerDecisionEvent`](crate::types::TelemetryEvent::UserTriggerDecisionEvent),\nextracting the inner [`UserTriggerDecisionEvent`](crate::types::UserTriggerDecisionEvent).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_telemetry_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d6c84c6f45243f2c53d3aa5355a5fc8b23f0d3132c28b4ffd807c64dcabcada1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TerminalUserInteractionEvent`](crate::types::TerminalUserInteractionEvent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::TerminalUserInteractionEvent {\n crate::types::TerminalUserInteractionEvent {\n terminal_user_interaction_event_type: self.terminal_user_interaction_event_type,\n terminal: self.terminal,\n terminal_version: self.terminal_version,\n shell: self.shell,\n shell_version: self.shell_version,\n duration: self.duration,\n time_to_suggestion: self.time_to_suggestion,\n is_completion_accepted: self.is_completion_accepted,\n cli_tool_command: self.cli_tool_command,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TerminalUserInteractionEvent`](crate::types::TerminalUserInteractionEvent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_terminal_user_interaction_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_terminal_user_interaction_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51bcb3799a2982545c58362c04efc315407663b4d504ddee1d35494c4fcab1f1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TestGenerationEvent`](crate::types::TestGenerationEvent). This method will fail if any\nof the following fields are not set:\n- [`job_id`](crate::types::builders::TestGenerationEventBuilder::job_id)\n- [`group_name`](crate::types::builders::TestGenerationEventBuilder::group_name)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::TestGenerationEvent {\n job_id: self.job_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"job_id\",\n \"job_id was not specified but it is required when building TestGenerationEvent\",\n )\n })?,\n group_name: self.group_name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"group_name\",\n \"group_name was not specified but it is required when building TestGenerationEvent\",\n )\n })?,\n timestamp: self.timestamp,\n ide_category: self.ide_category,\n programming_language: self.programming_language,\n number_of_unit_test_cases_generated: self.number_of_unit_test_cases_generated,\n number_of_unit_test_cases_accepted: self.number_of_unit_test_cases_accepted,\n lines_of_code_generated: self.lines_of_code_generated,\n lines_of_code_accepted: self.lines_of_code_accepted,\n chars_of_code_generated: self.chars_of_code_generated,\n chars_of_code_accepted: self.chars_of_code_accepted,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TestGenerationEvent`](crate::types::TestGenerationEvent). This method will fail if any\nof the following fields are not set:\n- [`job_id`](crate::types::builders::TestGenerationEventBuilder::job_id)\n- [`group_name`](crate::types::builders::TestGenerationEventBuilder::group_name)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_test_generation_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_test_generation_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1570c27e33d838a7ed59102d2e65f0cbc85bf9bd17c3cb5cfcfd400967bd04e1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: package_info_list\n\nDocumentation:\nAppends an item to `package_info_list`.\n\nTo override the contents of this collection use\n[`set_package_info_list`](Self::set_package_info_list).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn package_info_list(mut self, input: crate::types::PackageInfo) -> Self {\n let mut v = self.package_info_list.unwrap_or_default();\n v.push(input);\n self.package_info_list = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "package_info_list", "docstring": "Appends an item to `package_info_list`.\n\nTo override the contents of this collection use\n[`set_package_info_list`](Self::set_package_info_list).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_test_generation_job.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_test_generation_job.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93fb65922cbe9e3c7edfcfe0437abcec449dbe8fc676c99b0e5a00918e164a39"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TestGenerationJob`](crate::types::TestGenerationJob). This method will fail if any of\nthe following fields are not set:\n- [`test_generation_job_id`](crate::types::builders::TestGenerationJobBuilder::test_generation_job_id)\n- [`test_generation_job_group_name`](crate::types::builders::TestGenerationJobBuilder::test_generation_job_group_name)\n- [`status`](crate::types::builders::TestGenerationJobBuilder::status)\n- [`creation_time`](crate::types::builders::TestGenerationJobBuilder::creation_time)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::TestGenerationJob {\n test_generation_job_id: self.test_generation_job_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"test_generation_job_id\",\n \"test_generation_job_id was not specified but it is required when building TestGenerationJob\",\n )\n })?,\n test_generation_job_group_name: self.test_generation_job_group_name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"test_generation_job_group_name\",\n \"test_generation_job_group_name was not specified but it is required when building TestGenerationJob\",\n )\n })?,\n status: self.status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"status\",\n \"status was not specified but it is required when building TestGenerationJob\",\n )\n })?,\n short_answer: self.short_answer,\n creation_time: self.creation_time.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"creation_time\",\n \"creation_time was not specified but it is required when building TestGenerationJob\",\n )\n })?,\n progress_rate: self.progress_rate,\n job_status_reason: self.job_status_reason,\n job_summary: self.job_summary,\n job_plan: self.job_plan,\n package_info_list: self.package_info_list,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TestGenerationJob`](crate::types::TestGenerationJob). This method will fail if any of\nthe following fields are not set:\n- [`test_generation_job_id`](crate::types::builders::TestGenerationJobBuilder::test_generation_job_id)\n- [`test_generation_job_group_name`](crate::types::builders::TestGenerationJobBuilder::test_generation_job_group_name)\n- [`status`](crate::types::builders::TestGenerationJobBuilder::status)\n- [`creation_time`](crate::types::builders::TestGenerationJobBuilder::creation_time)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_test_generation_job.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_test_generation_job.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3202d8e8e859f5800d91b81eec08b3d926f3a57b571b6d188a9e7a5df6fc04c1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`TextDocument`](crate::types::TextDocument).\nThis method will fail if any of the following fields are not set:\n- [`relative_file_path`](crate::types::builders::TextDocumentBuilder::relative_file_path)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::TextDocument {\n relative_file_path: self.relative_file_path.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"relative_file_path\",\n \"relative_file_path was not specified but it is required when building TextDocument\",\n )\n })?,\n programming_language: self.programming_language,\n text: self.text,\n document_symbols: self.document_symbols,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`TextDocument`](crate::types::TextDocument).\nThis method will fail if any of the following fields are not set:\n- [`relative_file_path`](crate::types::builders::TextDocumentBuilder::relative_file_path)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_text_document.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_text_document.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ebd04e931dc65a2afd423653cc5f035db7aec8523912fe8f0b3e31a0971fbb4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: document\n\nDocumentation:\nRepresents a Text Document associated with Diagnostic\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn document(mut self, input: crate::types::TextDocument) -> Self {\n self.document = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "document", "docstring": "Represents a Text Document associated with Diagnostic\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93363a43d8420358682c559ccfa8c9355248c9bdb8c2622e7c90da0789e1b164"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_document\n\nDocumentation:\nRepresents a Text Document associated with Diagnostic\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_document(mut self, input: ::std::option::Option) -> Self {\n self.document = input;\n self\n }\n```"}], "func_name": "set_document", "docstring": "Represents a Text Document associated with Diagnostic", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a28709f40403c35521606b175c3847061aab1fa0b66f0a7ff3a493b6a10d708"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: code_description\n\nDocumentation:\nAn optional property to describe the error code.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn code_description(mut self, input: crate::types::CodeDescription) -> Self {\n self.code_description = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "code_description", "docstring": "An optional property to describe the error code.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d1ef552296ab7001192d557fc7f68a2e2553a18cc14a27e47fd9149a22ac7621"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tags\n\nDocumentation:\nAppends an item to `tags`.\n\nTo override the contents of this collection use [`set_tags`](Self::set_tags).\n\nAdditional metadata about the diagnostic.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn tags(mut self, input: crate::types::DiagnosticTag) -> Self {\n let mut v = self.tags.unwrap_or_default();\n v.push(input);\n self.tags = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "tags", "docstring": "Appends an item to `tags`.\n\nTo override the contents of this collection use [`set_tags`](Self::set_tags).\n\nAdditional metadata about the diagnostic.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f336a16731872833c3687c91d4813b72eb4231a808c964dc07cd28492d44cea2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: related_information\n\nDocumentation:\nAppends an item to `related_information`.\n\nTo override the contents of this collection use\n[`set_related_information`](Self::set_related_information).\n\nan array of related diagnostic information, e.g. when symbol-names within a scope collide\nall definitions can be marked via this property.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn related_information(mut self, input: crate::types::DiagnosticRelatedInformation) -> Self {\n let mut v = self.related_information.unwrap_or_default();\n v.push(input);\n self.related_information = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "related_information", "docstring": "Appends an item to `related_information`.\n\nTo override the contents of this collection use\n[`set_related_information`](Self::set_related_information).\n\nan array of related diagnostic information, e.g. when symbol-names within a scope collide\nall definitions can be marked via this property.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2779a1199416d5ef6a07ab3368b83e95dc91104d17f3573ea00b26cd304f2a2b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_related_information\n\nDocumentation:\nan array of related diagnostic information, e.g. when symbol-names within a scope collide\nall definitions can be marked via this property.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_related_information(\n mut self,\n input: ::std::option::Option<::std::vec::Vec>,\n ) -> Self {\n self.related_information = input;\n self\n }\n```"}], "func_name": "set_related_information", "docstring": "an array of related diagnostic information, e.g. when symbol-names within a scope collide\nall definitions can be marked via this property.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc81c6c412fb797ffe208010455cdabd5f67ce1be625268451b0f0ab27fd648d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TextDocumentDiagnostic`](crate::types::TextDocumentDiagnostic). This method will fail\nif any of the following fields are not set:\n- [`document`](crate::types::builders::TextDocumentDiagnosticBuilder::document)\n- [`range`](crate::types::builders::TextDocumentDiagnosticBuilder::range)\n- [`source`](crate::types::builders::TextDocumentDiagnosticBuilder::source)\n- [`severity`](crate::types::builders::TextDocumentDiagnosticBuilder::severity)\n- [`message`](crate::types::builders::TextDocumentDiagnosticBuilder::message)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::TextDocumentDiagnostic {\n document: self.document.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"document\",\n \"document was not specified but it is required when building TextDocumentDiagnostic\",\n )\n })?,\n range: self.range.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"range\",\n \"range was not specified but it is required when building TextDocumentDiagnostic\",\n )\n })?,\n source: self.source.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"source\",\n \"source was not specified but it is required when building TextDocumentDiagnostic\",\n )\n })?,\n severity: self.severity.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"severity\",\n \"severity was not specified but it is required when building TextDocumentDiagnostic\",\n )\n })?,\n message: self.message.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message\",\n \"message was not specified but it is required when building TextDocumentDiagnostic\",\n )\n })?,\n code: self.code,\n code_description: self.code_description,\n tags: self.tags,\n related_information: self.related_information,\n data: self.data,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TextDocumentDiagnostic`](crate::types::TextDocumentDiagnostic). This method will fail\nif any of the following fields are not set:\n- [`document`](crate::types::builders::TextDocumentDiagnosticBuilder::document)\n- [`range`](crate::types::builders::TextDocumentDiagnosticBuilder::range)\n- [`source`](crate::types::builders::TextDocumentDiagnosticBuilder::source)\n- [`severity`](crate::types::builders::TextDocumentDiagnosticBuilder::severity)\n- [`message`](crate::types::builders::TextDocumentDiagnosticBuilder::message)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_text_document_diagnostic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "30430ad9e38bd7cd49c9551c8351f359c70b0d4117626219414c0a48ea799d39"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_tool_specification\n\nDocumentation:\nTries to convert the enum instance into\n[`ToolSpecification`](crate::types::Tool::ToolSpecification), extracting the inner\n[`ToolSpecification`](crate::types::ToolSpecification). Returns `Err(&Self)` if it can't\nbe converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_tool_specification(&self) -> ::std::result::Result<&crate::types::ToolSpecification, &Self> {\n if let Tool::ToolSpecification(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_tool_specification", "docstring": "Tries to convert the enum instance into\n[`ToolSpecification`](crate::types::Tool::ToolSpecification), extracting the inner\n[`ToolSpecification`](crate::types::ToolSpecification). Returns `Err(&Self)` if it can't\nbe converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_tool.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_tool.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e70204b0f187e3b44d2224b5beb4ed1eb473d40d4ab79ca6fce3ee297dfee7f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ToolInputSchema`](crate::types::ToolInputSchema).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::ToolInputSchema {\n crate::types::ToolInputSchema { json: self.json }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ToolInputSchema`](crate::types::ToolInputSchema).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_tool_input_schema.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_tool_input_schema.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69bd7006d37e15dbe6eb5fc738d08c58dbc8172f56c190c63cbf24ec9377b68b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tool_use_id\n\nDocumentation:\nThe ID for the tool request.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn tool_use_id(&self) -> &str {\n use std::ops::Deref;\n self.tool_use_id.deref()\n }\n```"}], "func_name": "tool_use_id", "docstring": "The ID for the tool request.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_tool_result.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_tool_result.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "83b0f93f820e6b013eeef377fe78118fecd94144c099a0ac6e26baa200235e0f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tool_use_id\n\nDocumentation:\nThe ID for the tool request.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn tool_use_id(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.tool_use_id = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "tool_use_id", "docstring": "The ID for the tool request.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_tool_result.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_tool_result.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9e11d3e847261d7868527806e78647213ea8758294ac2e62a4be64e80d1b5343"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: content\n\nDocumentation:\nAppends an item to `content`.\n\nTo override the contents of this collection use [`set_content`](Self::set_content).\n\nContent of the tool result.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn content(mut self, input: crate::types::ToolResultContentBlock) -> Self {\n let mut v = self.content.unwrap_or_default();\n v.push(input);\n self.content = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "content", "docstring": "Appends an item to `content`.\n\nTo override the contents of this collection use [`set_content`](Self::set_content).\n\nContent of the tool result.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_tool_result.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_tool_result.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1aa4e7388f30c10213bdc7def8f1dbc36fdc1cdc99d3a3aae80a31ccc40b97b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ToolResult`](crate::types::ToolResult).\nThis method will fail if any of the following fields are not set:\n- [`tool_use_id`](crate::types::builders::ToolResultBuilder::tool_use_id)\n- [`content`](crate::types::builders::ToolResultBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::ToolResult {\n tool_use_id: self.tool_use_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"tool_use_id\",\n \"tool_use_id was not specified but it is required when building ToolResult\",\n )\n })?,\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building ToolResult\",\n )\n })?,\n status: self.status,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ToolResult`](crate::types::ToolResult).\nThis method will fail if any of the following fields are not set:\n- [`tool_use_id`](crate::types::builders::ToolResultBuilder::tool_use_id)\n- [`content`](crate::types::builders::ToolResultBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_tool_result.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_tool_result.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4015ca85e5103d4c88a7fa1ef4f4de0b2b709423a0d10390b0e334ed67c71c6b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ToolSpecification`](crate::types::ToolSpecification). This method will fail if any of\nthe following fields are not set:\n- [`input_schema`](crate::types::builders::ToolSpecificationBuilder::input_schema)\n- [`name`](crate::types::builders::ToolSpecificationBuilder::name)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::ToolSpecification {\n input_schema: self.input_schema.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"input_schema\",\n \"input_schema was not specified but it is required when building ToolSpecification\",\n )\n })?,\n name: self.name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"name\",\n \"name was not specified but it is required when building ToolSpecification\",\n )\n })?,\n description: self.description,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ToolSpecification`](crate::types::ToolSpecification). This method will fail if any of\nthe following fields are not set:\n- [`input_schema`](crate::types::builders::ToolSpecificationBuilder::input_schema)\n- [`name`](crate::types::builders::ToolSpecificationBuilder::name)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_tool_specification.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_tool_specification.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6196566203b9855592edea07c247d276321c2c2c381d7048fa6916608753c906"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: input\n\nDocumentation:\nThe input to pass to the tool.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn input(mut self, input: ::aws_smithy_types::Document) -> Self {\n self.input = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "input", "docstring": "The input to pass to the tool.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_tool_use.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_tool_use.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "86bb2449b2d47dd45d52d13da33963d248b7d54a19bf19c8762e8542e5bd10b1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_input\n\nDocumentation:\nThe input to pass to the tool.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_input(mut self, input: ::std::option::Option<::aws_smithy_types::Document>) -> Self {\n self.input = input;\n self\n }\n```"}], "func_name": "set_input", "docstring": "The input to pass to the tool.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_tool_use.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_tool_use.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "35815722d7a8d9e5aaabc78b231805b39ae36dcff6507f34af8097a0e8fbea0f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ToolUse`](crate::types::ToolUse).\nThis method will fail if any of the following fields are not set:\n- [`tool_use_id`](crate::types::builders::ToolUseBuilder::tool_use_id)\n- [`name`](crate::types::builders::ToolUseBuilder::name)\n- [`input`](crate::types::builders::ToolUseBuilder::input)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::ToolUse {\n tool_use_id: self.tool_use_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"tool_use_id\",\n \"tool_use_id was not specified but it is required when building ToolUse\",\n )\n })?,\n name: self.name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"name\",\n \"name was not specified but it is required when building ToolUse\",\n )\n })?,\n input: self.input.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"input\",\n \"input was not specified but it is required when building ToolUse\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ToolUse`](crate::types::ToolUse).\nThis method will fail if any of the following fields are not set:\n- [`tool_use_id`](crate::types::builders::ToolUseBuilder::tool_use_id)\n- [`name`](crate::types::builders::ToolUseBuilder::name)\n- [`input`](crate::types::builders::ToolUseBuilder::input)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_tool_use.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_tool_use.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6fe081f7762ebe36b5c054174846312cbc8ada33807f493bd112daa0e303eaa9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TransformationDownloadArtifact`](crate::types::TransformationDownloadArtifact).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::TransformationDownloadArtifact {\n crate::types::TransformationDownloadArtifact {\n download_artifact_type: self.download_artifact_type,\n download_artifact_id: self.download_artifact_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TransformationDownloadArtifact`](crate::types::TransformationDownloadArtifact).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_download_artifact.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_download_artifact.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "98e36ad63684ae82176a7336d401c36c2c93644aee8875e5e2655e1b5384e2f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TransformationJob`](crate::types::TransformationJob).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::TransformationJob {\n crate::types::TransformationJob {\n job_id: self.job_id,\n transformation_spec: self.transformation_spec,\n status: self.status,\n reason: self.reason,\n creation_time: self.creation_time,\n start_execution_time: self.start_execution_time,\n end_execution_time: self.end_execution_time,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TransformationJob`](crate::types::TransformationJob).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_job.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_job.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d70cb87d74d2af6cc152f71e165efe172840afafc361f458514de577a6a25403"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: transformation_steps\n\nDocumentation:\nAppends an item to `transformation_steps`.\n\nTo override the contents of this collection use\n[`set_transformation_steps`](Self::set_transformation_steps).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn transformation_steps(mut self, input: crate::types::TransformationStep) -> Self {\n let mut v = self.transformation_steps.unwrap_or_default();\n v.push(input);\n self.transformation_steps = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "transformation_steps", "docstring": "Appends an item to `transformation_steps`.\n\nTo override the contents of this collection use\n[`set_transformation_steps`](Self::set_transformation_steps).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_plan.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_plan.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a90a523ed9167a8a3be5ad04740663e598c5fbd4ba85a7b460bb231eae55cb9f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TransformationPlan`](crate::types::TransformationPlan). This method will fail if any\nof the following fields are not set:\n- [`transformation_steps`](crate::types::builders::TransformationPlanBuilder::transformation_steps)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::TransformationPlan {\n transformation_steps: self.transformation_steps.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"transformation_steps\",\n \"transformation_steps was not specified but it is required when building TransformationPlan\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TransformationPlan`](crate::types::TransformationPlan). This method will fail if any\nof the following fields are not set:\n- [`transformation_steps`](crate::types::builders::TransformationPlanBuilder::transformation_steps)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_plan.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_plan.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9d8ccf85b14576ae8264131f3f3a3622456b9bf9bdae51d42e349044c06caf6f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TransformationPlatformConfig`](crate::types::TransformationPlatformConfig).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::TransformationPlatformConfig {\n crate::types::TransformationPlatformConfig {\n operating_system_family: self.operating_system_family,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TransformationPlatformConfig`](crate::types::TransformationPlatformConfig).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_platform_config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_platform_config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c65db53b5542614a2fa74af146c827276be34b0a026648875db5cef821286c8d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: download_artifacts\n\nDocumentation:\nAppends an item to `download_artifacts`.\n\nTo override the contents of this collection use\n[`set_download_artifacts`](Self::set_download_artifacts).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn download_artifacts(mut self, input: crate::types::TransformationDownloadArtifact) -> Self {\n let mut v = self.download_artifacts.unwrap_or_default();\n v.push(input);\n self.download_artifacts = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "download_artifacts", "docstring": "Appends an item to `download_artifacts`.\n\nTo override the contents of this collection use\n[`set_download_artifacts`](Self::set_download_artifacts).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_progress_update.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_progress_update.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5fca032bc1ab8b7022a7449bc2731b752b78192835569244daf72e1f7574271"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TransformationProgressUpdate`](crate::types::TransformationProgressUpdate).\nThis method will fail if any of the following fields are not set:\n- [`name`](crate::types::builders::TransformationProgressUpdateBuilder::name)\n- [`status`](crate::types::builders::TransformationProgressUpdateBuilder::status)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::TransformationProgressUpdate,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::TransformationProgressUpdate {\n name: self.name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"name\",\n \"name was not specified but it is required when building TransformationProgressUpdate\",\n )\n })?,\n status: self.status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"status\",\n \"status was not specified but it is required when building TransformationProgressUpdate\",\n )\n })?,\n description: self.description,\n start_time: self.start_time,\n end_time: self.end_time,\n download_artifacts: self.download_artifacts,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TransformationProgressUpdate`](crate::types::TransformationProgressUpdate).\nThis method will fail if any of the following fields are not set:\n- [`name`](crate::types::builders::TransformationProgressUpdateBuilder::name)\n- [`status`](crate::types::builders::TransformationProgressUpdateBuilder::status)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_progress_update.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_progress_update.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4175b35dc6337a3780d7f4d14d7ec3d72e096a2540f889c1a0ab515ab2aea1ef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_source_code_artifact\n\nDocumentation:\nTries to convert the enum instance into\n[`SourceCodeArtifact`](crate::types::TransformationProjectArtifactDescriptor::SourceCodeArtifact),\nextracting the inner\n[`TransformationSourceCodeArtifactDescriptor`](crate::types::TransformationSourceCodeArtifactDescriptor).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_source_code_artifact(\n &self,\n ) -> ::std::result::Result<&crate::types::TransformationSourceCodeArtifactDescriptor, &Self> {\n if let TransformationProjectArtifactDescriptor::SourceCodeArtifact(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_source_code_artifact", "docstring": "Tries to convert the enum instance into\n[`SourceCodeArtifact`](crate::types::TransformationProjectArtifactDescriptor::SourceCodeArtifact),\nextracting the inner\n[`TransformationSourceCodeArtifactDescriptor`](crate::types::TransformationSourceCodeArtifactDescriptor).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_project_artifact_descriptor.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_project_artifact_descriptor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cade02d98c1cb623b8cef2eb25f8101eb334b496cd914647d8414e5e8e01f6db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TransformationProjectState`](crate::types::TransformationProjectState).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::TransformationProjectState {\n crate::types::TransformationProjectState {\n language: self.language,\n runtime_env: self.runtime_env,\n platform_config: self.platform_config,\n project_artifact: self.project_artifact,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TransformationProjectState`](crate::types::TransformationProjectState).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_project_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_project_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c486f7aabf3d2175dc542bdd1f918e43f42ec67ffa61448a90fcc2d3fdd3bda"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_dot_net\n\nDocumentation:\nTries to convert the enum instance into\n[`DotNet`](crate::types::TransformationRuntimeEnv::DotNet), extracting the inner\n[`TransformationDotNetRuntimeEnv`](crate::types::TransformationDotNetRuntimeEnv).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_dot_net(&self) -> ::std::result::Result<&crate::types::TransformationDotNetRuntimeEnv, &Self> {\n if let TransformationRuntimeEnv::DotNet(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_dot_net", "docstring": "Tries to convert the enum instance into\n[`DotNet`](crate::types::TransformationRuntimeEnv::DotNet), extracting the inner\n[`TransformationDotNetRuntimeEnv`](crate::types::TransformationDotNetRuntimeEnv).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_runtime_env.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_runtime_env.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81531fe8b65b2cf07c72d035a9e3939c1f4b71d72dee1f924e568274a09437f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_java\n\nDocumentation:\nTries to convert the enum instance into\n[`Java`](crate::types::TransformationRuntimeEnv::Java), extracting the inner\n[`TransformationJavaRuntimeEnv`](crate::types::TransformationJavaRuntimeEnv).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_java(&self) -> ::std::result::Result<&crate::types::TransformationJavaRuntimeEnv, &Self> {\n if let TransformationRuntimeEnv::Java(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_java", "docstring": "Tries to convert the enum instance into\n[`Java`](crate::types::TransformationRuntimeEnv::Java), extracting the inner\n[`TransformationJavaRuntimeEnv`](crate::types::TransformationJavaRuntimeEnv).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_runtime_env.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_runtime_env.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d385a36d4187e2dfdd9004d064ba68a7491c0e9765f9242bcd77f48cace5d6b2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_mainframe\n\nDocumentation:\nTries to convert the enum instance into\n[`Mainframe`](crate::types::TransformationRuntimeEnv::Mainframe), extracting the inner\n[`TransformationMainframeRuntimeEnv`](crate::types::TransformationMainframeRuntimeEnv).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_mainframe(&self) -> ::std::result::Result<&crate::types::TransformationMainframeRuntimeEnv, &Self> {\n if let TransformationRuntimeEnv::Mainframe(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_mainframe", "docstring": "Tries to convert the enum instance into\n[`Mainframe`](crate::types::TransformationRuntimeEnv::Mainframe), extracting the inner\n[`TransformationMainframeRuntimeEnv`](crate::types::TransformationMainframeRuntimeEnv).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_runtime_env.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_runtime_env.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3d5984d2fd5cba02699b15f39422c6e08822a3b9f3ead53e6807deaa8b41e5f9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: languages\n\nDocumentation:\nAppends an item to `languages`.\n\nTo override the contents of this collection use [`set_languages`](Self::set_languages).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn languages(mut self, input: crate::types::TransformationLanguage) -> Self {\n let mut v = self.languages.unwrap_or_default();\n v.push(input);\n self.languages = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "languages", "docstring": "Appends an item to `languages`.\n\nTo override the contents of this collection use [`set_languages`](Self::set_languages).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_source_code_artifact_descriptor.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_source_code_artifact_descriptor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "762d80129e2cd3148a01d577a1e1f025934886e0416634628772ffa9b6f8d94f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TransformationSourceCodeArtifactDescriptor`](crate::types::TransformationSourceCodeArtifactDescriptor).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::TransformationSourceCodeArtifactDescriptor {\n crate::types::TransformationSourceCodeArtifactDescriptor {\n languages: self.languages,\n runtime_env: self.runtime_env,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TransformationSourceCodeArtifactDescriptor`](crate::types::TransformationSourceCodeArtifactDescriptor).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_source_code_artifact_descriptor.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_source_code_artifact_descriptor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2306cc678d9c86bd7b0048c00e838c2d7311d1b5689961192fe36b8daed8054c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TransformationSpec`](crate::types::TransformationSpec).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::TransformationSpec {\n crate::types::TransformationSpec {\n transformation_type: self.transformation_type,\n source: self.source,\n target: self.target,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TransformationSpec`](crate::types::TransformationSpec).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_spec.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_spec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a367e28d5f58efda58a5cba368fab3deaab9567132d1ea40002aeba021b4d10"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: progress_updates\n\nDocumentation:\nAppends an item to `progress_updates`.\n\nTo override the contents of this collection use\n[`set_progress_updates`](Self::set_progress_updates).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn progress_updates(mut self, input: crate::types::TransformationProgressUpdate) -> Self {\n let mut v = self.progress_updates.unwrap_or_default();\n v.push(input);\n self.progress_updates = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "progress_updates", "docstring": "Appends an item to `progress_updates`.\n\nTo override the contents of this collection use\n[`set_progress_updates`](Self::set_progress_updates).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_step.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_step.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5a5ec453dbb301558ee6f2e4d3a7001cdfaa5b180da0d41981a39b70d2d5b3e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TransformationStep`](crate::types::TransformationStep). This method will fail if any\nof the following fields are not set:\n- [`id`](crate::types::builders::TransformationStepBuilder::id)\n- [`name`](crate::types::builders::TransformationStepBuilder::name)\n- [`description`](crate::types::builders::TransformationStepBuilder::description)\n- [`status`](crate::types::builders::TransformationStepBuilder::status)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::TransformationStep {\n id: self.id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"id\",\n \"id was not specified but it is required when building TransformationStep\",\n )\n })?,\n name: self.name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"name\",\n \"name was not specified but it is required when building TransformationStep\",\n )\n })?,\n description: self.description.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"description\",\n \"description was not specified but it is required when building TransformationStep\",\n )\n })?,\n status: self.status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"status\",\n \"status was not specified but it is required when building TransformationStep\",\n )\n })?,\n progress_updates: self.progress_updates,\n start_time: self.start_time,\n end_time: self.end_time,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TransformationStep`](crate::types::TransformationStep). This method will fail if any\nof the following fields are not set:\n- [`id`](crate::types::builders::TransformationStepBuilder::id)\n- [`name`](crate::types::builders::TransformationStepBuilder::name)\n- [`description`](crate::types::builders::TransformationStepBuilder::description)\n- [`status`](crate::types::builders::TransformationStepBuilder::status)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_step.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_step.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e331e902427036d8c30a82109471d5d27cf70b1366fced10864d161d0f66d808"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TransformationUploadContext`](crate::types::TransformationUploadContext). This method\nwill fail if any of the following fields are not set:\n- [`job_id`](crate::types::builders::TransformationUploadContextBuilder::job_id)\n- [`upload_artifact_type`](crate::types::builders::TransformationUploadContextBuilder::upload_artifact_type)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::TransformationUploadContext,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::TransformationUploadContext {\n job_id: self.job_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"job_id\",\n \"job_id was not specified but it is required when building TransformationUploadContext\",\n )\n })?,\n upload_artifact_type: self.upload_artifact_type.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"upload_artifact_type\",\n \"upload_artifact_type was not specified but it is required when building TransformationUploadContext\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TransformationUploadContext`](crate::types::TransformationUploadContext). This method\nwill fail if any of the following fields are not set:\n- [`job_id`](crate::types::builders::TransformationUploadContextBuilder::job_id)\n- [`upload_artifact_type`](crate::types::builders::TransformationUploadContextBuilder::upload_artifact_type)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transformation_upload_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transformation_upload_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f44b0357ccaa9b7318c29ac9f1e855cb31e39c01eefd9c00e5207989bc732b89"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`TransformEvent`](crate::types::TransformEvent).\nThis method will fail if any of the following fields are not set:\n- [`job_id`](crate::types::builders::TransformEventBuilder::job_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::TransformEvent {\n job_id: self.job_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"job_id\",\n \"job_id was not specified but it is required when building TransformEvent\",\n )\n })?,\n timestamp: self.timestamp,\n ide_category: self.ide_category,\n programming_language: self.programming_language,\n lines_of_code_changed: self.lines_of_code_changed,\n chars_of_code_changed: self.chars_of_code_changed,\n lines_of_code_submitted: self.lines_of_code_submitted,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`TransformEvent`](crate::types::TransformEvent).\nThis method will fail if any of the following fields are not set:\n- [`job_id`](crate::types::builders::TransformEventBuilder::job_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_transform_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_transform_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "58ec39e7d723e55673bb1ecee7c2eaf4871d088749893501d42d50eabce0a24f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_code_analysis_upload_context\n\nDocumentation:\nTries to convert the enum instance into\n[`CodeAnalysisUploadContext`](crate::types::UploadContext::CodeAnalysisUploadContext),\nextracting the inner [`CodeAnalysisUploadContext`](crate::types::CodeAnalysisUploadContext).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_code_analysis_upload_context(\n &self,\n ) -> ::std::result::Result<&crate::types::CodeAnalysisUploadContext, &Self> {\n if let UploadContext::CodeAnalysisUploadContext(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_code_analysis_upload_context", "docstring": "Tries to convert the enum instance into\n[`CodeAnalysisUploadContext`](crate::types::UploadContext::CodeAnalysisUploadContext),\nextracting the inner [`CodeAnalysisUploadContext`](crate::types::CodeAnalysisUploadContext).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_upload_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_upload_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "88886a319640cad85807706fc3ec3ce988832fd1d6a4e68c87f784fd2ee5a5c1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_code_fix_upload_context\n\nDocumentation:\nTries to convert the enum instance into\n[`CodeFixUploadContext`](crate::types::UploadContext::CodeFixUploadContext), extracting the\ninner [`CodeFixUploadContext`](crate::types::CodeFixUploadContext). Returns `Err(&Self)`\nif it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_code_fix_upload_context(&self) -> ::std::result::Result<&crate::types::CodeFixUploadContext, &Self> {\n if let UploadContext::CodeFixUploadContext(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_code_fix_upload_context", "docstring": "Tries to convert the enum instance into\n[`CodeFixUploadContext`](crate::types::UploadContext::CodeFixUploadContext), extracting the\ninner [`CodeFixUploadContext`](crate::types::CodeFixUploadContext). Returns `Err(&Self)`\nif it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_upload_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_upload_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca25c89a757b0d85f42db44256a0333a5871aeea0a1ce35f8dfa44acebbbbe9f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_task_assist_planning_upload_context\n\nDocumentation:\nTries to convert the enum instance into\n[`TaskAssistPlanningUploadContext`](crate::types::UploadContext::TaskAssistPlanningUploadContext),\nextracting the inner\n[`TaskAssistPlanningUploadContext`](crate::types::TaskAssistPlanningUploadContext).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_task_assist_planning_upload_context(\n &self,\n ) -> ::std::result::Result<&crate::types::TaskAssistPlanningUploadContext, &Self> {\n if let UploadContext::TaskAssistPlanningUploadContext(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_task_assist_planning_upload_context", "docstring": "Tries to convert the enum instance into\n[`TaskAssistPlanningUploadContext`](crate::types::UploadContext::TaskAssistPlanningUploadContext),\nextracting the inner\n[`TaskAssistPlanningUploadContext`](crate::types::TaskAssistPlanningUploadContext).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_upload_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_upload_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac47ce4ca3e70d6422a6b181b2293058739952d509f85eef233864087942b293"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_transformation_upload_context\n\nDocumentation:\nTries to convert the enum instance into\n[`TransformationUploadContext`](crate::types::UploadContext::TransformationUploadContext),\nextracting the inner\n[`TransformationUploadContext`](crate::types::TransformationUploadContext).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_transformation_upload_context(\n &self,\n ) -> ::std::result::Result<&crate::types::TransformationUploadContext, &Self> {\n if let UploadContext::TransformationUploadContext(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_transformation_upload_context", "docstring": "Tries to convert the enum instance into\n[`TransformationUploadContext`](crate::types::UploadContext::TransformationUploadContext),\nextracting the inner\n[`TransformationUploadContext`](crate::types::TransformationUploadContext).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_upload_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_upload_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a7102f84d7afbb02a4d0c372e10ffda73705c407a9496af098677256543d7b32"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_workspace_context_upload_context\n\nDocumentation:\nTries to convert the enum instance into\n[`WorkspaceContextUploadContext`](crate::types::UploadContext::WorkspaceContextUploadContext),\nextracting the inner\n[`WorkspaceContextUploadContext`](crate::types::WorkspaceContextUploadContext).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_workspace_context_upload_context(\n &self,\n ) -> ::std::result::Result<&crate::types::WorkspaceContextUploadContext, &Self> {\n if let UploadContext::WorkspaceContextUploadContext(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_workspace_context_upload_context", "docstring": "Tries to convert the enum instance into\n[`WorkspaceContextUploadContext`](crate::types::UploadContext::WorkspaceContextUploadContext),\nextracting the inner\n[`WorkspaceContextUploadContext`](crate::types::WorkspaceContextUploadContext).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_upload_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_upload_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a9ade912800f39769b6867e8e1220edeebe48105fd65c0be7accce2b68b044d7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`UserContext`](crate::types::UserContext).\nThis method will fail if any of the following fields are not set:\n- [`ide_category`](crate::types::builders::UserContextBuilder::ide_category)\n- [`operating_system`](crate::types::builders::UserContextBuilder::operating_system)\n- [`product`](crate::types::builders::UserContextBuilder::product)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::UserContext {\n ide_category: self.ide_category.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"ide_category\",\n \"ide_category was not specified but it is required when building UserContext\",\n )\n })?,\n operating_system: self.operating_system.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"operating_system\",\n \"operating_system was not specified but it is required when building UserContext\",\n )\n })?,\n product: self.product.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"product\",\n \"product was not specified but it is required when building UserContext\",\n )\n })?,\n client_id: self.client_id,\n ide_version: self.ide_version,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`UserContext`](crate::types::UserContext).\nThis method will fail if any of the following fields are not set:\n- [`ide_category`](crate::types::builders::UserContextBuilder::ide_category)\n- [`operating_system`](crate::types::builders::UserContextBuilder::operating_system)\n- [`product`](crate::types::builders::UserContextBuilder::product)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4b5b0a118e69643759f2dce99bc7458071320d39ead0faeab79e4246ed8cd701"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: user_input_message_context\n\nDocumentation:\nChat message context associated with the Chat Message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn user_input_message_context(mut self, input: crate::types::UserInputMessageContext) -> Self {\n self.user_input_message_context = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "user_input_message_context", "docstring": "Chat message context associated with the Chat Message.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_input_message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_input_message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c99799cf3dcdc186ed5b1d542aec06a1ea2d9a6fe87dd7a055b156673eb71e76"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: images\n\nDocumentation:\nAppends an item to `images`.\n\nTo override the contents of this collection use [`set_images`](Self::set_images).\n\nImages associated with the Chat Message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn images(mut self, input: crate::types::ImageBlock) -> Self {\n let mut v = self.images.unwrap_or_default();\n v.push(input);\n self.images = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "images", "docstring": "Appends an item to `images`.\n\nTo override the contents of this collection use [`set_images`](Self::set_images).\n\nImages associated with the Chat Message.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_input_message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_input_message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b71826152944b565f0a5ead910d72cbe44eac512384388bdf14fc7a16b30395"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_images\n\nDocumentation:\nImages associated with the Chat Message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_images(mut self, input: ::std::option::Option<::std::vec::Vec>) -> Self {\n self.images = input;\n self\n }\n```"}], "func_name": "set_images", "docstring": "Images associated with the Chat Message.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_input_message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_input_message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3aaa05cc166404bd80578dea8a7200061e10a8bb588e5ab0bf5977b0be33e357"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`UserInputMessage`](crate::types::UserInputMessage).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::UserInputMessageBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::UserInputMessage {\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building UserInputMessage\",\n )\n })?,\n user_input_message_context: self.user_input_message_context,\n user_intent: self.user_intent,\n origin: self.origin,\n images: self.images,\n model_id: self.model_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`UserInputMessage`](crate::types::UserInputMessage).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::UserInputMessageBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_input_message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_input_message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "124febda8d749edf63a11b943895b488fe802aa4ac3fb6759f038b2e3bcba855"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: app_studio_context\n\nDocumentation:\nThe state of a user's AppStudio UI when sending a message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn app_studio_context(mut self, input: crate::types::AppStudioState) -> Self {\n self.app_studio_context = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "app_studio_context", "docstring": "The state of a user's AppStudio UI when sending a message.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "683977315c37d542ebc2d1339d7fdfa2b783477c14e17fd2354e2f8d0adc690b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: console_state\n\nDocumentation:\nContextual information about the environment from which the user is calling.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn console_state(mut self, input: crate::types::ConsoleState) -> Self {\n self.console_state = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "console_state", "docstring": "Contextual information about the environment from which the user is calling.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c788fabed366d5fb3806146f04eaf2c86474002d7a4fc8f93201c6a9b0d663a0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: user_settings\n\nDocumentation:\nSettings information, e.g., whether the user has enabled cross-region API calls.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn user_settings(mut self, input: crate::types::UserSettings) -> Self {\n self.user_settings = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "user_settings", "docstring": "Settings information, e.g., whether the user has enabled cross-region API calls.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "64193b66a0d653f0c05ba0773c4fcb8795e54956a9e4fb604a9d9607ecb771a9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: additional_context\n\nDocumentation:\nAppends an item to `additional_context`.\n\nTo override the contents of this collection use\n[`set_additional_context`](Self::set_additional_context).\n\nList of additional contextual content entries that can be included with the message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn additional_context(mut self, input: crate::types::AdditionalContentEntry) -> Self {\n let mut v = self.additional_context.unwrap_or_default();\n v.push(input);\n self.additional_context = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "additional_context", "docstring": "Appends an item to `additional_context`.\n\nTo override the contents of this collection use\n[`set_additional_context`](Self::set_additional_context).\n\nList of additional contextual content entries that can be included with the message.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51f6a4e8793e08d8f80b01165347ec661b7f7412a9cd7695f6e0b0e20811127b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_additional_context\n\nDocumentation:\nList of additional contextual content entries that can be included with the message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_additional_context(\n mut self,\n input: ::std::option::Option<::std::vec::Vec>,\n ) -> Self {\n self.additional_context = input;\n self\n }\n```"}], "func_name": "set_additional_context", "docstring": "List of additional contextual content entries that can be included with the message.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ed35213b76ea7728763bf7ffc91a4e77572b001e3bfd31a8630c925dd38e28a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tool_results\n\nDocumentation:\nAppends an item to `tool_results`.\n\nTo override the contents of this collection use\n[`set_tool_results`](Self::set_tool_results).\n\nToolResults for the requested ToolUses.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn tool_results(mut self, input: crate::types::ToolResult) -> Self {\n let mut v = self.tool_results.unwrap_or_default();\n v.push(input);\n self.tool_results = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "tool_results", "docstring": "Appends an item to `tool_results`.\n\nTo override the contents of this collection use\n[`set_tool_results`](Self::set_tool_results).\n\nToolResults for the requested ToolUses.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "331f1f7785e84efb6fdc5147b076992bcb66644d1e25e8f6952b252a858cbc68"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`UserInputMessageContext`](crate::types::UserInputMessageContext).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::UserInputMessageContext {\n crate::types::UserInputMessageContext {\n editor_state: self.editor_state,\n shell_state: self.shell_state,\n git_state: self.git_state,\n env_state: self.env_state,\n app_studio_context: self.app_studio_context,\n diagnostic: self.diagnostic,\n console_state: self.console_state,\n user_settings: self.user_settings,\n additional_context: self.additional_context,\n tool_results: self.tool_results,\n tools: self.tools,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`UserInputMessageContext`](crate::types::UserInputMessageContext).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_input_message_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e32e2c55cd7abbaeb5a0571cf5c0ef24592a1b964a22071d6795a342cee34718"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`UserModificationEvent`](crate::types::UserModificationEvent). This method will fail if\nany of the following fields are not set:\n- [`session_id`](crate::types::builders::UserModificationEventBuilder::session_id)\n- [`request_id`](crate::types::builders::UserModificationEventBuilder::request_id)\n- [`programming_language`](crate::types::builders::UserModificationEventBuilder::programming_language)\n- [`modification_percentage`](crate::types::builders::UserModificationEventBuilder::modification_percentage)\n- [`timestamp`](crate::types::builders::UserModificationEventBuilder::timestamp)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::UserModificationEvent {\n session_id: self.session_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"session_id\",\n \"session_id was not specified but it is required when building UserModificationEvent\",\n )\n })?,\n request_id: self.request_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"request_id\",\n \"request_id was not specified but it is required when building UserModificationEvent\",\n )\n })?,\n programming_language: self.programming_language.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"programming_language\",\n \"programming_language was not specified but it is required when building UserModificationEvent\",\n )\n })?,\n modification_percentage: self.modification_percentage.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"modification_percentage\",\n \"modification_percentage was not specified but it is required when building UserModificationEvent\",\n )\n })?,\n customization_arn: self.customization_arn,\n timestamp: self.timestamp.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"timestamp\",\n \"timestamp was not specified but it is required when building UserModificationEvent\",\n )\n })?,\n accepted_character_count: self.accepted_character_count.unwrap_or_default(),\n unmodified_accepted_character_count: self.unmodified_accepted_character_count.unwrap_or_default(),\n added_character_count: self.added_character_count.unwrap_or_default(),\n unmodified_added_character_count: self.unmodified_added_character_count.unwrap_or_default(),\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`UserModificationEvent`](crate::types::UserModificationEvent). This method will fail if\nany of the following fields are not set:\n- [`session_id`](crate::types::builders::UserModificationEventBuilder::session_id)\n- [`request_id`](crate::types::builders::UserModificationEventBuilder::request_id)\n- [`programming_language`](crate::types::builders::UserModificationEventBuilder::programming_language)\n- [`modification_percentage`](crate::types::builders::UserModificationEventBuilder::modification_percentage)\n- [`timestamp`](crate::types::builders::UserModificationEventBuilder::timestamp)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_modification_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_modification_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7732eac0168c3f217ada325ffc6fa89315553867b2d4cdc58cff879ece7c4fb9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`UserSettings`](crate::types::UserSettings).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::UserSettings {\n crate::types::UserSettings {\n has_consented_to_cross_region_calls: self.has_consented_to_cross_region_calls,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`UserSettings`](crate::types::UserSettings).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_settings.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_settings.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc42be831b5c284a6562c9854b77ab61bf57e87a5962e4c76b0209b975492796"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`UserTriggerDecisionEvent`](crate::types::UserTriggerDecisionEvent). This method will\nfail if any of the following fields are not set:\n- [`session_id`](crate::types::builders::UserTriggerDecisionEventBuilder::session_id)\n- [`request_id`](crate::types::builders::UserTriggerDecisionEventBuilder::request_id)\n- [`programming_language`](crate::types::builders::UserTriggerDecisionEventBuilder::programming_language)\n- [`completion_type`](crate::types::builders::UserTriggerDecisionEventBuilder::completion_type)\n- [`suggestion_state`](crate::types::builders::UserTriggerDecisionEventBuilder::suggestion_state)\n- [`recommendation_latency_milliseconds`](crate::types::builders::UserTriggerDecisionEventBuilder::recommendation_latency_milliseconds)\n- [`timestamp`](crate::types::builders::UserTriggerDecisionEventBuilder::timestamp)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::UserTriggerDecisionEvent {\n session_id: self.session_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"session_id\",\n \"session_id was not specified but it is required when building UserTriggerDecisionEvent\",\n )\n })?,\n request_id: self.request_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"request_id\",\n \"request_id was not specified but it is required when building UserTriggerDecisionEvent\",\n )\n })?,\n customization_arn: self.customization_arn,\n programming_language: self.programming_language.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"programming_language\",\n \"programming_language was not specified but it is required when building UserTriggerDecisionEvent\",\n )\n })?,\n completion_type: self.completion_type.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"completion_type\",\n \"completion_type was not specified but it is required when building UserTriggerDecisionEvent\",\n )\n })?,\n suggestion_state: self.suggestion_state.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"suggestion_state\",\n \"suggestion_state was not specified but it is required when building UserTriggerDecisionEvent\",\n )\n })?,\n recommendation_latency_milliseconds: self.recommendation_latency_milliseconds.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"recommendation_latency_milliseconds\",\n \"recommendation_latency_milliseconds was not specified but it is required when building UserTriggerDecisionEvent\",\n )\n })?,\n timestamp: self.timestamp.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"timestamp\",\n \"timestamp was not specified but it is required when building UserTriggerDecisionEvent\",\n )\n })?,\n trigger_to_response_latency_milliseconds: self.trigger_to_response_latency_milliseconds,\n suggestion_reference_count: self.suggestion_reference_count.unwrap_or_default(),\n generated_line: self.generated_line.unwrap_or_default(),\n number_of_recommendations: self.number_of_recommendations.unwrap_or_default(),\n perceived_latency_milliseconds: self.perceived_latency_milliseconds,\n accepted_character_count: self.accepted_character_count.unwrap_or_default(),\n added_ide_diagnostics: self.added_ide_diagnostics,\n removed_ide_diagnostics: self.removed_ide_diagnostics,\n added_character_count: self.added_character_count.unwrap_or_default(),\n deleted_character_count: self.deleted_character_count.unwrap_or_default(),\n streak_length: self.streak_length.unwrap_or_default(),\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`UserTriggerDecisionEvent`](crate::types::UserTriggerDecisionEvent). This method will\nfail if any of the following fields are not set:\n- [`session_id`](crate::types::builders::UserTriggerDecisionEventBuilder::session_id)\n- [`request_id`](crate::types::builders::UserTriggerDecisionEventBuilder::request_id)\n- [`programming_language`](crate::types::builders::UserTriggerDecisionEventBuilder::programming_language)\n- [`completion_type`](crate::types::builders::UserTriggerDecisionEventBuilder::completion_type)\n- [`suggestion_state`](crate::types::builders::UserTriggerDecisionEventBuilder::suggestion_state)\n- [`recommendation_latency_milliseconds`](crate::types::builders::UserTriggerDecisionEventBuilder::recommendation_latency_milliseconds)\n- [`timestamp`](crate::types::builders::UserTriggerDecisionEventBuilder::timestamp)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_user_trigger_decision_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_user_trigger_decision_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69789d956b4ce24829415ee2d48654ec090a566ef7bb76ec8da24da02278e29f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`WorkspaceContext`](crate::types::WorkspaceContext).\nThis method will fail if any of the following fields are not set:\n- [`toggle`](crate::types::builders::WorkspaceContextBuilder::toggle)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::WorkspaceContext {\n toggle: self.toggle.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"toggle\",\n \"toggle was not specified but it is required when building WorkspaceContext\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`WorkspaceContext`](crate::types::WorkspaceContext).\nThis method will fail if any of the following fields are not set:\n- [`toggle`](crate::types::builders::WorkspaceContextBuilder::toggle)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_workspace_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_workspace_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "71791660a481921620a9e84463ff0eedfb3b6bcbf1869156d9706e00c5a571a4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`WorkspaceContextUploadContext`](crate::types::WorkspaceContextUploadContext).\nThis method will fail if any of the following fields are not set:\n- [`workspace_id`](crate::types::builders::WorkspaceContextUploadContextBuilder::workspace_id)\n- [`relative_path`](crate::types::builders::WorkspaceContextUploadContextBuilder::relative_path)\n- [`programming_language`](crate::types::builders::WorkspaceContextUploadContextBuilder::programming_language)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::WorkspaceContextUploadContext,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::WorkspaceContextUploadContext {\n workspace_id: self.workspace_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"workspace_id\",\n \"workspace_id was not specified but it is required when building WorkspaceContextUploadContext\",\n )\n })?,\n relative_path: self.relative_path.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"relative_path\",\n \"relative_path was not specified but it is required when building WorkspaceContextUploadContext\",\n )\n })?,\n programming_language: self.programming_language.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"programming_language\",\n \"programming_language was not specified but it is required when building WorkspaceContextUploadContext\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`WorkspaceContextUploadContext`](crate::types::WorkspaceContextUploadContext).\nThis method will fail if any of the following fields are not set:\n- [`workspace_id`](crate::types::builders::WorkspaceContextUploadContextBuilder::workspace_id)\n- [`relative_path`](crate::types::builders::WorkspaceContextUploadContextBuilder::relative_path)\n- [`programming_language`](crate::types::builders::WorkspaceContextUploadContextBuilder::programming_language)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_workspace_context_upload_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_workspace_context_upload_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "900a97ba8072e1a671ea88cd21d34e89513f6dd77e1799fd652330adc5c13df8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`WorkspaceMetadata`](crate::types::WorkspaceMetadata). This method will fail if any of\nthe following fields are not set:\n- [`workspace_id`](crate::types::builders::WorkspaceMetadataBuilder::workspace_id)\n- [`workspace_status`](crate::types::builders::WorkspaceMetadataBuilder::workspace_status)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::WorkspaceMetadata {\n workspace_id: self.workspace_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"workspace_id\",\n \"workspace_id was not specified but it is required when building WorkspaceMetadata\",\n )\n })?,\n workspace_status: self.workspace_status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"workspace_status\",\n \"workspace_status was not specified but it is required when building WorkspaceMetadata\",\n )\n })?,\n environment_address: self.environment_address,\n environment_id: self.environment_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`WorkspaceMetadata`](crate::types::WorkspaceMetadata). This method will fail if any of\nthe following fields are not set:\n- [`workspace_id`](crate::types::builders::WorkspaceMetadataBuilder::workspace_id)\n- [`workspace_status`](crate::types::builders::WorkspaceMetadataBuilder::workspace_status)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_workspace_metadata.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_workspace_metadata.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f1ad17745258a16f4bc1066a3f3b7581a0b785ffafac25e6a175b6a0b0514bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_programming_language\n\nDocumentation:\nPrimary programming language of the Workspace\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_programming_language(mut self, input: ::std::option::Option) -> Self {\n self.programming_language = input;\n self\n }\n```"}], "func_name": "set_programming_language", "docstring": "Primary programming language of the Workspace", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_workspace_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_workspace_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a020bc329d89c26180bd7e8d4f8c4b33a18b835379c1d5ecb1c8633682d4e7a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: context_truncation_scheme\n\nDocumentation:\nWorkspace context truncation schemes based on usecase\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn context_truncation_scheme(mut self, input: crate::types::ContextTruncationScheme) -> Self {\n self.context_truncation_scheme = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "context_truncation_scheme", "docstring": "Workspace context truncation schemes based on usecase", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_workspace_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_workspace_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d1ab652432c9a19db7d456e6f792d9361fc6915ddc5cac55a2efbc9cdddfd07"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`WorkspaceState`](crate::types::WorkspaceState).\nThis method will fail if any of the following fields are not set:\n- [`upload_id`](crate::types::builders::WorkspaceStateBuilder::upload_id)\n- [`programming_language`](crate::types::builders::WorkspaceStateBuilder::programming_language)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::WorkspaceState {\n upload_id: self.upload_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"upload_id\",\n \"upload_id was not specified but it is required when building WorkspaceState\",\n )\n })?,\n programming_language: self.programming_language.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"programming_language\",\n \"programming_language was not specified but it is required when building WorkspaceState\",\n )\n })?,\n context_truncation_scheme: self.context_truncation_scheme,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`WorkspaceState`](crate::types::WorkspaceState).\nThis method will fail if any of the following fields are not set:\n- [`upload_id`](crate::types::builders::WorkspaceStateBuilder::upload_id)\n- [`programming_language`](crate::types::builders::WorkspaceStateBuilder::programming_language)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/_workspace_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/_workspace_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be716b286a592cb3566d21165f462de54d5a6c2027837bcc0dab42f5142cfbc0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`AccessDeniedError`](crate::types::error::AccessDeniedError). This method will fail if\nany of the following fields are not set:\n- [`message`](crate::types::error::builders::AccessDeniedErrorBuilder::message)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::error::AccessDeniedError {\n message: self.message.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message\",\n \"message was not specified but it is required when building AccessDeniedError\",\n )\n })?,\n reason: self.reason,\n meta: self.meta.unwrap_or_default(),\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`AccessDeniedError`](crate::types::error::AccessDeniedError). This method will fail if\nany of the following fields are not set:\n- [`message`](crate::types::error::builders::AccessDeniedErrorBuilder::message)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/error/_access_denied_exception.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/error/_access_denied_exception.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dabee5d607da7df9ccae0ed9c66c3d4e5f923ac4ed109d308310f10f0d5372f1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ConflictError`](crate::types::error::ConflictError).\nThis method will fail if any of the following fields are not set:\n- [`message`](crate::types::error::builders::ConflictErrorBuilder::message)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::error::ConflictError {\n message: self.message.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message\",\n \"message was not specified but it is required when building ConflictError\",\n )\n })?,\n reason: self.reason,\n meta: self.meta.unwrap_or_default(),\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ConflictError`](crate::types::error::ConflictError).\nThis method will fail if any of the following fields are not set:\n- [`message`](crate::types::error::builders::ConflictErrorBuilder::message)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/error/_conflict_exception.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/error/_conflict_exception.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f6f2fad3083dd31b64da06e89127f547fa49bfeb83322ecf408305ad423228c9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`InternalServerError`](crate::types::error::InternalServerError). This method will fail\nif any of the following fields are not set:\n- [`message`](crate::types::error::builders::InternalServerErrorBuilder::message)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::error::InternalServerError {\n message: self.message.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message\",\n \"message was not specified but it is required when building InternalServerError\",\n )\n })?,\n meta: self.meta.unwrap_or_default(),\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`InternalServerError`](crate::types::error::InternalServerError). This method will fail\nif any of the following fields are not set:\n- [`message`](crate::types::error::builders::InternalServerErrorBuilder::message)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/error/_internal_server_exception.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/error/_internal_server_exception.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80a568fbe98c076f6a94bfa7fc3f35a239dff7e1f2ffc5828c9449ef50067966"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ResourceNotFoundError`](crate::types::error::ResourceNotFoundError). This method will\nfail if any of the following fields are not set:\n- [`message`](crate::types::error::builders::ResourceNotFoundErrorBuilder::message)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::error::ResourceNotFoundError,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::error::ResourceNotFoundError {\n message: self.message.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message\",\n \"message was not specified but it is required when building ResourceNotFoundError\",\n )\n })?,\n meta: self.meta.unwrap_or_default(),\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ResourceNotFoundError`](crate::types::error::ResourceNotFoundError). This method will\nfail if any of the following fields are not set:\n- [`message`](crate::types::error::builders::ResourceNotFoundErrorBuilder::message)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/error/_resource_not_found_exception.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/error/_resource_not_found_exception.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "99fa1dc4d5d3c2fe6dd3a0c83135f5d6a9eaa1bf09c754058c5cc5a8272a5a4c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ServiceQuotaExceededError`](crate::types::error::ServiceQuotaExceededError).\nThis method will fail if any of the following fields are not set:\n- [`message`](crate::types::error::builders::ServiceQuotaExceededErrorBuilder::message)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::error::ServiceQuotaExceededError,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::error::ServiceQuotaExceededError {\n message: self.message.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message\",\n \"message was not specified but it is required when building ServiceQuotaExceededError\",\n )\n })?,\n reason: self.reason,\n meta: self.meta.unwrap_or_default(),\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ServiceQuotaExceededError`](crate::types::error::ServiceQuotaExceededError).\nThis method will fail if any of the following fields are not set:\n- [`message`](crate::types::error::builders::ServiceQuotaExceededErrorBuilder::message)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/error/_service_quota_exceeded_exception.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/error/_service_quota_exceeded_exception.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "038812aac19183651ab6dfae3135ca84680e8a22e7269b7a417c356420535648"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ThrottlingError`](crate::types::error::ThrottlingError). This method will fail if any\nof the following fields are not set:\n- [`message`](crate::types::error::builders::ThrottlingErrorBuilder::message)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::error::ThrottlingError {\n message: self.message.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message\",\n \"message was not specified but it is required when building ThrottlingError\",\n )\n })?,\n reason: self.reason,\n meta: self.meta.unwrap_or_default(),\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ThrottlingError`](crate::types::error::ThrottlingError). This method will fail if any\nof the following fields are not set:\n- [`message`](crate::types::error::builders::ThrottlingErrorBuilder::message)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/error/_throttling_exception.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/error/_throttling_exception.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3fb8968a233bc5cb5b66afd067e6b0493fc8ab3509283d5c8a1c3cd48b1bee25"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ValidationError`](crate::types::error::ValidationError). This method will fail if any\nof the following fields are not set:\n- [`message`](crate::types::error::builders::ValidationErrorBuilder::message)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::error::ValidationError {\n message: self.message.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message\",\n \"message was not specified but it is required when building ValidationError\",\n )\n })?,\n reason: self.reason,\n meta: self.meta.unwrap_or_default(),\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ValidationError`](crate::types::error::ValidationError). This method will fail if any\nof the following fields are not set:\n- [`message`](crate::types::error::builders::ValidationErrorBuilder::message)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-client/src/types/error/_validation_exception.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-client/src/types/error/_validation_exception.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ef76d0f83cda59ea63412931b6e781e4cc8682c842c59899dfc0a05c2bcf5e3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_identity_cache\n\nDocumentation:\nSet the identity cache for auth.\n\nThe identity cache defaults to a lazy caching implementation that will resolve\nan identity when it is requested, and place it in the cache thereafter. Subsequent\nrequests will take the value from the cache while it is still valid. Once it expires,\nthe next request will result in refreshing the identity.\n\nThis configuration allows you to disable or change the default caching mechanism.\nTo use a custom caching mechanism, implement the\n[`ResolveCachedIdentity`](crate::config::ResolveCachedIdentity) trait and pass that\nimplementation into this function.\n\n# Examples\n\nDisabling identity caching:\n\n```no_run\nuse amzn_codewhisperer_streaming_client::config::IdentityCache;\n\nlet config = amzn_codewhisperer_streaming_client::Config::builder()\n.identity_cache(IdentityCache::no_cache())\n// ...\n.build();\nlet client = amzn_codewhisperer_streaming_client::Client::from_conf(config);\n```\n\nCustomizing lazy caching:\n\n```no_run\nuse std::time::Duration;\n\nuse amzn_codewhisperer_streaming_client::config::IdentityCache;\n\nlet config = amzn_codewhisperer_streaming_client::Config::builder()\n.identity_cache(\nIdentityCache::lazy()\n// change the load timeout to 10 seconds\n.load_timeout(Duration::from_secs(10))\n.build()\n)\n// ...\n.build();\nlet client = amzn_codewhisperer_streaming_client::Client::from_conf(config);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_identity_cache(\n &mut self,\n identity_cache: impl crate::config::ResolveCachedIdentity + 'static,\n ) -> &mut Self {\n self.runtime_components\n .set_identity_cache(::std::option::Option::Some(identity_cache));\n self\n }\n```"}], "func_name": "set_identity_cache", "docstring": "Set the identity cache for auth.\n\nThe identity cache defaults to a lazy caching implementation that will resolve\nan identity when it is requested, and place it in the cache thereafter. Subsequent\nrequests will take the value from the cache while it is still valid. Once it expires,\nthe next request will result in refreshing the identity.\n\nThis configuration allows you to disable or change the default caching mechanism.\nTo use a custom caching mechanism, implement the\n[`ResolveCachedIdentity`](crate::config::ResolveCachedIdentity) trait and pass that\nimplementation into this function.\n\n# Examples\n\nDisabling identity caching:\n\n```no_run\nuse amzn_codewhisperer_streaming_client::config::IdentityCache;\n\nlet config = amzn_codewhisperer_streaming_client::Config::builder()\n.identity_cache(IdentityCache::no_cache())\n// ...\n.build();\nlet client = amzn_codewhisperer_streaming_client::Client::from_conf(config);\n```\n\nCustomizing lazy caching:\n\n```no_run\nuse std::time::Duration;\n\nuse amzn_codewhisperer_streaming_client::config::IdentityCache;\n\nlet config = amzn_codewhisperer_streaming_client::Config::builder()\n.identity_cache(\nIdentityCache::lazy()\n// change the load timeout to 10 seconds\n.load_timeout(Duration::from_secs(10))\n.build()\n)\n// ...\n.build();\nlet client = amzn_codewhisperer_streaming_client::Client::from_conf(config);\n```", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f7a569fced3450a09676d75f49103dee17965082cccf25b7ed56f806e39306c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: export_result_archive\n\nDocumentation:\nConstructs a fluent builder for the\n[`ExportResultArchive`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`export_id(impl Into)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::export_id) / [`set_export_id(Option)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::set_export_id):
required: **true**
(undocumented)
\n- [`export_intent(ExportIntent)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::export_intent) / [`set_export_intent(Option)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::set_export_intent):
required: **true**
Export Intent
\n- [`export_context(ExportContext)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::export_context) / [`set_export_context(Option)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::set_export_context):
required: **false**
Export Context
\n- [`profile_arn(impl Into)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`ExportResultArchiveOutput`](crate::operation::export_result_archive::ExportResultArchiveOutput)\nwith field(s):\n- [`body(EventReceiver)`](crate::operation::export_result_archive::ExportResultArchiveOutput::body):\nResponse Stream\n- On failure, responds with\n[`SdkError`](crate::operation::export_result_archive::ExportResultArchiveError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn export_result_archive(\n &self,\n ) -> crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder {\n crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "export_result_archive", "docstring": "Constructs a fluent builder for the\n[`ExportResultArchive`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`export_id(impl Into)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::export_id) / [`set_export_id(Option)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::set_export_id):
required: **true**
(undocumented)
\n- [`export_intent(ExportIntent)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::export_intent) / [`set_export_intent(Option)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::set_export_intent):
required: **true**
Export Intent
\n- [`export_context(ExportContext)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::export_context) / [`set_export_context(Option)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::set_export_context):
required: **false**
Export Context
\n- [`profile_arn(impl Into)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::export_result_archive::builders::ExportResultArchiveFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`ExportResultArchiveOutput`](crate::operation::export_result_archive::ExportResultArchiveOutput)\nwith field(s):\n- [`body(EventReceiver)`](crate::operation::export_result_archive::ExportResultArchiveOutput::body):\nResponse Stream\n- On failure, responds with\n[`SdkError`](crate::operation::export_result_archive::ExportResultArchiveError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/client/export_result_archive.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/client/export_result_archive.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c7be5d50694e23a79efa80bef1da137fa03acf31e503b48b39ac69af3d8c2d4e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_assistant_response\n\nDocumentation:\nConstructs a fluent builder for the\n[`GenerateAssistantResponse`](crate::operation::generate_assistant_response::builders::GenerateAssistantResponseFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`conversation_state(ConversationState)`](crate::operation::generate_assistant_response::builders::GenerateAssistantResponseFluentBuilder::conversation_state) / [`set_conversation_state(Option)`](crate::operation::generate_assistant_response::builders::GenerateAssistantResponseFluentBuilder::set_conversation_state):
required: **true**
Structure to represent the current state of a chat conversation.
\n- [`profile_arn(impl Into)`](crate::operation::generate_assistant_response::builders::GenerateAssistantResponseFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::generate_assistant_response::builders::GenerateAssistantResponseFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`GenerateAssistantResponseOutput`](crate::operation::generate_assistant_response::GenerateAssistantResponseOutput)\nwith field(s):\n- [`generate_assistant_response_response(EventReceiver)`](crate::operation::generate_assistant_response::GenerateAssistantResponseOutput::generate_assistant_response_response): Streaming events from UniDirectional Streaming Conversational APIs.\n- On failure, responds with [`SdkError`](crate::operation::generate_assistant_response::GenerateAssistantResponseError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate_assistant_response(\n &self,\n ) -> crate::operation::generate_assistant_response::builders::GenerateAssistantResponseFluentBuilder {\n crate::operation::generate_assistant_response::builders::GenerateAssistantResponseFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "generate_assistant_response", "docstring": "Constructs a fluent builder for the\n[`GenerateAssistantResponse`](crate::operation::generate_assistant_response::builders::GenerateAssistantResponseFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`conversation_state(ConversationState)`](crate::operation::generate_assistant_response::builders::GenerateAssistantResponseFluentBuilder::conversation_state) / [`set_conversation_state(Option)`](crate::operation::generate_assistant_response::builders::GenerateAssistantResponseFluentBuilder::set_conversation_state):
required: **true**
Structure to represent the current state of a chat conversation.
\n- [`profile_arn(impl Into)`](crate::operation::generate_assistant_response::builders::GenerateAssistantResponseFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::generate_assistant_response::builders::GenerateAssistantResponseFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`GenerateAssistantResponseOutput`](crate::operation::generate_assistant_response::GenerateAssistantResponseOutput)\nwith field(s):\n- [`generate_assistant_response_response(EventReceiver)`](crate::operation::generate_assistant_response::GenerateAssistantResponseOutput::generate_assistant_response_response): Streaming events from UniDirectional Streaming Conversational APIs.\n- On failure, responds with [`SdkError`](crate::operation::generate_assistant_response::GenerateAssistantResponseError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/client/generate_assistant_response.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/client/generate_assistant_response.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "05c1be107ecf5ba073cb88892dc4a01da3b7ea0294289547bb21d50914c51d9b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_task_assist_plan\n\nDocumentation:\nConstructs a fluent builder for the\n[`GenerateTaskAssistPlan`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`conversation_state(ConversationState)`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder::conversation_state) / [`set_conversation_state(Option)`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder::set_conversation_state):
required: **true**
Structure to represent the current state of a chat conversation.
\n- [`workspace_state(WorkspaceState)`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder::workspace_state) / [`set_workspace_state(Option)`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder::set_workspace_state):
required: **true**
Represents a Workspace state uploaded to S3 for Async Code Actions
\n- [`profile_arn(impl Into)`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`GenerateTaskAssistPlanOutput`](crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanOutput)\nwith field(s):\n- [`planning_response_stream(EventReceiver)`](crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanOutput::planning_response_stream): Streaming events from UniDirectional Streaming Conversational APIs.\n- On failure, responds with\n[`SdkError`](crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate_task_assist_plan(\n &self,\n ) -> crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder {\n crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "generate_task_assist_plan", "docstring": "Constructs a fluent builder for the\n[`GenerateTaskAssistPlan`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`conversation_state(ConversationState)`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder::conversation_state) / [`set_conversation_state(Option)`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder::set_conversation_state):
required: **true**
Structure to represent the current state of a chat conversation.
\n- [`workspace_state(WorkspaceState)`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder::workspace_state) / [`set_workspace_state(Option)`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder::set_workspace_state):
required: **true**
Represents a Workspace state uploaded to S3 for Async Code Actions
\n- [`profile_arn(impl Into)`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanFluentBuilder::set_profile_arn):
required: **false**
(undocumented)
\n- On success, responds with\n[`GenerateTaskAssistPlanOutput`](crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanOutput)\nwith field(s):\n- [`planning_response_stream(EventReceiver)`](crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanOutput::planning_response_stream): Streaming events from UniDirectional Streaming Conversational APIs.\n- On failure, responds with\n[`SdkError`](crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/client/generate_task_assist_plan.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/client/generate_task_assist_plan.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f650b1435410e338a452211516a06a2395f257dda25a8c44df89a27fd31e640d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_dry_run_operation_error\n\nDocumentation:\nReturns `true` if the error kind is `SendMessageError::DryRunOperationError`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_dry_run_operation_error(&self) -> bool {\n matches!(self, Self::DryRunOperationError(_))\n }\n```"}], "func_name": "is_dry_run_operation_error", "docstring": "Returns `true` if the error kind is `SendMessageError::DryRunOperationError`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/send_message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/send_message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "026b552c4de1ea0859e4bbfe0ca82a61840bd166907df5372d3c6133a66f0718"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: export_intent\n\nDocumentation:\nExport Intent\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn export_intent(mut self, input: crate::types::ExportIntent) -> Self {\n self.export_intent = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "export_intent", "docstring": "Export Intent\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/export_result_archive/_export_result_archive_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/export_result_archive/_export_result_archive_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5ffa02dc1f21cabaa4f2c60fdb27d5fc97c968b358a88dcae478196e083668f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ExportResultArchiveInput`](crate::operation::export_result_archive::ExportResultArchiveInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::export_result_archive::ExportResultArchiveInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::export_result_archive::ExportResultArchiveInput {\n export_id: self.export_id,\n export_intent: self.export_intent,\n export_context: self.export_context,\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ExportResultArchiveInput`](crate::operation::export_result_archive::ExportResultArchiveInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/export_result_archive/_export_result_archive_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/export_result_archive/_export_result_archive_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "72d694850a3bed68343f5f9c75ea7fe54a3204b81992e65f88d5f41f11ec7fd4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: body\n\nDocumentation:\nResponse Stream\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn body(\n mut self,\n input: crate::event_receiver::EventReceiver<\n crate::types::ResultArchiveStream,\n crate::types::error::ResultArchiveStreamError,\n >,\n ) -> Self {\n self.body = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "body", "docstring": "Response Stream\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/export_result_archive/_export_result_archive_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/export_result_archive/_export_result_archive_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fd362316eb6d7b9101ed992c2c396bf9ddffb68878a0457d80012013c5f89dd9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ExportResultArchiveOutput`](crate::operation::export_result_archive::ExportResultArchiveOutput).\nThis method will fail if any of the following fields are not set:\n- [`body`](crate::operation::export_result_archive::builders::ExportResultArchiveOutputBuilder::body)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::export_result_archive::ExportResultArchiveOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::export_result_archive::ExportResultArchiveOutput {\n body: self.body.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"body\",\n \"body was not specified but it is required when building ExportResultArchiveOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ExportResultArchiveOutput`](crate::operation::export_result_archive::ExportResultArchiveOutput).\nThis method will fail if any of the following fields are not set:\n- [`body`](crate::operation::export_result_archive::builders::ExportResultArchiveOutputBuilder::body)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/export_result_archive/_export_result_archive_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/export_result_archive/_export_result_archive_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "34191622569919c586d309e8e2436792b9c6e9d4a8ab0cd94ab5ed9732243485"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GenerateAssistantResponseInput`](crate::operation::generate_assistant_response::GenerateAssistantResponseInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::generate_assistant_response::GenerateAssistantResponseInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::generate_assistant_response::GenerateAssistantResponseInput {\n conversation_state: self.conversation_state,\n profile_arn: self.profile_arn,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GenerateAssistantResponseInput`](crate::operation::generate_assistant_response::GenerateAssistantResponseInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/generate_assistant_response/_generate_assistant_response_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/generate_assistant_response/_generate_assistant_response_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5a078faaa07e711350b683f00b92381deb6f6a75fdfbfe0de618f3cb3a602e15"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_assistant_response_response\n\nDocumentation:\nStreaming events from UniDirectional Streaming Conversational APIs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate_assistant_response_response(\n &self,\n ) -> &crate::event_receiver::EventReceiver<\n crate::types::ChatResponseStream,\n crate::types::error::ChatResponseStreamError,\n > {\n &self.generate_assistant_response_response\n }\n```"}], "func_name": "generate_assistant_response_response", "docstring": "Streaming events from UniDirectional Streaming Conversational APIs.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/generate_assistant_response/_generate_assistant_response_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/generate_assistant_response/_generate_assistant_response_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dfb028e16b4289fc33484a614eb1c9439229d351210135b7d5b4657a8a476f4c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`GenerateAssistantResponseOutput`](crate::operation::generate_assistant_response::GenerateAssistantResponseOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder() -> crate::operation::generate_assistant_response::builders::GenerateAssistantResponseOutputBuilder\n {\n crate::operation::generate_assistant_response::builders::GenerateAssistantResponseOutputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`GenerateAssistantResponseOutput`](crate::operation::generate_assistant_response::GenerateAssistantResponseOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/generate_assistant_response/_generate_assistant_response_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/generate_assistant_response/_generate_assistant_response_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "61b558093480561e96d4300ad82f03453026ac67029a0cfed6fcc9fad8ad819b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_assistant_response_response\n\nDocumentation:\nStreaming events from UniDirectional Streaming Conversational APIs.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate_assistant_response_response(\n mut self,\n input: crate::event_receiver::EventReceiver<\n crate::types::ChatResponseStream,\n crate::types::error::ChatResponseStreamError,\n >,\n ) -> Self {\n self.generate_assistant_response_response = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "generate_assistant_response_response", "docstring": "Streaming events from UniDirectional Streaming Conversational APIs.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/generate_assistant_response/_generate_assistant_response_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/generate_assistant_response/_generate_assistant_response_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3be1f8f27438060ce7080f3e0ca6afe3ffa69d4a98b09e42129e58d4d2c4c529"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GenerateAssistantResponseOutput`](crate::operation::generate_assistant_response::GenerateAssistantResponseOutput).\nThis method will fail if any of the following fields are not set:\n- [`generate_assistant_response_response`](crate::operation::generate_assistant_response::builders::GenerateAssistantResponseOutputBuilder::generate_assistant_response_response)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::generate_assistant_response::GenerateAssistantResponseOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::generate_assistant_response::GenerateAssistantResponseOutput {\n generate_assistant_response_response: self.generate_assistant_response_response.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"generate_assistant_response_response\",\n \"generate_assistant_response_response was not specified but it is required when building GenerateAssistantResponseOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GenerateAssistantResponseOutput`](crate::operation::generate_assistant_response::GenerateAssistantResponseOutput).\nThis method will fail if any of the following fields are not set:\n- [`generate_assistant_response_response`](crate::operation::generate_assistant_response::builders::GenerateAssistantResponseOutputBuilder::generate_assistant_response_response)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/generate_assistant_response/_generate_assistant_response_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/generate_assistant_response/_generate_assistant_response_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "79a5fccd544e823f564afef16da2b81161edb3d1b646f21d35c304e7b8223b44"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GenerateTaskAssistPlanInput`](crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanInput {\n conversation_state: self.conversation_state,\n workspace_state: self.workspace_state,\n profile_arn: self.profile_arn,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GenerateTaskAssistPlanInput`](crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/generate_task_assist_plan/_generate_task_assist_plan_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/generate_task_assist_plan/_generate_task_assist_plan_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "76c05b5fdbf61a0d75d9997ba546ed4e0ca2a6a6951dc71f93e939c708c3ab50"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GenerateTaskAssistPlanOutput`](crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanOutput).\nThis method will fail if any of the following fields are not set:\n- [`planning_response_stream`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanOutputBuilder::planning_response_stream)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanOutput {\n planning_response_stream: self.planning_response_stream.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"planning_response_stream\",\n \"planning_response_stream was not specified but it is required when building GenerateTaskAssistPlanOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GenerateTaskAssistPlanOutput`](crate::operation::generate_task_assist_plan::GenerateTaskAssistPlanOutput).\nThis method will fail if any of the following fields are not set:\n- [`planning_response_stream`](crate::operation::generate_task_assist_plan::builders::GenerateTaskAssistPlanOutputBuilder::planning_response_stream)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/generate_task_assist_plan/_generate_task_assist_plan_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/generate_task_assist_plan/_generate_task_assist_plan_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc4da973ceb5d88e853c329a98df4f90e7167b5f7527b8636f7918285c509e81"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`SendMessageInput`](crate::operation::send_message::SendMessageInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::send_message::SendMessageInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::send_message::SendMessageInput {\n conversation_state: self.conversation_state,\n profile_arn: self.profile_arn,\n source: self.source,\n dry_run: self.dry_run,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`SendMessageInput`](crate::operation::send_message::SendMessageInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/send_message/_send_message_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/send_message/_send_message_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc9fc4891326565f29ac214bfb2df9b26e530504465163e1f4ba6a7c94fe8d01"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`SendMessageOutput`](crate::operation::send_message::SendMessageOutput). This method\nwill fail if any of the following fields are not set:\n- [`send_message_response`](crate::operation::send_message::builders::SendMessageOutputBuilder::send_message_response)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::send_message::SendMessageOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::send_message::SendMessageOutput {\n send_message_response: self.send_message_response.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"send_message_response\",\n \"send_message_response was not specified but it is required when building SendMessageOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`SendMessageOutput`](crate::operation::send_message::SendMessageOutput). This method\nwill fail if any of the following fields are not set:\n- [`send_message_response`](crate::operation::send_message::builders::SendMessageOutputBuilder::send_message_response)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/operation/send_message/_send_message_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/operation/send_message/_send_message_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "640428870149a87f3da196b491b72e71f7c11aacac37279e599ccf5e360291e0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Action`](crate::types::Action).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::Action {\n crate::types::Action {\n web_link: self.web_link,\n module_link: self.module_link,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Action`](crate::types::Action).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_action.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_action.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "28e41119fd4fb011aa9f6f5a48ac08182f7ab2490ca1bb2cff3f1b6b405524bf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: content\n\nDocumentation:\nContains the content of the alert, which may include sensitive information.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn content(&self) -> &[crate::types::AlertComponent] {\n use std::ops::Deref;\n self.content.deref()\n }\n```"}], "func_name": "content", "docstring": "Contains the content of the alert, which may include sensitive information.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_alert.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_alert.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "045164db62a2180ad1ff79c8f89251607bc334ef5450301ce2469c710b674bc5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: r#type\n\nDocumentation:\nEnum defining types of alerts that can be issued.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn r#type(mut self, input: crate::types::AlertType) -> Self {\n self.r#type = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "r#type", "docstring": "Enum defining types of alerts that can be issued.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_alert.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_alert.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "df09795ecb26049d805ba993539ee6a6d914a52479de8d6cf8403736616697c1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_type\n\nDocumentation:\nEnum defining types of alerts that can be issued.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_type(mut self, input: ::std::option::Option) -> Self {\n self.r#type = input;\n self\n }\n```"}], "func_name": "set_type", "docstring": "Enum defining types of alerts that can be issued.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_alert.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_alert.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b8768725b52b80397f04a5bb553a6069d39b31b9efb918d9aea0f1c22e2d6aaa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: content\n\nDocumentation:\nAppends an item to `content`.\n\nTo override the contents of this collection use [`set_content`](Self::set_content).\n\nContains the content of the alert, which may include sensitive information.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn content(mut self, input: crate::types::AlertComponent) -> Self {\n let mut v = self.content.unwrap_or_default();\n v.push(input);\n self.content = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "content", "docstring": "Appends an item to `content`.\n\nTo override the contents of this collection use [`set_content`](Self::set_content).\n\nContains the content of the alert, which may include sensitive information.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_alert.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_alert.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e7c0993d96ecdcaf65defbcf8c5d7d29474eeb52570ac88e23779b2ac0f0073"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Alert`](crate::types::Alert).\nThis method will fail if any of the following fields are not set:\n- [`r#type`](crate::types::builders::AlertBuilder::type)\n- [`content`](crate::types::builders::AlertBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Alert {\n r#type: self.r#type.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"r#type\",\n \"r#type was not specified but it is required when building Alert\",\n )\n })?,\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building Alert\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Alert`](crate::types::Alert).\nThis method will fail if any of the following fields are not set:\n- [`r#type`](crate::types::builders::AlertBuilder::type)\n- [`content`](crate::types::builders::AlertBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_alert.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_alert.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ddad021b35136776d79652cf3294d222b71d7f938174e1ec27f3b9dc2537a3de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: text\n\nDocumentation:\nStructure representing a simple text component with sensitive content, which can include\nMarkdown formatting.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn text(mut self, input: crate::types::Text) -> Self {\n self.text = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "text", "docstring": "Structure representing a simple text component with sensitive content, which can include\nMarkdown formatting.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_alert_component.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_alert_component.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7fe8780eadcd306c004eedf175a38843b189299a2cb5cf444db016a6f175c4cc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`AlertComponent`](crate::types::AlertComponent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::AlertComponent {\n crate::types::AlertComponent { text: self.text }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`AlertComponent`](crate::types::AlertComponent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_alert_component.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_alert_component.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e20770d827fe655221f0487ff40f0696c655f6aca18127c01e1b48db107fbc2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`AssistantResponseEvent`](crate::types::AssistantResponseEvent). This method will fail\nif any of the following fields are not set:\n- [`content`](crate::types::builders::AssistantResponseEventBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::AssistantResponseEvent {\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building AssistantResponseEvent\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`AssistantResponseEvent`](crate::types::AssistantResponseEvent). This method will fail\nif any of the following fields are not set:\n- [`content`](crate::types::builders::AssistantResponseEventBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_assistant_response_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_assistant_response_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82fe29b55488d3700fb14d8b7608e7782f6501cca45e39c9aa123fa80f93b248"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: content_checksum\n\nDocumentation:\nContent checksum of the binary payload\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn content_checksum(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.content_checksum = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "content_checksum", "docstring": "Content checksum of the binary payload", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_binary_metadata_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_binary_metadata_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ab3e31617b7d6bf29634462ad2020d302f9b29f8a1134d342d8736205f4adcb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: content_checksum_type\n\nDocumentation:\nContent checksum type of the binary payload\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn content_checksum_type(mut self, input: crate::types::ContentChecksumType) -> Self {\n self.content_checksum_type = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "content_checksum_type", "docstring": "Content checksum type of the binary payload", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_binary_metadata_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_binary_metadata_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9fdb5cce9f861a4ae6d2974b7d52e477f86aca21854bcdb326d707095161a60d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`BinaryMetadataEvent`](crate::types::BinaryMetadataEvent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::BinaryMetadataEvent {\n crate::types::BinaryMetadataEvent {\n size: self.size,\n mime_type: self.mime_type,\n content_checksum: self.content_checksum,\n content_checksum_type: self.content_checksum_type,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`BinaryMetadataEvent`](crate::types::BinaryMetadataEvent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_binary_metadata_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_binary_metadata_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3b4be716f3a6c7315c852830fd2c02f3685d67405172a3c45b99b00bc1b8b0ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`BinaryPayloadEvent`](crate::types::BinaryPayloadEvent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::BinaryPayloadEvent {\n crate::types::BinaryPayloadEvent { bytes: self.bytes }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`BinaryPayloadEvent`](crate::types::BinaryPayloadEvent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_binary_payload_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_binary_payload_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1d863d8f8a46adb497a28d348d87f638e190aee1bb6041457ab4aa4f2776f638"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_assistant_response_event\n\nDocumentation:\nTries to convert the enum instance into\n[`AssistantResponseEvent`](crate::types::ChatResponseStream::AssistantResponseEvent),\nextracting the inner [`AssistantResponseEvent`](crate::types::AssistantResponseEvent).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_assistant_response_event(&self) -> ::std::result::Result<&crate::types::AssistantResponseEvent, &Self> {\n if let ChatResponseStream::AssistantResponseEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_assistant_response_event", "docstring": "Tries to convert the enum instance into\n[`AssistantResponseEvent`](crate::types::ChatResponseStream::AssistantResponseEvent),\nextracting the inner [`AssistantResponseEvent`](crate::types::AssistantResponseEvent).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f1ae34c21a03531d245a6c545668421d91f503522a3fa999ce274a6c932cdbe7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_citation_event\n\nDocumentation:\nTries to convert the enum instance into\n[`CitationEvent`](crate::types::ChatResponseStream::CitationEvent), extracting the inner\n[`CitationEvent`](crate::types::CitationEvent). Returns `Err(&Self)` if it can't be\nconverted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_citation_event(&self) -> ::std::result::Result<&crate::types::CitationEvent, &Self> {\n if let ChatResponseStream::CitationEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_citation_event", "docstring": "Tries to convert the enum instance into\n[`CitationEvent`](crate::types::ChatResponseStream::CitationEvent), extracting the inner\n[`CitationEvent`](crate::types::CitationEvent). Returns `Err(&Self)` if it can't be\nconverted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b6a0d01dcc0500d7dacef7cc1141f7fa589bc8158d90a02ccd3edf3165941d2e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_code_event\n\nDocumentation:\nTries to convert the enum instance into\n[`CodeEvent`](crate::types::ChatResponseStream::CodeEvent), extracting the inner\n[`CodeEvent`](crate::types::CodeEvent). Returns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_code_event(&self) -> ::std::result::Result<&crate::types::CodeEvent, &Self> {\n if let ChatResponseStream::CodeEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_code_event", "docstring": "Tries to convert the enum instance into\n[`CodeEvent`](crate::types::ChatResponseStream::CodeEvent), extracting the inner\n[`CodeEvent`](crate::types::CodeEvent). Returns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5965116bd9ba381e0d8e38d723e420debcff6da09bf319f36912975f7fbffc99"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_code_reference_event\n\nDocumentation:\nTries to convert the enum instance into\n[`CodeReferenceEvent`](crate::types::ChatResponseStream::CodeReferenceEvent), extracting the\ninner [`CodeReferenceEvent`](crate::types::CodeReferenceEvent). Returns `Err(&Self)` if\nit can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_code_reference_event(&self) -> ::std::result::Result<&crate::types::CodeReferenceEvent, &Self> {\n if let ChatResponseStream::CodeReferenceEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_code_reference_event", "docstring": "Tries to convert the enum instance into\n[`CodeReferenceEvent`](crate::types::ChatResponseStream::CodeReferenceEvent), extracting the\ninner [`CodeReferenceEvent`](crate::types::CodeReferenceEvent). Returns `Err(&Self)` if\nit can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2aa75f00a1095b8b79ffc65b83792ca8f75e08ddd35c3e992cc6e5973eb6808e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_dry_run_succeed_event\n\nDocumentation:\nTries to convert the enum instance into\n[`DryRunSucceedEvent`](crate::types::ChatResponseStream::DryRunSucceedEvent), extracting the\ninner [`DryRunSucceedEvent`](crate::types::DryRunSucceedEvent). Returns `Err(&Self)` if\nit can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_dry_run_succeed_event(&self) -> ::std::result::Result<&crate::types::DryRunSucceedEvent, &Self> {\n if let ChatResponseStream::DryRunSucceedEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_dry_run_succeed_event", "docstring": "Tries to convert the enum instance into\n[`DryRunSucceedEvent`](crate::types::ChatResponseStream::DryRunSucceedEvent), extracting the\ninner [`DryRunSucceedEvent`](crate::types::DryRunSucceedEvent). Returns `Err(&Self)` if\nit can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "645d24a1929292fe202b37a402dafbf035aae224ee98a9176d587a1beb3433ee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_followup_prompt_event\n\nDocumentation:\nTries to convert the enum instance into\n[`FollowupPromptEvent`](crate::types::ChatResponseStream::FollowupPromptEvent), extracting\nthe inner [`FollowupPromptEvent`](crate::types::FollowupPromptEvent). Returns `Err(&\nSelf)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_followup_prompt_event(&self) -> ::std::result::Result<&crate::types::FollowupPromptEvent, &Self> {\n if let ChatResponseStream::FollowupPromptEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_followup_prompt_event", "docstring": "Tries to convert the enum instance into\n[`FollowupPromptEvent`](crate::types::ChatResponseStream::FollowupPromptEvent), extracting\nthe inner [`FollowupPromptEvent`](crate::types::FollowupPromptEvent). Returns `Err(&\nSelf)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "79928e5d4c38d949bef9c39572f479b41f4028121a458686027ddb1d187d572b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_intents_event\n\nDocumentation:\nTries to convert the enum instance into\n[`IntentsEvent`](crate::types::ChatResponseStream::IntentsEvent), extracting the inner\n[`IntentsEvent`](crate::types::IntentsEvent). Returns `Err(&Self)` if it can't be\nconverted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_intents_event(&self) -> ::std::result::Result<&crate::types::IntentsEvent, &Self> {\n if let ChatResponseStream::IntentsEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_intents_event", "docstring": "Tries to convert the enum instance into\n[`IntentsEvent`](crate::types::ChatResponseStream::IntentsEvent), extracting the inner\n[`IntentsEvent`](crate::types::IntentsEvent). Returns `Err(&Self)` if it can't be\nconverted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bbb552ccafec97f06f526700238edfd0f40a1576ff3e93029c23a02bfdad9a3e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_interaction_components_event\n\nDocumentation:\nTries to convert the enum instance into\n[`InteractionComponentsEvent`](crate::types::ChatResponseStream::InteractionComponentsEvent),\nextracting the inner\n[`InteractionComponentsEvent`](crate::types::InteractionComponentsEvent). Returns `Err(&\nSelf)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_interaction_components_event(\n &self,\n ) -> ::std::result::Result<&crate::types::InteractionComponentsEvent, &Self> {\n if let ChatResponseStream::InteractionComponentsEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_interaction_components_event", "docstring": "Tries to convert the enum instance into\n[`InteractionComponentsEvent`](crate::types::ChatResponseStream::InteractionComponentsEvent),\nextracting the inner\n[`InteractionComponentsEvent`](crate::types::InteractionComponentsEvent). Returns `Err(&\nSelf)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f40f1bac03d9b8fb980cf82c579f1f53228fdde37b331b990b325f7f0b5fec97"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_invalid_state_event\n\nDocumentation:\nTries to convert the enum instance into\n[`InvalidStateEvent`](crate::types::ChatResponseStream::InvalidStateEvent), extracting the\ninner [`InvalidStateEvent`](crate::types::InvalidStateEvent). Returns `Err(&Self)` if it\ncan't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_invalid_state_event(&self) -> ::std::result::Result<&crate::types::InvalidStateEvent, &Self> {\n if let ChatResponseStream::InvalidStateEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_invalid_state_event", "docstring": "Tries to convert the enum instance into\n[`InvalidStateEvent`](crate::types::ChatResponseStream::InvalidStateEvent), extracting the\ninner [`InvalidStateEvent`](crate::types::InvalidStateEvent). Returns `Err(&Self)` if it\ncan't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0423411cb0ad5afe14bdc79546c421eaf45d3752cacf6e4686378eff47166ede"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_message_metadata_event\n\nDocumentation:\nTries to convert the enum instance into\n[`MessageMetadataEvent`](crate::types::ChatResponseStream::MessageMetadataEvent), extracting\nthe inner [`MessageMetadataEvent`](crate::types::MessageMetadataEvent). Returns `Err(&\nSelf)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_message_metadata_event(&self) -> ::std::result::Result<&crate::types::MessageMetadataEvent, &Self> {\n if let ChatResponseStream::MessageMetadataEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_message_metadata_event", "docstring": "Tries to convert the enum instance into\n[`MessageMetadataEvent`](crate::types::ChatResponseStream::MessageMetadataEvent), extracting\nthe inner [`MessageMetadataEvent`](crate::types::MessageMetadataEvent). Returns `Err(&\nSelf)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7796525e035d6e5984f5acef065275364946f55d15b23856a00c120d8b4f00c2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_supplementary_web_links_event\n\nDocumentation:\nTries to convert the enum instance into\n[`SupplementaryWebLinksEvent`](crate::types::ChatResponseStream::SupplementaryWebLinksEvent),\nextracting the inner\n[`SupplementaryWebLinksEvent`](crate::types::SupplementaryWebLinksEvent). Returns `Err(&\nSelf)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_supplementary_web_links_event(\n &self,\n ) -> ::std::result::Result<&crate::types::SupplementaryWebLinksEvent, &Self> {\n if let ChatResponseStream::SupplementaryWebLinksEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_supplementary_web_links_event", "docstring": "Tries to convert the enum instance into\n[`SupplementaryWebLinksEvent`](crate::types::ChatResponseStream::SupplementaryWebLinksEvent),\nextracting the inner\n[`SupplementaryWebLinksEvent`](crate::types::SupplementaryWebLinksEvent). Returns `Err(&\nSelf)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d094ce95f4ef76c6fb3ed967897c27bb13cf26d3a07b8fb092fa9e917db9e660"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_tool_result_event\n\nDocumentation:\nTries to convert the enum instance into\n[`ToolResultEvent`](crate::types::ChatResponseStream::ToolResultEvent), extracting the inner\n[`ToolResultEvent`](crate::types::ToolResultEvent). Returns `Err(&Self)` if it can't be\nconverted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_tool_result_event(&self) -> ::std::result::Result<&crate::types::ToolResultEvent, &Self> {\n if let ChatResponseStream::ToolResultEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_tool_result_event", "docstring": "Tries to convert the enum instance into\n[`ToolResultEvent`](crate::types::ChatResponseStream::ToolResultEvent), extracting the inner\n[`ToolResultEvent`](crate::types::ToolResultEvent). Returns `Err(&Self)` if it can't be\nconverted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ed2e7f3deef67db3416a1447a717ea51a109cd7035aac167847be9effef430a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_tool_use_event\n\nDocumentation:\nTries to convert the enum instance into\n[`ToolUseEvent`](crate::types::ChatResponseStream::ToolUseEvent), extracting the inner\n[`ToolUseEvent`](crate::types::ToolUseEvent). Returns `Err(&Self)` if it can't be\nconverted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_tool_use_event(&self) -> ::std::result::Result<&crate::types::ToolUseEvent, &Self> {\n if let ChatResponseStream::ToolUseEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_tool_use_event", "docstring": "Tries to convert the enum instance into\n[`ToolUseEvent`](crate::types::ChatResponseStream::ToolUseEvent), extracting the inner\n[`ToolUseEvent`](crate::types::ToolUseEvent). Returns `Err(&Self)` if it can't be\nconverted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_chat_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f974c689d82690bed2dd9a5e87ff75db4c56954a3da81fdab1d2b2e938ea979d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: citation_link\n\nDocumentation:\nThe link to the document being cited\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn citation_link(&self) -> &str {\n use std::ops::Deref;\n self.citation_link.deref()\n }\n```"}], "func_name": "citation_link", "docstring": "The link to the document being cited", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_citation_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_citation_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "afd7679ab8849a6fe40476af74aea6ed3b95d4e21674665bb7fc7ca6796e98a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: target\n\nDocumentation:\nThe position or the range of the response text to be cited\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn target(mut self, input: crate::types::CitationTarget) -> Self {\n self.target = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "target", "docstring": "The position or the range of the response text to be cited\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_citation_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_citation_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b3201a61b3bbb561db00c13011bff4c5ade3c95117638026efc60c884f640708"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_target\n\nDocumentation:\nThe position or the range of the response text to be cited\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_target(mut self, input: ::std::option::Option) -> Self {\n self.target = input;\n self\n }\n```"}], "func_name": "set_target", "docstring": "The position or the range of the response text to be cited", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_citation_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_citation_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "07a8105d6a5acb9b223092d9d0d0dcc67c1cc22dfbc6e9b63415523274de7020"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: citation_text\n\nDocumentation:\nThe text inside the citation '1' in \\[1\\]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn citation_text(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.citation_text = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "citation_text", "docstring": "The text inside the citation '1' in \\[1\\]", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_citation_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_citation_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63b69800e4f69cb29b2becfa16e5ec73cfc230d5cfa77e9ba7eed7c0127786a4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: citation_link\n\nDocumentation:\nThe link to the document being cited\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn citation_link(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.citation_link = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "citation_link", "docstring": "The link to the document being cited\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_citation_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_citation_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b8d47404d5e0b44f0e7970115e821b344abbe177d9eff3a2f6cb200a433fa98"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`CitationEvent`](crate::types::CitationEvent).\nThis method will fail if any of the following fields are not set:\n- [`target`](crate::types::builders::CitationEventBuilder::target)\n- [`citation_link`](crate::types::builders::CitationEventBuilder::citation_link)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::CitationEvent {\n target: self.target.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"target\",\n \"target was not specified but it is required when building CitationEvent\",\n )\n })?,\n citation_text: self.citation_text,\n citation_link: self.citation_link.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"citation_link\",\n \"citation_link was not specified but it is required when building CitationEvent\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`CitationEvent`](crate::types::CitationEvent).\nThis method will fail if any of the following fields are not set:\n- [`target`](crate::types::builders::CitationEventBuilder::target)\n- [`citation_link`](crate::types::builders::CitationEventBuilder::citation_link)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_citation_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_citation_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ef5923a06f71ace0eb93d77758f8e9eb051eb27ae6b6c493169b8350acf0d45"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_location\n\nDocumentation:\nTries to convert the enum instance into\n[`Location`](crate::types::CitationTarget::Location), extracting the inner [`i32`](i32).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_location(&self) -> ::std::result::Result<&i32, &Self> {\n if let CitationTarget::Location(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_location", "docstring": "Tries to convert the enum instance into\n[`Location`](crate::types::CitationTarget::Location), extracting the inner [`i32`](i32).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_citation_target.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_citation_target.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7262c46e431f7e3462e6cbf58c3a90a3f68dcbbc9c67b9a4a5c8c4360d488263"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_range\n\nDocumentation:\nTries to convert the enum instance into [`Range`](crate::types::CitationTarget::Range),\nextracting the inner [`Span`](crate::types::Span). Returns `Err(&Self)` if it can't be\nconverted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_range(&self) -> ::std::result::Result<&crate::types::Span, &Self> {\n if let CitationTarget::Range(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_range", "docstring": "Tries to convert the enum instance into [`Range`](crate::types::CitationTarget::Range),\nextracting the inner [`Span`](crate::types::Span). Returns `Err(&Self)` if it can't be\nconverted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_citation_target.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_citation_target.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6917a95e7e3eded2007b944f848199386ad1c6cdb175ee55e98ca034382906fc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_text\n\nDocumentation:\nFallback string, if target channel does not support the CloudWatchTroubleshootingLink.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn default_text(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.default_text = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "default_text", "docstring": "Fallback string, if target channel does not support the CloudWatchTroubleshootingLink.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_cloud_watch_troubleshooting_link.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_cloud_watch_troubleshooting_link.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54cc8e38eb81390296b61da75b3881ceaca973d9dfbf22f47ef3d9c62ca58129"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CloudWatchTroubleshootingLink`](crate::types::CloudWatchTroubleshootingLink).\nThis method will fail if any of the following fields are not set:\n- [`label`](crate::types::builders::CloudWatchTroubleshootingLinkBuilder::label)\n- [`investigation_payload`](crate::types::builders::CloudWatchTroubleshootingLinkBuilder::investigation_payload)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::CloudWatchTroubleshootingLink,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::CloudWatchTroubleshootingLink {\n label: self.label.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"label\",\n \"label was not specified but it is required when building CloudWatchTroubleshootingLink\",\n )\n })?,\n investigation_payload: self.investigation_payload.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"investigation_payload\",\n \"investigation_payload was not specified but it is required when building CloudWatchTroubleshootingLink\",\n )\n })?,\n default_text: self.default_text,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CloudWatchTroubleshootingLink`](crate::types::CloudWatchTroubleshootingLink).\nThis method will fail if any of the following fields are not set:\n- [`label`](crate::types::builders::CloudWatchTroubleshootingLinkBuilder::label)\n- [`investigation_payload`](crate::types::builders::CloudWatchTroubleshootingLinkBuilder::investigation_payload)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_cloud_watch_troubleshooting_link.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_cloud_watch_troubleshooting_link.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ca6757d9eef893ea499e89e4cae5d7759bc64f8acf92fca76d96db07873d0c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`CodeEvent`](crate::types::CodeEvent).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::CodeEventBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::CodeEvent {\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building CodeEvent\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`CodeEvent`](crate::types::CodeEvent).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::CodeEventBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_code_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_code_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "935657123b1d009c661c7fa5fbe3fb25b0bb7947b1743911358097024cdc6bbc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_references\n\nDocumentation:\nCode References for Assistant Response Message\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_references(mut self, input: ::std::option::Option<::std::vec::Vec>) -> Self {\n self.references = input;\n self\n }\n```"}], "func_name": "set_references", "docstring": "Code References for Assistant Response Message", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_code_reference_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_code_reference_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c6531ae235d339f76b6bf2aa63acf21c866ae5379be06ee2cdc1eb59575b309a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CodeReferenceEvent`](crate::types::CodeReferenceEvent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::CodeReferenceEvent {\n crate::types::CodeReferenceEvent {\n references: self.references,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CodeReferenceEvent`](crate::types::CodeReferenceEvent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_code_reference_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_code_reference_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d0727d34ae10007255c3b7d10eff3ea5eb0a3d32e773dc5e761272c0ea04a877"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DryRunSucceedEvent`](crate::types::DryRunSucceedEvent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::DryRunSucceedEvent {\n crate::types::DryRunSucceedEvent {}\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DryRunSucceedEvent`](crate::types::DryRunSucceedEvent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_dry_run_succeed_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_dry_run_succeed_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c221b679fdadab87473193026c7212365a83dddb40a242c2e5d884725782940"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_transformation_export_context\n\nDocumentation:\nTries to convert the enum instance into\n[`TransformationExportContext`](crate::types::ExportContext::TransformationExportContext),\nextracting the inner\n[`TransformationExportContext`](crate::types::TransformationExportContext).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_transformation_export_context(\n &self,\n ) -> ::std::result::Result<&crate::types::TransformationExportContext, &Self> {\n if let ExportContext::TransformationExportContext(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_transformation_export_context", "docstring": "Tries to convert the enum instance into\n[`TransformationExportContext`](crate::types::ExportContext::TransformationExportContext),\nextracting the inner\n[`TransformationExportContext`](crate::types::TransformationExportContext).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_export_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_export_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5e3a8c9a2fa87eccd16fdcce080de48e615210a60c1ce686cc77f8feedadc28c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_unit_test_generation_export_context\n\nDocumentation:\nTries to convert the enum instance into\n[`UnitTestGenerationExportContext`](crate::types::ExportContext::UnitTestGenerationExportContext),\nextracting the inner\n[`UnitTestGenerationExportContext`](crate::types::UnitTestGenerationExportContext).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_unit_test_generation_export_context(\n &self,\n ) -> ::std::result::Result<&crate::types::UnitTestGenerationExportContext, &Self> {\n if let ExportContext::UnitTestGenerationExportContext(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_unit_test_generation_export_context", "docstring": "Tries to convert the enum instance into\n[`UnitTestGenerationExportContext`](crate::types::ExportContext::UnitTestGenerationExportContext),\nextracting the inner\n[`UnitTestGenerationExportContext`](crate::types::UnitTestGenerationExportContext).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_export_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_export_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "01baa2b93e9b4a8d5b920d42d2fbeccb9f15f5415b1d64b02e31a5025c1f151a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: followup_prompt\n\nDocumentation:\nFollowup Prompt for the Assistant Response\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn followup_prompt(mut self, input: crate::types::FollowupPrompt) -> Self {\n self.followup_prompt = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "followup_prompt", "docstring": "Followup Prompt for the Assistant Response", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_followup_prompt_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_followup_prompt_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f822ce18ecb5c3df70de34ff3304e605055e2a3c7d6bba3014dc587e470c501e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`FollowupPromptEvent`](crate::types::FollowupPromptEvent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::FollowupPromptEvent {\n crate::types::FollowupPromptEvent {\n followup_prompt: self.followup_prompt,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`FollowupPromptEvent`](crate::types::FollowupPromptEvent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_followup_prompt_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_followup_prompt_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e2cb1c35e6072fb27483c258988e3ff3c5877e8ef7d839dd8d468deccfdd966"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: transition\n\nDocumentation:\nStructure describing a transition between two states in an infrastructure update.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn transition(mut self, input: crate::types::InfrastructureUpdateTransition) -> Self {\n self.transition = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "transition", "docstring": "Structure describing a transition between two states in an infrastructure update.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bef23e1f26665d0ba901e32275adba47022d7ee38911b1bcd0a12d28954bc70c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`InfrastructureUpdate`](crate::types::InfrastructureUpdate).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::InfrastructureUpdate {\n crate::types::InfrastructureUpdate {\n transition: self.transition,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`InfrastructureUpdate`](crate::types::InfrastructureUpdate).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9e3a92edba9d307fa51947ded692c84d3595e6986bede0170bd6b4edc0a9e320"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: current_state\n\nDocumentation:\nThe current state of the infrastructure before the update.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn current_state(&self) -> &str {\n use std::ops::Deref;\n self.current_state.deref()\n }\n```"}], "func_name": "current_state", "docstring": "The current state of the infrastructure before the update.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update_transition.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update_transition.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c73cf6ae624b292b3420f0e5d23b553d927e50612022a33ef3560fbefc09b019"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next_state\n\nDocumentation:\nThe next state of the infrastructure following the update.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn next_state(&self) -> &str {\n use std::ops::Deref;\n self.next_state.deref()\n }\n```"}], "func_name": "next_state", "docstring": "The next state of the infrastructure following the update.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update_transition.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update_transition.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d904d5ea9629512483d511c63964dd61e2f30249a0a7e33130e0a6d99dd05cac"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: current_state\n\nDocumentation:\nThe current state of the infrastructure before the update.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn current_state(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.current_state = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "current_state", "docstring": "The current state of the infrastructure before the update.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update_transition.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update_transition.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "16595a2f8cf6f4c9ad48fa7a4d00253b2cf6997c251d9b580187f9196ac277e8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next_state\n\nDocumentation:\nThe next state of the infrastructure following the update.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn next_state(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.next_state = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "next_state", "docstring": "The next state of the infrastructure following the update.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update_transition.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update_transition.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "de484182a1fb26c8b1476599800c354b09310be2d862bc3d234acf1ccff582d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`InfrastructureUpdateTransition`](crate::types::InfrastructureUpdateTransition).\nThis method will fail if any of the following fields are not set:\n- [`current_state`](crate::types::builders::InfrastructureUpdateTransitionBuilder::current_state)\n- [`next_state`](crate::types::builders::InfrastructureUpdateTransitionBuilder::next_state)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::InfrastructureUpdateTransition,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::InfrastructureUpdateTransition {\n current_state: self.current_state.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"current_state\",\n \"current_state was not specified but it is required when building InfrastructureUpdateTransition\",\n )\n })?,\n next_state: self.next_state.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"next_state\",\n \"next_state was not specified but it is required when building InfrastructureUpdateTransition\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`InfrastructureUpdateTransition`](crate::types::InfrastructureUpdateTransition).\nThis method will fail if any of the following fields are not set:\n- [`current_state`](crate::types::builders::InfrastructureUpdateTransitionBuilder::current_state)\n- [`next_state`](crate::types::builders::InfrastructureUpdateTransitionBuilder::next_state)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update_transition.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_infrastructure_update_transition.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "723a7a0cf61fb57cf9604eed8f28b80790b5aeb77b18d1bd303fc19de5538a6f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: intents\n\nDocumentation:\nAdds a key-value pair to `intents`.\n\nTo override the contents of this collection use [`set_intents`](Self::set_intents).\n\nA map of Intent objects\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn intents(\n mut self,\n k: crate::types::IntentType,\n v: ::std::collections::HashMap<::std::string::String, crate::types::IntentDataType>,\n ) -> Self {\n let mut hash_map = self.intents.unwrap_or_default();\n hash_map.insert(k, v);\n self.intents = ::std::option::Option::Some(hash_map);\n self\n }\n```"}], "func_name": "intents", "docstring": "Adds a key-value pair to `intents`.\n\nTo override the contents of this collection use [`set_intents`](Self::set_intents).\n\nA map of Intent objects", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_intents_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_intents_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd8f52732a8b5841389cb06f35e1e885a057ecb2670a482154eaaac47bb5f840"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`IntentsEvent`](crate::types::IntentsEvent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::IntentsEvent {\n crate::types::IntentsEvent { intents: self.intents }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`IntentsEvent`](crate::types::IntentsEvent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_intents_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_intents_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "121e697571319d1327e1921070abb33e059dd4167f8738b117fa1d4c59d90c2b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_string\n\nDocumentation:\nTries to convert the enum instance into [`String`](crate::types::IntentDataType::String),\nextracting the inner [`String`](::std::string::String). Returns `Err(&Self)` if it can't\nbe converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_string(&self) -> ::std::result::Result<&::std::string::String, &Self> {\n if let IntentDataType::String(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_string", "docstring": "Tries to convert the enum instance into [`String`](crate::types::IntentDataType::String),\nextracting the inner [`String`](::std::string::String). Returns `Err(&Self)` if it can't\nbe converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_intent_data_type.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_intent_data_type.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "feecdfc064903b4a720b3773452802910ab7d5114057b854aa95fad6eccb9c1d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: alert\n\nDocumentation:\nStructure representing an alert with a type and content.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn alert(mut self, input: crate::types::Alert) -> Self {\n self.alert = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "alert", "docstring": "Structure representing an alert with a type and content.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "16008da32167a808ec9119f53605d93d77fe08a9cd3236f6f559f9c699f83783"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: infrastructure_update\n\nDocumentation:\nStructure representing different types of infrastructure updates.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn infrastructure_update(mut self, input: crate::types::InfrastructureUpdate) -> Self {\n self.infrastructure_update = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "infrastructure_update", "docstring": "Structure representing different types of infrastructure updates.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "796779aab7ed16999be23db2679b7be40f8c38a5fa26cbf6453e37335ec373d2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: progress\n\nDocumentation:\nStructure representing a collection of steps in a process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn progress(mut self, input: crate::types::Progress) -> Self {\n self.progress = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "progress", "docstring": "Structure representing a collection of steps in a process.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c5d8b5622e763c9b515f1d8dfa674df9b5a1111c521642a5536da0f458711ad7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`InteractionComponent`](crate::types::InteractionComponent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::InteractionComponent {\n crate::types::InteractionComponent {\n text: self.text,\n alert: self.alert,\n infrastructure_update: self.infrastructure_update,\n progress: self.progress,\n step: self.step,\n task_details: self.task_details,\n task_reference: self.task_reference,\n suggestions: self.suggestions,\n section: self.section,\n resource: self.resource,\n resource_list: self.resource_list,\n action: self.action,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`InteractionComponent`](crate::types::InteractionComponent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5599e2f33a4c1db1a652a03b25ac3737f81a4fa2db8b1e8b67829730512a8a3a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: interaction_component_entries\n\nDocumentation:\nAppends an item to `interaction_component_entries`.\n\nTo override the contents of this collection use\n[`set_interaction_component_entries`](Self::set_interaction_component_entries).\n\nList of identifiable interaction components\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn interaction_component_entries(mut self, input: crate::types::InteractionComponentEntry) -> Self {\n let mut v = self.interaction_component_entries.unwrap_or_default();\n v.push(input);\n self.interaction_component_entries = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "interaction_component_entries", "docstring": "Appends an item to `interaction_component_entries`.\n\nTo override the contents of this collection use\n[`set_interaction_component_entries`](Self::set_interaction_component_entries).\n\nList of identifiable interaction components", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_interaction_components_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_interaction_components_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "10b3054c1386d2a2ee13d80e3af00b7bb5c355b8c92d0823e70a61e9a8082e46"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`InteractionComponentsEvent`](crate::types::InteractionComponentsEvent). This method\nwill fail if any of the following fields are not set:\n- [`interaction_component_entries`](crate::types::builders::InteractionComponentsEventBuilder::interaction_component_entries)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::InteractionComponentsEvent {\n interaction_component_entries: self.interaction_component_entries.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"interaction_component_entries\",\n \"interaction_component_entries was not specified but it is required when building InteractionComponentsEvent\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`InteractionComponentsEvent`](crate::types::InteractionComponentsEvent). This method\nwill fail if any of the following fields are not set:\n- [`interaction_component_entries`](crate::types::builders::InteractionComponentsEventBuilder::interaction_component_entries)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_interaction_components_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_interaction_components_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e29ed6f46695c9955627d801c94a9cada6b7b95cd1773de67b8fa3775cbd4c0f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: interaction_component_id\n\nDocumentation:\nIdentifier that can uniquely identify the interaction component within stream response. This\nfield is optional.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn interaction_component_id(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.interaction_component_id = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "interaction_component_id", "docstring": "Identifier that can uniquely identify the interaction component within stream response. This\nfield is optional.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component_entry.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component_entry.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8a0cc2e313395df7ea3b2aa85dd0ca580b2c2df634a692599c9dfb1c433e63b1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: interaction_component\n\nDocumentation:\nInteraction component\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn interaction_component(mut self, input: crate::types::InteractionComponent) -> Self {\n self.interaction_component = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "interaction_component", "docstring": "Interaction component\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component_entry.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component_entry.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b73eccce0002adf00d79b1b20feca524b2be9dd889ccedc13169529ab4770483"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`InteractionComponentEntry`](crate::types::InteractionComponentEntry). This method will\nfail if any of the following fields are not set:\n- [`interaction_component`](crate::types::builders::InteractionComponentEntryBuilder::interaction_component)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::InteractionComponentEntry {\n interaction_component_id: self.interaction_component_id,\n interaction_component: self.interaction_component.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"interaction_component\",\n \"interaction_component was not specified but it is required when building InteractionComponentEntry\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`InteractionComponentEntry`](crate::types::InteractionComponentEntry). This method will\nfail if any of the following fields are not set:\n- [`interaction_component`](crate::types::builders::InteractionComponentEntryBuilder::interaction_component)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component_entry.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_interaction_component_entry.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d0a26a92758064ac9307c71851947065d55e97e8fc1c63f276c40042ab538184"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reason\n\nDocumentation:\nReasons for Invalid State Event\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reason(mut self, input: crate::types::InvalidStateReason) -> Self {\n self.reason = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "reason", "docstring": "Reasons for Invalid State Event\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_invalid_state_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_invalid_state_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b32431796df91696bb40d725b471115e9c9744556cec0f4cadfcf15f7f9e0a21"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`InvalidStateEvent`](crate::types::InvalidStateEvent). This method will fail if any of\nthe following fields are not set:\n- [`reason`](crate::types::builders::InvalidStateEventBuilder::reason)\n- [`message`](crate::types::builders::InvalidStateEventBuilder::message)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::InvalidStateEvent {\n reason: self.reason.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"reason\",\n \"reason was not specified but it is required when building InvalidStateEvent\",\n )\n })?,\n message: self.message.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"message\",\n \"message was not specified but it is required when building InvalidStateEvent\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`InvalidStateEvent`](crate::types::InvalidStateEvent). This method will fail if any of\nthe following fields are not set:\n- [`reason`](crate::types::builders::InvalidStateEventBuilder::reason)\n- [`message`](crate::types::builders::InvalidStateEventBuilder::message)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_invalid_state_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_invalid_state_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ffc6ec6075109e90cfb6b549d94dc8fdfa21be63bb19b9bb8237a6425bab1a16"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`MessageMetadataEvent`](crate::types::MessageMetadataEvent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::MessageMetadataEvent {\n crate::types::MessageMetadataEvent {\n conversation_id: self.conversation_id,\n utterance_id: self.utterance_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`MessageMetadataEvent`](crate::types::MessageMetadataEvent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_message_metadata_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_message_metadata_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb51a076cdd489ef461c373c177ee4b7bae8d12c29a49db2e93dc58706748c73"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ModuleLink`](crate::types::ModuleLink).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::ModuleLink {\n crate::types::ModuleLink {\n cloud_watch_troubleshooting_link: self.cloud_watch_troubleshooting_link,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ModuleLink`](crate::types::ModuleLink).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_module_link.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_module_link.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "40df5c3367d7e3a3278e3ba1f981224f85dae6c35992bf5a17d7eabede21da18"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: content\n\nDocumentation:\nA collection of steps that make up a process. Each step is detailed using the Step\nstructure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn content(&self) -> &[crate::types::ProgressComponent] {\n use std::ops::Deref;\n self.content.deref()\n }\n```"}], "func_name": "content", "docstring": "A collection of steps that make up a process. Each step is detailed using the Step\nstructure.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_progress.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_progress.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "efde7210ba2ced447ea3dd3ec451fdfe5eae6de4b07e28c6c0dc09a13b56f54b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: content\n\nDocumentation:\nAppends an item to `content`.\n\nTo override the contents of this collection use [`set_content`](Self::set_content).\n\nA collection of steps that make up a process. Each step is detailed using the Step\nstructure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn content(mut self, input: crate::types::ProgressComponent) -> Self {\n let mut v = self.content.unwrap_or_default();\n v.push(input);\n self.content = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "content", "docstring": "Appends an item to `content`.\n\nTo override the contents of this collection use [`set_content`](Self::set_content).\n\nA collection of steps that make up a process. Each step is detailed using the Step\nstructure.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_progress.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_progress.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54af05cbee927f734ee20ae84c20cbdde2c25a31baa9ce55a2589de644c30afb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Progress`](crate::types::Progress).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::ProgressBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Progress {\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building Progress\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Progress`](crate::types::Progress).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::ProgressBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_progress.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_progress.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d3c54ca98d622ea3571d56de397f9842bcbccfccef48c800684807a4057b3ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ProgressComponent`](crate::types::ProgressComponent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::ProgressComponent {\n crate::types::ProgressComponent { step: self.step }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ProgressComponent`](crate::types::ProgressComponent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_progress_component.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_progress_component.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ff4a3fe41c5546d87e856555008b725af57fa27006846d91a401dfca3f318a42"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resource_json_string\n\nDocumentation:\nA stringified object\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn resource_json_string(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n self.resource_json_string = ::std::option::Option::Some(input.into());\n self\n }\n```"}], "func_name": "resource_json_string", "docstring": "A stringified object\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_resource.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_resource.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "106ed709b1fe042acf8319277cb0b000076033342b8afd14938bd0f3ffa598ea"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Resource`](crate::types::Resource).\nThis method will fail if any of the following fields are not set:\n- [`title`](crate::types::builders::ResourceBuilder::title)\n- [`link`](crate::types::builders::ResourceBuilder::link)\n- [`description`](crate::types::builders::ResourceBuilder::description)\n- [`r#type`](crate::types::builders::ResourceBuilder::type)\n- [`arn`](crate::types::builders::ResourceBuilder::arn)\n- [`resource_json_string`](crate::types::builders::ResourceBuilder::resource_json_string)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Resource {\n title: self.title.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"title\",\n \"title was not specified but it is required when building Resource\",\n )\n })?,\n link: self.link.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"link\",\n \"link was not specified but it is required when building Resource\",\n )\n })?,\n description: self.description.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"description\",\n \"description was not specified but it is required when building Resource\",\n )\n })?,\n r#type: self.r#type.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"r#type\",\n \"r#type was not specified but it is required when building Resource\",\n )\n })?,\n arn: self.arn.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"arn\",\n \"arn was not specified but it is required when building Resource\",\n )\n })?,\n resource_json_string: self.resource_json_string.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"resource_json_string\",\n \"resource_json_string was not specified but it is required when building Resource\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Resource`](crate::types::Resource).\nThis method will fail if any of the following fields are not set:\n- [`title`](crate::types::builders::ResourceBuilder::title)\n- [`link`](crate::types::builders::ResourceBuilder::link)\n- [`description`](crate::types::builders::ResourceBuilder::description)\n- [`r#type`](crate::types::builders::ResourceBuilder::type)\n- [`arn`](crate::types::builders::ResourceBuilder::arn)\n- [`resource_json_string`](crate::types::builders::ResourceBuilder::resource_json_string)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_resource.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_resource.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80f0e13ac01d0f14cd284f6a457f1ef0ee459a81ff8224334e27e9913b7d9be1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ResourceList`](crate::types::ResourceList).\nThis method will fail if any of the following fields are not set:\n- [`items`](crate::types::builders::ResourceListBuilder::items)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::ResourceList {\n action: self.action,\n items: self.items.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"items\",\n \"items was not specified but it is required when building ResourceList\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ResourceList`](crate::types::ResourceList).\nThis method will fail if any of the following fields are not set:\n- [`items`](crate::types::builders::ResourceListBuilder::items)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_resource_list.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_resource_list.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb116ad2cd78a1b932f74eac89ffe537ee470739d96f0ed92f2d2851e2015662"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_binary_metadata_event\n\nDocumentation:\nTries to convert the enum instance into\n[`BinaryMetadataEvent`](crate::types::ResultArchiveStream::BinaryMetadataEvent), extracting\nthe inner [`BinaryMetadataEvent`](crate::types::BinaryMetadataEvent). Returns `Err(&\nSelf)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_binary_metadata_event(&self) -> ::std::result::Result<&crate::types::BinaryMetadataEvent, &Self> {\n if let ResultArchiveStream::BinaryMetadataEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_binary_metadata_event", "docstring": "Tries to convert the enum instance into\n[`BinaryMetadataEvent`](crate::types::ResultArchiveStream::BinaryMetadataEvent), extracting\nthe inner [`BinaryMetadataEvent`](crate::types::BinaryMetadataEvent). Returns `Err(&\nSelf)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_result_archive_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_result_archive_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1996fba8b4118611b2a776f113e3fb5025f90367d5d9ddf8d83aa1a2939bc620"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_binary_payload_event\n\nDocumentation:\nTries to convert the enum instance into\n[`BinaryPayloadEvent`](crate::types::ResultArchiveStream::BinaryPayloadEvent), extracting\nthe inner [`BinaryPayloadEvent`](crate::types::BinaryPayloadEvent). Returns `Err(&Self)`\nif it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_binary_payload_event(&self) -> ::std::result::Result<&crate::types::BinaryPayloadEvent, &Self> {\n if let ResultArchiveStream::BinaryPayloadEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_binary_payload_event", "docstring": "Tries to convert the enum instance into\n[`BinaryPayloadEvent`](crate::types::ResultArchiveStream::BinaryPayloadEvent), extracting\nthe inner [`BinaryPayloadEvent`](crate::types::BinaryPayloadEvent). Returns `Err(&Self)`\nif it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_result_archive_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_result_archive_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8393c1f048dcb2de30a2638cecf054716109d4314a1d89864aa3b7a56f9ddf27"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: content\n\nDocumentation:\nContains a list of interaction components e.g Text, Alert, List, etc.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn content(&self) -> &[crate::types::SectionComponent] {\n use std::ops::Deref;\n self.content.deref()\n }\n```"}], "func_name": "content", "docstring": "Contains a list of interaction components e.g Text, Alert, List, etc.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_section.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_section.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d686d072a05c1079faf98d890d81a2cacf6ddcfe8b5b2ecde5e6c09b4b5dfad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: content\n\nDocumentation:\nAppends an item to `content`.\n\nTo override the contents of this collection use [`set_content`](Self::set_content).\n\nContains a list of interaction components e.g Text, Alert, List, etc.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn content(mut self, input: crate::types::SectionComponent) -> Self {\n let mut v = self.content.unwrap_or_default();\n v.push(input);\n self.content = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "content", "docstring": "Appends an item to `content`.\n\nTo override the contents of this collection use [`set_content`](Self::set_content).\n\nContains a list of interaction components e.g Text, Alert, List, etc.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_section.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_section.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "695c15b4916d825141b0e62ae2d3eea75bbf7a7eb47d808b0ac0ca4bca605e8c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Section`](crate::types::Section).\nThis method will fail if any of the following fields are not set:\n- [`title`](crate::types::builders::SectionBuilder::title)\n- [`content`](crate::types::builders::SectionBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Section {\n title: self.title.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"title\",\n \"title was not specified but it is required when building Section\",\n )\n })?,\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building Section\",\n )\n })?,\n action: self.action,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Section`](crate::types::Section).\nThis method will fail if any of the following fields are not set:\n- [`title`](crate::types::builders::SectionBuilder::title)\n- [`content`](crate::types::builders::SectionBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_section.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_section.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d71f0fbc139bafba27d719f3f7141e21c8db000774cf857d4a86fc49f8a07250"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`SectionComponent`](crate::types::SectionComponent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::SectionComponent {\n crate::types::SectionComponent {\n text: self.text,\n alert: self.alert,\n resource: self.resource,\n resource_list: self.resource_list,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`SectionComponent`](crate::types::SectionComponent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_section_component.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_section_component.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aeea8be8dc6716e2ac7090b5a15f54d0446a1b45eff5e1c8df0eb57f11b6d6a2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: label\n\nDocumentation:\nA label for the step, providing a concise description.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn label(&self) -> &str {\n use std::ops::Deref;\n self.label.deref()\n }\n```"}], "func_name": "label", "docstring": "A label for the step, providing a concise description.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_step.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_step.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "87f1ea1c40f50a3088f5b450bc1e734bff0c6e99f8d7459d768e9cc89c973b07"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_state\n\nDocumentation:\nEnum representing all possible step states, combining terminal and non-terminal states.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_state(mut self, input: ::std::option::Option) -> Self {\n self.state = input;\n self\n }\n```"}], "func_name": "set_state", "docstring": "Enum representing all possible step states, combining terminal and non-terminal states.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_step.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_step.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef1abe1d220b2fedb41568450f1f827ba2e8065c8a5f3ce6a55aca5ebfa67ac5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: content\n\nDocumentation:\nAppends an item to `content`.\n\nTo override the contents of this collection use [`set_content`](Self::set_content).\n\nOptional content providing additional details about the step.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn content(mut self, input: crate::types::StepComponent) -> Self {\n let mut v = self.content.unwrap_or_default();\n v.push(input);\n self.content = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "content", "docstring": "Appends an item to `content`.\n\nTo override the contents of this collection use [`set_content`](Self::set_content).\n\nOptional content providing additional details about the step.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_step.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_step.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5fff1a8cda178e6cdc244c7e2bcecc0c84800f0688716441f9ab0a39f8f20587"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_content\n\nDocumentation:\nOptional content providing additional details about the step.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_content(mut self, input: ::std::option::Option<::std::vec::Vec>) -> Self {\n self.content = input;\n self\n }\n```"}], "func_name": "set_content", "docstring": "Optional content providing additional details about the step.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_step.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_step.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "67a43b2ee84fdcab478c11cf6b2123b06f0de143ded6f233aff3f2dce7106fad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Step`](crate::types::Step).\nThis method will fail if any of the following fields are not set:\n- [`id`](crate::types::builders::StepBuilder::id)\n- [`state`](crate::types::builders::StepBuilder::state)\n- [`label`](crate::types::builders::StepBuilder::label)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Step {\n id: self.id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"id\",\n \"id was not specified but it is required when building Step\",\n )\n })?,\n state: self.state.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"state\",\n \"state was not specified but it is required when building Step\",\n )\n })?,\n label: self.label.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"label\",\n \"label was not specified but it is required when building Step\",\n )\n })?,\n content: self.content,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Step`](crate::types::Step).\nThis method will fail if any of the following fields are not set:\n- [`id`](crate::types::builders::StepBuilder::id)\n- [`state`](crate::types::builders::StepBuilder::state)\n- [`label`](crate::types::builders::StepBuilder::label)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_step.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_step.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a79289d1c6d65a55098e59d1f238df62410456426b8d5825399123f9df4a34bf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`StepComponent`](crate::types::StepComponent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::StepComponent {\n crate::types::StepComponent { text: self.text }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`StepComponent`](crate::types::StepComponent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_step_component.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_step_component.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8729c2fb352c99c394746d6ba99ebde0a144ed06a94e56312bd98ac0b697cee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Suggestion`](crate::types::Suggestion).\nThis method will fail if any of the following fields are not set:\n- [`value`](crate::types::builders::SuggestionBuilder::value)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Suggestion {\n value: self.value.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"value\",\n \"value was not specified but it is required when building Suggestion\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Suggestion`](crate::types::Suggestion).\nThis method will fail if any of the following fields are not set:\n- [`value`](crate::types::builders::SuggestionBuilder::value)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_suggestion.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_suggestion.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "76503b199f5af66330d54dbf2249ab7b10576bbfa7e71955a53524703a6565e1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: items\n\nDocumentation:\nAppends an item to `items`.\n\nTo override the contents of this collection use [`set_items`](Self::set_items).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn items(mut self, input: crate::types::Suggestion) -> Self {\n let mut v = self.items.unwrap_or_default();\n v.push(input);\n self.items = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "items", "docstring": "Appends an item to `items`.\n\nTo override the contents of this collection use [`set_items`](Self::set_items).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_suggestions.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_suggestions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e91f61e174a1f12cb61d80c829f251672d9c09cf400418b3fd6bdae7d9d3c010"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Suggestions`](crate::types::Suggestions).\nThis method will fail if any of the following fields are not set:\n- [`items`](crate::types::builders::SuggestionsBuilder::items)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Suggestions {\n items: self.items.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"items\",\n \"items was not specified but it is required when building Suggestions\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Suggestions`](crate::types::Suggestions).\nThis method will fail if any of the following fields are not set:\n- [`items`](crate::types::builders::SuggestionsBuilder::items)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_suggestions.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_suggestions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "903274d2c5373c62c859c53f4b9d2185196bacf6af851c3557a1fdc1ce1da33f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_supplementary_web_links\n\nDocumentation:\nWeb References for Assistant Response Message\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_supplementary_web_links(\n mut self,\n input: ::std::option::Option<::std::vec::Vec>,\n ) -> Self {\n self.supplementary_web_links = input;\n self\n }\n```"}], "func_name": "set_supplementary_web_links", "docstring": "Web References for Assistant Response Message", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_supplementary_web_links_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_supplementary_web_links_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f0097df9b5817f561b5082448de7af3934c181236b048aa1288ffba50c43fea"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`SupplementaryWebLinksEvent`](crate::types::SupplementaryWebLinksEvent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::SupplementaryWebLinksEvent {\n crate::types::SupplementaryWebLinksEvent {\n supplementary_web_links: self.supplementary_web_links,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`SupplementaryWebLinksEvent`](crate::types::SupplementaryWebLinksEvent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_supplementary_web_links_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_supplementary_web_links_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f287a52f2463bb9731cf4d2d6cce2c1c247a3e635bf4e8f23d2f90296a8ae04a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: note\n\nDocumentation:\nStructure representing a note associated with a task action.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn note(mut self, input: crate::types::TaskActionNote) -> Self {\n self.note = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "note", "docstring": "Structure representing a note associated with a task action.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_action.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_action.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "15e6470d7fb17ff75794b61438e3916f7fc1359bd6733d1ef72682a65e04380b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: payload\n\nDocumentation:\nAdds a key-value pair to `payload`.\n\nTo override the contents of this collection use [`set_payload`](Self::set_payload).\n\nMap representing key-value pairs for the payload of a task action.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn payload(\n mut self,\n k: impl ::std::convert::Into<::std::string::String>,\n v: impl ::std::convert::Into<::std::string::String>,\n ) -> Self {\n let mut hash_map = self.payload.unwrap_or_default();\n hash_map.insert(k.into(), v.into());\n self.payload = ::std::option::Option::Some(hash_map);\n self\n }\n```"}], "func_name": "payload", "docstring": "Adds a key-value pair to `payload`.\n\nTo override the contents of this collection use [`set_payload`](Self::set_payload).\n\nMap representing key-value pairs for the payload of a task action.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_action.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_action.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ae25760b7c584bb8b806cf072d2ca90da4ee33283dd3a07f1a0e45f5eb8032e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_payload\n\nDocumentation:\nMap representing key-value pairs for the payload of a task action.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_payload(\n mut self,\n input: ::std::option::Option<::std::collections::HashMap<::std::string::String, ::std::string::String>>,\n ) -> Self {\n self.payload = input;\n self\n }\n```"}], "func_name": "set_payload", "docstring": "Map representing key-value pairs for the payload of a task action.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_action.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_action.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "200ecc4777dcb59398692a525b46ab5de14b723ac38d7d316951c1331db6bfe2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: confirmation\n\nDocumentation:\nStructure representing a confirmation message related to a task action.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn confirmation(mut self, input: crate::types::TaskActionConfirmation) -> Self {\n self.confirmation = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "confirmation", "docstring": "Structure representing a confirmation message related to a task action.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_action.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_action.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44e1081025417bd78c1ee28591d6dad9ece1ae309eb15ec432322ffe6a57d6cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`TaskAction`](crate::types::TaskAction).\nThis method will fail if any of the following fields are not set:\n- [`label`](crate::types::builders::TaskActionBuilder::label)\n- [`payload`](crate::types::builders::TaskActionBuilder::payload)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::TaskAction {\n label: self.label.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"label\",\n \"label was not specified but it is required when building TaskAction\",\n )\n })?,\n note: self.note,\n primary: self.primary,\n disabled: self.disabled,\n payload: self.payload.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"payload\",\n \"payload was not specified but it is required when building TaskAction\",\n )\n })?,\n confirmation: self.confirmation,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`TaskAction`](crate::types::TaskAction).\nThis method will fail if any of the following fields are not set:\n- [`label`](crate::types::builders::TaskActionBuilder::label)\n- [`payload`](crate::types::builders::TaskActionBuilder::payload)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_action.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_action.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be78ec0fd096f0a56e71f03731bdc483181c9a91cae9be3c1d41ad67d886041e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TaskActionConfirmation`](crate::types::TaskActionConfirmation).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::TaskActionConfirmation {\n crate::types::TaskActionConfirmation { content: self.content }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TaskActionConfirmation`](crate::types::TaskActionConfirmation).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_action_confirmation.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_action_confirmation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "deac8ebb81a1b93ef5480d40280bb888d64f1636cabbc385811d4a011dcf3359"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: r#type\n\nDocumentation:\nEnum defining the types of notes that can be associated with a task action.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn r#type(mut self, input: crate::types::TaskActionNoteType) -> Self {\n self.r#type = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "r#type", "docstring": "Enum defining the types of notes that can be associated with a task action.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_action_note.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_action_note.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2e078a1f799ffeb0d989338a61626dcc6705d466768ddcbfcec7b410edff2090"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`TaskActionNote`](crate::types::TaskActionNote).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::TaskActionNoteBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::TaskActionNote {\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building TaskActionNote\",\n )\n })?,\n r#type: self.r#type,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`TaskActionNote`](crate::types::TaskActionNote).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::TaskActionNoteBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_action_note.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_action_note.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "297ebcb1588549abccefe2c2baf84a28a033c16f5bee10156e909c69adfaae81"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`TaskComponent`](crate::types::TaskComponent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::TaskComponent {\n crate::types::TaskComponent {\n text: self.text,\n infrastructure_update: self.infrastructure_update,\n alert: self.alert,\n progress: self.progress,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`TaskComponent`](crate::types::TaskComponent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_component.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_component.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dc1e8a18016424269a78ac153711d272f17d69e01a1137bb9984cb3cd3621d57"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: content\n\nDocumentation:\nLists the components that can be used to form the task's content.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn content(&self) -> &[crate::types::TaskComponent] {\n use std::ops::Deref;\n self.content.deref()\n }\n```"}], "func_name": "content", "docstring": "Lists the components that can be used to form the task's content.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7a137301d7fdb4bc6752d8b4187e36fc151ff9fc960edad7bef8e25017cb1637"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: overview\n\nDocumentation:\nStructure representing an overview of a task, including a label and description.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn overview(mut self, input: crate::types::TaskOverview) -> Self {\n self.overview = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "overview", "docstring": "Structure representing an overview of a task, including a label and description.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "155d543e8e33469e441b9b017360267344ce1dc576adf85c3bb0bf9df10b6ec1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_overview\n\nDocumentation:\nStructure representing an overview of a task, including a label and description.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_overview(mut self, input: ::std::option::Option) -> Self {\n self.overview = input;\n self\n }\n```"}], "func_name": "set_overview", "docstring": "Structure representing an overview of a task, including a label and description.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb17f980f1dff50f18f1c0ab2dcc22b81d2e9c23b98228abe60fd21953760e78"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: content\n\nDocumentation:\nAppends an item to `content`.\n\nTo override the contents of this collection use [`set_content`](Self::set_content).\n\nLists the components that can be used to form the task's content.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn content(mut self, input: crate::types::TaskComponent) -> Self {\n let mut v = self.content.unwrap_or_default();\n v.push(input);\n self.content = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "content", "docstring": "Appends an item to `content`.\n\nTo override the contents of this collection use [`set_content`](Self::set_content).\n\nLists the components that can be used to form the task's content.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5466368f304f9db10f8eb5e509292bcaf8583c6e5ff2646349aa32b1ac996e9d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: actions\n\nDocumentation:\nAppends an item to `actions`.\n\nTo override the contents of this collection use [`set_actions`](Self::set_actions).\n\nOptional list of actions associated with the task.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn actions(mut self, input: crate::types::TaskAction) -> Self {\n let mut v = self.actions.unwrap_or_default();\n v.push(input);\n self.actions = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "actions", "docstring": "Appends an item to `actions`.\n\nTo override the contents of this collection use [`set_actions`](Self::set_actions).\n\nOptional list of actions associated with the task.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c78103b4d7c6d4dc6285ed0c4d9320d3f32c0acd6c3bcdb5be207d2c924e3efa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_actions\n\nDocumentation:\nOptional list of actions associated with the task.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_actions(mut self, input: ::std::option::Option<::std::vec::Vec>) -> Self {\n self.actions = input;\n self\n }\n```"}], "func_name": "set_actions", "docstring": "Optional list of actions associated with the task.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4b5d1d842db63ef94bc83bdacb09dd11b3b84dbadbcc487072b7b6367279778d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`TaskDetails`](crate::types::TaskDetails).\nThis method will fail if any of the following fields are not set:\n- [`overview`](crate::types::builders::TaskDetailsBuilder::overview)\n- [`content`](crate::types::builders::TaskDetailsBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::TaskDetails {\n overview: self.overview.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"overview\",\n \"overview was not specified but it is required when building TaskDetails\",\n )\n })?,\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building TaskDetails\",\n )\n })?,\n actions: self.actions,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`TaskDetails`](crate::types::TaskDetails).\nThis method will fail if any of the following fields are not set:\n- [`overview`](crate::types::builders::TaskDetailsBuilder::overview)\n- [`content`](crate::types::builders::TaskDetailsBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_details.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "41e2e3b29045707ed45b84245627f524742910e87824689c5d43982c843d7346"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`TaskOverview`](crate::types::TaskOverview).\nThis method will fail if any of the following fields are not set:\n- [`label`](crate::types::builders::TaskOverviewBuilder::label)\n- [`description`](crate::types::builders::TaskOverviewBuilder::description)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::TaskOverview {\n label: self.label.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"label\",\n \"label was not specified but it is required when building TaskOverview\",\n )\n })?,\n description: self.description.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"description\",\n \"description was not specified but it is required when building TaskOverview\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`TaskOverview`](crate::types::TaskOverview).\nThis method will fail if any of the following fields are not set:\n- [`label`](crate::types::builders::TaskOverviewBuilder::label)\n- [`description`](crate::types::builders::TaskOverviewBuilder::description)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_overview.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_overview.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "df8071f5eff9c3db9f6b8227da71a5436a1c106894f94a8998dd5b9cca2cfa0a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`TaskReference`](crate::types::TaskReference).\nThis method will fail if any of the following fields are not set:\n- [`task_id`](crate::types::builders::TaskReferenceBuilder::task_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::TaskReference {\n task_id: self.task_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"task_id\",\n \"task_id was not specified but it is required when building TaskReference\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`TaskReference`](crate::types::TaskReference).\nThis method will fail if any of the following fields are not set:\n- [`task_id`](crate::types::builders::TaskReferenceBuilder::task_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_task_reference.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_task_reference.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5a87cb8b03b400e4a5ead3e057e7c738ce0db1fb60a359865d542063bf6c4fbd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Text`](crate::types::Text).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::TextBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Text {\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building Text\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Text`](crate::types::Text).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::TextBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_text.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_text.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5aee83b50497b3c263a1da44211cf94b8af1b4048e4e5cff129d91165e22badf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tool_result\n\nDocumentation:\nA tool result that contains the results for a tool request that was previously made.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn tool_result(mut self, input: crate::types::ToolResult) -> Self {\n self.tool_result = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "tool_result", "docstring": "A tool result that contains the results for a tool request that was previously made.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_tool_result_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_tool_result_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f521e8762486e3ad3325974dd6104c9404e751d2c1427695755d295b0bf823d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ToolResultEvent`](crate::types::ToolResultEvent).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::ToolResultEvent {\n crate::types::ToolResultEvent {\n tool_result: self.tool_result,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ToolResultEvent`](crate::types::ToolResultEvent).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_tool_result_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_tool_result_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5eb864b6754f4a6daf6f2c4319cc830bb1b13ab3445c706d126b3e60222c16ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stop\n\nDocumentation:\nThis field is true when all of the serialized input for this ToolUse request has been sent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stop(mut self, input: bool) -> Self {\n self.stop = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "stop", "docstring": "This field is true when all of the serialized input for this ToolUse request has been sent.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_tool_use_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_tool_use_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d17517bac308d9be3ea1cc5b27f83a0973d3f5c63fcda766ef100388bca8f657"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ToolUseEvent`](crate::types::ToolUseEvent).\nThis method will fail if any of the following fields are not set:\n- [`tool_use_id`](crate::types::builders::ToolUseEventBuilder::tool_use_id)\n- [`name`](crate::types::builders::ToolUseEventBuilder::name)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::ToolUseEvent {\n tool_use_id: self.tool_use_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"tool_use_id\",\n \"tool_use_id was not specified but it is required when building ToolUseEvent\",\n )\n })?,\n name: self.name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"name\",\n \"name was not specified but it is required when building ToolUseEvent\",\n )\n })?,\n input: self.input,\n stop: self.stop,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ToolUseEvent`](crate::types::ToolUseEvent).\nThis method will fail if any of the following fields are not set:\n- [`tool_use_id`](crate::types::builders::ToolUseEventBuilder::tool_use_id)\n- [`name`](crate::types::builders::ToolUseEventBuilder::name)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_tool_use_event.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_tool_use_event.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "96569ec3a1903cc8b71396e4deee177d01edcd60619f15c633159517923b05c1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TransformationExportContext`](crate::types::TransformationExportContext). This method\nwill fail if any of the following fields are not set:\n- [`download_artifact_id`](crate::types::builders::TransformationExportContextBuilder::download_artifact_id)\n- [`download_artifact_type`](crate::types::builders::TransformationExportContextBuilder::download_artifact_type)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::TransformationExportContext,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::TransformationExportContext {\n download_artifact_id: self.download_artifact_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"download_artifact_id\",\n \"download_artifact_id was not specified but it is required when building TransformationExportContext\",\n )\n })?,\n download_artifact_type: self.download_artifact_type.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"download_artifact_type\",\n \"download_artifact_type was not specified but it is required when building TransformationExportContext\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TransformationExportContext`](crate::types::TransformationExportContext). This method\nwill fail if any of the following fields are not set:\n- [`download_artifact_id`](crate::types::builders::TransformationExportContextBuilder::download_artifact_id)\n- [`download_artifact_type`](crate::types::builders::TransformationExportContextBuilder::download_artifact_type)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_transformation_export_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_transformation_export_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef50a17371ec7be6b64103ffe1a2dc31849e39b9bf8338368c49dab32f7f2017"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`UnitTestGenerationExportContext`](crate::types::UnitTestGenerationExportContext). This\nmethod will fail if any of the following fields are not set:\n- [`test_generation_job_group_name`](crate::types::builders::UnitTestGenerationExportContextBuilder::test_generation_job_group_name)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::UnitTestGenerationExportContext,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::UnitTestGenerationExportContext {\n test_generation_job_group_name: self.test_generation_job_group_name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"test_generation_job_group_name\",\n \"test_generation_job_group_name was not specified but it is required when building UnitTestGenerationExportContext\",\n )\n })?,\n test_generation_job_id: self.test_generation_job_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`UnitTestGenerationExportContext`](crate::types::UnitTestGenerationExportContext). This\nmethod will fail if any of the following fields are not set:\n- [`test_generation_job_group_name`](crate::types::builders::UnitTestGenerationExportContextBuilder::test_generation_job_group_name)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_unit_test_generation_export_context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_unit_test_generation_export_context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54f930ed0c364917888741f6f0ac75db6e83affe72ceb10225c914263790073b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`WebLink`](crate::types::WebLink).\nThis method will fail if any of the following fields are not set:\n- [`label`](crate::types::builders::WebLinkBuilder::label)\n- [`url`](crate::types::builders::WebLinkBuilder::url)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::WebLink {\n label: self.label.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"label\",\n \"label was not specified but it is required when building WebLink\",\n )\n })?,\n url: self.url.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"url\",\n \"url was not specified but it is required when building WebLink\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`WebLink`](crate::types::WebLink).\nThis method will fail if any of the following fields are not set:\n- [`label`](crate::types::builders::WebLinkBuilder::label)\n- [`url`](crate::types::builders::WebLinkBuilder::url)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/_web_link.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/_web_link.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f44f022afc3d3de166cb38f59097009a8d821d8cd1eec498dcb216f57423b51"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DryRunOperationError`](crate::types::error::DryRunOperationError).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::error::DryRunOperationError {\n crate::types::error::DryRunOperationError {\n message: self.message,\n response_code: self.response_code,\n meta: self.meta.unwrap_or_default(),\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DryRunOperationError`](crate::types::error::DryRunOperationError).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-codewhisperer-streaming-client/src/types/error/_dry_run_operation_exception.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-codewhisperer-streaming-client/src/types/error/_dry_run_operation_exception.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ea29f6d37dbfdf6a588af2dd1206c4fb077be164e01a0ad0b661041d9c737a9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: credentials_provider\n\nDocumentation:\nSets the credentials provider for this service\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn credentials_provider(\n mut self,\n credentials_provider: impl crate::config::ProvideCredentials + 'static,\n ) -> Self {\n self.set_credentials_provider(::std::option::Option::Some(\n crate::config::SharedCredentialsProvider::new(credentials_provider),\n ));\n self\n }\n```"}], "func_name": "credentials_provider", "docstring": "Sets the credentials provider for this service", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "19c90309445516661a7145f7443d899c8417b31fe2720065e83222af8a57a9ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: allow_vended_log_delivery_for_resource\n\nDocumentation:\nConstructs a fluent builder for the\n[`AllowVendedLogDeliveryForResource`](crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`resource_arn_being_authorized(impl Into)`](crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceFluentBuilder::resource_arn_being_authorized) / [`set_resource_arn_being_authorized(Option)`](crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceFluentBuilder::set_resource_arn_being_authorized):
required: **true**
(undocumented)
\n- [`delivery_source_arn(impl Into)`](crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceFluentBuilder::delivery_source_arn) / [`set_delivery_source_arn(Option)`](crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceFluentBuilder::set_delivery_source_arn):
required: **true**
(undocumented)
\n- On success, responds with [`AllowVendedLogDeliveryForResourceOutput`](crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceOutput) with field(s):\n- [`message(Option)`](crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceOutput::message): (undocumented)\n- On failure, responds with [`SdkError`](crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn allow_vended_log_delivery_for_resource(\n &self,\n ) -> crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceFluentBuilder{\n crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "allow_vended_log_delivery_for_resource", "docstring": "Constructs a fluent builder for the\n[`AllowVendedLogDeliveryForResource`](crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`resource_arn_being_authorized(impl Into)`](crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceFluentBuilder::resource_arn_being_authorized) / [`set_resource_arn_being_authorized(Option)`](crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceFluentBuilder::set_resource_arn_being_authorized):
required: **true**
(undocumented)
\n- [`delivery_source_arn(impl Into)`](crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceFluentBuilder::delivery_source_arn) / [`set_delivery_source_arn(Option)`](crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceFluentBuilder::set_delivery_source_arn):
required: **true**
(undocumented)
\n- On success, responds with [`AllowVendedLogDeliveryForResourceOutput`](crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceOutput) with field(s):\n- [`message(Option)`](crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceOutput::message): (undocumented)\n- On failure, responds with [`SdkError`](crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/allow_vended_log_delivery_for_resource.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/allow_vended_log_delivery_for_resource.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e4d6caf0363949d60d7269cafa4b79638248c70b1185a013d7bb34dbccb6ecdd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: associate_customization_permission\n\nDocumentation:\nConstructs a fluent builder for the\n[`AssociateCustomizationPermission`](crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- [`permission(CustomizationPermission)`](crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionFluentBuilder::permission) / [`set_permission(Option)`](crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionFluentBuilder::set_permission):
required: **true**
(undocumented)
\n- On success, responds with [`AssociateCustomizationPermissionOutput`](crate::operation::associate_customization_permission::AssociateCustomizationPermissionOutput)\n- On failure, responds with [`SdkError`](crate::operation::associate_customization_permission::AssociateCustomizationPermissionError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn associate_customization_permission(\n &self,\n ) -> crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionFluentBuilder\n {\n crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "associate_customization_permission", "docstring": "Constructs a fluent builder for the\n[`AssociateCustomizationPermission`](crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- [`permission(CustomizationPermission)`](crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionFluentBuilder::permission) / [`set_permission(Option)`](crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionFluentBuilder::set_permission):
required: **true**
(undocumented)
\n- On success, responds with [`AssociateCustomizationPermissionOutput`](crate::operation::associate_customization_permission::AssociateCustomizationPermissionOutput)\n- On failure, responds with [`SdkError`](crate::operation::associate_customization_permission::AssociateCustomizationPermissionError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/associate_customization_permission.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/associate_customization_permission.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e1b9f8b8c9042043144f362234027a39dd486215eeb110bc3b6be2f03c37e3c1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_customization\n\nDocumentation:\nConstructs a fluent builder for the\n[`CreateCustomization`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`data_reference(DataReference)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::data_reference) / [`set_data_reference(Option)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_data_reference):
required: **true**
(undocumented)
\n- [`customization_name(impl Into)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::customization_name) / [`set_customization_name(Option)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_customization_name):
required: **true**
(undocumented)
\n- [`description(impl Into)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::description) / [`set_description(Option)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_description):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_profile_arn):
required: **true**
(undocumented)
\n- [`tags(Tag)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::tags) / [`set_tags(Option>)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_tags):
required: **false**
(undocumented)
\n- [`client_token(impl Into)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- [`include_repos(impl Into)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::include_repos) / [`set_include_repos(Option>)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_include_repos):
required: **false**
(undocumented)
\n- On success, responds with\n[`CreateCustomizationOutput`](crate::operation::create_customization::CreateCustomizationOutput)\nwith field(s):\n- [`customization_arn(String)`](crate::operation::create_customization::CreateCustomizationOutput::customization_arn): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::create_customization::CreateCustomizationError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn create_customization(\n &self,\n ) -> crate::operation::create_customization::builders::CreateCustomizationFluentBuilder {\n crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "create_customization", "docstring": "Constructs a fluent builder for the\n[`CreateCustomization`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`data_reference(DataReference)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::data_reference) / [`set_data_reference(Option)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_data_reference):
required: **true**
(undocumented)
\n- [`customization_name(impl Into)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::customization_name) / [`set_customization_name(Option)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_customization_name):
required: **true**
(undocumented)
\n- [`description(impl Into)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::description) / [`set_description(Option)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_description):
required: **false**
(undocumented)
\n- [`profile_arn(impl Into)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::profile_arn) / [`set_profile_arn(Option)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_profile_arn):
required: **true**
(undocumented)
\n- [`tags(Tag)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::tags) / [`set_tags(Option>)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_tags):
required: **false**
(undocumented)
\n- [`client_token(impl Into)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- [`include_repos(impl Into)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::include_repos) / [`set_include_repos(Option>)`](crate::operation::create_customization::builders::CreateCustomizationFluentBuilder::set_include_repos):
required: **false**
(undocumented)
\n- On success, responds with\n[`CreateCustomizationOutput`](crate::operation::create_customization::CreateCustomizationOutput)\nwith field(s):\n- [`customization_arn(String)`](crate::operation::create_customization::CreateCustomizationOutput::customization_arn): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::create_customization::CreateCustomizationError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/create_customization.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/create_customization.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "088a8c99e113fcb7bf5b5134dbbb2c6ab1475428c7b06cf75a733c03537e6361"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_customization\n\nDocumentation:\nConstructs a fluent builder for the\n[`DeleteCustomization`](crate::operation::delete_customization::builders::DeleteCustomizationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::delete_customization::builders::DeleteCustomizationFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::delete_customization::builders::DeleteCustomizationFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- [`client_token(impl Into)`](crate::operation::delete_customization::builders::DeleteCustomizationFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::delete_customization::builders::DeleteCustomizationFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`DeleteCustomizationOutput`](crate::operation::delete_customization::DeleteCustomizationOutput)\n- On failure, responds with\n[`SdkError`](crate::operation::delete_customization::DeleteCustomizationError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn delete_customization(\n &self,\n ) -> crate::operation::delete_customization::builders::DeleteCustomizationFluentBuilder {\n crate::operation::delete_customization::builders::DeleteCustomizationFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "delete_customization", "docstring": "Constructs a fluent builder for the\n[`DeleteCustomization`](crate::operation::delete_customization::builders::DeleteCustomizationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::delete_customization::builders::DeleteCustomizationFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::delete_customization::builders::DeleteCustomizationFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- [`client_token(impl Into)`](crate::operation::delete_customization::builders::DeleteCustomizationFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::delete_customization::builders::DeleteCustomizationFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`DeleteCustomizationOutput`](crate::operation::delete_customization::DeleteCustomizationOutput)\n- On failure, responds with\n[`SdkError`](crate::operation::delete_customization::DeleteCustomizationError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/delete_customization.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/delete_customization.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "702722c83c0be875a2d1c645c5d689ec336a63847946682a92600f14092a8869"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_customization_permissions\n\nDocumentation:\nConstructs a fluent builder for the\n[`DeleteCustomizationPermissions`](crate::operation::delete_customization_permissions::builders::DeleteCustomizationPermissionsFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::delete_customization_permissions::builders::DeleteCustomizationPermissionsFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::delete_customization_permissions::builders::DeleteCustomizationPermissionsFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- On success, responds with [`DeleteCustomizationPermissionsOutput`](crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsOutput)\n- On failure, responds with [`SdkError`](crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn delete_customization_permissions(\n &self,\n ) -> crate::operation::delete_customization_permissions::builders::DeleteCustomizationPermissionsFluentBuilder {\n crate::operation::delete_customization_permissions::builders::DeleteCustomizationPermissionsFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "delete_customization_permissions", "docstring": "Constructs a fluent builder for the\n[`DeleteCustomizationPermissions`](crate::operation::delete_customization_permissions::builders::DeleteCustomizationPermissionsFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::delete_customization_permissions::builders::DeleteCustomizationPermissionsFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::delete_customization_permissions::builders::DeleteCustomizationPermissionsFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- On success, responds with [`DeleteCustomizationPermissionsOutput`](crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsOutput)\n- On failure, responds with [`SdkError`](crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/delete_customization_permissions.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/delete_customization_permissions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf9f9fbb04a0df3779878b96aa2b27bf33c10b91201340a7a0f5dd9ff2c1be42"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: disassociate_customization_permission\n\nDocumentation:\nConstructs a fluent builder for the\n[`DisassociateCustomizationPermission`](crate::operation::disassociate_customization_permission::builders::DisassociateCustomizationPermissionFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::disassociate_customization_permission::builders::DisassociateCustomizationPermissionFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::disassociate_customization_permission::builders::DisassociateCustomizationPermissionFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- [`permission(CustomizationPermission)`](crate::operation::disassociate_customization_permission::builders::DisassociateCustomizationPermissionFluentBuilder::permission) / [`set_permission(Option)`](crate::operation::disassociate_customization_permission::builders::DisassociateCustomizationPermissionFluentBuilder::set_permission):
required: **true**
(undocumented)
\n- On success, responds with [`DisassociateCustomizationPermissionOutput`](crate::operation::disassociate_customization_permission::DisassociateCustomizationPermissionOutput)\n- On failure, responds with [`SdkError`](crate::operation::disassociate_customization_permission::DisassociateCustomizationPermissionError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn disassociate_customization_permission(\n &self,\n ) -> crate::operation::disassociate_customization_permission::builders::DisassociateCustomizationPermissionFluentBuilder{\n crate::operation::disassociate_customization_permission::builders::DisassociateCustomizationPermissionFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "disassociate_customization_permission", "docstring": "Constructs a fluent builder for the\n[`DisassociateCustomizationPermission`](crate::operation::disassociate_customization_permission::builders::DisassociateCustomizationPermissionFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::disassociate_customization_permission::builders::DisassociateCustomizationPermissionFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::disassociate_customization_permission::builders::DisassociateCustomizationPermissionFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- [`permission(CustomizationPermission)`](crate::operation::disassociate_customization_permission::builders::DisassociateCustomizationPermissionFluentBuilder::permission) / [`set_permission(Option)`](crate::operation::disassociate_customization_permission::builders::DisassociateCustomizationPermissionFluentBuilder::set_permission):
required: **true**
(undocumented)
\n- On success, responds with [`DisassociateCustomizationPermissionOutput`](crate::operation::disassociate_customization_permission::DisassociateCustomizationPermissionOutput)\n- On failure, responds with [`SdkError`](crate::operation::disassociate_customization_permission::DisassociateCustomizationPermissionError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/disassociate_customization_permission.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/disassociate_customization_permission.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c4086545864c22518d64b7f9b4ada2514b98f8594a64244d62112bcf833fca6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_recommendations\n\nDocumentation:\nConstructs a fluent builder for the\n[`GenerateRecommendations`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`file_context(FileContext)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::file_context) / [`set_file_context(Option)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::set_file_context):
required: **true**
(undocumented)
\n- [`max_results(i32)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- [`reference_tracker_configuration(ReferenceTrackerConfiguration)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::reference_tracker_configuration) / [`set_reference_tracker_configuration(Option)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::set_reference_tracker_configuration):
required: **false**
(undocumented)
\n- [`supplemental_contexts(SupplementalContext)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::supplemental_contexts) / [`set_supplemental_contexts(Option>)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::set_supplemental_contexts):
required: **false**
(undocumented)
\n- On success, responds with\n[`GenerateRecommendationsOutput`](crate::operation::generate_recommendations::GenerateRecommendationsOutput)\nwith field(s):\n- [`recommendations(Option>)`](crate::operation::generate_recommendations::GenerateRecommendationsOutput::recommendations): (undocumented)\n- [`next_token(Option)`](crate::operation::generate_recommendations::GenerateRecommendationsOutput::next_token): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::generate_recommendations::GenerateRecommendationsError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate_recommendations(\n &self,\n ) -> crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder {\n crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "generate_recommendations", "docstring": "Constructs a fluent builder for the\n[`GenerateRecommendations`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`file_context(FileContext)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::file_context) / [`set_file_context(Option)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::set_file_context):
required: **true**
(undocumented)
\n- [`max_results(i32)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- [`reference_tracker_configuration(ReferenceTrackerConfiguration)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::reference_tracker_configuration) / [`set_reference_tracker_configuration(Option)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::set_reference_tracker_configuration):
required: **false**
(undocumented)
\n- [`supplemental_contexts(SupplementalContext)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::supplemental_contexts) / [`set_supplemental_contexts(Option>)`](crate::operation::generate_recommendations::builders::GenerateRecommendationsFluentBuilder::set_supplemental_contexts):
required: **false**
(undocumented)
\n- On success, responds with\n[`GenerateRecommendationsOutput`](crate::operation::generate_recommendations::GenerateRecommendationsOutput)\nwith field(s):\n- [`recommendations(Option>)`](crate::operation::generate_recommendations::GenerateRecommendationsOutput::recommendations): (undocumented)\n- [`next_token(Option)`](crate::operation::generate_recommendations::GenerateRecommendationsOutput::next_token): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::generate_recommendations::GenerateRecommendationsError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/generate_recommendations.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/generate_recommendations.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "32a7d5a233d4e0b011f67cbaf893797af1183e46157461a21aeb4b77dc9d63b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_customizations\n\nDocumentation:\nConstructs a fluent builder for the\n[`ListCustomizations`](crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`max_results(i32)`](crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListCustomizationsOutput`](crate::operation::list_customizations::ListCustomizationsOutput)\nwith field(s):\n- [`customizations(Vec::)`](crate::operation::list_customizations::ListCustomizationsOutput::customizations): (undocumented)\n- [`next_token(Option)`](crate::operation::list_customizations::ListCustomizationsOutput::next_token): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::list_customizations::ListCustomizationsError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_customizations(\n &self,\n ) -> crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder {\n crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "list_customizations", "docstring": "Constructs a fluent builder for the\n[`ListCustomizations`](crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`max_results(i32)`](crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_customizations::builders::ListCustomizationsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListCustomizationsOutput`](crate::operation::list_customizations::ListCustomizationsOutput)\nwith field(s):\n- [`customizations(Vec::)`](crate::operation::list_customizations::ListCustomizationsOutput::customizations): (undocumented)\n- [`next_token(Option)`](crate::operation::list_customizations::ListCustomizationsOutput::next_token): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::list_customizations::ListCustomizationsError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/list_customizations.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/list_customizations.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d866428505bcbc39166a581ec29fc2ae7dcef5677952665b00dfd8c2d6507761"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_customization_permissions\n\nDocumentation:\nConstructs a fluent builder for the\n[`ListCustomizationPermissions`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- [`max_results(i32)`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- On success, responds with [`ListCustomizationPermissionsOutput`](crate::operation::list_customization_permissions::ListCustomizationPermissionsOutput) with field(s):\n- [`permissions(Vec::)`](crate::operation::list_customization_permissions::ListCustomizationPermissionsOutput::permissions): (undocumented)\n- [`next_token(Option)`](crate::operation::list_customization_permissions::ListCustomizationPermissionsOutput::next_token): (undocumented)\n- On failure, responds with [`SdkError`](crate::operation::list_customization_permissions::ListCustomizationPermissionsError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_customization_permissions(\n &self,\n ) -> crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder {\n crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "list_customization_permissions", "docstring": "Constructs a fluent builder for the\n[`ListCustomizationPermissions`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- [`max_results(i32)`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- On success, responds with [`ListCustomizationPermissionsOutput`](crate::operation::list_customization_permissions::ListCustomizationPermissionsOutput) with field(s):\n- [`permissions(Vec::)`](crate::operation::list_customization_permissions::ListCustomizationPermissionsOutput::permissions): (undocumented)\n- [`next_token(Option)`](crate::operation::list_customization_permissions::ListCustomizationPermissionsOutput::next_token): (undocumented)\n- On failure, responds with [`SdkError`](crate::operation::list_customization_permissions::ListCustomizationPermissionsError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/list_customization_permissions.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/list_customization_permissions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef681898321dceb36a5ba9a2d75098f39a7fb6cefb83fa9fddc25d2076758c9b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_customization_versions\n\nDocumentation:\nConstructs a fluent builder for the\n[`ListCustomizationVersions`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- [`max_results(i32)`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListCustomizationVersionsOutput`](crate::operation::list_customization_versions::ListCustomizationVersionsOutput)\nwith field(s):\n- [`versions(Vec::)`](crate::operation::list_customization_versions::ListCustomizationVersionsOutput::versions): (undocumented)\n- [`next_token(Option)`](crate::operation::list_customization_versions::ListCustomizationVersionsOutput::next_token): (undocumented)\n- On failure, responds with [`SdkError`](crate::operation::list_customization_versions::ListCustomizationVersionsError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_customization_versions(\n &self,\n ) -> crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder {\n crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "list_customization_versions", "docstring": "Constructs a fluent builder for the\n[`ListCustomizationVersions`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder)\noperation. This operation supports pagination; See\n[`into_paginator()`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::into_paginator).\n\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- [`max_results(i32)`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::max_results) / [`set_max_results(Option)`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::set_max_results):
required: **false**
(undocumented)
\n- [`next_token(impl Into)`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::next_token) / [`set_next_token(Option)`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsFluentBuilder::set_next_token):
required: **false**
(undocumented)
\n- On success, responds with\n[`ListCustomizationVersionsOutput`](crate::operation::list_customization_versions::ListCustomizationVersionsOutput)\nwith field(s):\n- [`versions(Vec::)`](crate::operation::list_customization_versions::ListCustomizationVersionsOutput::versions): (undocumented)\n- [`next_token(Option)`](crate::operation::list_customization_versions::ListCustomizationVersionsOutput::next_token): (undocumented)\n- On failure, responds with [`SdkError`](crate::operation::list_customization_versions::ListCustomizationVersionsError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/list_customization_versions.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/list_customization_versions.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8b2f285fb9f2327f8a7cb42b9287e24cdc7ab814f27db1c36f2d70368fd363bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_tags_for_resource\n\nDocumentation:\nConstructs a fluent builder for the\n[`ListTagsForResource`](crate::operation::list_tags_for_resource::builders::ListTagsForResourceFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`resource_arn(impl Into)`](crate::operation::list_tags_for_resource::builders::ListTagsForResourceFluentBuilder::resource_arn) / [`set_resource_arn(Option)`](crate::operation::list_tags_for_resource::builders::ListTagsForResourceFluentBuilder::set_resource_arn):
required: **true**
(undocumented)
\n- On success, responds with\n[`ListTagsForResourceOutput`](crate::operation::list_tags_for_resource::ListTagsForResourceOutput)\nwith field(s):\n- [`tags(Option>)`](crate::operation::list_tags_for_resource::ListTagsForResourceOutput::tags): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::list_tags_for_resource::ListTagsForResourceError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_tags_for_resource(\n &self,\n ) -> crate::operation::list_tags_for_resource::builders::ListTagsForResourceFluentBuilder {\n crate::operation::list_tags_for_resource::builders::ListTagsForResourceFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "list_tags_for_resource", "docstring": "Constructs a fluent builder for the\n[`ListTagsForResource`](crate::operation::list_tags_for_resource::builders::ListTagsForResourceFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`resource_arn(impl Into)`](crate::operation::list_tags_for_resource::builders::ListTagsForResourceFluentBuilder::resource_arn) / [`set_resource_arn(Option)`](crate::operation::list_tags_for_resource::builders::ListTagsForResourceFluentBuilder::set_resource_arn):
required: **true**
(undocumented)
\n- On success, responds with\n[`ListTagsForResourceOutput`](crate::operation::list_tags_for_resource::ListTagsForResourceOutput)\nwith field(s):\n- [`tags(Option>)`](crate::operation::list_tags_for_resource::ListTagsForResourceOutput::tags): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::list_tags_for_resource::ListTagsForResourceError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/list_tags_for_resource.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/list_tags_for_resource.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "724f2247c83fc7bf6f26eb51a6059463499d7792c31bac1b73bedd6a2a682a8b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lock_service_linked_role\n\nDocumentation:\nConstructs a fluent builder for the\n[`LockServiceLinkedRole`](crate::operation::lock_service_linked_role::builders::LockServiceLinkedRoleFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`role_arn(impl Into)`](crate::operation::lock_service_linked_role::builders::LockServiceLinkedRoleFluentBuilder::role_arn) / [`set_role_arn(Option)`](crate::operation::lock_service_linked_role::builders::LockServiceLinkedRoleFluentBuilder::set_role_arn):
required: **true**
(undocumented)
\n- [`timeout(i64)`](crate::operation::lock_service_linked_role::builders::LockServiceLinkedRoleFluentBuilder::timeout) / [`set_timeout(Option)`](crate::operation::lock_service_linked_role::builders::LockServiceLinkedRoleFluentBuilder::set_timeout):
required: **true**
(undocumented)
\n- On success, responds with\n[`LockServiceLinkedRoleOutput`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleOutput)\nwith field(s):\n- [`can_be_deleted(bool)`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleOutput::can_be_deleted): (undocumented)\n- [`reason_of_failure(Option)`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleOutput::reason_of_failure): (undocumented)\n- [`related_resources(Option>)`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleOutput::related_resources): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn lock_service_linked_role(\n &self,\n ) -> crate::operation::lock_service_linked_role::builders::LockServiceLinkedRoleFluentBuilder {\n crate::operation::lock_service_linked_role::builders::LockServiceLinkedRoleFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "lock_service_linked_role", "docstring": "Constructs a fluent builder for the\n[`LockServiceLinkedRole`](crate::operation::lock_service_linked_role::builders::LockServiceLinkedRoleFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`role_arn(impl Into)`](crate::operation::lock_service_linked_role::builders::LockServiceLinkedRoleFluentBuilder::role_arn) / [`set_role_arn(Option)`](crate::operation::lock_service_linked_role::builders::LockServiceLinkedRoleFluentBuilder::set_role_arn):
required: **true**
(undocumented)
\n- [`timeout(i64)`](crate::operation::lock_service_linked_role::builders::LockServiceLinkedRoleFluentBuilder::timeout) / [`set_timeout(Option)`](crate::operation::lock_service_linked_role::builders::LockServiceLinkedRoleFluentBuilder::set_timeout):
required: **true**
(undocumented)
\n- On success, responds with\n[`LockServiceLinkedRoleOutput`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleOutput)\nwith field(s):\n- [`can_be_deleted(bool)`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleOutput::can_be_deleted): (undocumented)\n- [`reason_of_failure(Option)`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleOutput::reason_of_failure): (undocumented)\n- [`related_resources(Option>)`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleOutput::related_resources): (undocumented)\n- On failure, responds with\n[`SdkError`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/lock_service_linked_role.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/lock_service_linked_role.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ea074ed999f55e832de166921d35473ababcf127e1342c7f127b77abdc3b2c9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unlock_service_linked_role\n\nDocumentation:\nConstructs a fluent builder for the\n[`UnlockServiceLinkedRole`](crate::operation::unlock_service_linked_role::builders::UnlockServiceLinkedRoleFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`role_arn(impl Into)`](crate::operation::unlock_service_linked_role::builders::UnlockServiceLinkedRoleFluentBuilder::role_arn) / [`set_role_arn(Option)`](crate::operation::unlock_service_linked_role::builders::UnlockServiceLinkedRoleFluentBuilder::set_role_arn):
required: **true**
(undocumented)
\n- [`deletion_status(DeletionStatus)`](crate::operation::unlock_service_linked_role::builders::UnlockServiceLinkedRoleFluentBuilder::deletion_status) / [`set_deletion_status(Option)`](crate::operation::unlock_service_linked_role::builders::UnlockServiceLinkedRoleFluentBuilder::set_deletion_status):
required: **false**
(undocumented)
\n- On success, responds with\n[`UnlockServiceLinkedRoleOutput`](crate::operation::unlock_service_linked_role::UnlockServiceLinkedRoleOutput)\n- On failure, responds with\n[`SdkError`](crate::operation::unlock_service_linked_role::UnlockServiceLinkedRoleError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unlock_service_linked_role(\n &self,\n ) -> crate::operation::unlock_service_linked_role::builders::UnlockServiceLinkedRoleFluentBuilder {\n crate::operation::unlock_service_linked_role::builders::UnlockServiceLinkedRoleFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "unlock_service_linked_role", "docstring": "Constructs a fluent builder for the\n[`UnlockServiceLinkedRole`](crate::operation::unlock_service_linked_role::builders::UnlockServiceLinkedRoleFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`role_arn(impl Into)`](crate::operation::unlock_service_linked_role::builders::UnlockServiceLinkedRoleFluentBuilder::role_arn) / [`set_role_arn(Option)`](crate::operation::unlock_service_linked_role::builders::UnlockServiceLinkedRoleFluentBuilder::set_role_arn):
required: **true**
(undocumented)
\n- [`deletion_status(DeletionStatus)`](crate::operation::unlock_service_linked_role::builders::UnlockServiceLinkedRoleFluentBuilder::deletion_status) / [`set_deletion_status(Option)`](crate::operation::unlock_service_linked_role::builders::UnlockServiceLinkedRoleFluentBuilder::set_deletion_status):
required: **false**
(undocumented)
\n- On success, responds with\n[`UnlockServiceLinkedRoleOutput`](crate::operation::unlock_service_linked_role::UnlockServiceLinkedRoleOutput)\n- On failure, responds with\n[`SdkError`](crate::operation::unlock_service_linked_role::UnlockServiceLinkedRoleError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/unlock_service_linked_role.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/unlock_service_linked_role.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0fd93be41110a442fbd57a541a8ecb4699e23d591f44fe0fa216e151e18900f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_customization\n\nDocumentation:\nConstructs a fluent builder for the\n[`UpdateCustomization`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- [`operation(UpdateOperation)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::operation) / [`set_operation(Option)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::set_operation):
required: **true**
(undocumented)
\n- [`client_token(impl Into)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- [`data_reference(DataReference)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::data_reference) / [`set_data_reference(Option)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::set_data_reference):
required: **false**
(undocumented)
\n- [`version(i64)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::version) / [`set_version(Option)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::set_version):
required: **false**
(undocumented)
\n- [`include_repos(impl Into)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::include_repos) / [`set_include_repos(Option>)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::set_include_repos):
required: **false**
(undocumented)
\n- On success, responds with\n[`UpdateCustomizationOutput`](crate::operation::update_customization::UpdateCustomizationOutput)\n- On failure, responds with\n[`SdkError`](crate::operation::update_customization::UpdateCustomizationError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn update_customization(\n &self,\n ) -> crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder {\n crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::new(self.handle.clone())\n }\n```"}], "func_name": "update_customization", "docstring": "Constructs a fluent builder for the\n[`UpdateCustomization`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`identifier(impl Into)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::identifier) / [`set_identifier(Option)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::set_identifier):
required: **true**
(undocumented)
\n- [`operation(UpdateOperation)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::operation) / [`set_operation(Option)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::set_operation):
required: **true**
(undocumented)
\n- [`client_token(impl Into)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::client_token) / [`set_client_token(Option)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::set_client_token):
required: **false**
(undocumented)
\n- [`data_reference(DataReference)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::data_reference) / [`set_data_reference(Option)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::set_data_reference):
required: **false**
(undocumented)
\n- [`version(i64)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::version) / [`set_version(Option)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::set_version):
required: **false**
(undocumented)
\n- [`include_repos(impl Into)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::include_repos) / [`set_include_repos(Option>)`](crate::operation::update_customization::builders::UpdateCustomizationFluentBuilder::set_include_repos):
required: **false**
(undocumented)
\n- On success, responds with\n[`UpdateCustomizationOutput`](crate::operation::update_customization::UpdateCustomizationOutput)\n- On failure, responds with\n[`SdkError`](crate::operation::update_customization::UpdateCustomizationError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/client/update_customization.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/client/update_customization.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "10b488a5e25aa50472432a6af3398a69480d7e8702d8e9f04e76d985d022625d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_service_linked_role_lock_client_error\n\nDocumentation:\nReturns `true` if the error kind is\n`LockServiceLinkedRoleError::ServiceLinkedRoleLockClientError`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_service_linked_role_lock_client_error(&self) -> bool {\n matches!(self, Self::ServiceLinkedRoleLockClientError(_))\n }\n```"}], "func_name": "is_service_linked_role_lock_client_error", "docstring": "Returns `true` if the error kind is\n`LockServiceLinkedRoleError::ServiceLinkedRoleLockClientError`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/lock_service_linked_role.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/lock_service_linked_role.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d959fa536076fd3e526bcd4a0cd4eed893189b8a4ddf7a1e7e5de10fec1fbe3f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_service_linked_role_lock_service_error\n\nDocumentation:\nReturns `true` if the error kind is\n`LockServiceLinkedRoleError::ServiceLinkedRoleLockServiceError`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_service_linked_role_lock_service_error(&self) -> bool {\n matches!(self, Self::ServiceLinkedRoleLockServiceError(_))\n }\n```"}], "func_name": "is_service_linked_role_lock_service_error", "docstring": "Returns `true` if the error kind is\n`LockServiceLinkedRoleError::ServiceLinkedRoleLockServiceError`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/lock_service_linked_role.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/lock_service_linked_role.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0fd01fb196b3ed8370845f83ad5734fc41d3734b3ff025df4f6679e3b70df81c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`AllowVendedLogDeliveryForResourceInput`](crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceInputBuilder\n {\n crate::operation::allow_vended_log_delivery_for_resource::builders::AllowVendedLogDeliveryForResourceInputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`AllowVendedLogDeliveryForResourceInput`](crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/allow_vended_log_delivery_for_resource/_allow_vended_log_delivery_for_resource_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/allow_vended_log_delivery_for_resource/_allow_vended_log_delivery_for_resource_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "46278d40b89ff4a491d15228f8b9828462ea7b92afca88c3239768ea594c1f4d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`AllowVendedLogDeliveryForResourceInput`](crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceInput {\n resource_arn_being_authorized: self.resource_arn_being_authorized,\n delivery_source_arn: self.delivery_source_arn,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`AllowVendedLogDeliveryForResourceInput`](crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/allow_vended_log_delivery_for_resource/_allow_vended_log_delivery_for_resource_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/allow_vended_log_delivery_for_resource/_allow_vended_log_delivery_for_resource_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "42fc1114fc472ab961fd699c4079c600c0b143f7c91d9ab3b79038f8428a765a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`AllowVendedLogDeliveryForResourceOutput`](crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceOutput {\n crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceOutput {\n message: self.message,\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`AllowVendedLogDeliveryForResourceOutput`](crate::operation::allow_vended_log_delivery_for_resource::AllowVendedLogDeliveryForResourceOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/allow_vended_log_delivery_for_resource/_allow_vended_log_delivery_for_resource_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/allow_vended_log_delivery_for_resource/_allow_vended_log_delivery_for_resource_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fae67455eaee61ece436aed3c0daae3d32f59afb08d5728d183ddc31bb87a2b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`AssociateCustomizationPermissionInput`](crate::operation::associate_customization_permission::AssociateCustomizationPermissionInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionInputBuilder\n {\n crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionInputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`AssociateCustomizationPermissionInput`](crate::operation::associate_customization_permission::AssociateCustomizationPermissionInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/associate_customization_permission/_associate_customization_permission_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/associate_customization_permission/_associate_customization_permission_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a124be306afb1066d669d80bc9aa54814ca548d1afdd156c40b55853384b5a1e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`AssociateCustomizationPermissionInput`](crate::operation::associate_customization_permission::AssociateCustomizationPermissionInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::associate_customization_permission::AssociateCustomizationPermissionInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::associate_customization_permission::AssociateCustomizationPermissionInput {\n identifier: self.identifier,\n permission: self.permission,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`AssociateCustomizationPermissionInput`](crate::operation::associate_customization_permission::AssociateCustomizationPermissionInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/associate_customization_permission/_associate_customization_permission_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/associate_customization_permission/_associate_customization_permission_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9bb37f51c4ea78b4c2efd0ae1e674f04302666a533072e9e0e4228c1467be448"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`AssociateCustomizationPermissionOutput`](crate::operation::associate_customization_permission::AssociateCustomizationPermissionOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionOutputBuilder\n {\n crate::operation::associate_customization_permission::builders::AssociateCustomizationPermissionOutputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`AssociateCustomizationPermissionOutput`](crate::operation::associate_customization_permission::AssociateCustomizationPermissionOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/associate_customization_permission/_associate_customization_permission_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/associate_customization_permission/_associate_customization_permission_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bd84cf4ec679738b6d0c7fdc890044a455ccf5653f2f61ccdbe137a2dc170100"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`AssociateCustomizationPermissionOutput`](crate::operation::associate_customization_permission::AssociateCustomizationPermissionOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::associate_customization_permission::AssociateCustomizationPermissionOutput {\n crate::operation::associate_customization_permission::AssociateCustomizationPermissionOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`AssociateCustomizationPermissionOutput`](crate::operation::associate_customization_permission::AssociateCustomizationPermissionOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/associate_customization_permission/_associate_customization_permission_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/associate_customization_permission/_associate_customization_permission_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "11cd7827ba7ac2d4988f69822ac532c80255c50857a693abf84d02ed7ef7146c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: include_repos\n\nDocumentation:\nAppends an item to `include_repos`.\n\nTo override the contents of this collection use\n[`set_include_repos`](Self::set_include_repos).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn include_repos(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n let mut v = self.include_repos.unwrap_or_default();\n v.push(input.into());\n self.include_repos = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "include_repos", "docstring": "Appends an item to `include_repos`.\n\nTo override the contents of this collection use\n[`set_include_repos`](Self::set_include_repos).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/create_customization/_create_customization_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/create_customization/_create_customization_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c8aceeeb4e270e070c0eba349c6074d24403d4a8fb05b320e5a6d1d3b2e8d909"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateCustomizationInput`](crate::operation::create_customization::CreateCustomizationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_customization::CreateCustomizationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::create_customization::CreateCustomizationInput {\n data_reference: self.data_reference,\n customization_name: self.customization_name,\n description: self.description,\n profile_arn: self.profile_arn,\n tags: self.tags,\n client_token: self.client_token,\n include_repos: self.include_repos,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateCustomizationInput`](crate::operation::create_customization::CreateCustomizationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/create_customization/_create_customization_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/create_customization/_create_customization_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aace8550ba0dc9e8c9f584267a2c99aa13b185589a1e054411c9759cc5aa419c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateCustomizationOutput`](crate::operation::create_customization::CreateCustomizationOutput).\nThis method will fail if any of the following fields are not set:\n- [`customization_arn`](crate::operation::create_customization::builders::CreateCustomizationOutputBuilder::customization_arn)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_customization::CreateCustomizationOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::create_customization::CreateCustomizationOutput {\n customization_arn: self.customization_arn.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"customization_arn\",\n \"customization_arn was not specified but it is required when building CreateCustomizationOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateCustomizationOutput`](crate::operation::create_customization::CreateCustomizationOutput).\nThis method will fail if any of the following fields are not set:\n- [`customization_arn`](crate::operation::create_customization::builders::CreateCustomizationOutputBuilder::customization_arn)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/create_customization/_create_customization_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/create_customization/_create_customization_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0488ca4e214f19b49aadb89f9ee7c60072f94155a57485a4f56f7e223f525aab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateProfileInput`](crate::operation::create_profile::CreateProfileInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_profile::CreateProfileInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::create_profile::CreateProfileInput {\n identity_source: self.identity_source,\n profile_name: self.profile_name,\n description: self.description,\n reference_tracker_configuration: self.reference_tracker_configuration,\n active_functionalities: self.active_functionalities,\n client_token: self.client_token,\n kms_key_arn: self.kms_key_arn,\n tags: self.tags,\n resource_policy: self.resource_policy,\n opt_in_features: self.opt_in_features,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateProfileInput`](crate::operation::create_profile::CreateProfileInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/create_profile/_create_profile_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/create_profile/_create_profile_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0a450b51bb0efb1bdf9e39b39674b5b06d7d91bbdd73e418ffc32a24e7d1643e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CreateProfileOutput`](crate::operation::create_profile::CreateProfileOutput).\nThis method will fail if any of the following fields are not set:\n- [`profile_arn`](crate::operation::create_profile::builders::CreateProfileOutputBuilder::profile_arn)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::create_profile::CreateProfileOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::create_profile::CreateProfileOutput {\n profile_arn: self.profile_arn.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"profile_arn\",\n \"profile_arn was not specified but it is required when building CreateProfileOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CreateProfileOutput`](crate::operation::create_profile::CreateProfileOutput).\nThis method will fail if any of the following fields are not set:\n- [`profile_arn`](crate::operation::create_profile::builders::CreateProfileOutputBuilder::profile_arn)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/create_profile/_create_profile_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/create_profile/_create_profile_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2cd3f5dbe2815427ddcabca19c578c387583b00942a781ea3c982fd3b00f5970"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DeleteCustomizationInput`](crate::operation::delete_customization::DeleteCustomizationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::delete_customization::DeleteCustomizationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::delete_customization::DeleteCustomizationInput {\n identifier: self.identifier,\n client_token: self.client_token,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DeleteCustomizationInput`](crate::operation::delete_customization::DeleteCustomizationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/delete_customization/_delete_customization_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/delete_customization/_delete_customization_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "36690b9e74811790103e051f9a652a6caccc737e8306a17b459bde25cae7366a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DeleteCustomizationOutput`](crate::operation::delete_customization::DeleteCustomizationOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::delete_customization::DeleteCustomizationOutput {\n crate::operation::delete_customization::DeleteCustomizationOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DeleteCustomizationOutput`](crate::operation::delete_customization::DeleteCustomizationOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/delete_customization/_delete_customization_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/delete_customization/_delete_customization_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6948da6bd6628b74b314efe51ad812e2ca4cb0913b6ffe466a7922f086c69ee0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`DeleteCustomizationPermissionsInput`](crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::delete_customization_permissions::builders::DeleteCustomizationPermissionsInputBuilder {\n crate::operation::delete_customization_permissions::builders::DeleteCustomizationPermissionsInputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`DeleteCustomizationPermissionsInput`](crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/delete_customization_permissions/_delete_customization_permissions_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/delete_customization_permissions/_delete_customization_permissions_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f7987cbee0f41eb5f83a83b54b61baa22b57548244e5e8671756f75725d51d6d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DeleteCustomizationPermissionsInput`](crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsInput {\n identifier: self.identifier,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DeleteCustomizationPermissionsInput`](crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/delete_customization_permissions/_delete_customization_permissions_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/delete_customization_permissions/_delete_customization_permissions_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a3658e4c5d43658e089ac5fdb2e5d3ab65403c9dfb88ad60202075f88ccf6f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`DeleteCustomizationPermissionsOutput`](crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::delete_customization_permissions::builders::DeleteCustomizationPermissionsOutputBuilder {\n crate::operation::delete_customization_permissions::builders::DeleteCustomizationPermissionsOutputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`DeleteCustomizationPermissionsOutput`](crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/delete_customization_permissions/_delete_customization_permissions_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/delete_customization_permissions/_delete_customization_permissions_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "539d63c19d8d62163a79bf77374e12037a2a637b2e660ab991152b0c7cf7da98"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DeleteCustomizationPermissionsOutput`](crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsOutput {\n crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DeleteCustomizationPermissionsOutput`](crate::operation::delete_customization_permissions::DeleteCustomizationPermissionsOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/delete_customization_permissions/_delete_customization_permissions_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/delete_customization_permissions/_delete_customization_permissions_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc09fe67f6ae5fab0d7aadf4ffa65b626b8262265b70dc4c8afa7e1ee2fe0b30"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DeleteProfileInput`](crate::operation::delete_profile::DeleteProfileInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::delete_profile::DeleteProfileInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::delete_profile::DeleteProfileInput {\n profile_arn: self.profile_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DeleteProfileInput`](crate::operation::delete_profile::DeleteProfileInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/delete_profile/_delete_profile_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/delete_profile/_delete_profile_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c697f0e57334a3277d1833180e6e6fffd24a7626b6f73b8257e5998eb3340ecf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DeleteProfileOutput`](crate::operation::delete_profile::DeleteProfileOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::delete_profile::DeleteProfileOutput {\n crate::operation::delete_profile::DeleteProfileOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DeleteProfileOutput`](crate::operation::delete_profile::DeleteProfileOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/delete_profile/_delete_profile_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/delete_profile/_delete_profile_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "45e9a48c880e96ef9dde462a2e2dbd791ccf9937e73e7c58c904e888af545108"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DisassociateCustomizationPermissionInput`](crate::operation::disassociate_customization_permission::DisassociateCustomizationPermissionInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::disassociate_customization_permission::DisassociateCustomizationPermissionInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::disassociate_customization_permission::DisassociateCustomizationPermissionInput {\n identifier: self.identifier,\n permission: self.permission,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DisassociateCustomizationPermissionInput`](crate::operation::disassociate_customization_permission::DisassociateCustomizationPermissionInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/disassociate_customization_permission/_disassociate_customization_permission_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/disassociate_customization_permission/_disassociate_customization_permission_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c48ed35ff832bbe1fca7e52fd751d37c5ce962f6d27d6830577f8cb3ef2709c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`DisassociateCustomizationPermissionOutput`](crate::operation::disassociate_customization_permission::DisassociateCustomizationPermissionOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> crate::operation::disassociate_customization_permission::DisassociateCustomizationPermissionOutput {\n crate::operation::disassociate_customization_permission::DisassociateCustomizationPermissionOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`DisassociateCustomizationPermissionOutput`](crate::operation::disassociate_customization_permission::DisassociateCustomizationPermissionOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/disassociate_customization_permission/_disassociate_customization_permission_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/disassociate_customization_permission/_disassociate_customization_permission_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "962ab72eadc9973e8ef78bdaf8468960466062ef61db2c0c17b1fcbb2611487e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GenerateRecommendationsInput`](crate::operation::generate_recommendations::GenerateRecommendationsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::generate_recommendations::GenerateRecommendationsInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::generate_recommendations::GenerateRecommendationsInput {\n file_context: self.file_context,\n max_results: self.max_results,\n next_token: self.next_token,\n reference_tracker_configuration: self.reference_tracker_configuration,\n supplemental_contexts: self.supplemental_contexts,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GenerateRecommendationsInput`](crate::operation::generate_recommendations::GenerateRecommendationsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/generate_recommendations/_generate_recommendations_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/generate_recommendations/_generate_recommendations_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d4ac2bee89e3819cd8ce077f9713d42a851c5ceba6d2e89a24413dffe0192c66"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GenerateRecommendationsOutput`](crate::operation::generate_recommendations::GenerateRecommendationsOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::generate_recommendations::GenerateRecommendationsOutput {\n crate::operation::generate_recommendations::GenerateRecommendationsOutput {\n recommendations: self.recommendations,\n next_token: self.next_token,\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GenerateRecommendationsOutput`](crate::operation::generate_recommendations::GenerateRecommendationsOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/generate_recommendations/_generate_recommendations_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/generate_recommendations/_generate_recommendations_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "214770b96b8bfadd202fc6386838c50869caef71ff244b06d97b3afc7ac881e3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetCustomizationInput`](crate::operation::get_customization::GetCustomizationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::get_customization::GetCustomizationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::get_customization::GetCustomizationInput {\n identifier: self.identifier,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetCustomizationInput`](crate::operation::get_customization::GetCustomizationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/get_customization/_get_customization_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/get_customization/_get_customization_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c0fc687cad33b627b1435bb9b7c300ec74a6b77b6101d3c5bd4ad3b08b169d5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GetCustomizationOutput`](crate::operation::get_customization::GetCustomizationOutput).\nThis method will fail if any of the following fields are not set:\n- [`arn`](crate::operation::get_customization::builders::GetCustomizationOutputBuilder::arn)\n- [`status`](crate::operation::get_customization::builders::GetCustomizationOutputBuilder::status)\n- [`data_reference`](crate::operation::get_customization::builders::GetCustomizationOutputBuilder::data_reference)\n- [`customization_name`](crate::operation::get_customization::builders::GetCustomizationOutputBuilder::customization_name)\n- [`profile_arn`](crate::operation::get_customization::builders::GetCustomizationOutputBuilder::profile_arn)\n- [`updated_at`](crate::operation::get_customization::builders::GetCustomizationOutputBuilder::updated_at)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::get_customization::GetCustomizationOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::get_customization::GetCustomizationOutput {\n arn: self.arn.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"arn\",\n \"arn was not specified but it is required when building GetCustomizationOutput\",\n )\n })?,\n version: self.version,\n status: self.status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"status\",\n \"status was not specified but it is required when building GetCustomizationOutput\",\n )\n })?,\n error_details: self.error_details,\n data_reference: self.data_reference.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"data_reference\",\n \"data_reference was not specified but it is required when building GetCustomizationOutput\",\n )\n })?,\n customization_name: self.customization_name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"customization_name\",\n \"customization_name was not specified but it is required when building GetCustomizationOutput\",\n )\n })?,\n description: self.description,\n profile_arn: self.profile_arn.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"profile_arn\",\n \"profile_arn was not specified but it is required when building GetCustomizationOutput\",\n )\n })?,\n updated_at: self.updated_at.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"updated_at\",\n \"updated_at was not specified but it is required when building GetCustomizationOutput\",\n )\n })?,\n evaluation_metrics: self.evaluation_metrics,\n include_repos: self.include_repos,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GetCustomizationOutput`](crate::operation::get_customization::GetCustomizationOutput).\nThis method will fail if any of the following fields are not set:\n- [`arn`](crate::operation::get_customization::builders::GetCustomizationOutputBuilder::arn)\n- [`status`](crate::operation::get_customization::builders::GetCustomizationOutputBuilder::status)\n- [`data_reference`](crate::operation::get_customization::builders::GetCustomizationOutputBuilder::data_reference)\n- [`customization_name`](crate::operation::get_customization::builders::GetCustomizationOutputBuilder::customization_name)\n- [`profile_arn`](crate::operation::get_customization::builders::GetCustomizationOutputBuilder::profile_arn)\n- [`updated_at`](crate::operation::get_customization::builders::GetCustomizationOutputBuilder::updated_at)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/get_customization/_get_customization_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/get_customization/_get_customization_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0abafcf738af8a25232aa477c6df434468c2674d42fe285a92ead83d7807798a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListCustomizationsInput`](crate::operation::list_customizations::ListCustomizationsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_customizations::ListCustomizationsInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_customizations::ListCustomizationsInput {\n max_results: self.max_results,\n next_token: self.next_token,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListCustomizationsInput`](crate::operation::list_customizations::ListCustomizationsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_customizations/_list_customizations_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_customizations/_list_customizations_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d380ba01d0fb90e2604d2c8ff415126131f554105b150ec4f327e00f22ad7a73"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListCustomizationsOutput`](crate::operation::list_customizations::ListCustomizationsOutput).\nThis method will fail if any of the following fields are not set:\n- [`customizations`](crate::operation::list_customizations::builders::ListCustomizationsOutputBuilder::customizations)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_customizations::ListCustomizationsOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_customizations::ListCustomizationsOutput {\n customizations: self.customizations.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"customizations\",\n \"customizations was not specified but it is required when building ListCustomizationsOutput\",\n )\n })?,\n next_token: self.next_token,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListCustomizationsOutput`](crate::operation::list_customizations::ListCustomizationsOutput).\nThis method will fail if any of the following fields are not set:\n- [`customizations`](crate::operation::list_customizations::builders::ListCustomizationsOutputBuilder::customizations)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_customizations/_list_customizations_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_customizations/_list_customizations_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cec0abdf6f241289d259025dce4c62608b298a530d9b209477a8649f1702601a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: items\n\nDocumentation:\nCreate a flattened paginator\n\nThis paginator automatically flattens results using `permissions`. Queries to the underlying\nservice are dispatched lazily.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn items(\n self,\n ) -> crate::operation::list_customization_permissions::paginator::ListCustomizationPermissionsPaginatorItems {\n crate::operation::list_customization_permissions::paginator::ListCustomizationPermissionsPaginatorItems(self)\n }\n```"}], "func_name": "items", "docstring": "Create a flattened paginator\n\nThis paginator automatically flattens results using `permissions`. Queries to the underlying\nservice are dispatched lazily.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_customization_permissions/paginator.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_customization_permissions/paginator.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e18041696aef089e66a5dbe9e32826bc2e1e40c4fb4f78ec5ea8f297834a681c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`ListCustomizationPermissionsInput`](crate::operation::list_customization_permissions::ListCustomizationPermissionsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsInputBuilder {\n crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsInputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`ListCustomizationPermissionsInput`](crate::operation::list_customization_permissions::ListCustomizationPermissionsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_customization_permissions/_list_customization_permissions_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_customization_permissions/_list_customization_permissions_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "647c0f47ba65a080213c1796a4b5fbe4ced5073eba6954b49c2b50e8d5df7dba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListCustomizationPermissionsInput`](crate::operation::list_customization_permissions::ListCustomizationPermissionsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_customization_permissions::ListCustomizationPermissionsInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::list_customization_permissions::ListCustomizationPermissionsInput {\n identifier: self.identifier,\n max_results: self.max_results,\n next_token: self.next_token,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListCustomizationPermissionsInput`](crate::operation::list_customization_permissions::ListCustomizationPermissionsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_customization_permissions/_list_customization_permissions_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_customization_permissions/_list_customization_permissions_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "45d8f8040b3e3c9601ab9032ed2cebbdc8340888bd454f9a814adeac8c0d4851"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`ListCustomizationPermissionsOutput`](crate::operation::list_customization_permissions::ListCustomizationPermissionsOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder()\n -> crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsOutputBuilder {\n crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsOutputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`ListCustomizationPermissionsOutput`](crate::operation::list_customization_permissions::ListCustomizationPermissionsOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_customization_permissions/_list_customization_permissions_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_customization_permissions/_list_customization_permissions_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b3e759f4c1ec9ab2921d041b51f2f10730e13f23cdecaa882f95ec8c50baf21f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: permissions\n\nDocumentation:\nAppends an item to `permissions`.\n\nTo override the contents of this collection use [`set_permissions`](Self::set_permissions).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn permissions(mut self, input: crate::types::CustomizationPermission) -> Self {\n let mut v = self.permissions.unwrap_or_default();\n v.push(input);\n self.permissions = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "permissions", "docstring": "Appends an item to `permissions`.\n\nTo override the contents of this collection use [`set_permissions`](Self::set_permissions).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_customization_permissions/_list_customization_permissions_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_customization_permissions/_list_customization_permissions_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fd41afcf2cd841599f6fafd1050d209dd6cbac7fed0df7412c418088658f4540"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListCustomizationPermissionsOutput`](crate::operation::list_customization_permissions::ListCustomizationPermissionsOutput).\nThis method will fail if any of the following fields are not set:\n- [`permissions`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsOutputBuilder::permissions)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_customization_permissions::ListCustomizationPermissionsOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_customization_permissions::ListCustomizationPermissionsOutput {\n permissions: self.permissions.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"permissions\",\n \"permissions was not specified but it is required when building ListCustomizationPermissionsOutput\",\n )\n })?,\n next_token: self.next_token,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListCustomizationPermissionsOutput`](crate::operation::list_customization_permissions::ListCustomizationPermissionsOutput).\nThis method will fail if any of the following fields are not set:\n- [`permissions`](crate::operation::list_customization_permissions::builders::ListCustomizationPermissionsOutputBuilder::permissions)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_customization_permissions/_list_customization_permissions_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_customization_permissions/_list_customization_permissions_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad214daed68a76ad6c19eba802fdb4dcba90e13c76f291cc1561241a0361fa88"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: items\n\nDocumentation:\nCreate a flattened paginator\n\nThis paginator automatically flattens results using `versions`. Queries to the underlying\nservice are dispatched lazily.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn items(\n self,\n ) -> crate::operation::list_customization_versions::paginator::ListCustomizationVersionsPaginatorItems {\n crate::operation::list_customization_versions::paginator::ListCustomizationVersionsPaginatorItems(self)\n }\n```"}], "func_name": "items", "docstring": "Create a flattened paginator\n\nThis paginator automatically flattens results using `versions`. Queries to the underlying\nservice are dispatched lazily.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_customization_versions/paginator.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_customization_versions/paginator.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "805f4b5bdb00f240ac24d2afb14513d047e52a0dbcfb0900b7e5edb599876910"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListCustomizationVersionsInput`](crate::operation::list_customization_versions::ListCustomizationVersionsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_customization_versions::ListCustomizationVersionsInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::list_customization_versions::ListCustomizationVersionsInput {\n identifier: self.identifier,\n max_results: self.max_results,\n next_token: self.next_token,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListCustomizationVersionsInput`](crate::operation::list_customization_versions::ListCustomizationVersionsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_customization_versions/_list_customization_versions_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_customization_versions/_list_customization_versions_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "30b2a65842c1c84cacafaa456c7125f3b1ba41729dabf9e3cf933fffe620b7b2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: builder\n\nDocumentation:\nCreates a new builder-style object to manufacture\n[`ListCustomizationVersionsOutput`](crate::operation::list_customization_versions::ListCustomizationVersionsOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn builder() -> crate::operation::list_customization_versions::builders::ListCustomizationVersionsOutputBuilder\n {\n crate::operation::list_customization_versions::builders::ListCustomizationVersionsOutputBuilder::default()\n }\n```"}], "func_name": "builder", "docstring": "Creates a new builder-style object to manufacture\n[`ListCustomizationVersionsOutput`](crate::operation::list_customization_versions::ListCustomizationVersionsOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_customization_versions/_list_customization_versions_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_customization_versions/_list_customization_versions_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e414eb59e8193e703ebf88f02977348d87b10d772f24a72cfce14f2c850210d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: versions\n\nDocumentation:\nAppends an item to `versions`.\n\nTo override the contents of this collection use [`set_versions`](Self::set_versions).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn versions(mut self, input: crate::types::CustomizationVersionSummary) -> Self {\n let mut v = self.versions.unwrap_or_default();\n v.push(input);\n self.versions = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "versions", "docstring": "Appends an item to `versions`.\n\nTo override the contents of this collection use [`set_versions`](Self::set_versions).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_customization_versions/_list_customization_versions_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_customization_versions/_list_customization_versions_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f35e3b667634ef38ccdd6a7f7203fe85c12eeb1f5678d81c59ebaa63cc8a5ce"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListCustomizationVersionsOutput`](crate::operation::list_customization_versions::ListCustomizationVersionsOutput).\nThis method will fail if any of the following fields are not set:\n- [`versions`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsOutputBuilder::versions)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_customization_versions::ListCustomizationVersionsOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::list_customization_versions::ListCustomizationVersionsOutput {\n versions: self.versions.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"versions\",\n \"versions was not specified but it is required when building ListCustomizationVersionsOutput\",\n )\n })?,\n next_token: self.next_token,\n _request_id: self._request_id,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListCustomizationVersionsOutput`](crate::operation::list_customization_versions::ListCustomizationVersionsOutput).\nThis method will fail if any of the following fields are not set:\n- [`versions`](crate::operation::list_customization_versions::builders::ListCustomizationVersionsOutputBuilder::versions)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_customization_versions/_list_customization_versions_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_customization_versions/_list_customization_versions_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9172cadb7a62ef13add954bc62e8dc8a56870fa383035837d0585a1f7719058a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListProfilesInput`](crate::operation::list_profiles::ListProfilesInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_profiles::ListProfilesInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_profiles::ListProfilesInput {\n max_results: self.max_results,\n next_token: self.next_token,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListProfilesInput`](crate::operation::list_profiles::ListProfilesInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_profiles/_list_profiles_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_profiles/_list_profiles_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8bf689b0c32b6fcd5ac2fa010f8ba36f671e3c55b7bf9f10a726ce94ec987661"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListProfilesOutput`](crate::operation::list_profiles::ListProfilesOutput). This method\nwill fail if any of the following fields are not set:\n- [`profiles`](crate::operation::list_profiles::builders::ListProfilesOutputBuilder::profiles)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_profiles::ListProfilesOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_profiles::ListProfilesOutput {\n profiles: self.profiles.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"profiles\",\n \"profiles was not specified but it is required when building ListProfilesOutput\",\n )\n })?,\n next_token: self.next_token,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListProfilesOutput`](crate::operation::list_profiles::ListProfilesOutput). This method\nwill fail if any of the following fields are not set:\n- [`profiles`](crate::operation::list_profiles::builders::ListProfilesOutputBuilder::profiles)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_profiles/_list_profiles_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_profiles/_list_profiles_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "79c04d5ba4b623bba979e13443ce06c020b5bea87fb81d48d9d8f5d6b4f63492"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ListTagsForResourceInput`](crate::operation::list_tags_for_resource::ListTagsForResourceInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::list_tags_for_resource::ListTagsForResourceInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::list_tags_for_resource::ListTagsForResourceInput {\n resource_arn: self.resource_arn,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ListTagsForResourceInput`](crate::operation::list_tags_for_resource::ListTagsForResourceInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/list_tags_for_resource/_list_tags_for_resource_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/list_tags_for_resource/_list_tags_for_resource_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8bc2bcf38611e18e0ddea8fd5c6da36ae7eabed7d449033c65f9584e3c9ae68f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`LockServiceLinkedRoleInput`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::lock_service_linked_role::LockServiceLinkedRoleInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::lock_service_linked_role::LockServiceLinkedRoleInput {\n role_arn: self.role_arn,\n timeout: self.timeout,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`LockServiceLinkedRoleInput`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/lock_service_linked_role/_lock_service_linked_role_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/lock_service_linked_role/_lock_service_linked_role_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "92d897d49936d43f9e87874fededb49ab44d0e4f823fe808bf46bcb5c1294036"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: related_resources\n\nDocumentation:\nAppends an item to `related_resources`.\n\nTo override the contents of this collection use\n[`set_related_resources`](Self::set_related_resources).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn related_resources(mut self, input: impl ::std::convert::Into<::std::string::String>) -> Self {\n let mut v = self.related_resources.unwrap_or_default();\n v.push(input.into());\n self.related_resources = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "related_resources", "docstring": "Appends an item to `related_resources`.\n\nTo override the contents of this collection use\n[`set_related_resources`](Self::set_related_resources).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/lock_service_linked_role/_lock_service_linked_role_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/lock_service_linked_role/_lock_service_linked_role_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "678ffa785ea5a1cf4f794e6736ed1385ca401561fb01d8997df3e2bbdaa5d67a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`LockServiceLinkedRoleOutput`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::lock_service_linked_role::LockServiceLinkedRoleOutput {\n crate::operation::lock_service_linked_role::LockServiceLinkedRoleOutput {\n can_be_deleted: self.can_be_deleted.unwrap_or_default(),\n reason_of_failure: self.reason_of_failure,\n related_resources: self.related_resources,\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`LockServiceLinkedRoleOutput`](crate::operation::lock_service_linked_role::LockServiceLinkedRoleOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/lock_service_linked_role/_lock_service_linked_role_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/lock_service_linked_role/_lock_service_linked_role_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ab502cda7a7323d8486faf7da8695afe1ac4330388fb8799f1c2d1b94ccc7b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`TagResourceInput`](crate::operation::tag_resource::TagResourceInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::tag_resource::TagResourceInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::tag_resource::TagResourceInput {\n resource_arn: self.resource_arn,\n tags: self.tags,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`TagResourceInput`](crate::operation::tag_resource::TagResourceInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/tag_resource/_tag_resource_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/tag_resource/_tag_resource_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "62351062ea402c5b5dddefc0ef6e0384ab6a5657b53ba8742b60c1b5f81778eb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`UnlockServiceLinkedRoleInput`](crate::operation::unlock_service_linked_role::UnlockServiceLinkedRoleInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::unlock_service_linked_role::UnlockServiceLinkedRoleInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::unlock_service_linked_role::UnlockServiceLinkedRoleInput {\n role_arn: self.role_arn,\n deletion_status: self.deletion_status,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`UnlockServiceLinkedRoleInput`](crate::operation::unlock_service_linked_role::UnlockServiceLinkedRoleInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/unlock_service_linked_role/_unlock_service_linked_role_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/unlock_service_linked_role/_unlock_service_linked_role_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "26f85aff659bee48c86be7be9dafe3dcb6260c061964943db29f02e2c8b28104"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`UnlockServiceLinkedRoleOutput`](crate::operation::unlock_service_linked_role::UnlockServiceLinkedRoleOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::unlock_service_linked_role::UnlockServiceLinkedRoleOutput {\n crate::operation::unlock_service_linked_role::UnlockServiceLinkedRoleOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`UnlockServiceLinkedRoleOutput`](crate::operation::unlock_service_linked_role::UnlockServiceLinkedRoleOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/unlock_service_linked_role/_unlock_service_linked_role_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/unlock_service_linked_role/_unlock_service_linked_role_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3dbc0da838e92502df56c372dfd2884cd814cdd63ce511426ac9b817581b88de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`UntagResourceInput`](crate::operation::untag_resource::UntagResourceInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::untag_resource::UntagResourceInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::untag_resource::UntagResourceInput {\n resource_arn: self.resource_arn,\n tag_keys: self.tag_keys,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`UntagResourceInput`](crate::operation::untag_resource::UntagResourceInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/untag_resource/_untag_resource_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/untag_resource/_untag_resource_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c06d5f58ff678cb7f78482a25a494b0a64a1ee01465fa07813fbf46d843ae2ed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`UpdateCustomizationInput`](crate::operation::update_customization::UpdateCustomizationInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::update_customization::UpdateCustomizationInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::update_customization::UpdateCustomizationInput {\n identifier: self.identifier,\n operation: self.operation,\n client_token: self.client_token,\n data_reference: self.data_reference,\n version: self.version,\n include_repos: self.include_repos,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`UpdateCustomizationInput`](crate::operation::update_customization::UpdateCustomizationInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/update_customization/_update_customization_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/update_customization/_update_customization_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b023993ce8c177365d3e86f022116d6281e28d0762061bc7bfb4ec7dddf9759"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`UpdateCustomizationOutput`](crate::operation::update_customization::UpdateCustomizationOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::update_customization::UpdateCustomizationOutput {\n crate::operation::update_customization::UpdateCustomizationOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`UpdateCustomizationOutput`](crate::operation::update_customization::UpdateCustomizationOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/update_customization/_update_customization_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/update_customization/_update_customization_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aaa4f5dcde746045ebe31a0fb63688a19418a41c26e517055adff7360ef608e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`UpdateProfileInput`](crate::operation::update_profile::UpdateProfileInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::update_profile::UpdateProfileInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::update_profile::UpdateProfileInput {\n profile_arn: self.profile_arn,\n identity_source: self.identity_source,\n profile_name: self.profile_name,\n description: self.description,\n reference_tracker_configuration: self.reference_tracker_configuration,\n active_functionalities: self.active_functionalities,\n kms_key_arn: self.kms_key_arn,\n resource_policy: self.resource_policy,\n target_profile_type: self.target_profile_type,\n opt_in_features: self.opt_in_features,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`UpdateProfileInput`](crate::operation::update_profile::UpdateProfileInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/update_profile/_update_profile_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/update_profile/_update_profile_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9556dadaad10b116f3356e36d0b5a5c545133d8eab85207a503ef9b299e9e737"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`UpdateProfileOutput`](crate::operation::update_profile::UpdateProfileOutput).\nThis method will fail if any of the following fields are not set:\n- [`profile_arn`](crate::operation::update_profile::builders::UpdateProfileOutputBuilder::profile_arn)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::update_profile::UpdateProfileOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::update_profile::UpdateProfileOutput {\n profile_arn: self.profile_arn.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"profile_arn\",\n \"profile_arn was not specified but it is required when building UpdateProfileOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`UpdateProfileOutput`](crate::operation::update_profile::UpdateProfileOutput).\nThis method will fail if any of the following fields are not set:\n- [`profile_arn`](crate::operation::update_profile::builders::UpdateProfileOutputBuilder::profile_arn)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/update_profile/_update_profile_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/update_profile/_update_profile_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "383a4c8ca651af83982fa96a60dc4344b32778990fd8077122f22a820dd6cd08"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`VendKeyGrantInput`](crate::operation::vend_key_grant::VendKeyGrantInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::vend_key_grant::VendKeyGrantInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::vend_key_grant::VendKeyGrantInput {\n account_id: self.account_id,\n usecase: self.usecase,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`VendKeyGrantInput`](crate::operation::vend_key_grant::VendKeyGrantInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/vend_key_grant/_vend_key_grant_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/vend_key_grant/_vend_key_grant_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f1d139b42299838c39b095a72a2240733c18a4b5f0914a82436599284c78174"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`VendKeyGrantOutput`](crate::operation::vend_key_grant::VendKeyGrantOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::vend_key_grant::VendKeyGrantOutput {\n crate::operation::vend_key_grant::VendKeyGrantOutput {\n cmk_arn: self.cmk_arn,\n grant_id: self.grant_id,\n grant_token: self.grant_token,\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`VendKeyGrantOutput`](crate::operation::vend_key_grant::VendKeyGrantOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/operation/vend_key_grant/_vend_key_grant_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/operation/vend_key_grant/_vend_key_grant_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4958af6bdcafcdc5c83c262d89b9d9fbbc9cce6b064354be194dd99cfba9d7ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CodeStarReference`](crate::types::CodeStarReference). This method will fail if any of\nthe following fields are not set:\n- [`connection_arn`](crate::types::builders::CodeStarReferenceBuilder::connection_arn)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::CodeStarReference {\n connection_arn: self.connection_arn.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"connection_arn\",\n \"connection_arn was not specified but it is required when building CodeStarReference\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CodeStarReference`](crate::types::CodeStarReference). This method will fail if any of\nthe following fields are not set:\n- [`connection_arn`](crate::types::builders::CodeStarReferenceBuilder::connection_arn)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_code_star_reference.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_code_star_reference.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9246a80b9846d550f2c79cc7d2146c85b639aa1607816a6f6f705ae05826a2ea"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_group\n\nDocumentation:\nTries to convert the enum instance into\n[`Group`](crate::types::CustomizationPermission::Group), extracting the inner\n[`String`](::std::string::String). Returns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_group(&self) -> ::std::result::Result<&::std::string::String, &Self> {\n if let CustomizationPermission::Group(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_group", "docstring": "Tries to convert the enum instance into\n[`Group`](crate::types::CustomizationPermission::Group), extracting the inner\n[`String`](::std::string::String). Returns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_customization_permission.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_customization_permission.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3d82ab0ad0b618a3faac76ff28397ce5d29c08aef30afb26b57324f1db5bc4e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_user\n\nDocumentation:\nTries to convert the enum instance into\n[`User`](crate::types::CustomizationPermission::User), extracting the inner\n[`String`](::std::string::String). Returns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_user(&self) -> ::std::result::Result<&::std::string::String, &Self> {\n if let CustomizationPermission::User(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_user", "docstring": "Tries to convert the enum instance into\n[`User`](crate::types::CustomizationPermission::User), extracting the inner\n[`String`](::std::string::String). Returns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_customization_permission.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_customization_permission.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a6d3c0e456112b8225db0976b2a1d2f0c4fc6eb860761b9c6e572fdbabe2f187"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CustomizationSummary`](crate::types::CustomizationSummary). This method will fail if\nany of the following fields are not set:\n- [`arn`](crate::types::builders::CustomizationSummaryBuilder::arn)\n- [`customization_name`](crate::types::builders::CustomizationSummaryBuilder::customization_name)\n- [`status`](crate::types::builders::CustomizationSummaryBuilder::status)\n- [`updated_at`](crate::types::builders::CustomizationSummaryBuilder::updated_at)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::CustomizationSummary {\n arn: self.arn.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"arn\",\n \"arn was not specified but it is required when building CustomizationSummary\",\n )\n })?,\n version: self.version,\n customization_name: self.customization_name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"customization_name\",\n \"customization_name was not specified but it is required when building CustomizationSummary\",\n )\n })?,\n description: self.description,\n status: self.status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"status\",\n \"status was not specified but it is required when building CustomizationSummary\",\n )\n })?,\n updated_at: self.updated_at.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"updated_at\",\n \"updated_at was not specified but it is required when building CustomizationSummary\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CustomizationSummary`](crate::types::CustomizationSummary). This method will fail if\nany of the following fields are not set:\n- [`arn`](crate::types::builders::CustomizationSummaryBuilder::arn)\n- [`customization_name`](crate::types::builders::CustomizationSummaryBuilder::customization_name)\n- [`status`](crate::types::builders::CustomizationSummaryBuilder::status)\n- [`updated_at`](crate::types::builders::CustomizationSummaryBuilder::updated_at)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_customization_summary.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_customization_summary.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a64d9fa400b2ee908d54504100caf018705a3cf41909d4fe7c585365c307f38"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`CustomizationVersionSummary`](crate::types::CustomizationVersionSummary). This method\nwill fail if any of the following fields are not set:\n- [`version`](crate::types::builders::CustomizationVersionSummaryBuilder::version)\n- [`status`](crate::types::builders::CustomizationVersionSummaryBuilder::status)\n- [`data_reference`](crate::types::builders::CustomizationVersionSummaryBuilder::data_reference)\n- [`updated_at`](crate::types::builders::CustomizationVersionSummaryBuilder::updated_at)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::types::CustomizationVersionSummary,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::types::CustomizationVersionSummary {\n version: self.version.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"version\",\n \"version was not specified but it is required when building CustomizationVersionSummary\",\n )\n })?,\n base_version: self.base_version,\n status: self.status.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"status\",\n \"status was not specified but it is required when building CustomizationVersionSummary\",\n )\n })?,\n data_reference: self.data_reference.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"data_reference\",\n \"data_reference was not specified but it is required when building CustomizationVersionSummary\",\n )\n })?,\n updated_at: self.updated_at.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"updated_at\",\n \"updated_at was not specified but it is required when building CustomizationVersionSummary\",\n )\n })?,\n evaluation_metrics: self.evaluation_metrics,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`CustomizationVersionSummary`](crate::types::CustomizationVersionSummary). This method\nwill fail if any of the following fields are not set:\n- [`version`](crate::types::builders::CustomizationVersionSummaryBuilder::version)\n- [`status`](crate::types::builders::CustomizationVersionSummaryBuilder::status)\n- [`data_reference`](crate::types::builders::CustomizationVersionSummaryBuilder::data_reference)\n- [`updated_at`](crate::types::builders::CustomizationVersionSummaryBuilder::updated_at)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_customization_version_summary.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_customization_version_summary.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "90c6de5cb4d4706d6092d2c5ee2580db61714eabd4b7975d62d16d1c0154d422"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_code_star_reference\n\nDocumentation:\nTries to convert the enum instance into\n[`CodeStarReference`](crate::types::DataReference::CodeStarReference), extracting the inner\n[`CodeStarReference`](crate::types::CodeStarReference). Returns `Err(&Self)` if it can't\nbe converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_code_star_reference(&self) -> ::std::result::Result<&crate::types::CodeStarReference, &Self> {\n if let DataReference::CodeStarReference(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_code_star_reference", "docstring": "Tries to convert the enum instance into\n[`CodeStarReference`](crate::types::DataReference::CodeStarReference), extracting the inner\n[`CodeStarReference`](crate::types::CodeStarReference). Returns `Err(&Self)` if it can't\nbe converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_data_reference.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_data_reference.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "829f3349088fdefcf838099e168052e5c06d3513d1934fa2785078ff8347d393"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_s3_reference\n\nDocumentation:\nTries to convert the enum instance into\n[`S3Reference`](crate::types::DataReference::S3Reference), extracting the inner\n[`S3Reference`](crate::types::S3Reference). Returns `Err(&Self)` if it can't be\nconverted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_s3_reference(&self) -> ::std::result::Result<&crate::types::S3Reference, &Self> {\n if let DataReference::S3Reference(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_s3_reference", "docstring": "Tries to convert the enum instance into\n[`S3Reference`](crate::types::DataReference::S3Reference), extracting the inner\n[`S3Reference`](crate::types::S3Reference). Returns `Err(&Self)` if it can't be\nconverted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_data_reference.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_data_reference.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba8d9614344b3c9c8240bf9f0b3b68e5fb85a572a7285ac547e52448d148fef6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`EvaluationMetrics`](crate::types::EvaluationMetrics). This method will fail if any of\nthe following fields are not set:\n- [`composite_score`](crate::types::builders::EvaluationMetricsBuilder::composite_score)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::EvaluationMetrics {\n composite_score: self.composite_score.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"composite_score\",\n \"composite_score was not specified but it is required when building EvaluationMetrics\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`EvaluationMetrics`](crate::types::EvaluationMetrics). This method will fail if any of\nthe following fields are not set:\n- [`composite_score`](crate::types::builders::EvaluationMetricsBuilder::composite_score)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_evaluation_metrics.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_evaluation_metrics.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "288a06c28d110577db3fd47909fbe1418ea58cda0e4e951ca289d7ebac70ccaa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ExternalIdentitySource`](crate::types::ExternalIdentitySource). This method will fail\nif any of the following fields are not set:\n- [`issuer_url`](crate::types::builders::ExternalIdentitySourceBuilder::issuer_url)\n- [`client_id`](crate::types::builders::ExternalIdentitySourceBuilder::client_id)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result\n {\n ::std::result::Result::Ok(crate::types::ExternalIdentitySource {\n issuer_url: self.issuer_url.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"issuer_url\",\n \"issuer_url was not specified but it is required when building ExternalIdentitySource\",\n )\n })?,\n client_id: self.client_id.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"client_id\",\n \"client_id was not specified but it is required when building ExternalIdentitySource\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ExternalIdentitySource`](crate::types::ExternalIdentitySource). This method will fail\nif any of the following fields are not set:\n- [`issuer_url`](crate::types::builders::ExternalIdentitySourceBuilder::issuer_url)\n- [`client_id`](crate::types::builders::ExternalIdentitySourceBuilder::client_id)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_external_identity_source.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_external_identity_source.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "71e4a0697e7351a0b664c56f20fd4cb44bdc696ce34bbca1ce52b73d197368dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_external_identity_source\n\nDocumentation:\nTries to convert the enum instance into\n[`ExternalIdentitySource`](crate::types::IdentitySource::ExternalIdentitySource), extracting\nthe inner [`ExternalIdentitySource`](crate::types::ExternalIdentitySource).\nReturns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_external_identity_source(&self) -> ::std::result::Result<&crate::types::ExternalIdentitySource, &Self> {\n if let IdentitySource::ExternalIdentitySource(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_external_identity_source", "docstring": "Tries to convert the enum instance into\n[`ExternalIdentitySource`](crate::types::IdentitySource::ExternalIdentitySource), extracting\nthe inner [`ExternalIdentitySource`](crate::types::ExternalIdentitySource).\nReturns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_identity_source.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_identity_source.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b7121934d908e79a3603b65a16a2d1ca58a0af55f5afc67ae7d4b589576bea20"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_sso_identity_source\n\nDocumentation:\nTries to convert the enum instance into\n[`SsoIdentitySource`](crate::types::IdentitySource::SsoIdentitySource), extracting the inner\n[`SsoIdentitySource`](crate::types::SsoIdentitySource). Returns `Err(&Self)` if it can't\nbe converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_sso_identity_source(&self) -> ::std::result::Result<&crate::types::SsoIdentitySource, &Self> {\n if let IdentitySource::SsoIdentitySource(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_sso_identity_source", "docstring": "Tries to convert the enum instance into\n[`SsoIdentitySource`](crate::types::IdentitySource::SsoIdentitySource), extracting the inner\n[`SsoIdentitySource`](crate::types::SsoIdentitySource). Returns `Err(&Self)` if it can't\nbe converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_identity_source.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_identity_source.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f3e4b480810a3a5ad9f481aba8c9b878cff4db0bca20f1ba3209f667cf04c18"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Recommendation`](crate::types::Recommendation).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::RecommendationBuilder::content)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Recommendation {\n content: self.content.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"content\",\n \"content was not specified but it is required when building Recommendation\",\n )\n })?,\n references: self.references,\n most_relevant_missing_imports: self.most_relevant_missing_imports,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Recommendation`](crate::types::Recommendation).\nThis method will fail if any of the following fields are not set:\n- [`content`](crate::types::builders::RecommendationBuilder::content)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_recommendation.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_recommendation.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e48d959bb4045d0f9ed035e24cd1f41d28ab4c47b169047e8a0fb8474af5546"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`S3Reference`](crate::types::S3Reference).\nThis method will fail if any of the following fields are not set:\n- [`uri`](crate::types::builders::S3ReferenceBuilder::uri)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::S3Reference {\n uri: self.uri.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"uri\",\n \"uri was not specified but it is required when building S3Reference\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`S3Reference`](crate::types::S3Reference).\nThis method will fail if any of the following fields are not set:\n- [`uri`](crate::types::builders::S3ReferenceBuilder::uri)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_s3_reference.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_s3_reference.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c01627199c780ee5aa6f28fc28e5db5e4ac54a32be0a72d32d70a2fcd3eafe49"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`SsoIdentitySource`](crate::types::SsoIdentitySource). This method will fail if any of\nthe following fields are not set:\n- [`instance_arn`](crate::types::builders::SsoIdentitySourceBuilder::instance_arn)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::SsoIdentitySource {\n instance_arn: self.instance_arn.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"instance_arn\",\n \"instance_arn was not specified but it is required when building SsoIdentitySource\",\n )\n })?,\n sso_region: self.sso_region,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`SsoIdentitySource`](crate::types::SsoIdentitySource). This method will fail if any of\nthe following fields are not set:\n- [`instance_arn`](crate::types::builders::SsoIdentitySourceBuilder::instance_arn)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_sso_identity_source.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_sso_identity_source.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8d28ccff4470a1b63c0f8a2f57d8406353a17dcfccebdd289c99b281979be5a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Tag`](crate::types::Tag).\nThis method will fail if any of the following fields are not set:\n- [`key`](crate::types::builders::TagBuilder::key)\n- [`value`](crate::types::builders::TagBuilder::value)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::Tag {\n key: self.key.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"key\",\n \"key was not specified but it is required when building Tag\",\n )\n })?,\n value: self.value.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"value\",\n \"value was not specified but it is required when building Tag\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Tag`](crate::types::Tag).\nThis method will fail if any of the following fields are not set:\n- [`key`](crate::types::builders::TagBuilder::key)\n- [`value`](crate::types::builders::TagBuilder::value)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/_tag.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/_tag.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "76127efab20c143d380ab971503b4ecec0b4c31372910169b1d2fd4ca4040365"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ServiceLinkedRoleLockClientError`](crate::types::error::ServiceLinkedRoleLockClientError).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::error::ServiceLinkedRoleLockClientError {\n crate::types::error::ServiceLinkedRoleLockClientError {\n message: self.message,\n meta: self.meta.unwrap_or_default(),\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ServiceLinkedRoleLockClientError`](crate::types::error::ServiceLinkedRoleLockClientError).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/error/_service_linked_role_lock_client_exception.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/error/_service_linked_role_lock_client_exception.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "882a622a2d7736116b0df1887c8a51acc50cbdac520104a9025f1a36afd59746"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`ServiceLinkedRoleLockServiceError`](crate::types::error::ServiceLinkedRoleLockServiceError).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::error::ServiceLinkedRoleLockServiceError {\n crate::types::error::ServiceLinkedRoleLockServiceError {\n message: self.message,\n meta: self.meta.unwrap_or_default(),\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`ServiceLinkedRoleLockServiceError`](crate::types::error::ServiceLinkedRoleLockServiceError).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-consolas-client/src/types/error/_service_linked_role_lock_service_exception.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-consolas-client/src/types/error/_service_linked_role_lock_service_exception.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63b7a4a306a89d72ec6aeb75d7b94902bda12c138a2b93a266417b1253195903"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_code_from_commands\n\nDocumentation:\nConstructs a fluent builder for the\n[`GenerateCodeFromCommands`](crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`output_format(OutputFormat)`](crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsFluentBuilder::output_format) / [`set_output_format(Option)`](crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsFluentBuilder::set_output_format):
required: **true**
Format of the output - language/format eg. typescript/cdk
\n- [`commands(CommandInput)`](crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsFluentBuilder::commands) / [`set_commands(Option)`](crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsFluentBuilder::set_commands):
required: **true**
CommandInput can be extended to either a list of strings or a single string.
\n- On success, responds with\n[`GenerateCodeFromCommandsOutput`](crate::operation::generate_code_from_commands::GenerateCodeFromCommandsOutput)\nwith field(s):\n- [`generated_code_from_commands_response(EventReceiver)`](crate::operation::generate_code_from_commands::GenerateCodeFromCommandsOutput::generated_code_from_commands_response): Streaming events from UniDirectional streaming infrastructure code generation APIs.\n- On failure, responds with [`SdkError`](crate::operation::generate_code_from_commands::GenerateCodeFromCommandsError)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate_code_from_commands(\n &self,\n ) -> crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsFluentBuilder {\n crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsFluentBuilder::new(\n self.handle.clone(),\n )\n }\n```"}], "func_name": "generate_code_from_commands", "docstring": "Constructs a fluent builder for the\n[`GenerateCodeFromCommands`](crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsFluentBuilder)\noperation.\n\n- The fluent builder is configurable:\n- [`output_format(OutputFormat)`](crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsFluentBuilder::output_format) / [`set_output_format(Option)`](crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsFluentBuilder::set_output_format):
required: **true**
Format of the output - language/format eg. typescript/cdk
\n- [`commands(CommandInput)`](crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsFluentBuilder::commands) / [`set_commands(Option)`](crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsFluentBuilder::set_commands):
required: **true**
CommandInput can be extended to either a list of strings or a single string.
\n- On success, responds with\n[`GenerateCodeFromCommandsOutput`](crate::operation::generate_code_from_commands::GenerateCodeFromCommandsOutput)\nwith field(s):\n- [`generated_code_from_commands_response(EventReceiver)`](crate::operation::generate_code_from_commands::GenerateCodeFromCommandsOutput::generated_code_from_commands_response): Streaming events from UniDirectional streaming infrastructure code generation APIs.\n- On failure, responds with [`SdkError`](crate::operation::generate_code_from_commands::GenerateCodeFromCommandsError)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-qdeveloper-streaming-client/src/client/generate_code_from_commands.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-qdeveloper-streaming-client/src/client/generate_code_from_commands.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8f429e14f58a8f17603064a9b227816e7248ee646a2a4c0891e284fe2bb7902e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: commands\n\nDocumentation:\nCommandInput can be extended to either a list of strings or a single string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn commands(mut self, input: crate::types::CommandInput) -> Self {\n self.inner = self.inner.commands(input);\n self\n }\n```"}], "func_name": "commands", "docstring": "CommandInput can be extended to either a list of strings or a single string.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-qdeveloper-streaming-client/src/operation/generate_code_from_commands/builders.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-qdeveloper-streaming-client/src/operation/generate_code_from_commands/builders.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6fbc24fc36b997329b760e611aea6ed1bd4597c8ac72ad567382c6a056bd16fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: commands\n\nDocumentation:\nCommandInput can be extended to either a list of strings or a single string.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn commands(mut self, input: crate::types::CommandInput) -> Self {\n self.commands = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "commands", "docstring": "CommandInput can be extended to either a list of strings or a single string.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-qdeveloper-streaming-client/src/operation/generate_code_from_commands/_generate_code_from_commands_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-qdeveloper-streaming-client/src/operation/generate_code_from_commands/_generate_code_from_commands_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "470c890dc28013106f9b67cb319e2ec8ab18ef9f1dd7124605fae84823e4b454"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GenerateCodeFromCommandsInput`](crate::operation::generate_code_from_commands::GenerateCodeFromCommandsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::generate_code_from_commands::GenerateCodeFromCommandsInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(\n crate::operation::generate_code_from_commands::GenerateCodeFromCommandsInput {\n output_format: self.output_format,\n commands: self.commands,\n },\n )\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GenerateCodeFromCommandsInput`](crate::operation::generate_code_from_commands::GenerateCodeFromCommandsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-qdeveloper-streaming-client/src/operation/generate_code_from_commands/_generate_code_from_commands_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-qdeveloper-streaming-client/src/operation/generate_code_from_commands/_generate_code_from_commands_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "83a1ed2bf17adab6586efb4046d503dafbfad375feedb500739f43ea0ac8047e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generated_code_from_commands_response\n\nDocumentation:\nStreaming events from UniDirectional streaming infrastructure code generation APIs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generated_code_from_commands_response(\n &self,\n ) -> &crate::event_receiver::EventReceiver<\n crate::types::GenerateCodeFromCommandsResponseStream,\n crate::types::error::GenerateCodeFromCommandsResponseStreamError,\n > {\n &self.generated_code_from_commands_response\n }\n```"}], "func_name": "generated_code_from_commands_response", "docstring": "Streaming events from UniDirectional streaming infrastructure code generation APIs.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-qdeveloper-streaming-client/src/operation/generate_code_from_commands/_generate_code_from_commands_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-qdeveloper-streaming-client/src/operation/generate_code_from_commands/_generate_code_from_commands_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "08088cddd945bd8bd45cf49397d9923a49f3d7f689df957c6b24c2eb01c3b61d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generated_code_from_commands_response\n\nDocumentation:\nStreaming events from UniDirectional streaming infrastructure code generation APIs.\nThis field is required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generated_code_from_commands_response(\n mut self,\n input: crate::event_receiver::EventReceiver<\n crate::types::GenerateCodeFromCommandsResponseStream,\n crate::types::error::GenerateCodeFromCommandsResponseStreamError,\n >,\n ) -> Self {\n self.generated_code_from_commands_response = ::std::option::Option::Some(input);\n self\n }\n```"}], "func_name": "generated_code_from_commands_response", "docstring": "Streaming events from UniDirectional streaming infrastructure code generation APIs.\nThis field is required.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-qdeveloper-streaming-client/src/operation/generate_code_from_commands/_generate_code_from_commands_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-qdeveloper-streaming-client/src/operation/generate_code_from_commands/_generate_code_from_commands_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3e9d78f0ead5197764647af6966542fce200be824d817f1ab872cf96805957d2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`GenerateCodeFromCommandsOutput`](crate::operation::generate_code_from_commands::GenerateCodeFromCommandsOutput).\nThis method will fail if any of the following fields are not set:\n- [`generated_code_from_commands_response`](crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsOutputBuilder::generated_code_from_commands_response)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::generate_code_from_commands::GenerateCodeFromCommandsOutput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::generate_code_from_commands::GenerateCodeFromCommandsOutput {\n generated_code_from_commands_response: self.generated_code_from_commands_response.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"generated_code_from_commands_response\",\n \"generated_code_from_commands_response was not specified but it is required when building GenerateCodeFromCommandsOutput\",\n )\n })?,\n _request_id: self._request_id,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`GenerateCodeFromCommandsOutput`](crate::operation::generate_code_from_commands::GenerateCodeFromCommandsOutput).\nThis method will fail if any of the following fields are not set:\n- [`generated_code_from_commands_response`](crate::operation::generate_code_from_commands::builders::GenerateCodeFromCommandsOutputBuilder::generated_code_from_commands_response)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-qdeveloper-streaming-client/src/operation/generate_code_from_commands/_generate_code_from_commands_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-qdeveloper-streaming-client/src/operation/generate_code_from_commands/_generate_code_from_commands_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "af2f94168eee47e6c89fcc7008a8c72ddbbd331769fb9a20fe4a8d9eded586a0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_commands_list\n\nDocumentation:\nTries to convert the enum instance into\n[`CommandsList`](crate::types::CommandInput::CommandsList), extracting the inner\n[`Vec`](::std::vec::Vec). Returns `Err(&Self)` if it can't be converted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_commands_list(&self) -> ::std::result::Result<&::std::vec::Vec<::std::string::String>, &Self> {\n if let CommandInput::CommandsList(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_commands_list", "docstring": "Tries to convert the enum instance into\n[`CommandsList`](crate::types::CommandInput::CommandsList), extracting the inner\n[`Vec`](::std::vec::Vec). Returns `Err(&Self)` if it can't be converted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-qdeveloper-streaming-client/src/types/_command_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-qdeveloper-streaming-client/src/types/_command_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e86c0d721c27649be2ab22d51de5bd0960f48ec6233e597028e2fe6b75bee328"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_code_event\n\nDocumentation:\nTries to convert the enum instance into\n[`CodeEvent`](crate::types::GenerateCodeFromCommandsResponseStream::CodeEvent), extracting\nthe inner [`CodeEvent`](crate::types::CodeEvent). Returns `Err(&Self)` if it can't be\nconverted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_code_event(&self) -> ::std::result::Result<&crate::types::CodeEvent, &Self> {\n if let GenerateCodeFromCommandsResponseStream::CodeEvent(val) = &self {\n ::std::result::Result::Ok(val)\n } else {\n ::std::result::Result::Err(self)\n }\n }\n```"}], "func_name": "as_code_event", "docstring": "Tries to convert the enum instance into\n[`CodeEvent`](crate::types::GenerateCodeFromCommandsResponseStream::CodeEvent), extracting\nthe inner [`CodeEvent`](crate::types::CodeEvent). Returns `Err(&Self)` if it can't be\nconverted.", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-qdeveloper-streaming-client/src/types/_generate_code_from_commands_response_stream.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-qdeveloper-streaming-client/src/types/_generate_code_from_commands_response_stream.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d38ec7b825665289668997fe9614b452541215d4a3a382eb56cf7da2d32dfa7c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_timeout_config\n\nDocumentation:\nSet the timeout_config for the builder\n\n# Examples\n\n```no_run\n# use std::time::Duration;\nuse amzn_toolkit_telemetry_client::config::timeout::TimeoutConfig;\nuse amzn_toolkit_telemetry_client::config::{\nBuilder,\nConfig,\n};\n\nfn set_request_timeout(builder: &mut Builder) {\nlet timeout_config = TimeoutConfig::builder()\n.operation_attempt_timeout(Duration::from_secs(1))\n.build();\nbuilder.set_timeout_config(Some(timeout_config));\n}\n\nlet mut builder = Config::builder();\nset_request_timeout(&mut builder);\nlet config = builder.build();\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_timeout_config(\n &mut self,\n timeout_config: ::std::option::Option<::aws_smithy_types::timeout::TimeoutConfig>,\n ) -> &mut Self {\n timeout_config.map(|t| self.config.store_put(t));\n self\n }\n```"}], "func_name": "set_timeout_config", "docstring": "Set the timeout_config for the builder\n\n# Examples\n\n```no_run\n# use std::time::Duration;\nuse amzn_toolkit_telemetry_client::config::timeout::TimeoutConfig;\nuse amzn_toolkit_telemetry_client::config::{\nBuilder,\nConfig,\n};\n\nfn set_request_timeout(builder: &mut Builder) {\nlet timeout_config = TimeoutConfig::builder()\n.operation_attempt_timeout(Duration::from_secs(1))\n.build();\nbuilder.set_timeout_config(Some(timeout_config));\n}\n\nlet mut builder = Config::builder();\nset_request_timeout(&mut builder);\nlet config = builder.build();\n```", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-toolkit-telemetry-client/src/config.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-toolkit-telemetry-client/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "313165457266d5b1816f215d28edebf96bb183a5ecad4e7a9fb53a6134c1a243"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: metadata\n\nDocumentation:\nAppends an item to `metadata`.\n\nTo override the contents of this collection use [`set_metadata`](Self::set_metadata).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn metadata(mut self, input: crate::types::MetadataEntry) -> Self {\n let mut v = self.metadata.unwrap_or_default();\n v.push(input);\n self.metadata = ::std::option::Option::Some(v);\n self\n }\n```"}], "func_name": "metadata", "docstring": "Appends an item to `metadata`.\n\nTo override the contents of this collection use [`set_metadata`](Self::set_metadata).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-toolkit-telemetry-client/src/operation/post_error_report/_post_error_report_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-toolkit-telemetry-client/src/operation/post_error_report/_post_error_report_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "283d5431d678eb78eebf39dbb2b640825c4a559b0d76897e36a44b7d736290b1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`PostErrorReportInput`](crate::operation::post_error_report::PostErrorReportInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::post_error_report::PostErrorReportInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::post_error_report::PostErrorReportInput {\n aws_product: self.aws_product,\n aws_product_version: self.aws_product_version,\n metadata: self.metadata,\n userdata: self.userdata,\n error_details: self.error_details,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`PostErrorReportInput`](crate::operation::post_error_report::PostErrorReportInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-toolkit-telemetry-client/src/operation/post_error_report/_post_error_report_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-toolkit-telemetry-client/src/operation/post_error_report/_post_error_report_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "77792c301507ce3a37b77dcb3f01e261a3a791ee9ae2d83684cecec8b93f90f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`PostErrorReportOutput`](crate::operation::post_error_report::PostErrorReportOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::post_error_report::PostErrorReportOutput {\n crate::operation::post_error_report::PostErrorReportOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`PostErrorReportOutput`](crate::operation::post_error_report::PostErrorReportOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-toolkit-telemetry-client/src/operation/post_error_report/_post_error_report_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-toolkit-telemetry-client/src/operation/post_error_report/_post_error_report_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d24425b4f4da5945bd1637ad0d09c86ef36bcf0679c0b0f138ad0dd452155ad6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`PostFeedbackInput`](crate::operation::post_feedback::PostFeedbackInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::post_feedback::PostFeedbackInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::post_feedback::PostFeedbackInput {\n aws_product: self.aws_product,\n aws_product_version: self.aws_product_version,\n os: self.os,\n os_version: self.os_version,\n parent_product: self.parent_product,\n parent_product_version: self.parent_product_version,\n metadata: self.metadata,\n sentiment: self.sentiment,\n comment: self.comment,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`PostFeedbackInput`](crate::operation::post_feedback::PostFeedbackInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-toolkit-telemetry-client/src/operation/post_feedback/_post_feedback_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-toolkit-telemetry-client/src/operation/post_feedback/_post_feedback_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "528920fcab16441deb8ab0e432b88d9e1cda00b758e6613875418d3992be1cc1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`PostFeedbackOutput`](crate::operation::post_feedback::PostFeedbackOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::post_feedback::PostFeedbackOutput {\n crate::operation::post_feedback::PostFeedbackOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`PostFeedbackOutput`](crate::operation::post_feedback::PostFeedbackOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-toolkit-telemetry-client/src/operation/post_feedback/_post_feedback_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-toolkit-telemetry-client/src/operation/post_feedback/_post_feedback_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f1f77b73d52fefe76b45b4933bb5952a0d5abeba8a65378a3c812bdc9be8035"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`PostMetricsInput`](crate::operation::post_metrics::PostMetricsInput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result<\n crate::operation::post_metrics::PostMetricsInput,\n ::aws_smithy_types::error::operation::BuildError,\n > {\n ::std::result::Result::Ok(crate::operation::post_metrics::PostMetricsInput {\n aws_product: self.aws_product,\n aws_product_version: self.aws_product_version,\n client_id: self.client_id,\n os: self.os,\n os_architecture: self.os_architecture,\n os_version: self.os_version,\n parent_product: self.parent_product,\n parent_product_version: self.parent_product_version,\n metric_data: self.metric_data,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`PostMetricsInput`](crate::operation::post_metrics::PostMetricsInput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-toolkit-telemetry-client/src/operation/post_metrics/_post_metrics_input.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-toolkit-telemetry-client/src/operation/post_metrics/_post_metrics_input.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63e9a2c65a4a1e093b9ff8bab7e7e1e31970b363c0127775cb1d6f9f87ab485e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a\n[`PostMetricsOutput`](crate::operation::post_metrics::PostMetricsOutput).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::operation::post_metrics::PostMetricsOutput {\n crate::operation::post_metrics::PostMetricsOutput {\n _request_id: self._request_id,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a\n[`PostMetricsOutput`](crate::operation::post_metrics::PostMetricsOutput).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-toolkit-telemetry-client/src/operation/post_metrics/_post_metrics_output.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-toolkit-telemetry-client/src/operation/post_metrics/_post_metrics_output.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c575a55c298fcf682d1c57bbe6391e0ede3f8ef4f0657f289c7dce2fe48fb5d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`ErrorDetails`](crate::types::ErrorDetails).\nThis method will fail if any of the following fields are not set:\n- [`command`](crate::types::builders::ErrorDetailsBuilder::command)\n- [`r#type`](crate::types::builders::ErrorDetailsBuilder::r#type)\n- [`stack_trace`](crate::types::builders::ErrorDetailsBuilder::stack_trace)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::ErrorDetails {\n command: self.command.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"command\",\n \"command was not specified but it is required when building ErrorDetails\",\n )\n })?,\n epoch_timestamp: self.epoch_timestamp.unwrap_or_default(),\n r#type: self.r#type.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"r#type\",\n \"r#type was not specified but it is required when building ErrorDetails\",\n )\n })?,\n message: self.message,\n stack_trace: self.stack_trace.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"stack_trace\",\n \"stack_trace was not specified but it is required when building ErrorDetails\",\n )\n })?,\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`ErrorDetails`](crate::types::ErrorDetails).\nThis method will fail if any of the following fields are not set:\n- [`command`](crate::types::builders::ErrorDetailsBuilder::command)\n- [`r#type`](crate::types::builders::ErrorDetailsBuilder::r#type)\n- [`stack_trace`](crate::types::builders::ErrorDetailsBuilder::stack_trace)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-toolkit-telemetry-client/src/types/_error_details.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-toolkit-telemetry-client/src/types/_error_details.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c76fbdff8fde9cfe01d693812fec5506aac821a55f39ea9db355da19102c32b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`MetadataEntry`](crate::types::MetadataEntry).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::MetadataEntry {\n crate::types::MetadataEntry {\n key: self.key,\n value: self.value,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`MetadataEntry`](crate::types::MetadataEntry).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-toolkit-telemetry-client/src/types/_metadata_entry.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-toolkit-telemetry-client/src/types/_metadata_entry.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7a06ee3f532ea1d75a253878866a6355f9fccb271b546cd252618da0c6c4174c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`MetricDatum`](crate::types::MetricDatum).\nThis method will fail if any of the following fields are not set:\n- [`metric_name`](crate::types::builders::MetricDatumBuilder::metric_name)\n- [`unit`](crate::types::builders::MetricDatumBuilder::unit)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(\n self,\n ) -> ::std::result::Result {\n ::std::result::Result::Ok(crate::types::MetricDatum {\n metric_name: self.metric_name.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"metric_name\",\n \"metric_name was not specified but it is required when building MetricDatum\",\n )\n })?,\n epoch_timestamp: self.epoch_timestamp.unwrap_or_default(),\n unit: self.unit.ok_or_else(|| {\n ::aws_smithy_types::error::operation::BuildError::missing_field(\n \"unit\",\n \"unit was not specified but it is required when building MetricDatum\",\n )\n })?,\n value: self.value.unwrap_or_default(),\n metadata: self.metadata,\n passive: self.passive.unwrap_or_default(),\n })\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`MetricDatum`](crate::types::MetricDatum).\nThis method will fail if any of the following fields are not set:\n- [`metric_name`](crate::types::builders::MetricDatumBuilder::metric_name)\n- [`unit`](crate::types::builders::MetricDatumBuilder::unit)", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-toolkit-telemetry-client/src/types/_metric_datum.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-toolkit-telemetry-client/src/types/_metric_datum.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ce04d429d7a1fd84e4d379f8fb6cbf2f2dd1b90ee8943aaf4eb7bc9736cc73b7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nConsumes the builder and constructs a [`Userdata`](crate::types::Userdata).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> crate::types::Userdata {\n crate::types::Userdata {\n email: self.email,\n comment: self.comment,\n }\n }\n```"}], "func_name": "build", "docstring": "Consumes the builder and constructs a [`Userdata`](crate::types::Userdata).", "repo": "aws/amazon-q-developer-cli", "path": "crates/amzn-toolkit-telemetry-client/src/types/_userdata.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/amzn-toolkit-telemetry-client/src/types/_userdata.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3ac5322ba3944830da77a37a2462fd1d5d5f994c68acb53758e279f9fb956a46"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_log_level\n\nDocumentation:\nGet the current log level by first seeing if it is set in application, then environment, then\notherwise using the default\n\n# Returns\n\nReturns a string identifying the current log level.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_log_level() -> String {\n Q_LOG_LEVEL_GLOBAL\n .lock()\n .unwrap()\n .clone()\n .unwrap_or_else(|| std::env::var(Q_LOG_LEVEL).unwrap_or_else(|_| DEFAULT_FILTER.to_string()))\n}\n```"}], "func_name": "get_log_level", "docstring": "Get the current log level by first seeing if it is set in application, then environment, then\notherwise using the default\n\n# Returns\n\nReturns a string identifying the current log level.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/logging.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/logging.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f9c4fb2e6ba2b71e1af1563d55645f46957eeaafeb9e2e7ccc710549db29f1e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_log_level\n\nDocumentation:\nSet the log level to the given level.\n\n# Returns\n\nOn success, returns the old log level.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_log_level(level: String) -> Result {\n info!(\"Setting log level to {level:?}\");\n\n let old_level = get_log_level();\n *Q_LOG_LEVEL_GLOBAL.lock().unwrap() = Some(level);\n\n let filter_layer = create_filter_layer();\n *MAX_LEVEL.lock().unwrap() = filter_layer.max_level_hint();\n\n ENV_FILTER_RELOADABLE_HANDLE\n .lock()\n .unwrap()\n .as_ref()\n .expect(\"set_log_level must not be called before logging is initialized\")\n .reload(filter_layer)?;\n\n Ok(old_level)\n}\n```"}], "func_name": "set_log_level", "docstring": "Set the log level to the given level.\n\n# Returns\n\nOn success, returns the old log level.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/logging.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/logging.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f8e3e716a28bf19b9d89ab2dbf2416aec8a4540618fa66d34f9606313c4915df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_log_level_max\n\nDocumentation:\nGet the current max log level\n\n# Returns\n\nThe max log level which is set every time the log level is set.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_log_level_max() -> LevelFilter {\n let max_level = *MAX_LEVEL.lock().unwrap();\n match max_level {\n Some(level) => level,\n None => {\n let filter_layer = create_filter_layer();\n *MAX_LEVEL.lock().unwrap() = filter_layer.max_level_hint();\n filter_layer.max_level_hint().unwrap_or(DEFAULT_FILTER)\n },\n }\n}\n```"}], "func_name": "get_log_level_max", "docstring": "Get the current max log level\n\n# Returns\n\nThe max log level which is set every time the log level is set.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/logging.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/logging.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44b4897f0fef1c18895959c660f9c21a2cd5378998c6b05f0c69620a778dc16d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nBased on code the code for\n[aws_config::default_provider::credentials::DefaultCredentialsChain]: \n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn new() -> Self {\n let region = DefaultRegionChain::builder().build().region().await;\n let config = ProviderConfig::default().with_region(region.clone());\n\n let env_provider = EnvironmentVariableCredentialsProvider::new();\n let profile_provider = ProfileFileCredentialsProvider::builder().configure(&config).build();\n let web_identity_token_provider = WebIdentityTokenCredentialsProvider::builder()\n .configure(&config)\n .build();\n let imds_provider = ImdsCredentialsProvider::builder().configure(&config).build();\n let ecs_provider = EcsCredentialsProvider::builder().configure(&config).build();\n\n let mut provider_chain = CredentialsProviderChain::first_try(\"Environment\", env_provider);\n\n provider_chain = provider_chain\n .or_else(\"Profile\", profile_provider)\n .or_else(\"WebIdentityToken\", web_identity_token_provider)\n .or_else(\"EcsContainer\", ecs_provider)\n .or_else(\"Ec2InstanceMetadata\", imds_provider);\n\n CredentialsChain { provider_chain }\n }\n```"}], "func_name": "new", "docstring": "Based on code the code for\n[aws_config::default_provider::credentials::DefaultCredentialsChain]: ", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/api_client/credentials/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/api_client/credentials/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "beafd40793c5d7784713f3c6ca8ecb8e2ffa9623ca6e792889452f8c91644020"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_expired\n\nDocumentation:\nIndicates if an expiration time has passed, there is a small 1 min window that is removed\nso the token will not expire in transit\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_expired(expiration_time: &OffsetDateTime) -> bool {\n let now = time::OffsetDateTime::now_utc();\n &(now + time::Duration::minutes(1)) > expiration_time\n}\n```"}], "func_name": "is_expired", "docstring": "Indicates if an expiration time has passed, there is a small 1 min window that is removed\nso the token will not expire in transit", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/builder_id.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/builder_id.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e9a2e73ce89b27499e8f052070db3954568a6b1b248ceb06e768620d3600e146"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_from_secret_store\n\nDocumentation:\nLoads the OIDC registered client from the secret store, deleting it if it is expired.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn load_from_secret_store(database: &Database, region: &Region) -> Result, AuthError> {\n trace!(?region, \"loading device registration from secret store\");\n let device_registration = database.get_secret(Self::SECRET_KEY).await?;\n\n if let Some(device_registration) = device_registration {\n // check that the data is not expired, assume it is invalid if not present\n let device_registration: Self = serde_json::from_str(&device_registration.0)?;\n\n if let Some(client_secret_expires_at) = device_registration.client_secret_expires_at {\n let is_expired = is_expired(&client_secret_expires_at);\n let registration_region_is_valid = device_registration.region == region.as_ref();\n trace!(\n ?is_expired,\n ?registration_region_is_valid,\n \"checking if device registration is valid\"\n );\n if !is_expired && registration_region_is_valid {\n return Ok(Some(device_registration));\n }\n } else {\n warn!(\"no expiration time found for the client secret\");\n }\n }\n\n // delete the data if its expired or invalid\n if let Err(err) = database.delete_secret(Self::SECRET_KEY).await {\n error!(?err, \"Failed to delete device registration from keychain\");\n }\n\n Ok(None)\n }\n```"}], "func_name": "load_from_secret_store", "docstring": "Loads the OIDC registered client from the secret store, deleting it if it is expired.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/builder_id.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/builder_id.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aa1858be91badb135590d48a68aa0b083bfb2898cedd5b87009a47a1167911b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init_device_code_registration\n\nDocumentation:\nLoads the client saved in the secret store if available, otherwise registers a new client\nand saves it in the secret store.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn init_device_code_registration(\n database: &Database,\n client: &Client,\n region: &Region,\n ) -> Result {\n match Self::load_from_secret_store(database, region).await {\n Ok(Some(registration)) if registration.oauth_flow == OAuthFlow::DeviceCode => match ®istration.scopes {\n Some(scopes) if is_scopes(scopes) => return Ok(registration),\n _ => warn!(\"Invalid scopes in device registration, ignoring\"),\n },\n // If it doesn't exist or is for another OAuth flow,\n // then continue with creating a new one.\n Ok(None | Some(_)) => {},\n Err(err) => {\n error!(?err, \"Failed to read device registration from keychain\");\n },\n };\n\n let mut register = client\n .register_client()\n .client_name(CLIENT_NAME)\n .client_type(CLIENT_TYPE);\n for scope in SCOPES {\n register = register.scopes(*scope);\n }\n let output = register.send().await?;\n\n let device_registration = Self::from_output(\n output,\n region,\n OAuthFlow::DeviceCode,\n SCOPES.iter().map(|s| (*s).to_owned()).collect(),\n );\n\n if let Err(err) = device_registration.save(database).await {\n error!(?err, \"Failed to write device registration to keychain\");\n }\n\n Ok(device_registration)\n }\n```"}], "func_name": "init_device_code_registration", "docstring": "Loads the client saved in the secret store if available, otherwise registers a new client\nand saves it in the secret store.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/builder_id.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/builder_id.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18b8652e6c68d752a4162dc645c4c6a92833888917c37f8e24027f340df22264"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: save\n\nDocumentation:\nSaves to the passed secret store.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn save(&self, secret_store: &Database) -> Result<(), AuthError> {\n secret_store\n .set_secret(Self::SECRET_KEY, &serde_json::to_string(&self)?)\n .await?;\n Ok(())\n }\n```"}], "func_name": "save", "docstring": "Saves to the passed secret store.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/builder_id.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/builder_id.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3578ae47b5a8c2cc5d9acdfcc7aefc0570a5d248c6474e975226cea7da63e298"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load\n\nDocumentation:\nLoad the token from the keychain, refresh the token if it is expired and return it\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn load(database: &Database) -> Result, AuthError> {\n match database.get_secret(Self::SECRET_KEY).await {\n Ok(Some(secret)) => {\n let token: Option = serde_json::from_str(&secret.0)?;\n match token {\n Some(token) => {\n let region = token.region.clone().map_or(OIDC_BUILDER_ID_REGION, Region::new);\n let client = client(region.clone());\n\n if token.is_expired() {\n trace!(\"token is expired, refreshing\");\n token.refresh_token(&client, database, ®ion).await\n } else {\n Ok(Some(token))\n }\n },\n None => {\n debug!(\"secret stored in the database was empty\");\n Ok(None)\n },\n }\n },\n Ok(None) => {\n debug!(\"no secret found in the database\");\n Ok(None)\n },\n Err(err) => {\n error!(%err, \"Error getting builder id token from keychain\");\n Err(err)?\n },\n }\n }\n```"}], "func_name": "load", "docstring": "Load the token from the keychain, refresh the token if it is expired and return it", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/builder_id.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/builder_id.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cbe8d94d52b10124684af028e057716be8e506843aba9c2f735d7f3175d3902a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: save\n\nDocumentation:\nSave the token to the keychain\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn save(&self, database: &Database) -> Result<(), AuthError> {\n database\n .set_secret(Self::SECRET_KEY, &serde_json::to_string(self)?)\n .await?;\n Ok(())\n }\n```"}], "func_name": "save", "docstring": "Save the token to the keychain", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/builder_id.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/builder_id.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6b25783a4040f6ef48e21b9ae9c1dde0fb9083eb79aa06535231d0d06059be62"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete\n\nDocumentation:\nDelete the token from the keychain\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn delete(&self, database: &Database) -> Result<(), AuthError> {\n database.delete_secret(Self::SECRET_KEY).await?;\n Ok(())\n }\n```"}], "func_name": "delete", "docstring": "Delete the token from the keychain", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/builder_id.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/builder_id.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "70e3372c8661052aa6c82b80200b19cb65df37d1de06913e4a52f0a441fd59b3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: poll_create_token\n\nDocumentation:\nPoll for the create token response\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn poll_create_token(\n database: &Database,\n device_code: String,\n start_url: Option,\n region: Option,\n) -> PollCreateToken {\n let region = region.clone().map_or(OIDC_BUILDER_ID_REGION, Region::new);\n let client = client(region.clone());\n\n let DeviceRegistration {\n client_id,\n client_secret,\n scopes,\n ..\n } = match DeviceRegistration::init_device_code_registration(database, &client, ®ion).await {\n Ok(res) => res,\n Err(err) => {\n return PollCreateToken::Error(err);\n },\n };\n\n match client\n .create_token()\n .grant_type(DEVICE_GRANT_TYPE)\n .device_code(device_code)\n .client_id(client_id)\n .client_secret(client_secret.0)\n .send()\n .await\n {\n Ok(output) => {\n let token: BuilderIdToken =\n BuilderIdToken::from_output(output, region, start_url, OAuthFlow::DeviceCode, scopes);\n\n if let Err(err) = token.save(database).await {\n error!(?err, \"Failed to store builder id token\");\n };\n\n PollCreateToken::Complete\n },\n Err(SdkError::ServiceError(service_error)) if service_error.err().is_authorization_pending_exception() => {\n PollCreateToken::Pending\n },\n Err(err) => {\n error!(?err, \"Failed to poll for builder id token\");\n PollCreateToken::Error(err.into())\n },\n }\n}\n```"}], "func_name": "poll_create_token", "docstring": "Poll for the create token response", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/builder_id.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/builder_id.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b38d12ec1ff659e73cecf4ac6783261d3d44b05c87803165aeb9336d2912c78e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_pkce_authorization\n\nDocumentation:\nStarts the PKCE authorization flow, using [`START_URL`] and [`OIDC_BUILDER_ID_REGION`] as the\ndefault issuer URL and region. Returns the [`PkceClient`] to use to finish the flow.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn start_pkce_authorization(\n start_url: Option,\n region: Option,\n) -> Result<(Client, PkceRegistration), AuthError> {\n let issuer_url = start_url.as_deref().unwrap_or(START_URL);\n let region = region.clone().map_or(OIDC_BUILDER_ID_REGION, Region::new);\n let client = client(region.clone());\n let registration = PkceRegistration::register(&client, region, issuer_url.to_string(), None).await?;\n Ok((client, registration))\n}\n```"}], "func_name": "start_pkce_authorization", "docstring": "Starts the PKCE authorization flow, using [`START_URL`] and [`OIDC_BUILDER_ID_REGION`] as the\ndefault issuer URL and region. Returns the [`PkceClient`] to use to finish the flow.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/pkce.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/pkce.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "51f87efea1149d8f507878388e5b3c72a75f0cecede50275907f53accba2a117"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish\n\nDocumentation:\nHosts a local HTTP server to listen for browser redirects. If a [`Database`] is passed,\nthen the access and refresh tokens will be saved.\n\nOnly the first connection will be served.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn finish(self, client: &C, database: Option<&mut Database>) -> Result<(), AuthError> {\n let code = tokio::select! {\n code = Self::recv_code(self.listener, self.state) => {\n code?\n },\n _ = tokio::time::sleep(self.timeout) => {\n return Err(AuthError::OAuthTimeout);\n }\n };\n\n let response = client\n .create_token(CreateTokenArgs {\n client_id: self.registered_client.client_id().to_string(),\n client_secret: self.registered_client.client_secret().to_string(),\n redirect_uri: self.redirect_uri,\n code_verifier: self.code_verifier,\n code,\n })\n .await?;\n\n // Tokens are redacted in the log output.\n debug!(?response, \"Received create_token response\");\n\n let token = BuilderIdToken::from_output(\n response.output,\n self.region.clone(),\n Some(self.issuer_url),\n OAuthFlow::Pkce,\n Some(C::scopes()),\n );\n\n let device_registration = DeviceRegistration::from_output(\n self.registered_client.output,\n &self.region,\n OAuthFlow::Pkce,\n C::scopes(),\n );\n\n if let Some(database) = database {\n if let Err(err) = device_registration.save(database).await {\n error!(?err, \"Failed to store pkce registration to secret store\");\n }\n\n if let Err(err) = token.save(database).await {\n error!(?err, \"Failed to store builder id token\");\n };\n }\n\n Ok(())\n }\n```"}], "func_name": "finish", "docstring": "Hosts a local HTTP server to listen for browser redirects. If a [`Database`] is passed,\nthen the access and refresh tokens will be saved.\n\nOnly the first connection will be served.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/pkce.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/pkce.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "de2e2a57416a664c7e803f1468d896da4a1f338c183e749210bc06940b1e0eca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_oauth_callback\n\nDocumentation:\nHandles the browser redirect to `\"http://{host}/oauth/callback\"` which contains either the\ncode and state query params, or an error query param. Redirects to \"/index.html\".\n\nThe [`Request`] doesn't actually contain the host, hence the `host` argument.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_oauth_callback(\n code_tx: CodeSender,\n host: String,\n req: Request,\n ) -> Result {\n let query_params = req\n .uri()\n .query()\n .map(|query| {\n query\n .split('&')\n .filter_map(|kv| kv.split_once('='))\n .collect::>()\n })\n .ok_or(AuthError::OAuthCustomError(\"query parameters are missing\".into()))?;\n\n // Error handling: if something goes wrong at the authorization endpoint, the\n // client will be redirected to the redirect url with \"error\" and\n // \"error_description\" query parameters.\n if let Some(error) = query_params.get(\"error\") {\n let error_description = query_params.get(\"error_description\").unwrap_or(&\"\");\n let _ = code_tx\n .send(Err(AuthError::OAuthCustomError(format!(\n \"error occurred during authorization: {:?}, {:?}\",\n error, error_description\n ))))\n .await;\n return Self::redirect_to_index(&host, &format!(\"?error={}\", error));\n } else {\n let code = query_params.get(\"code\");\n let state = query_params.get(\"state\");\n if let (Some(code), Some(state)) = (code, state) {\n let _ = code_tx.send(Ok(((*code).to_string(), (*state).to_string()))).await;\n } else {\n let _ = code_tx\n .send(Err(AuthError::OAuthCustomError(\n \"missing code and/or state in the query parameters\".into(),\n )))\n .await;\n return Self::redirect_to_index(&host, \"?error=missing%20required%20query%20parameters\");\n }\n }\n\n Self::redirect_to_index(&host, \"\")\n }\n```"}], "func_name": "handle_oauth_callback", "docstring": "Handles the browser redirect to `\"http://{host}/oauth/callback\"` which contains either the\ncode and state query params, or an error query param. Redirects to \"/index.html\".\n\nThe [`Request`] doesn't actually contain the host, hence the `host` argument.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/pkce.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/pkce.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7769bfc2cfafb7f3d77db616ff4df2de096b44444f0dfaeaccc1084e0d632ce9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_code_verifier\n\nDocumentation:\nGenerates a random 43-octet URL safe string according to the RFC recommendation.\n\nReference: https://datatracker.ietf.org/doc/html/rfc7636#section-4.1\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_code_verifier() -> String {\n URL_SAFE.encode(rand::random::<[u8; 32]>()).replace('=', \"\")\n}\n```"}], "func_name": "generate_code_verifier", "docstring": "Generates a random 43-octet URL safe string according to the RFC recommendation.\n\nReference: https://datatracker.ietf.org/doc/html/rfc7636#section-4.1", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/pkce.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/pkce.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0470472bdc73441a22b8c6e8f04e8bc186f650cfb390c83541fc1040e7c3fc40"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_code_challenge\n\nDocumentation:\nBase64 URL encoded sha256 hash of the code verifier.\n\nReference: https://datatracker.ietf.org/doc/html/rfc7636#section-4.2\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_code_challenge(code_verifier: &str) -> String {\n use sha2::{\n Digest,\n Sha256,\n };\n let mut hasher = Sha256::new();\n hasher.update(code_verifier);\n URL_SAFE.encode(hasher.finalize()).replace('=', \"\")\n}\n```"}], "func_name": "generate_code_challenge", "docstring": "Base64 URL encoded sha256 hash of the code verifier.\n\nReference: https://datatracker.ietf.org/doc/html/rfc7636#section-4.2", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/pkce.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/pkce.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "187e366feeaa0f54f57d53e0f449485dafa1c1e70fed50df26840400e0dc028b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_scopes\n\nDocumentation:\nChecks if the given scopes match the predefined scopes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn is_scopes>(scopes: &[S]) -> bool {\n scopes_match(SCOPES, scopes)\n}\n```"}], "func_name": "is_scopes", "docstring": "Checks if the given scopes match the predefined scopes.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/auth/scope.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/auth/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0a1c6f9baed9a49aac9a6f9a7a07e5770e853eb200b6771a62eeb5deb67fb983"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: client\n\nDocumentation:\nReturns a wrapper around the global [fig_request::client] that implements\n[HttpClient].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn client() -> Client {\n let client = crate::request::new_client().expect(\"failed to create http client\");\n Client::new(client.clone())\n}\n```"}], "func_name": "client", "docstring": "Returns a wrapper around the global [fig_request::client] that implements\n[HttpClient].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/aws_common/http_client.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/aws_common/http_client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "05ebec6d539b58020c9f775b41a0fd2dfdc23911b3814c7ca5a9cd547c1ed4ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new ContextManager with default settings.\n\nThis will:\n1. Create the necessary directories if they don't exist\n2. Load the global configuration\n3. Load the default profile configuration\n\n# Arguments\n* `ctx` - The context to use\n* `max_context_files_size` - Optional maximum token size for context files. If not provided,\ndefaults to `CONTEXT_FILES_MAX_SIZE`.\n\n# Returns\nA Result containing the new ContextManager or an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn new(ctx: Arc, max_context_files_size: Option) -> Result {\n let max_context_files_size = max_context_files_size.unwrap_or(CONTEXT_FILES_MAX_SIZE);\n\n let profiles_dir = directories::chat_profiles_dir(&ctx)?;\n\n ctx.fs().create_dir_all(&profiles_dir).await?;\n\n let global_config = load_global_config(&ctx).await?;\n let current_profile = \"default\".to_string();\n let profile_config = load_profile_config(&ctx, ¤t_profile).await?;\n\n Ok(Self {\n ctx,\n max_context_files_size,\n global_config,\n current_profile,\n profile_config,\n hook_executor: HookExecutor::new(),\n })\n }\n```"}], "func_name": "new", "docstring": "Create a new ContextManager with default settings.\n\nThis will:\n1. Create the necessary directories if they don't exist\n2. Load the global configuration\n3. Load the default profile configuration\n\n# Arguments\n* `ctx` - The context to use\n* `max_context_files_size` - Optional maximum token size for context files. If not provided,\ndefaults to `CONTEXT_FILES_MAX_SIZE`.\n\n# Returns\nA Result containing the new ContextManager or an error", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9bf45ca5aef394f73f9e8a5e02fee1212e5f2d1edbe38855182c01bd3e16f9d5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: save_config\n\nDocumentation:\nSave the current configuration to disk.\n\n# Arguments\n* `global` - If true, save the global configuration; otherwise, save the current profile\nconfiguration\n\n# Returns\nA Result indicating success or an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn save_config(&self, global: bool) -> Result<()> {\n if global {\n let global_path = directories::chat_global_context_path(&self.ctx)?;\n let contents = serde_json::to_string_pretty(&self.global_config)\n .map_err(|e| eyre!(\"Failed to serialize global configuration: {}\", e))?;\n\n self.ctx.fs().write(&global_path, contents).await?;\n } else {\n let profile_path = profile_context_path(&self.ctx, &self.current_profile)?;\n if let Some(parent) = profile_path.parent() {\n self.ctx.fs().create_dir_all(parent).await?;\n }\n let contents = serde_json::to_string_pretty(&self.profile_config)\n .map_err(|e| eyre!(\"Failed to serialize profile configuration: {}\", e))?;\n\n self.ctx.fs().write(&profile_path, contents).await?;\n }\n\n Ok(())\n }\n```"}], "func_name": "save_config", "docstring": "Save the current configuration to disk.\n\n# Arguments\n* `global` - If true, save the global configuration; otherwise, save the current profile\nconfiguration\n\n# Returns\nA Result indicating success or an error", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7614986ea243dd0f835602ab39f269177ce1bb8e45b78f74b5731c35080fe149"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reload_config\n\nDocumentation:\nReloads the global and profile config from disk.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn reload_config(&mut self) -> Result<()> {\n self.global_config = load_global_config(&self.ctx).await?;\n self.profile_config = load_profile_config(&self.ctx, &self.current_profile).await?;\n Ok(())\n }\n```"}], "func_name": "reload_config", "docstring": "Reloads the global and profile config from disk.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1784d263bc52303d5b117ca65666909226567d72fcfbd09b23dc83c24740092a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_paths\n\nDocumentation:\nAdd paths to the context configuration.\n\n# Arguments\n* `paths` - List of paths to add\n* `global` - If true, add to global configuration; otherwise, add to current profile\nconfiguration\n* `force` - If true, skip validation that the path exists\n\n# Returns\nA Result indicating success or an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn add_paths(&mut self, paths: Vec, global: bool, force: bool) -> Result<()> {\n let mut all_paths = self.global_config.paths.clone();\n all_paths.append(&mut self.profile_config.paths.clone());\n\n // Validate paths exist before adding them\n if !force {\n let mut context_files = Vec::new();\n\n // Check each path to make sure it exists or matches at least one file\n for path in &paths {\n // We're using a temporary context_files vector just for validation\n // Pass is_validation=true to ensure we error if glob patterns don't match any files\n match process_path(&self.ctx, path, &mut context_files, true).await {\n Ok(_) => {}, // Path is valid\n Err(e) => return Err(eyre!(\"Invalid path '{}': {}. Use --force to add anyway.\", path, e)),\n }\n }\n }\n\n // Add each path, checking for duplicates\n for path in paths {\n if all_paths.contains(&path) {\n return Err(eyre!(\"Rule '{}' already exists.\", path));\n }\n if global {\n self.global_config.paths.push(path);\n } else {\n self.profile_config.paths.push(path);\n }\n }\n\n // Save the updated configuration\n self.save_config(global).await?;\n\n Ok(())\n }\n```"}], "func_name": "add_paths", "docstring": "Add paths to the context configuration.\n\n# Arguments\n* `paths` - List of paths to add\n* `global` - If true, add to global configuration; otherwise, add to current profile\nconfiguration\n* `force` - If true, skip validation that the path exists\n\n# Returns\nA Result indicating success or an error", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18f7acc0cb983b9ac172b2cee2fc2cf605ec834ff38cb2db284dfa530da5081d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_paths\n\nDocumentation:\nRemove paths from the context configuration.\n\n# Arguments\n* `paths` - List of paths to remove\n* `global` - If true, remove from global configuration; otherwise, remove from current\nprofile configuration\n\n# Returns\nA Result indicating success or an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn remove_paths(&mut self, paths: Vec, global: bool) -> Result<()> {\n // Get reference to the appropriate config\n let config = self.get_config_mut(global);\n\n // Track if any paths were removed\n let mut removed_any = false;\n\n // Remove each path if it exists\n for path in paths {\n let original_len = config.paths.len();\n config.paths.retain(|p| p != &path);\n\n if config.paths.len() < original_len {\n removed_any = true;\n }\n }\n\n if !removed_any {\n return Err(eyre!(\"None of the specified paths were found in the context\"));\n }\n\n // Save the updated configuration\n self.save_config(global).await?;\n\n Ok(())\n }\n```"}], "func_name": "remove_paths", "docstring": "Remove paths from the context configuration.\n\n# Arguments\n* `paths` - List of paths to remove\n* `global` - If true, remove from global configuration; otherwise, remove from current\nprofile configuration\n\n# Returns\nA Result indicating success or an error", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "363c7e5eae2275dc99c86228f861963ff9de2cbe41ba92a1fe9ed297b6c5a0b1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_profiles\n\nDocumentation:\nList all available profiles.\n\n# Returns\nA Result containing a vector of profile names, with \"default\" always first\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn list_profiles(&self) -> Result> {\n let mut profiles = Vec::new();\n\n // Always include default profile\n profiles.push(\"default\".to_string());\n\n // Read profile directory and extract profile names\n let profiles_dir = directories::chat_profiles_dir(&self.ctx)?;\n if profiles_dir.exists() {\n let mut read_dir = self.ctx.fs().read_dir(&profiles_dir).await?;\n while let Some(entry) = read_dir.next_entry().await? {\n let path = entry.path();\n if let (true, Some(name)) = (path.is_dir(), path.file_name()) {\n if name != \"default\" {\n profiles.push(name.to_string_lossy().to_string());\n }\n }\n }\n }\n\n // Sort non-default profiles alphabetically\n if profiles.len() > 1 {\n profiles[1..].sort();\n }\n\n Ok(profiles)\n }\n```"}], "func_name": "list_profiles", "docstring": "List all available profiles.\n\n# Returns\nA Result containing a vector of profile names, with \"default\" always first", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b1f81909b1ea6f9b1ec79be0a1a4cc206ced22ff4d4c872f991c1c7d2d3a17dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_profiles_blocking\n\nDocumentation:\nList all available profiles using blocking operations.\n\nSimilar to list_profiles but uses synchronous filesystem operations.\n\n# Returns\nA Result containing a vector of profile names, with \"default\" always first\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn list_profiles_blocking(&self) -> Result> {\n let mut profiles = Vec::new();\n\n // Always include default profile\n profiles.push(\"default\".to_string());\n\n // Read profile directory and extract profile names\n let profiles_dir = directories::chat_profiles_dir(&self.ctx)?;\n if profiles_dir.exists() {\n for entry in std::fs::read_dir(profiles_dir)? {\n let entry = entry?;\n let path = entry.path();\n if let (true, Some(name)) = (path.is_dir(), path.file_name()) {\n if name != \"default\" {\n profiles.push(name.to_string_lossy().to_string());\n }\n }\n }\n }\n\n // Sort non-default profiles alphabetically\n if profiles.len() > 1 {\n profiles[1..].sort();\n }\n\n Ok(profiles)\n }\n```"}], "func_name": "list_profiles_blocking", "docstring": "List all available profiles using blocking operations.\n\nSimilar to list_profiles but uses synchronous filesystem operations.\n\n# Returns\nA Result containing a vector of profile names, with \"default\" always first", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa6068f4a276e1d8d1ff4240ba570abc8743d0d209c6c458031f44da8ca8598a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clear\n\nDocumentation:\nClear all paths from the context configuration.\n\n# Arguments\n* `global` - If true, clear global configuration; otherwise, clear current profile\nconfiguration\n\n# Returns\nA Result indicating success or an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn clear(&mut self, global: bool) -> Result<()> {\n // Clear the appropriate config\n if global {\n self.global_config.paths.clear();\n } else {\n self.profile_config.paths.clear();\n }\n\n // Save the updated configuration\n self.save_config(global).await?;\n\n Ok(())\n }\n```"}], "func_name": "clear", "docstring": "Clear all paths from the context configuration.\n\n# Arguments\n* `global` - If true, clear global configuration; otherwise, clear current profile\nconfiguration\n\n# Returns\nA Result indicating success or an error", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e592564b7e0f52c047445690bb19c7b30ee0522366b0b69db9ecccbeb6f7416f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_profile\n\nDocumentation:\nCreate a new profile.\n\n# Arguments\n* `name` - Name of the profile to create\n\n# Returns\nA Result indicating success or an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn create_profile(&self, name: &str) -> Result<()> {\n validate_profile_name(name)?;\n\n // Check if profile already exists\n let profile_path = profile_context_path(&self.ctx, name)?;\n if profile_path.exists() {\n return Err(eyre!(\"Profile '{}' already exists\", name));\n }\n\n // Create empty profile configuration\n let config = ContextConfig::default();\n let contents = serde_json::to_string_pretty(&config)\n .map_err(|e| eyre!(\"Failed to serialize profile configuration: {}\", e))?;\n\n // Create the file\n if let Some(parent) = profile_path.parent() {\n self.ctx.fs().create_dir_all(parent).await?;\n }\n self.ctx.fs().write(&profile_path, contents).await?;\n\n Ok(())\n }\n```"}], "func_name": "create_profile", "docstring": "Create a new profile.\n\n# Arguments\n* `name` - Name of the profile to create\n\n# Returns\nA Result indicating success or an error", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c8c39cf738d70275d173c2b8c0f10eced35e10b683dba658e4c2e4dfeeba98a0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: delete_profile\n\nDocumentation:\nDelete a profile.\n\n# Arguments\n* `name` - Name of the profile to delete\n\n# Returns\nA Result indicating success or an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn delete_profile(&self, name: &str) -> Result<()> {\n if name == \"default\" {\n return Err(eyre!(\"Cannot delete the default profile\"));\n } else if name == self.current_profile {\n return Err(eyre!(\n \"Cannot delete the active profile. Switch to another profile first\"\n ));\n }\n\n let profile_path = profile_dir_path(&self.ctx, name)?;\n if !profile_path.exists() {\n return Err(eyre!(\"Profile '{}' does not exist\", name));\n }\n\n self.ctx.fs().remove_dir_all(&profile_path).await?;\n\n Ok(())\n }\n```"}], "func_name": "delete_profile", "docstring": "Delete a profile.\n\n# Arguments\n* `name` - Name of the profile to delete\n\n# Returns\nA Result indicating success or an error", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f1d0ae715012eb85692a60c6e0fd8c562d4d67485f7671f41a5649bd110a174"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rename_profile\n\nDocumentation:\nRename a profile.\n\n# Arguments\n* `old_name` - Current name of the profile\n* `new_name` - New name for the profile\n\n# Returns\nA Result indicating success or an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn rename_profile(&mut self, old_name: &str, new_name: &str) -> Result<()> {\n // Validate profile names\n if old_name == \"default\" {\n return Err(eyre!(\"Cannot rename the default profile\"));\n }\n if new_name == \"default\" {\n return Err(eyre!(\"Cannot rename to 'default' as it's a reserved profile name\"));\n }\n\n validate_profile_name(new_name)?;\n\n let old_profile_path = profile_dir_path(&self.ctx, old_name)?;\n if !old_profile_path.exists() {\n return Err(eyre!(\"Profile '{}' not found\", old_name));\n }\n\n let new_profile_path = profile_dir_path(&self.ctx, new_name)?;\n if new_profile_path.exists() {\n return Err(eyre!(\"Profile '{}' already exists\", new_name));\n }\n\n self.ctx.fs().rename(&old_profile_path, &new_profile_path).await?;\n\n // If the current profile is being renamed, update the current_profile field\n if self.current_profile == old_name {\n self.current_profile = new_name.to_string();\n self.profile_config = load_profile_config(&self.ctx, new_name).await?;\n }\n\n Ok(())\n }\n```"}], "func_name": "rename_profile", "docstring": "Rename a profile.\n\n# Arguments\n* `old_name` - Current name of the profile\n* `new_name` - New name for the profile\n\n# Returns\nA Result indicating success or an error", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "913b8498dfadd7ef5e4fe341365897b00208db29be314732df47ec4cbec60092"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: switch_profile\n\nDocumentation:\nSwitch to a different profile.\n\n# Arguments\n* `name` - Name of the profile to switch to\n\n# Returns\nA Result indicating success or an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn switch_profile(&mut self, name: &str) -> Result<()> {\n validate_profile_name(name)?;\n self.hook_executor.profile_cache.clear();\n\n // Special handling for default profile - it always exists\n if name == \"default\" {\n // Load the default profile configuration\n let profile_config = load_profile_config(&self.ctx, name).await?;\n\n // Update the current profile\n self.current_profile = name.to_string();\n self.profile_config = profile_config;\n\n return Ok(());\n }\n\n // Check if profile exists\n let profile_path = profile_context_path(&self.ctx, name)?;\n if !profile_path.exists() {\n return Err(eyre!(\"Profile '{}' does not exist. Use 'create' to create it\", name));\n }\n\n // Update the current profile\n self.current_profile = name.to_string();\n self.profile_config = load_profile_config(&self.ctx, name).await?;\n\n Ok(())\n }\n```"}], "func_name": "switch_profile", "docstring": "Switch to a different profile.\n\n# Arguments\n* `name` - Name of the profile to switch to\n\n# Returns\nA Result indicating success or an error", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5424cbd079ae0b688cdc27cddc9fec3151847d66c6638c496bf1ae0d5945414f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_context_files\n\nDocumentation:\nGet all context files (global + profile-specific).\n\nThis method:\n1. Processes all paths in the global and profile configurations\n2. Expands glob patterns to include matching files\n3. Reads the content of each file\n4. Returns a vector of (filename, content) pairs\n\n\n# Returns\nA Result containing a vector of (filename, content) pairs or an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_context_files(&self) -> Result> {\n let mut context_files = Vec::new();\n\n self.collect_context_files(&self.global_config.paths, &mut context_files)\n .await?;\n self.collect_context_files(&self.profile_config.paths, &mut context_files)\n .await?;\n\n context_files.sort_by(|a, b| a.0.cmp(&b.0));\n context_files.dedup_by(|a, b| a.0 == b.0);\n\n Ok(context_files)\n }\n```"}], "func_name": "get_context_files", "docstring": "Get all context files (global + profile-specific).\n\nThis method:\n1. Processes all paths in the global and profile configurations\n2. Expands glob patterns to include matching files\n3. Reads the content of each file\n4. Returns a vector of (filename, content) pairs\n\n\n# Returns\nA Result containing a vector of (filename, content) pairs or an error", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eb7fdc50e782a956c5577ebb9121c3549dc3d50e4cf47f3752e8a5a0c3bd6a02"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_global_context_files\n\nDocumentation:\nGet all context files from the global configuration.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_global_context_files(&self) -> Result> {\n let mut context_files = Vec::new();\n\n self.collect_context_files(&self.global_config.paths, &mut context_files)\n .await?;\n\n Ok(context_files)\n }\n```"}], "func_name": "get_global_context_files", "docstring": "Get all context files from the global configuration.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "075ee8c201ffeef1023717a7428ca7fb9f376298d23253ef6ced1c5c2f3c2fe4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_current_profile_context_files\n\nDocumentation:\nGet all context files from the current profile configuration.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_current_profile_context_files(&self) -> Result> {\n let mut context_files = Vec::new();\n\n self.collect_context_files(&self.profile_config.paths, &mut context_files)\n .await?;\n\n Ok(context_files)\n }\n```"}], "func_name": "get_current_profile_context_files", "docstring": "Get all context files from the current profile configuration.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "027cf3d41175e30506801de96031871eb72fceed68b70174529513caf500ee65"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_hook\n\nDocumentation:\nAdd hooks to the context config. If another hook with the same name already exists, throw an\nerror.\n\n# Arguments\n* `hook` - name of the hook to delete\n* `global` - If true, the add to the global config. If false, add to the current profile\nconfig.\n* `conversation_start` - If true, add the hook to conversation_start. Otherwise, it will be\nadded to per_prompt.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn add_hook(&mut self, name: String, hook: Hook, global: bool) -> Result<()> {\n let config = self.get_config_mut(global);\n\n if config.hooks.contains_key(&name) {\n return Err(eyre!(\"name already exists.\"));\n }\n\n config.hooks.insert(name, hook);\n self.save_config(global).await\n }\n```"}], "func_name": "add_hook", "docstring": "Add hooks to the context config. If another hook with the same name already exists, throw an\nerror.\n\n# Arguments\n* `hook` - name of the hook to delete\n* `global` - If true, the add to the global config. If false, add to the current profile\nconfig.\n* `conversation_start` - If true, add the hook to conversation_start. Otherwise, it will be\nadded to per_prompt.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd0223b34070b2fa4d3f30cefb9d41e5a1846afad3f87e1ee46da9de65a06f26"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_hook\n\nDocumentation:\nDelete hook(s) by name\n# Arguments\n* `name` - name of the hook to delete\n* `global` - If true, the delete from the global config. If false, delete from the current\nprofile config\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn remove_hook(&mut self, name: &str, global: bool) -> Result<()> {\n let config = self.get_config_mut(global);\n\n if !config.hooks.contains_key(name) {\n return Err(eyre!(\"does not exist.\"));\n }\n\n config.hooks.remove(name);\n\n self.save_config(global).await\n }\n```"}], "func_name": "remove_hook", "docstring": "Delete hook(s) by name\n# Arguments\n* `name` - name of the hook to delete\n* `global` - If true, the delete from the global config. If false, delete from the current\nprofile config", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aa5195c4f307ad52e4f3dce1c16bc851dc1e16ec9503c41f6a58bbd3deb393f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_hook_disabled\n\nDocumentation:\nSets the \"disabled\" field on any [`Hook`] with the given name\n# Arguments\n* `disable` - Set \"disabled\" field to this value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn set_hook_disabled(&mut self, name: &str, global: bool, disable: bool) -> Result<()> {\n let config = self.get_config_mut(global);\n\n if !config.hooks.contains_key(name) {\n return Err(eyre!(\"does not exist.\"));\n }\n\n if let Some(hook) = config.hooks.get_mut(name) {\n hook.disabled = disable;\n }\n\n self.save_config(global).await\n }\n```"}], "func_name": "set_hook_disabled", "docstring": "Sets the \"disabled\" field on any [`Hook`] with the given name\n# Arguments\n* `disable` - Set \"disabled\" field to this value", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "161cc1ffd1cfb6ced59e5c4ac25a7c1795a6b6ac8acb20e8c763ce7117731fe9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_all_hooks_disabled\n\nDocumentation:\nSets the \"disabled\" field on all [`Hook`]s\n# Arguments\n* `disable` - Set all \"disabled\" fields to this value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn set_all_hooks_disabled(&mut self, global: bool, disable: bool) -> Result<()> {\n let config = self.get_config_mut(global);\n\n config.hooks.iter_mut().for_each(|(_, h)| h.disabled = disable);\n\n self.save_config(global).await\n }\n```"}], "func_name": "set_all_hooks_disabled", "docstring": "Sets the \"disabled\" field on all [`Hook`]s\n# Arguments\n* `disable` - Set all \"disabled\" fields to this value", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e0d7266e46cab1b2fbeee72d95a126f4d49196cc610b2a928daf202046f7120c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_hooks\n\nDocumentation:\nRun all the currently enabled hooks from both the global and profile contexts.\nSkipped hooks (disabled) will not appear in the output.\n# Arguments\n* `updates` - output stream to write hook run status to if Some, else do nothing if None\n# Returns\nA vector containing pairs of a [`Hook`] definition and its execution output\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_hooks(&mut self, updates: Option<&mut impl Write>) -> Vec<(Hook, String)> {\n let mut hooks: Vec<&Hook> = Vec::new();\n\n // Set internal hook states\n let configs = [\n (&mut self.global_config.hooks, true),\n (&mut self.profile_config.hooks, false),\n ];\n\n for (hook_list, is_global) in configs {\n hooks.extend(hook_list.iter_mut().map(|(name, h)| {\n h.name = name.to_string();\n h.is_global = is_global;\n &*h\n }));\n }\n\n self.hook_executor.run_hooks(hooks, updates).await\n }\n```"}], "func_name": "run_hooks", "docstring": "Run all the currently enabled hooks from both the global and profile contexts.\nSkipped hooks (disabled) will not appear in the output.\n# Arguments\n* `updates` - output stream to write hook run status to if Some, else do nothing if None\n# Returns\nA vector containing pairs of a [`Hook`] definition and its execution output", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c81708a25c4b54dec8cf43714e461a8b8b4b2ca0813d5c2f23f4e5b6d554a04a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: profile_context_path\n\nDocumentation:\nPath to the context config file for `profile_name`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn profile_context_path(ctx: &Context, profile_name: &str) -> Result {\n Ok(directories::chat_profiles_dir(ctx)?\n .join(profile_name)\n .join(\"context.json\"))\n}\n```"}], "func_name": "profile_context_path", "docstring": "Path to the context config file for `profile_name`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a2ff150be95647cda02d824b3377d4a233c860300bfab9b3d719b1eee7db9d2d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_global_config\n\nDocumentation:\nLoad the global context configuration.\n\nIf the global configuration file doesn't exist, returns a default configuration.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn load_global_config(ctx: &Context) -> Result {\n let global_path = directories::chat_global_context_path(ctx)?;\n debug!(?global_path, \"loading profile config\");\n if ctx.fs().exists(&global_path) {\n let contents = ctx.fs().read_to_string(&global_path).await?;\n let config: ContextConfig =\n serde_json::from_str(&contents).map_err(|e| eyre!(\"Failed to parse global configuration: {}\", e))?;\n Ok(config)\n } else {\n // Return default global configuration with predefined paths\n Ok(ContextConfig {\n paths: vec![\n \".amazonq/rules/**/*.md\".to_string(),\n \"README.md\".to_string(),\n AMAZONQ_FILENAME.to_string(),\n ],\n hooks: HashMap::new(),\n })\n }\n}\n```"}], "func_name": "load_global_config", "docstring": "Load the global context configuration.\n\nIf the global configuration file doesn't exist, returns a default configuration.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "89fe8a6ff63fa93f953b1f2985f4ff29bef2c931e720ebc3be8f8ffc0113c6fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_profile_config\n\nDocumentation:\nLoad a profile's context configuration.\n\nIf the profile configuration file doesn't exist, creates a default configuration.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn load_profile_config(ctx: &Context, profile_name: &str) -> Result {\n let profile_path = profile_context_path(ctx, profile_name)?;\n debug!(?profile_path, \"loading profile config\");\n if ctx.fs().exists(&profile_path) {\n let contents = ctx.fs().read_to_string(&profile_path).await?;\n let config: ContextConfig =\n serde_json::from_str(&contents).map_err(|e| eyre!(\"Failed to parse profile configuration: {}\", e))?;\n Ok(config)\n } else {\n // Return empty configuration for new profiles\n Ok(ContextConfig::default())\n }\n}\n```"}], "func_name": "load_profile_config", "docstring": "Load a profile's context configuration.\n\nIf the profile configuration file doesn't exist, creates a default configuration.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0a3a459bc94837b4a526fac9a3a3fa1c89d60a95823644d4b74452214be4108c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_path\n\nDocumentation:\nProcess a path, handling glob patterns and file types.\n\nThis method:\n1. Expands the path (handling ~ for home directory)\n2. If the path contains glob patterns, expands them\n3. For each resulting path, adds the file to the context collection\n4. Handles directories by including all files in the directory (non-recursive)\n5. With force=true, includes paths that don't exist yet\n\n# Arguments\n* `path` - The path to process\n* `context_files` - The collection to add files to\n* `is_validation` - If true, error when glob patterns don't match; if false, silently skip\n\n# Returns\nA Result indicating success or an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn process_path(\n ctx: &Context,\n path: &str,\n context_files: &mut Vec<(String, String)>,\n is_validation: bool,\n) -> Result<()> {\n // Expand ~ to home directory\n let expanded_path = if path.starts_with('~') {\n if let Some(home_dir) = ctx.env().home() {\n home_dir.join(&path[2..]).to_string_lossy().to_string()\n } else {\n return Err(eyre!(\"Could not determine home directory\"));\n }\n } else {\n path.to_string()\n };\n\n // Handle absolute, relative paths, and glob patterns\n let full_path = if expanded_path.starts_with('/') {\n expanded_path\n } else {\n ctx.env()\n .current_dir()?\n .join(&expanded_path)\n .to_string_lossy()\n .to_string()\n };\n\n // Required in chroot testing scenarios so that we can use `Path::exists`.\n let full_path = ctx.fs().chroot_path_str(full_path);\n\n // Check if the path contains glob patterns\n if full_path.contains('*') || full_path.contains('?') || full_path.contains('[') {\n // Expand glob pattern\n match glob(&full_path) {\n Ok(entries) => {\n let mut found_any = false;\n\n for entry in entries {\n match entry {\n Ok(path) => {\n if path.is_file() {\n add_file_to_context(ctx, &path, context_files).await?;\n found_any = true;\n }\n },\n Err(e) => return Err(eyre!(\"Glob error: {}\", e)),\n }\n }\n\n if !found_any && is_validation {\n // When validating paths (e.g., for /context add), error if no files match\n return Err(eyre!(\"No files found matching glob pattern '{}'\", full_path));\n }\n // When just showing expanded files (e.g., for /context show --expand),\n // silently skip non-matching patterns (don't add anything to context_files)\n },\n Err(e) => return Err(eyre!(\"Invalid glob pattern '{}': {}\", full_path, e)),\n }\n } else {\n // Regular path\n let path = Path::new(&full_path);\n if path.exists() {\n if path.is_file() {\n add_file_to_context(ctx, path, context_files).await?;\n } else if path.is_dir() {\n // For directories, add all files in the directory (non-recursive)\n let mut read_dir = ctx.fs().read_dir(path).await?;\n while let Some(entry) = read_dir.next_entry().await? {\n let path = entry.path();\n if path.is_file() {\n add_file_to_context(ctx, &path, context_files).await?;\n }\n }\n }\n } else if is_validation {\n // When validating paths (e.g., for /context add), error if the path doesn't exist\n return Err(eyre!(\"Path '{}' does not exist\", full_path));\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "process_path", "docstring": "Process a path, handling glob patterns and file types.\n\nThis method:\n1. Expands the path (handling ~ for home directory)\n2. If the path contains glob patterns, expands them\n3. For each resulting path, adds the file to the context collection\n4. Handles directories by including all files in the directory (non-recursive)\n5. With force=true, includes paths that don't exist yet\n\n# Arguments\n* `path` - The path to process\n* `context_files` - The collection to add files to\n* `is_validation` - If true, error when glob patterns don't match; if false, silently skip\n\n# Returns\nA Result indicating success or an error", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9cd20b1f7483790901f2d4ccd8f38e73a88ddf77ed51b226f39b3338992c0afe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_file_to_context\n\nDocumentation:\nAdd a file to the context collection.\n\nThis method:\n1. Reads the content of the file\n2. Adds the (filename, content) pair to the context collection\n\n# Arguments\n* `path` - The path to the file\n* `context_files` - The collection to add the file to\n\n# Returns\nA Result indicating success or an error\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn add_file_to_context(ctx: &Context, path: &Path, context_files: &mut Vec<(String, String)>) -> Result<()> {\n let filename = path.to_string_lossy().to_string();\n let content = ctx.fs().read_to_string(path).await?;\n context_files.push((filename, content));\n Ok(())\n}\n```"}], "func_name": "add_file_to_context", "docstring": "Add a file to the context collection.\n\nThis method:\n1. Reads the content of the file\n2. Adds the (filename, content) pair to the context collection\n\n# Arguments\n* `path` - The path to the file\n* `context_files` - The collection to add the file to\n\n# Returns\nA Result indicating success or an error", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25d11b2e134dd572f2c6022645c0587c828b8a3ae881dd6c2cd60e758585b8a3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: validate_profile_name\n\nDocumentation:\nValidate a profile name.\n\nProfile names can only contain alphanumeric characters, hyphens, and underscores.\n\n# Arguments\n* `name` - Name to validate\n\n# Returns\nA Result indicating if the name is valid\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn validate_profile_name(name: &str) -> Result<()> {\n // Check if name is empty\n if name.is_empty() {\n return Err(eyre!(\"Profile name cannot be empty\"));\n }\n\n // Check if name contains only allowed characters and starts with an alphanumeric character\n let re = Regex::new(r\"^[a-zA-Z0-9][a-zA-Z0-9_-]*$\").unwrap();\n if !re.is_match(name) {\n return Err(eyre!(\n \"Profile name must start with an alphanumeric character and can only contain alphanumeric characters, hyphens, and underscores\"\n ));\n }\n\n Ok(())\n}\n```"}], "func_name": "validate_profile_name", "docstring": "Validate a profile name.\n\nProfile names can only contain alphanumeric characters, hyphens, and underscores.\n\n# Arguments\n* `name` - Name to validate\n\n# Returns\nA Result indicating if the name is valid", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/context.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/context.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e8fd0020df73ae16e59b544615dff26612e1bb151c4a86d035b9ac9aad27908b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reload_serialized_state\n\nDocumentation:\nReloads necessary fields after being deserialized. This should be called after\ndeserialization.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn reload_serialized_state(&mut self, ctx: Arc, updates: Option) {\n self.updates = updates;\n\n // Try to reload ContextManager, but do not return an error if we fail.\n // TODO: Currently the failure modes around ContextManager is unclear, and we don't return\n // errors in most cases. Thus, we try to preserve the same behavior here and simply have\n // self.context_manager equal to None if any errors are encountered. This needs to be\n // refactored.\n let mut failed = false;\n if let Some(context_manager) = self.context_manager.as_mut() {\n match context_manager.reload_config().await {\n Ok(_) => (),\n Err(err) => {\n error!(?err, \"failed to reload context config\");\n match ContextManager::new(ctx, None).await {\n Ok(v) => *context_manager = v,\n Err(err) => {\n failed = true;\n error!(?err, \"failed to construct context manager\");\n },\n }\n },\n }\n }\n if failed {\n self.context_manager.take();\n }\n }\n```"}], "func_name": "reload_serialized_state", "docstring": "Reloads necessary fields after being deserialized. This should be called after\ndeserialization.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "243d5579ae4f49c29b8607d37ff950d4b944d508037bc1a1091925a6906c28cc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clear\n\nDocumentation:\nClears the conversation history and optionally the summary.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clear(&mut self, preserve_summary: bool) {\n self.next_message = None;\n self.history.clear();\n if !preserve_summary {\n self.latest_summary = None;\n }\n }\n```"}], "func_name": "clear", "docstring": "Clears the conversation history and optionally the summary.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a0c731eb360e34e846e0f601d966f25c20b5ccdcc630999927a5a68806636f55"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: append_prompts\n\nDocumentation:\nAppends a collection prompts into history and returns the last message in the collection.\nIt asserts that the collection ends with a prompt that assumes the role of user.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn append_prompts(&mut self, mut prompts: VecDeque) -> Option {\n debug_assert!(self.next_message.is_none(), \"next_message should not exist\");\n debug_assert!(prompts.back().is_some_and(|p| p.role == crate::mcp_client::Role::User));\n let last_msg = prompts.pop_back()?;\n let (mut candidate_user, mut candidate_asst) = (None::, None::);\n while let Some(prompt) = prompts.pop_front() {\n let Prompt { role, content } = prompt;\n match role {\n crate::mcp_client::Role::User => {\n let user_msg = UserMessage::new_prompt(content.to_string());\n candidate_user.replace(user_msg);\n },\n crate::mcp_client::Role::Assistant => {\n let assistant_msg = AssistantMessage::new_response(None, content.into());\n candidate_asst.replace(assistant_msg);\n },\n }\n if candidate_asst.is_some() && candidate_user.is_some() {\n let asst = candidate_asst.take().unwrap();\n let user = candidate_user.take().unwrap();\n self.append_assistant_transcript(&asst);\n self.history.push_back((user, asst));\n }\n }\n Some(last_msg.content.to_string())\n }\n```"}], "func_name": "append_prompts", "docstring": "Appends a collection prompts into history and returns the last message in the collection.\nIt asserts that the collection ends with a prompt that assumes the role of user.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "82b722a64dc0592cf557f3dbbcf8e840ccf2fa7938fc5f2c3f71ab3db51503f8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_assistant_message\n\nDocumentation:\nSets the response message according to the currently set [Self::next_message].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn push_assistant_message(&mut self, message: AssistantMessage, database: &mut Database) {\n debug_assert!(self.next_message.is_some(), \"next_message should exist\");\n let next_user_message = self.next_message.take().expect(\"next user message should exist\");\n\n self.append_assistant_transcript(&message);\n self.history.push_back((next_user_message, message));\n\n if let Ok(cwd) = std::env::current_dir() {\n database.set_conversation_by_path(cwd, self).ok();\n }\n }\n```"}], "func_name": "push_assistant_message", "docstring": "Sets the response message according to the currently set [Self::next_message].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dcdc142bfcabb32a7e808201be7c58373fc507ed5b0c575ed227e288328d6bfd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: message_id\n\nDocumentation:\nReturns the message id associated with the last assistant message, if present.\n\nThis is equivalent to `utterance_id` in the Q API.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn message_id(&self) -> Option<&str> {\n self.history.back().and_then(|(_, msg)| msg.message_id())\n }\n```"}], "func_name": "message_id", "docstring": "Returns the message id associated with the last assistant message, if present.\n\nThis is equivalent to `utterance_id` in the Q API.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "53567b392b8f57e7b716f6337bff08c0e7b070d40ad37e1d1f1c0264eb85f71c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: enforce_conversation_invariants\n\nDocumentation:\nUpdates the history so that, when non-empty, the following invariants are in place:\n1. The history length is `<= MAX_CONVERSATION_STATE_HISTORY_LEN`. Oldest messages are\ndropped.\n2. The first message is from the user, and does not contain tool results. Oldest messages\nare dropped.\n3. If the last message from the assistant contains tool results, and a next user message is\nset without tool results, then the user message will have \"cancelled\" tool results.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn enforce_conversation_invariants(&mut self) {\n // First set the valid range as the entire history - this will be truncated as necessary\n // later below.\n self.valid_history_range = (0, self.history.len());\n\n // Trim the conversation history by finding the second oldest message from the user without\n // tool results - this will be the new oldest message in the history.\n //\n // Note that we reserve extra slots for [ConversationState::context_messages].\n if (self.history.len() * 2) > MAX_CONVERSATION_STATE_HISTORY_LEN - 6 {\n match self\n .history\n .iter()\n .enumerate()\n .skip(1)\n .find(|(_, (m, _))| -> bool { !m.has_tool_use_results() })\n .map(|v| v.0)\n {\n Some(i) => {\n debug!(\"removing the first {i} user/assistant response pairs in the history\");\n self.valid_history_range.0 = i;\n },\n None => {\n debug!(\"no valid starting user message found in the history, clearing\");\n self.valid_history_range = (0, 0);\n // Edge case: if the next message contains tool results, then we have to just\n // abandon them.\n if self.next_message.as_ref().is_some_and(|m| m.has_tool_use_results()) {\n debug!(\"abandoning tool results\");\n self.next_message = Some(UserMessage::new_prompt(\n \"The conversation history has overflowed, clearing state\".to_string(),\n ));\n }\n },\n }\n }\n\n // If the last message from the assistant contains tool uses AND next_message is set, we need to\n // ensure that next_message contains tool results.\n if let (Some((_, AssistantMessage::ToolUse { ref mut tool_uses, .. })), Some(user_msg)) = (\n self.history\n .range_mut(self.valid_history_range.0..self.valid_history_range.1)\n .last(),\n &mut self.next_message,\n ) {\n if !user_msg.has_tool_use_results() {\n debug!(\n \"last assistant message contains tool uses, but next message is set and does not contain tool results. setting tool results as cancelled\"\n );\n *user_msg = UserMessage::new_cancelled_tool_uses(\n user_msg.prompt().map(|p| p.to_string()),\n tool_uses.iter().map(|t| t.id.as_str()),\n );\n }\n }\n\n self.enforce_tool_use_history_invariants();\n }\n```"}], "func_name": "enforce_conversation_invariants", "docstring": "Updates the history so that, when non-empty, the following invariants are in place:\n1. The history length is `<= MAX_CONVERSATION_STATE_HISTORY_LEN`. Oldest messages are\ndropped.\n2. The first message is from the user, and does not contain tool results. Oldest messages\nare dropped.\n3. If the last message from the assistant contains tool results, and a next user message is\nset without tool results, then the user message will have \"cancelled\" tool results.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "67246563cdaca178ec3aedbfeda470018a0ef9d66e12989a06bf27de5d34a531"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: enforce_tool_use_history_invariants\n\nDocumentation:\nHere we also need to make sure that the tool result corresponds to one of the tools\nin the list. Otherwise we will see validation error from the backend. There are three\nsuch circumstances where intervention would be needed:\n1. The model had decided to call a tool with its partial name AND there is only one such\ntool, in which case we would automatically resolve this tool call to its correct name.\nThis will NOT result in an error in its tool result. The intervention here is to\nsubstitute the partial name with its full name.\n2. The model had decided to call a tool with its partial name AND there are multiple tools\nit could be referring to, in which case we WILL return an error in the tool result. The\nintervention here is to substitute the ambiguous, partial name with a dummy.\n3. The model had decided to call a tool that does not exist. The intervention here is to\nsubstitute the non-existent tool name with a dummy.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn enforce_tool_use_history_invariants(&mut self) {\n let tool_names: HashSet<_> = self\n .tools\n .values()\n .flat_map(|tools| {\n tools.iter().map(|tool| match tool {\n Tool::ToolSpecification(tool_specification) => tool_specification.name.as_str(),\n })\n })\n .filter(|name| *name != DUMMY_TOOL_NAME)\n .collect();\n\n for (_, assistant) in &mut self.history {\n if let AssistantMessage::ToolUse { ref mut tool_uses, .. } = assistant {\n for tool_use in tool_uses {\n if tool_names.contains(tool_use.name.as_str()) {\n continue;\n }\n\n if tool_names.contains(tool_use.orig_name.as_str()) {\n tool_use.name = tool_use.orig_name.clone();\n tool_use.args = tool_use.orig_args.clone();\n continue;\n }\n\n let names: Vec<&str> = tool_names\n .iter()\n .filter_map(|name| {\n if name.ends_with(&tool_use.name) {\n Some(*name)\n } else {\n None\n }\n })\n .collect();\n\n // There's only one tool use matching, so we can just replace it with the\n // found name.\n if names.len() == 1 {\n tool_use.name = (*names.first().unwrap()).to_string();\n continue;\n }\n\n // Otherwise, we have to replace it with a dummy.\n tool_use.name = DUMMY_TOOL_NAME.to_string();\n }\n }\n }\n }\n```"}], "func_name": "enforce_tool_use_history_invariants", "docstring": "Here we also need to make sure that the tool result corresponds to one of the tools\nin the list. Otherwise we will see validation error from the backend. There are three\nsuch circumstances where intervention would be needed:\n1. The model had decided to call a tool with its partial name AND there is only one such\ntool, in which case we would automatically resolve this tool call to its correct name.\nThis will NOT result in an error in its tool result. The intervention here is to\nsubstitute the partial name with its full name.\n2. The model had decided to call a tool with its partial name AND there are multiple tools\nit could be referring to, in which case we WILL return an error in the tool result. The\nintervention here is to substitute the ambiguous, partial name with a dummy.\n3. The model had decided to call a tool that does not exist. The intervention here is to\nsubstitute the non-existent tool name with a dummy.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "46cda01e0e28c0ee5efba5b6345708d35b1b3f947532a5b94039f5377359ee7f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: abandon_tool_use\n\nDocumentation:\nSets the next user message with \"cancelled\" tool results.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn abandon_tool_use(&mut self, tools_to_be_abandoned: Vec, deny_input: String) {\n self.next_message = Some(UserMessage::new_cancelled_tool_uses(\n Some(deny_input),\n tools_to_be_abandoned.iter().map(|t| t.id.as_str()),\n ));\n }\n```"}], "func_name": "abandon_tool_use", "docstring": "Sets the next user message with \"cancelled\" tool results.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c06ea5d7d2abdf8861f9ba63cd5a37954436762acf492b01b062a1ffc7b5abd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_sendable_conversation_state\n\nDocumentation:\nReturns a [FigConversationState] capable of being sent by [api_client::StreamingClient].\n\nParams:\n- `run_hooks` - whether hooks should be executed and included as context\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn as_sendable_conversation_state(&mut self, run_hooks: bool) -> FigConversationState {\n debug_assert!(self.next_message.is_some());\n self.enforce_conversation_invariants();\n self.history.drain(self.valid_history_range.1..);\n self.history.drain(..self.valid_history_range.0);\n\n let context = self.backend_conversation_state(run_hooks, false).await;\n if !context.dropped_context_files.is_empty() {\n let mut output = SharedWriter::stdout();\n execute!(\n output,\n style::SetForegroundColor(Color::DarkYellow),\n style::Print(\"\\nSome context files are dropped due to size limit, please run \"),\n style::SetForegroundColor(Color::DarkGreen),\n style::Print(\"/context show \"),\n style::SetForegroundColor(Color::DarkYellow),\n style::Print(\"to learn more.\\n\"),\n style::SetForegroundColor(style::Color::Reset)\n )\n .ok();\n }\n\n context\n .into_fig_conversation_state()\n .expect(\"unable to construct conversation state\")\n }\n```"}], "func_name": "as_sendable_conversation_state", "docstring": "Returns a [FigConversationState] capable of being sent by [api_client::StreamingClient].\n\nParams:\n- `run_hooks` - whether hooks should be executed and included as context", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d8c46cb743d3f31c4476192220bf6b4f28cf73da3a6269e32d96f5ff8f4fc5cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: backend_conversation_state\n\nDocumentation:\nReturns a conversation state representation which reflects the exact conversation to send\nback to the model.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn backend_conversation_state(&mut self, run_hooks: bool, quiet: bool) -> BackendConversationState<'_> {\n self.update_state(false).await;\n self.enforce_conversation_invariants();\n\n // Run hooks and add to conversation start and next user message.\n let mut conversation_start_context = None;\n if let (true, Some(cm)) = (run_hooks, self.context_manager.as_mut()) {\n let mut null_writer = SharedWriter::null();\n let updates = if quiet {\n None\n } else {\n Some(self.updates.as_mut().unwrap_or(&mut null_writer))\n };\n let hook_results = cm.run_hooks(updates).await;\n conversation_start_context = Some(format_hook_context(hook_results.iter(), HookTrigger::ConversationStart));\n\n // add per prompt content to next_user_message if available\n if let Some(next_message) = self.next_message.as_mut() {\n next_message.additional_context = format_hook_context(hook_results.iter(), HookTrigger::PerPrompt);\n }\n }\n\n let (context_messages, dropped_context_files) = self.context_messages(conversation_start_context).await;\n\n BackendConversationState {\n conversation_id: self.conversation_id.as_str(),\n next_user_message: self.next_message.as_ref(),\n history: self\n .history\n .range(self.valid_history_range.0..self.valid_history_range.1),\n context_messages,\n dropped_context_files,\n tools: &self.tools,\n }\n }\n```"}], "func_name": "backend_conversation_state", "docstring": "Returns a conversation state representation which reflects the exact conversation to send\nback to the model.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d654fa8392e4a58138044d81a14c8279dda2aefade24db3132b2aa20eb2b34d1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: can_create_summary_request\n\nDocumentation:\nWhether or not it is possible to create a summary out of this conversation state.\n\nCurrently only checks if we have enough messages in the history to create a summary out of.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn can_create_summary_request(&mut self) -> bool {\n self.backend_conversation_state(false, true).await.history.len() >= 2\n }\n```"}], "func_name": "can_create_summary_request", "docstring": "Whether or not it is possible to create a summary out of this conversation state.\n\nCurrently only checks if we have enough messages in the history to create a summary out of.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e083cb30726b3af406ce02d57b0a29808ef486a0dcbe2c3383053c0f327ac5f2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_summary_request\n\nDocumentation:\nReturns a [FigConversationState] capable of replacing the history of the current\nconversation with a summary generated by the model.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn create_summary_request(&mut self, custom_prompt: Option>) -> FigConversationState {\n let summary_content = match custom_prompt {\n Some(custom_prompt) => {\n // Make the custom instructions much more prominent and directive\n format!(\n \"[SYSTEM NOTE: This is an automated summarization request, not from the user]\\n\\n\\\n FORMAT REQUIREMENTS: Create a structured, concise summary in bullet-point format. DO NOT respond conversationally. DO NOT address the user directly.\\n\\n\\\n IMPORTANT CUSTOM INSTRUCTION: {}\\n\\n\\\n Your task is to create a structured summary document containing:\\n\\\n 1) A bullet-point list of key topics/questions covered\\n\\\n 2) Bullet points for all significant tools executed and their results\\n\\\n 3) Bullet points for any code or technical information shared\\n\\\n 4) A section of key insights gained\\n\\n\\\n FORMAT THE SUMMARY IN THIRD PERSON, NOT AS A DIRECT RESPONSE. Example format:\\n\\n\\\n ## CONVERSATION SUMMARY\\n\\\n * Topic 1: Key information\\n\\\n * Topic 2: Key information\\n\\n\\\n ## TOOLS EXECUTED\\n\\\n * Tool X: Result Y\\n\\n\\\n Remember this is a DOCUMENT not a chat response. The custom instruction above modifies what to prioritize.\\n\\\n FILTER OUT CHAT CONVENTIONS (greetings, offers to help, etc).\",\n custom_prompt.as_ref()\n )\n },\n None => {\n // Default prompt\n \"[SYSTEM NOTE: This is an automated summarization request, not from the user]\\n\\n\\\n FORMAT REQUIREMENTS: Create a structured, concise summary in bullet-point format. DO NOT respond conversationally. DO NOT address the user directly.\\n\\n\\\n Your task is to create a structured summary document containing:\\n\\\n 1) A bullet-point list of key topics/questions covered\\n\\\n 2) Bullet points for all significant tools executed and their results\\n\\\n 3) Bullet points for any code or technical information shared\\n\\\n 4) A section of key insights gained\\n\\n\\\n FORMAT THE SUMMARY IN THIRD PERSON, NOT AS A DIRECT RESPONSE. Example format:\\n\\n\\\n ## CONVERSATION SUMMARY\\n\\\n * Topic 1: Key information\\n\\\n * Topic 2: Key information\\n\\n\\\n ## TOOLS EXECUTED\\n\\\n * Tool X: Result Y\\n\\n\\\n Remember this is a DOCUMENT not a chat response.\\n\\\n FILTER OUT CHAT CONVENTIONS (greetings, offers to help, etc).\".to_string()\n },\n };\n\n let conv_state = self.backend_conversation_state(false, true).await;\n\n // Include everything but the last message in the history.\n let history_len = conv_state.history.len();\n let history = if history_len < 2 {\n vec![]\n } else {\n flatten_history(conv_state.history.take(history_len.saturating_sub(1)))\n };\n\n let mut summary_message = UserInputMessage {\n content: summary_content,\n user_input_message_context: None,\n user_intent: None,\n images: None,\n };\n\n // If the last message contains tool uses, then add cancelled tool results to the summary\n // message.\n if let Some(ChatMessage::AssistantResponseMessage(AssistantResponseMessage {\n tool_uses: Some(tool_uses),\n ..\n })) = history.last()\n {\n self.set_cancelled_tool_results(&mut summary_message, tool_uses);\n }\n\n FigConversationState {\n conversation_id: Some(self.conversation_id.clone()),\n user_input_message: summary_message,\n history: Some(history),\n }\n }\n```"}], "func_name": "create_summary_request", "docstring": "Returns a [FigConversationState] capable of replacing the history of the current\nconversation with a summary generated by the model.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4523934d438d73afad2fcba366a340c56654b14a39c7a9fcb1956f178cf2c6db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: context_messages\n\nDocumentation:\nReturns pairs of user and assistant messages to include as context in the message history\nincluding both summaries and context files if available, and the dropped context files.\n\nTODO:\n- Either add support for multiple context messages if the context is too large to fit inside\na single user message, or handle this case more gracefully. For now, always return 2\nmessages.\n- Cache this return for some period of time.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn context_messages(\n &mut self,\n conversation_start_context: Option,\n ) -> (Option>, Vec<(String, String)>) {\n let mut context_content = String::new();\n let mut dropped_context_files = Vec::new();\n if let Some(summary) = &self.latest_summary {\n context_content.push_str(CONTEXT_ENTRY_START_HEADER);\n context_content.push_str(\"This summary contains ALL relevant information from our previous conversation including tool uses, results, code analysis, and file operations. YOU MUST reference this information when answering questions and explicitly acknowledge specific details from the summary when they're relevant to the current question.\\n\\n\");\n context_content.push_str(\"SUMMARY CONTENT:\\n\");\n context_content.push_str(summary);\n context_content.push('\\n');\n context_content.push_str(CONTEXT_ENTRY_END_HEADER);\n }\n\n // Add context files if available\n if let Some(context_manager) = self.context_manager.as_mut() {\n match context_manager.collect_context_files_with_limit().await {\n Ok((files_to_use, files_dropped)) => {\n if !files_dropped.is_empty() {\n dropped_context_files.extend(files_dropped);\n }\n\n if !files_to_use.is_empty() {\n context_content.push_str(CONTEXT_ENTRY_START_HEADER);\n for (filename, content) in files_to_use {\n context_content.push_str(&format!(\"[{}]\\n{}\\n\", filename, content));\n }\n context_content.push_str(CONTEXT_ENTRY_END_HEADER);\n }\n },\n Err(e) => {\n warn!(\"Failed to get context files: {}\", e);\n },\n }\n }\n\n if let Some(context) = conversation_start_context {\n context_content.push_str(&context);\n }\n\n if !context_content.is_empty() {\n self.context_message_length = Some(context_content.len());\n let user_msg = UserMessage::new_prompt(context_content);\n let assistant_msg = AssistantMessage::new_response(None, \"I will fully incorporate this information when generating my responses, and explicitly acknowledge relevant parts of the summary when answering questions.\".into());\n (Some(vec![(user_msg, assistant_msg)]), dropped_context_files)\n } else {\n (None, dropped_context_files)\n }\n }\n```"}], "func_name": "context_messages", "docstring": "Returns pairs of user and assistant messages to include as context in the message history\nincluding both summaries and context files if available, and the dropped context files.\n\nTODO:\n- Either add support for multiple context messages if the context is too large to fit inside\na single user message, or handle this case more gracefully. For now, always return 2\nmessages.\n- Cache this return for some period of time.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ae4576bed34c3c4422d0116aa128791c7f2d0203a066b49497a044c4f79d1ef8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: calculate_char_count\n\nDocumentation:\nCalculate the total character count in the conversation\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn calculate_char_count(&mut self) -> CharCount {\n self.backend_conversation_state(false, true).await.char_count()\n }\n```"}], "func_name": "calculate_char_count", "docstring": "Calculate the total character count in the conversation", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "246636aabd4dc213a3975f1a5a8ff42dffb680f4a32bf8704846209ec89c8774"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_token_warning_level\n\nDocumentation:\nGet the current token warning level\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_token_warning_level(&mut self) -> TokenWarningLevel {\n let total_chars = self.calculate_char_count().await;\n\n if *total_chars >= MAX_CHARS {\n TokenWarningLevel::Critical\n } else {\n TokenWarningLevel::None\n }\n }\n```"}], "func_name": "get_token_warning_level", "docstring": "Get the current token warning level", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "adaf410c6ace7ec6beeb5f5a8ba89828d48c713bedcdc042271470d3157b77cc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_cancelled_tool_results\n\nDocumentation:\nMutates `msg` so that it will contain an appropriate [UserInputMessageContext] that\ncontains \"cancelled\" tool results for `tool_uses`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_cancelled_tool_results(&self, msg: &mut UserInputMessage, tool_uses: &[ToolUse]) {\n match msg.user_input_message_context.as_mut() {\n Some(ctx) => {\n if ctx.tool_results.as_ref().is_none_or(|r| r.is_empty()) {\n debug!(\n \"last assistant message contains tool uses, but next message is set and does not contain tool results. setting tool results as cancelled\"\n );\n ctx.tool_results = Some(\n tool_uses\n .iter()\n .map(|tool_use| ToolResult {\n tool_use_id: tool_use.tool_use_id.clone(),\n content: vec![ToolResultContentBlock::Text(\n \"Tool use was cancelled by the user\".to_string(),\n )],\n status: crate::api_client::model::ToolResultStatus::Error,\n })\n .collect::>(),\n );\n }\n },\n None => {\n debug!(\n \"last assistant message contains tool uses, but next message is set and does not contain tool results. setting tool results as cancelled\"\n );\n let tool_results = tool_uses\n .iter()\n .map(|tool_use| ToolResult {\n tool_use_id: tool_use.tool_use_id.clone(),\n content: vec![ToolResultContentBlock::Text(\n \"Tool use was cancelled by the user\".to_string(),\n )],\n status: crate::api_client::model::ToolResultStatus::Error,\n })\n .collect::>();\n let user_input_message_context = UserInputMessageContext {\n env_state: Some(build_env_state()),\n tool_results: Some(tool_results),\n tools: if self.tools.is_empty() {\n None\n } else {\n Some(self.tools.values().flatten().cloned().collect::>())\n },\n ..Default::default()\n };\n msg.user_input_message_context = Some(user_input_message_context);\n },\n }\n }\n```"}], "func_name": "set_cancelled_tool_results", "docstring": "Mutates `msg` so that it will contain an appropriate [UserInputMessageContext] that\ncontains \"cancelled\" tool results for `tool_uses`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a26a387f480512cefa86826ebff8bc2eea5cc43394886fb3200457f7420e1b2d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: flatten_history\n\nDocumentation:\nConverts a list of user/assistant message pairs into a flattened list of ChatMessage.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn flatten_history<'a, T>(history: T) -> Vec\nwhere\n T: Iterator,\n{\n history.fold(Vec::new(), |mut acc, (user, assistant)| {\n acc.push(ChatMessage::UserInputMessage(user.clone().into_history_entry()));\n acc.push(ChatMessage::AssistantResponseMessage(assistant.clone().into()));\n acc\n })\n}\n```"}], "func_name": "flatten_history", "docstring": "Converts a list of user/assistant message pairs into a flattened list of ChatMessage.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/conversation_state.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/conversation_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e67e57f30e8e044a93ac1f83f51f6fb584554ad1234bbbce6506fb98960b6664"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_prompt\n\nDocumentation:\nCreates a new [UserMessage::Prompt], automatically detecting and adding the user's\nenvironment [UserEnvContext].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_prompt(prompt: String) -> Self {\n Self {\n images: None,\n additional_context: String::new(),\n env_context: UserEnvContext::generate_new(),\n content: UserMessageContent::Prompt { prompt },\n }\n }\n```"}], "func_name": "new_prompt", "docstring": "Creates a new [UserMessage::Prompt], automatically detecting and adding the user's\nenvironment [UserEnvContext].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "19b4903f79c584dab1e74b7ab8d0edfedb74e78b99f8af17014c6887f5772adf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_history_entry\n\nDocumentation:\nConverts this message into a [UserInputMessage] to be stored in the history of\n[api_client::model::ConversationState].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_history_entry(self) -> UserInputMessage {\n UserInputMessage {\n images: None,\n content: self.prompt().unwrap_or_default().to_string(),\n user_input_message_context: Some(UserInputMessageContext {\n env_state: self.env_context.env_state,\n tool_results: match self.content {\n UserMessageContent::CancelledToolUses { tool_use_results, .. }\n | UserMessageContent::ToolUseResults { tool_use_results } => {\n Some(tool_use_results.into_iter().map(Into::into).collect())\n },\n UserMessageContent::Prompt { .. } => None,\n },\n tools: None,\n ..Default::default()\n }),\n user_intent: None,\n }\n }\n```"}], "func_name": "into_history_entry", "docstring": "Converts this message into a [UserInputMessage] to be stored in the history of\n[api_client::model::ConversationState].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c826547a43a1e9762a50fc552d421489fe7bb5c620d5e9e5bf51660e26c59834"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_user_input_message\n\nDocumentation:\nConverts this message into a [UserInputMessage] to be sent as\n[FigConversationState::user_input_message].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_user_input_message(self) -> UserInputMessage {\n let formatted_prompt = match self.prompt() {\n Some(prompt) if !prompt.is_empty() => {\n format!(\"{}{}{}\", USER_ENTRY_START_HEADER, prompt, USER_ENTRY_END_HEADER)\n },\n _ => String::new(),\n };\n UserInputMessage {\n images: self.images,\n content: format!(\"{} {}\", self.additional_context, formatted_prompt)\n .trim()\n .to_string(),\n user_input_message_context: Some(UserInputMessageContext {\n env_state: self.env_context.env_state,\n tool_results: match self.content {\n UserMessageContent::CancelledToolUses { tool_use_results, .. }\n | UserMessageContent::ToolUseResults { tool_use_results } => {\n Some(tool_use_results.into_iter().map(Into::into).collect())\n },\n UserMessageContent::Prompt { .. } => None,\n },\n tools: None,\n ..Default::default()\n }),\n user_intent: None,\n }\n }\n```"}], "func_name": "into_user_input_message", "docstring": "Converts this message into a [UserInputMessage] to be sent as\n[FigConversationState::user_input_message].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/message.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/message.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7b2d45fa11ac353e99ebb69be0add2171b27de0a7d3d6ee530062f3b14d523fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: recv\n\nDocumentation:\nConsumes the associated [ConverseStreamResponse] until a valid [ResponseEvent] is parsed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn recv(&mut self) -> Result {\n if let Some((id, name)) = self.parsing_tool_use.take() {\n let tool_use = self.parse_tool_use(id, name).await?;\n self.tool_uses.push(tool_use.clone());\n return Ok(ResponseEvent::ToolUse(tool_use));\n }\n\n // First, handle discarding AssistantResponseEvent's that immediately precede a\n // CodeReferenceEvent.\n let peek = self.peek().await?;\n if let Some(ChatResponseStream::AssistantResponseEvent { content }) = peek {\n // Cloning to bypass borrowchecker stuff.\n let content = content.clone();\n self.next().await?;\n match self.peek().await? {\n Some(ChatResponseStream::CodeReferenceEvent(_)) => (),\n _ => {\n self.assistant_text.push_str(&content);\n return Ok(ResponseEvent::AssistantText(content));\n },\n }\n }\n\n loop {\n match self.next().await {\n Ok(Some(output)) => match output {\n ChatResponseStream::AssistantResponseEvent { content } => {\n self.assistant_text.push_str(&content);\n return Ok(ResponseEvent::AssistantText(content));\n },\n ChatResponseStream::InvalidStateEvent { reason, message } => {\n error!(%reason, %message, \"invalid state event\");\n },\n ChatResponseStream::ToolUseEvent {\n tool_use_id,\n name,\n input,\n stop,\n } => {\n debug_assert!(input.is_none(), \"Unexpected initial content in first tool use event\");\n debug_assert!(\n stop.is_none_or(|v| !v),\n \"Unexpected immediate stop in first tool use event\"\n );\n self.parsing_tool_use = Some((tool_use_id.clone(), name.clone()));\n return Ok(ResponseEvent::ToolUseStart { name });\n },\n _ => {},\n },\n Ok(None) => {\n let message_id = Some(self.message_id.clone());\n let content = std::mem::take(&mut self.assistant_text);\n let message = if self.tool_uses.is_empty() {\n AssistantMessage::new_response(message_id, content)\n } else {\n AssistantMessage::new_tool_use(\n message_id,\n content,\n self.tool_uses.clone().into_iter().collect(),\n )\n };\n return Ok(ResponseEvent::EndStream { message });\n },\n Err(err) => return Err(err),\n }\n }\n }\n```"}], "func_name": "recv", "docstring": "Consumes the associated [ConverseStreamResponse] until a valid [ResponseEvent] is parsed.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/parser.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ced4b91d19e797a41c6999a213840e8245c3411cd22f64484d52040e7d2c0506"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_tool_use\n\nDocumentation:\nConsumes the response stream until a valid [ToolUse] is parsed.\n\nThe arguments are the fields from the first [ChatResponseStream::ToolUseEvent] consumed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn parse_tool_use(&mut self, id: String, name: String) -> Result {\n let mut tool_string = String::new();\n let start = Instant::now();\n while let Some(ChatResponseStream::ToolUseEvent { .. }) = self.peek().await? {\n if let Some(ChatResponseStream::ToolUseEvent { input, stop, .. }) = self.next().await? {\n if let Some(i) = input {\n tool_string.push_str(&i);\n }\n if let Some(true) = stop {\n break;\n }\n }\n }\n\n let args = match serde_json::from_str(&tool_string) {\n Ok(args) => args,\n Err(err) if !tool_string.is_empty() => {\n // If we failed deserializing after waiting for a long time, then this is most\n // likely bedrock responding with a stop event for some reason without actually\n // including the tool contents. Essentially, the tool was too large.\n // Timeouts have been seen as short as ~1 minute, so setting the time to 30.\n let time_elapsed = start.elapsed();\n let args = serde_json::Value::Object(\n [(\n \"key\".to_string(),\n serde_json::Value::String(\n \"WARNING: the actual tool use arguments were too complicated to be generated\".to_string(),\n ),\n )]\n .into_iter()\n .collect(),\n );\n if self.peek().await?.is_none() && time_elapsed > Duration::from_secs(30) {\n error!(\n \"Received an unexpected end of stream after spending ~{}s receiving tool events\",\n time_elapsed.as_secs_f64()\n );\n self.tool_uses.push(AssistantToolUse {\n id: id.clone(),\n name: name.clone(),\n orig_name: name.clone(),\n args: args.clone(),\n orig_args: args.clone(),\n });\n let message = Box::new(AssistantMessage::new_tool_use(\n Some(self.message_id.clone()),\n std::mem::take(&mut self.assistant_text),\n self.tool_uses.clone().into_iter().collect(),\n ));\n return Err(self.error(RecvErrorKind::UnexpectedToolUseEos {\n tool_use_id: id,\n name,\n message,\n time_elapsed,\n }));\n } else {\n return Err(self.error(err));\n }\n },\n // if the tool just does not need any input\n _ => serde_json::json!({}),\n };\n let orig_name = name.clone();\n let orig_args = args.clone();\n Ok(AssistantToolUse {\n id,\n name,\n orig_name,\n args,\n orig_args,\n })\n }\n```"}], "func_name": "parse_tool_use", "docstring": "Consumes the response stream until a valid [ToolUse] is parsed.\n\nThe arguments are the fields from the first [ChatResponseStream::ToolUseEvent] consumed.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/parser.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8fc92c8487ff66cb750d81b52ef64c3d23573b22749fcfdeab9abdf8e46898fc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: peek\n\nDocumentation:\nReturns the next event in the [SendMessageOutput] without consuming it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn peek(&mut self) -> Result, RecvError> {\n if self.peek.is_some() {\n return Ok(self.peek.as_ref());\n }\n match self.next().await? {\n Some(v) => {\n self.peek = Some(v);\n Ok(self.peek.as_ref())\n },\n None => Ok(None),\n }\n }\n```"}], "func_name": "peek", "docstring": "Returns the next event in the [SendMessageOutput] without consuming it.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/parser.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6dc2044c8a3a5c197c622522de31afcf45aad0c29dbb1511b19f1c988dcab3bc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: error\n\nDocumentation:\nHelper to create a new [RecvError] populated with the associated request id for the stream.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn error(&self, source: impl Into) -> RecvError {\n RecvError {\n request_id: self.request_id().map(str::to_string),\n source: source.into(),\n }\n }\n```"}], "func_name": "error", "docstring": "Helper to create a new [RecvError] populated with the associated request id for the stream.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/parser.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a2c679a30b09ca538fd89a9cbfd3c9ddc4712978f6f3dc7972127db51f022bd0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: complete_command\n\nDocumentation:\nComplete commands that start with a slash\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn complete_command(word: &str, start: usize) -> (usize, Vec) {\n (\n start,\n COMMANDS\n .iter()\n .filter(|p| p.starts_with(word))\n .map(|s| (*s).to_owned())\n .collect(),\n )\n}\n```"}], "func_name": "complete_command", "docstring": "Complete commands that start with a slash", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/prompt.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/prompt.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa02e08f56322386a6375112bc09ac3dfca78cc02622c3b0470cadb293b02930"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: complete_path\n\nDocumentation:\nAttempts to complete a file path at the given position in the line\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn complete_path(\n &self,\n line: &str,\n pos: usize,\n ctx: &Context<'_>,\n ) -> Result<(usize, Vec), ReadlineError> {\n // Use the filename completer to get path completions\n match self.filename_completer.complete(line, pos, ctx) {\n Ok((pos, completions)) => {\n // Convert the filename completer's pairs to strings\n let file_completions: Vec = completions.iter().map(|pair| pair.replacement.clone()).collect();\n\n // Return the completions if we have any\n Ok((pos, file_completions))\n },\n Err(err) => Err(err),\n }\n }\n```"}], "func_name": "complete_path", "docstring": "Attempts to complete a file path at the given position in the line", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/prompt.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/prompt.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9234e00b68c76dd4085b7caf66d8aedbc441ade6291365737691b273642869b5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nThis allows the ConditionalEventHandler handle function to be bound to a KeyEvent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(context_manager: Arc, tool_names: Vec) -> Self {\n Self {\n context_manager,\n tool_names,\n }\n }\n```"}], "func_name": "new", "docstring": "This allows the ConditionalEventHandler handle function to be bound to a KeyEvent.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/skim_integration.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/skim_integration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d82b3eeda233129ff759958d3cbaeca549a0d0ac1e0c05081446e34df2ec4ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_skim_options\n\nDocumentation:\nFormat commands for skim display\nCreate a standard set of skim options with consistent styling\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn create_skim_options(prompt: &str, multi: bool) -> Result {\n SkimOptionsBuilder::default()\n .height(\"100%\".to_string())\n .prompt(prompt.to_string())\n .reverse(true)\n .multi(multi)\n .build()\n .map_err(|e| eyre!(\"Failed to build skim options: {}\", e))\n}\n```"}], "func_name": "create_skim_options", "docstring": "Format commands for skim display\nCreate a standard set of skim options with consistent styling", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/skim_integration.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/skim_integration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "249243315fa79f6940b546bcb03e0cd1379a490d2107cf247efa829db754b86c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_skim_with_options\n\nDocumentation:\nRun skim with the given options and items in an alternate screen\nThis helper function handles entering/exiting the alternate screen and running skim\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn run_skim_with_options(options: &SkimOptions, items: SkimItemReceiver) -> Result>>> {\n // Enter alternate screen to prevent skim output from persisting in terminal history\n execute!(stdout(), EnterAlternateScreen).map_err(|e| eyre!(\"Failed to enter alternate screen: {}\", e))?;\n\n let selected_items =\n Skim::run_with(options, Some(items)).and_then(|out| if out.is_abort { None } else { Some(out.selected_items) });\n\n execute!(stdout(), LeaveAlternateScreen).map_err(|e| eyre!(\"Failed to leave alternate screen: {}\", e))?;\n\n Ok(selected_items)\n}\n```"}], "func_name": "run_skim_with_options", "docstring": "Run skim with the given options and items in an alternate screen\nThis helper function handles entering/exiting the alternate screen and running skim", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/skim_integration.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/skim_integration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0f14e59faeae0c5da382677d4f3b6b943be492883de6328175922db8c22b0aa6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: extract_selections\n\nDocumentation:\nExtract string selections from skim items\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn extract_selections(items: Vec>) -> Vec {\n items.iter().map(|item| item.output().to_string()).collect()\n}\n```"}], "func_name": "extract_selections", "docstring": "Extract string selections from skim items", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/skim_integration.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/skim_integration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c410dd45891ec34b97b3f0489e6568c9e18534c958da683af5e655a7b6868eae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: launch_skim_selector\n\nDocumentation:\nLaunch skim with the given items and return the selected item\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn launch_skim_selector(items: &[String], prompt: &str, multi: bool) -> Result>> {\n let mut temp_file_for_skim_input = NamedTempFile::new()?;\n temp_file_for_skim_input.write_all(items.join(\"\\n\").as_bytes())?;\n\n let options = create_skim_options(prompt, multi)?;\n let item_reader = SkimItemReader::default();\n let items = item_reader.of_bufread(BufReader::new(std::fs::File::open(temp_file_for_skim_input.path())?));\n\n // Run skim and get selected items\n match run_skim_with_options(&options, items)? {\n Some(items) if !items.is_empty() => {\n let selections = extract_selections(items);\n Ok(Some(selections))\n },\n _ => Ok(None), // User cancelled or no selection\n }\n}\n```"}], "func_name": "launch_skim_selector", "docstring": "Launch skim with the given items and return the selected item", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/skim_integration.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/skim_integration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc2cc4b2d28d3208f2fe03a958e02b7e438cc52373a4d4c5d45db40d711ea888"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: select_command\n\nDocumentation:\nLaunch the command selector and handle the selected command\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn select_command(context_manager: &ContextManager, tools: &[String]) -> Result> {\n let commands = get_available_commands();\n\n match launch_skim_selector(&commands, \"Select command: \", false)? {\n Some(selections) if !selections.is_empty() => {\n let selected_command = &selections[0];\n\n match CommandType::from_str(selected_command) {\n Some(CommandType::ContextAdd(cmd)) => {\n // For context add commands, we need to select files\n match select_files_with_skim()? {\n Some(files) if !files.is_empty() => {\n // Construct the full command with selected files\n let mut cmd = cmd.clone();\n for file in files {\n cmd.push_str(&format!(\" {}\", file));\n }\n Ok(Some(cmd))\n },\n _ => Ok(Some(selected_command.clone())), /* User cancelled file selection, return just the\n * command */\n }\n },\n Some(CommandType::ContextRemove(cmd)) => {\n // For context rm commands, we need to select from existing context paths\n match select_context_paths_with_skim(context_manager)? {\n Some((paths, has_global)) if !paths.is_empty() => {\n // Construct the full command with selected paths\n let mut full_cmd = cmd.clone();\n if has_global {\n full_cmd.push_str(\" --global\");\n }\n for path in paths {\n full_cmd.push_str(&format!(\" {}\", path));\n }\n Ok(Some(full_cmd))\n },\n Some((_, _)) => Ok(Some(format!(\"{} (No paths selected)\", cmd))),\n None => Ok(Some(selected_command.clone())), // User cancelled path selection\n }\n },\n Some(CommandType::Tools(_)) => {\n let options = create_skim_options(\"Select tool: \", false)?;\n let item_reader = SkimItemReader::default();\n let items = item_reader.of_bufread(Cursor::new(tools.join(\"\\n\")));\n let selected_tool = match run_skim_with_options(&options, items)? {\n Some(items) if !items.is_empty() => Some(items[0].output().to_string()),\n _ => None,\n };\n\n match selected_tool {\n Some(tool) => Ok(Some(format!(\"{} {}\", selected_command, tool))),\n None => Ok(Some(selected_command.clone())), /* User cancelled tool selection, return just the\n * command */\n }\n },\n Some(cmd @ CommandType::Profile(_)) if cmd.needs_profile_selection() => {\n // For profile operations that need a profile name, show profile selector\n match select_profile_with_skim(context_manager)? {\n Some(profile) => {\n let full_cmd = format!(\"{} {}\", selected_command, profile);\n Ok(Some(full_cmd))\n },\n None => Ok(Some(selected_command.clone())), // User cancelled profile selection\n }\n },\n Some(CommandType::Profile(_)) => {\n // For other profile operations (like create), just return the command\n Ok(Some(selected_command.clone()))\n },\n None => {\n // Command doesn't need additional parameters\n Ok(Some(selected_command.clone()))\n },\n }\n },\n _ => Ok(None), // User cancelled command selection\n }\n}\n```"}], "func_name": "select_command", "docstring": "Launch the command selector and handle the selected command", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/skim_integration.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/skim_integration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c7160f87dc8a34f6c2da27a32d7cf0316b3198552b27bd0761fa2c1211828d7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_command\n\nDocumentation:\nRun a bash command.\n# Arguments\n* `max_result_size` - max size of output streams, truncating if required\n* `updates` - output stream to push informational messages about the progress\n# Returns\nA [`CommandResult`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_command(\n command: &str,\n max_result_size: usize,\n mut updates: Option,\n) -> Result {\n // We need to maintain a handle on stderr and stdout, but pipe it to the terminal as well\n let mut child = tokio::process::Command::new(\"bash\")\n .arg(\"-c\")\n .arg(command)\n .stdin(Stdio::inherit())\n .stdout(Stdio::piped())\n .stderr(Stdio::piped())\n .spawn()\n .wrap_err_with(|| format!(\"Unable to spawn command '{}'\", command))?;\n\n let stdout_final: String;\n let stderr_final: String;\n let exit_status: ExitStatus;\n\n // Buffered output vs all-at-once\n if let Some(u) = updates.as_mut() {\n let stdout = child.stdout.take().unwrap();\n let stdout = tokio::io::BufReader::new(stdout);\n let mut stdout = stdout.lines();\n\n let stderr = child.stderr.take().unwrap();\n let stderr = tokio::io::BufReader::new(stderr);\n let mut stderr = stderr.lines();\n\n const LINE_COUNT: usize = 1024;\n let mut stdout_buf = VecDeque::with_capacity(LINE_COUNT);\n let mut stderr_buf = VecDeque::with_capacity(LINE_COUNT);\n\n let mut stdout_done = false;\n let mut stderr_done = false;\n exit_status = loop {\n select! {\n biased;\n line = stdout.next_line(), if !stdout_done => match line {\n Ok(Some(line)) => {\n writeln!(u, \"{line}\")?;\n if stdout_buf.len() >= LINE_COUNT {\n stdout_buf.pop_front();\n }\n stdout_buf.push_back(line);\n },\n Ok(None) => stdout_done = true,\n Err(err) => error!(%err, \"Failed to read stdout of child process\"),\n },\n line = stderr.next_line(), if !stderr_done => match line {\n Ok(Some(line)) => {\n writeln!(u, \"{line}\")?;\n if stderr_buf.len() >= LINE_COUNT {\n stderr_buf.pop_front();\n }\n stderr_buf.push_back(line);\n },\n Ok(None) => stderr_done = true,\n Err(err) => error!(%err, \"Failed to read stderr of child process\"),\n },\n exit_status = child.wait() => {\n break exit_status;\n },\n };\n }\n .wrap_err_with(|| format!(\"No exit status for '{}'\", command))?;\n\n u.flush()?;\n\n stdout_final = stdout_buf.into_iter().collect::>().join(\"\\n\");\n stderr_final = stderr_buf.into_iter().collect::>().join(\"\\n\");\n } else {\n // Take output all at once since we are not reporting anything in real time\n //\n // NOTE: If we don't split this logic, then any writes to stdout while calling\n // this function concurrently may cause the piped child output to be ignored\n\n let output = child\n .wait_with_output()\n .await\n .wrap_err_with(|| format!(\"No exit status for '{}'\", command))?;\n\n exit_status = output.status;\n stdout_final = from_utf8(&output.stdout).unwrap_or_default().to_string();\n stderr_final = from_utf8(&output.stderr).unwrap_or_default().to_string();\n }\n\n Ok(CommandResult {\n exit_status: exit_status.code(),\n stdout: format!(\n \"{}{}\",\n truncate_safe(&stdout_final, max_result_size),\n if stdout_final.len() > max_result_size {\n \" ... truncated\"\n } else {\n \"\"\n }\n ),\n stderr: format!(\n \"{}{}\",\n truncate_safe(&stderr_final, max_result_size),\n if stderr_final.len() > max_result_size {\n \" ... truncated\"\n } else {\n \"\"\n }\n ),\n })\n}\n```"}], "func_name": "run_command", "docstring": "Run a bash command.\n# Arguments\n* `max_result_size` - max size of output streams, truncating if required\n* `updates` - output stream to push informational messages about the progress\n# Returns\nA [`CommandResult`]", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/execute_bash.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/execute_bash.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "183b8644fc705224974212bd9d3abf4ca722c23ae32c9cfcc2c18b4cd7953aca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: canonical_create_command_text\n\nDocumentation:\nReturns the text to use for the [FsWrite::Create] command. This is required since we can't\nrely on the model always providing `file_text`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn canonical_create_command_text(&self) -> String {\n match self {\n FsWrite::Create { file_text, new_str, .. } => match (file_text, new_str) {\n (Some(file_text), _) => file_text.clone(),\n (None, Some(new_str)) => {\n warn!(\"required field `file_text` is missing, using the provided `new_str` instead\");\n new_str.clone()\n },\n _ => {\n warn!(\"no content provided for the create command\");\n String::new()\n },\n },\n _ => String::new(),\n }\n }\n```"}], "func_name": "canonical_create_command_text", "docstring": "Returns the text to use for the [FsWrite::Create] command. This is required since we can't\nrely on the model always providing `file_text`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/fs_write.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/fs_write.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6d1ab7817ac72b9f8bf874864352911f0ac551712fc722ebd4da8fad6776463a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_to_file\n\nDocumentation:\nWrites `content` to `path`, adding a newline if necessary.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn write_to_file(ctx: &Context, path: impl AsRef, mut content: String) -> Result<()> {\n if !content.ends_with_newline() {\n content.push('\\n');\n }\n ctx.fs().write(path.as_ref(), content).await?;\n Ok(())\n}\n```"}], "func_name": "write_to_file", "docstring": "Writes `content` to `path`, adding a newline if necessary.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/fs_write.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/fs_write.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "91cc73965c613df99da5117ee21e81ae1ca16e3ba43b0023da574dcdfa1ef43a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_lines_with_context\n\nDocumentation:\nReturns a prefix/suffix pair before and after the content dictated by `[start_line, end_line]`\nwithin `content`. The updated start and end lines containing the original context along with\nthe suffix and prefix are returned.\n\nParams:\n- `start_line` - 1-indexed starting line of the content.\n- `end_line` - 1-indexed ending line of the content.\n- `context_lines` - number of lines to include before the start and end.\n\nReturns `(prefix, new_start_line, suffix, new_end_line)`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_lines_with_context(\n content: &str,\n start_line: usize,\n end_line: usize,\n context_lines: usize,\n) -> (&str, usize, &str, usize) {\n let line_count = content.lines().count();\n // We want to support end_line being 0, in which case we should be able to set the first line\n // as the suffix.\n let zero_check_inc = if end_line == 0 { 0 } else { 1 };\n\n // Convert to 0-indexing.\n let (start_line, end_line) = (\n start_line.saturating_sub(1).clamp(0, line_count - 1),\n end_line.saturating_sub(1).clamp(0, line_count - 1),\n );\n let new_start_line = 0.max(start_line.saturating_sub(context_lines));\n let new_end_line = (line_count - 1).min(end_line + context_lines);\n\n // Build prefix\n let mut prefix_start = 0;\n for line in LinesWithEndings::from(content).take(new_start_line) {\n prefix_start += line.len();\n }\n let mut prefix_end = prefix_start;\n for line in LinesWithEndings::from(&content[prefix_start..]).take(start_line - new_start_line) {\n prefix_end += line.len();\n }\n\n // Build suffix\n let mut suffix_start = 0;\n for line in LinesWithEndings::from(content).take(end_line + zero_check_inc) {\n suffix_start += line.len();\n }\n let mut suffix_end = suffix_start;\n for line in LinesWithEndings::from(&content[suffix_start..]).take(new_end_line - end_line) {\n suffix_end += line.len();\n }\n\n (\n &content[prefix_start..prefix_end],\n new_start_line + 1,\n &content[suffix_start..suffix_end],\n new_end_line + zero_check_inc,\n )\n}\n```"}], "func_name": "get_lines_with_context", "docstring": "Returns a prefix/suffix pair before and after the content dictated by `[start_line, end_line]`\nwithin `content`. The updated start and end lines containing the original context along with\nthe suffix and prefix are returned.\n\nParams:\n- `start_line` - 1-indexed starting line of the content.\n- `end_line` - 1-indexed ending line of the content.\n- `context_lines` - number of lines to include before the start and end.\n\nReturns `(prefix, new_start_line, suffix, new_end_line)`", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/fs_write.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/fs_write.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a4f732e8a45171fe88d0a6965b4ad1e2cad9bb08ec67097b17e8f057920ebd06"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: print_diff\n\nDocumentation:\nPrints a git-diff style comparison between `old_str` and `new_str`.\n- `start_line` - 1-indexed line number that `old_str` and `new_str` start at.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn print_diff(\n updates: &mut impl Write,\n old_str: &StylizedFile,\n new_str: &StylizedFile,\n start_line: usize,\n) -> Result<()> {\n let diff = similar::TextDiff::from_lines(&old_str.content, &new_str.content);\n\n // First, get the gutter width required for both the old and new lines.\n let (mut max_old_i, mut max_new_i) = (1, 1);\n for change in diff.iter_all_changes() {\n if let Some(i) = change.old_index() {\n max_old_i = i + start_line;\n }\n if let Some(i) = change.new_index() {\n max_new_i = i + start_line;\n }\n }\n let old_line_num_width = terminal_width_required_for_line_count(max_old_i);\n let new_line_num_width = terminal_width_required_for_line_count(max_new_i);\n\n // Now, print\n fn fmt_index(i: Option, start_line: usize) -> String {\n match i {\n Some(i) => (i + start_line).to_string(),\n _ => \" \".to_string(),\n }\n }\n for change in diff.iter_all_changes() {\n // Define the colors per line.\n let (text_color, gutter_bg_color, line_bg_color) = match (change.tag(), new_str.truecolor) {\n (similar::ChangeTag::Equal, true) => (style::Color::Reset, new_str.gutter_bg, new_str.line_bg),\n (similar::ChangeTag::Delete, true) => (\n style::Color::Reset,\n style::Color::Rgb { r: 79, g: 40, b: 40 },\n style::Color::Rgb { r: 36, g: 25, b: 28 },\n ),\n (similar::ChangeTag::Insert, true) => (\n style::Color::Reset,\n style::Color::Rgb { r: 40, g: 67, b: 43 },\n style::Color::Rgb { r: 24, g: 38, b: 30 },\n ),\n (similar::ChangeTag::Equal, false) => (style::Color::Reset, new_str.gutter_bg, new_str.line_bg),\n (similar::ChangeTag::Delete, false) => (style::Color::Red, new_str.gutter_bg, new_str.line_bg),\n (similar::ChangeTag::Insert, false) => (style::Color::Green, new_str.gutter_bg, new_str.line_bg),\n };\n // Define the change tag character to print, if any.\n let sign = match change.tag() {\n similar::ChangeTag::Equal => \" \",\n similar::ChangeTag::Delete => \"-\",\n similar::ChangeTag::Insert => \"+\",\n };\n\n let old_i_str = fmt_index(change.old_index(), start_line);\n let new_i_str = fmt_index(change.new_index(), start_line);\n\n // Print the gutter and line numbers.\n queue!(updates, style::SetBackgroundColor(gutter_bg_color))?;\n queue!(\n updates,\n style::SetForegroundColor(text_color),\n style::Print(sign),\n style::Print(\" \")\n )?;\n queue!(\n updates,\n style::Print(format!(\n \"{:>old_line_num_width$}\",\n old_i_str,\n old_line_num_width = old_line_num_width\n ))\n )?;\n if sign == \" \" {\n queue!(updates, style::Print(\", \"))?;\n } else {\n queue!(updates, style::Print(\" \"))?;\n }\n queue!(\n updates,\n style::Print(format!(\n \"{:>new_line_num_width$}\",\n new_i_str,\n new_line_num_width = new_line_num_width\n ))\n )?;\n // Print the line.\n queue!(\n updates,\n style::SetForegroundColor(style::Color::Reset),\n style::Print(\":\"),\n style::SetForegroundColor(text_color),\n style::SetBackgroundColor(line_bg_color),\n style::Print(\" \"),\n style::Print(change),\n style::ResetColor,\n )?;\n }\n queue!(\n updates,\n crossterm::terminal::Clear(crossterm::terminal::ClearType::UntilNewLine),\n style::Print(\"\\n\"),\n )?;\n\n Ok(())\n}\n```"}], "func_name": "print_diff", "docstring": "Prints a git-diff style comparison between `old_str` and `new_str`.\n- `start_line` - 1-indexed line number that `old_str` and `new_str` start at.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/fs_write.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/fs_write.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc0985f4d857bde51786ed7a6cc7108d0c33fe008a376f6b41a1429ee9f04734"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: line_number_at\n\nDocumentation:\nReturns a 1-indexed line number range of the start and end of `needle` inside `file`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn line_number_at(file: impl AsRef, needle: impl AsRef) -> Option<(usize, usize)> {\n let file = file.as_ref();\n let needle = needle.as_ref();\n if let Some((i, _)) = file.match_indices(needle).next() {\n let start = file[..i].matches(\"\\n\").count();\n let end = needle.matches(\"\\n\").count();\n Some((start + 1, start + end + 1))\n } else {\n None\n }\n}\n```"}], "func_name": "line_number_at", "docstring": "Returns a 1-indexed line number range of the start and end of `needle` inside `file`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/fs_write.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/fs_write.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5a4ef7a35861a76f1eb83c00e1e1f3262aeff92cc496e1fe008e4a0024074b54"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stylized_file\n\nDocumentation:\nReturns a 24bit terminal escaped syntax-highlighted [String] of the file pointed to by `path`,\nif able.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn stylized_file(path: impl AsRef, file_text: impl AsRef) -> Result {\n let ps = &*SYNTAX_SET;\n let ts = &*THEME_SET;\n\n let extension = path\n .as_ref()\n .extension()\n .wrap_err(\"missing extension\")?\n .to_str()\n .wrap_err(\"not utf8\")?;\n\n let syntax = ps\n .find_syntax_by_extension(extension)\n .wrap_err_with(|| format!(\"missing extension: {}\", extension))?;\n\n let theme = &ts.themes[\"base16-ocean.dark\"];\n let mut highlighter = HighlightLines::new(syntax, theme);\n let file_text = file_text.as_ref().lines();\n let mut file = String::new();\n for line in file_text {\n let mut ranges = Vec::new();\n ranges.append(&mut highlighter.highlight_line(line, ps)?);\n let mut escaped_line = as_24_bit_terminal_escaped(&ranges[..], false);\n escaped_line.push_str(&format!(\n \"{}\\n\",\n crossterm::terminal::Clear(crossterm::terminal::ClearType::UntilNewLine),\n ));\n file.push_str(&escaped_line);\n }\n\n let (line_bg, gutter_bg) = match (theme.settings.background, theme.settings.gutter) {\n (Some(line_bg), Some(gutter_bg)) => (line_bg, gutter_bg),\n (Some(line_bg), None) => (line_bg, line_bg),\n _ => bail!(\"missing theme\"),\n };\n Ok(StylizedFile {\n truecolor: true,\n content: file,\n gutter_bg: syntect_to_crossterm_color(gutter_bg),\n line_bg: syntect_to_crossterm_color(line_bg),\n })\n}\n```"}], "func_name": "stylized_file", "docstring": "Returns a 24bit terminal escaped syntax-highlighted [String] of the file pointed to by `path`,\nif able.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/fs_write.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/fs_write.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5bb8ab0d1ef5ea1da92fc13ffeb2ababa0e637c0d2d685ed95c5d1f300a32ba6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: setup_test_directory\n\nDocumentation:\nSets up the following filesystem structure:\n```text\ntest_file.txt\n/home/testuser/\n/aaaa1/\n/bbbb1/\n/cccc1/\n/aaaa2/\n.hidden\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn setup_test_directory() -> Arc {\n let ctx = Context::builder().with_test_home().await.unwrap().build_fake();\n let fs = ctx.fs();\n fs.write(TEST_FILE_PATH, TEST_FILE_CONTENTS).await.unwrap();\n fs.create_dir_all(\"/aaaa1/bbbb1/cccc1\").await.unwrap();\n fs.create_dir_all(\"/aaaa2\").await.unwrap();\n fs.write(TEST_HIDDEN_FILE_PATH, \"this is a hidden file\").await.unwrap();\n ctx\n }\n```"}], "func_name": "setup_test_directory", "docstring": "Sets up the following filesystem structure:\n```text\ntest_file.txt\n/home/testuser/\n/aaaa1/\n/bbbb1/\n/cccc1/\n/aaaa2/\n.hidden\n```", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/fs_write.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/fs_write.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ea743a6f208aaf8e002c547a379080decf1ef9852d8a312d3fc5a04260f61ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: requires_acceptance\n\nDocumentation:\nWhether or not the tool should prompt the user to accept before [Self::invoke] is called.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn requires_acceptance(&self, _ctx: &Context) -> bool {\n match self {\n Tool::FsRead(_) => false,\n Tool::FsWrite(_) => true,\n Tool::ExecuteBash(execute_bash) => execute_bash.requires_acceptance(),\n Tool::UseAws(use_aws) => use_aws.requires_acceptance(),\n Tool::Custom(_) => true,\n Tool::GhIssue(_) => false,\n Tool::Thinking(_) => false,\n }\n }\n```"}], "func_name": "requires_acceptance", "docstring": "Whether or not the tool should prompt the user to accept before [Self::invoke] is called.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b0e3cbfe36faeed151e54c734f45f1d063e31dd68b08939de637add4b08cef7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: queue_description\n\nDocumentation:\nQueues up a tool's intention in a human readable format\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn queue_description(&self, ctx: &Context, updates: &mut impl Write) -> Result<()> {\n match self {\n Tool::FsRead(fs_read) => fs_read.queue_description(ctx, updates).await,\n Tool::FsWrite(fs_write) => fs_write.queue_description(ctx, updates),\n Tool::ExecuteBash(execute_bash) => execute_bash.queue_description(updates),\n Tool::UseAws(use_aws) => use_aws.queue_description(updates),\n Tool::Custom(custom_tool) => custom_tool.queue_description(updates),\n Tool::GhIssue(gh_issue) => gh_issue.queue_description(updates),\n Tool::Thinking(thinking) => thinking.queue_description(updates),\n }\n }\n```"}], "func_name": "queue_description", "docstring": "Queues up a tool's intention in a human readable format", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "90ebaa8ca7a34bd0d60270adb2be9160b16f3837643e58153d63e608c9a63e42"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: validate\n\nDocumentation:\nValidates the tool with the arguments supplied\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn validate(&mut self, ctx: &Context) -> Result<()> {\n match self {\n Tool::FsRead(fs_read) => fs_read.validate(ctx).await,\n Tool::FsWrite(fs_write) => fs_write.validate(ctx).await,\n Tool::ExecuteBash(execute_bash) => execute_bash.validate(ctx).await,\n Tool::UseAws(use_aws) => use_aws.validate(ctx).await,\n Tool::Custom(custom_tool) => custom_tool.validate(ctx).await,\n Tool::GhIssue(gh_issue) => gh_issue.validate(ctx).await,\n Tool::Thinking(think) => think.validate(ctx).await,\n }\n }\n```"}], "func_name": "validate", "docstring": "Validates the tool with the arguments supplied", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "151c280575f282d82cad71f1b01298851c2128dc42e8169d1a9b8f4b87bb6a59"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: display_label\n\nDocumentation:\nReturns a label to describe the permission status for a given tool.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn display_label(&self, tool_name: &str) -> String {\n if self.has(tool_name) || self.trust_all {\n if self.is_trusted(tool_name) {\n format!(\" {}\", \"trusted\".dark_green().bold())\n } else {\n format!(\" {}\", \"not trusted\".dark_grey())\n }\n } else {\n self.default_permission_label(tool_name)\n }\n }\n```"}], "func_name": "display_label", "docstring": "Returns a label to describe the permission status for a given tool.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "06c1ed1977751ddd51bfd96502b954f6dc5074c2da4adb48e0f9927ee8e6d9b7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: absolute_to_relative\n\nDocumentation:\nConverts `path` to a relative path according to the current working directory `cwd`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn absolute_to_relative(cwd: impl AsRef, path: impl AsRef) -> Result {\n let cwd = cwd.as_ref().canonicalize()?;\n let path = path.as_ref().canonicalize()?;\n let mut cwd_parts = cwd.components().peekable();\n let mut path_parts = path.components().peekable();\n\n // Skip common prefix\n while let (Some(a), Some(b)) = (cwd_parts.peek(), path_parts.peek()) {\n if a == b {\n cwd_parts.next();\n path_parts.next();\n } else {\n break;\n }\n }\n\n // \"..\" for any uncommon parts, then just append the rest of the path.\n let mut relative = PathBuf::new();\n for _ in cwd_parts {\n relative.push(\"..\");\n }\n for part in path_parts {\n relative.push(part);\n }\n\n Ok(relative)\n}\n```"}], "func_name": "absolute_to_relative", "docstring": "Converts `path` to a relative path according to the current working directory `cwd`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad1828fe3d82abd1d6fad4a4535f55f2d9d847470280dc21349595ec560b3c6c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: format_path\n\nDocumentation:\nSmall helper for formatting the path as a relative path, if able.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn format_path(cwd: impl AsRef, path: impl AsRef) -> String {\n absolute_to_relative(cwd, path.as_ref())\n .map(|p| p.to_string_lossy().to_string())\n // If we have three consecutive \"..\" then it should probably just stay as an absolute path.\n .map(|p| {\n if p.starts_with(\"../../..\") {\n path.as_ref().to_string_lossy().to_string()\n } else {\n p\n }\n })\n .unwrap_or(path.as_ref().to_string_lossy().to_string())\n}\n```"}], "func_name": "format_path", "docstring": "Small helper for formatting the path as a relative path, if able.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b5eaaf4457e72ae8c1ae54d842ceab8cd193abfaac36e77a5fce87d9c22f565"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: queue_description\n\nDocumentation:\nQueues up a description of the think tool for the user\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn queue_description(&self, updates: &mut impl Write) -> Result<()> {\n // Only show a description if there's actual thought content\n if !self.thought.trim().is_empty() {\n // Show a preview of the thought that will be displayed\n queue!(\n updates,\n style::SetForegroundColor(Color::Blue),\n style::Print(\"I'll share my reasoning process: \"),\n style::SetForegroundColor(Color::Reset),\n style::Print(&self.thought),\n style::Print(\"\\n\")\n )?;\n }\n Ok(())\n }\n```"}], "func_name": "queue_description", "docstring": "Queues up a description of the think tool for the user", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/thinking.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/thinking.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f9c5311e075bcb2e97289b5c5fc1fe5529966eb1fc417c013ba77a631eff01ce"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: invoke\n\nDocumentation:\nInvokes the think tool. This doesn't actually perform any system operations,\nit's purely for the model's internal reasoning process.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn invoke(&self, _updates: &mut impl Write) -> Result {\n // The think tool always returns an empty output because:\n // 1. When enabled with content: We've already shown the thought in queue_description\n // 2. When disabled or empty: Nothing should be shown\n Ok(InvokeOutput {\n output: OutputKind::Text(String::new()),\n })\n }\n```"}], "func_name": "invoke", "docstring": "Invokes the think tool. This doesn't actually perform any system operations,\nit's purely for the model's internal reasoning process.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/thinking.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/thinking.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d8c3feeda7ed3acd6aec8b06687db2352e1ddb5d9918242a0141623904f80d1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: validate\n\nDocumentation:\nValidates the thought - accepts empty thoughts\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn validate(&mut self, _ctx: &crate::platform::Context) -> Result<()> {\n // We accept empty thoughts - they'll just be ignored\n // This makes the tool more robust and prevents errors from blocking the model\n Ok(())\n }\n```"}], "func_name": "validate", "docstring": "Validates the thought - accepts empty thoughts", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/thinking.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/thinking.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ab594538f7e219193f6b7708cdc9392ba65daa8c032135242e5f08f9966fbff4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cli_parameters\n\nDocumentation:\nReturns the CLI arguments properly formatted as kebab case if parameters is\n[Option::Some], otherwise None\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn cli_parameters(&self) -> Option> {\n if let Some(parameters) = &self.parameters {\n let mut params = vec![];\n for (param_name, val) in parameters {\n let param_name = format!(\"--{}\", param_name.trim_start_matches(\"--\").to_case(Case::Kebab));\n let param_val = val.as_str().map(|s| s.to_string()).unwrap_or(val.to_string());\n params.push((param_name, param_val));\n }\n Some(params)\n } else {\n None\n }\n }\n```"}], "func_name": "cli_parameters", "docstring": "Returns the CLI arguments properly formatted as kebab case if parameters is\n[Option::Some], otherwise None", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/tools/use_aws.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/tools/use_aws.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "14695441bedde1cc1b445927dcc320b932d97bd1451ae79cbe0c95b32031547b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: play_notification_bell\n\nDocumentation:\nPlay the terminal bell notification sound\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn play_notification_bell(requires_confirmation: bool) {\n // Don't play bell for tools that don't require confirmation\n if !requires_confirmation {\n return;\n }\n\n // Check if we should play the bell based on terminal type\n if should_play_bell() {\n print!(\"\\x07\"); // ASCII bell character\n std::io::stdout().flush().unwrap();\n }\n}\n```"}], "func_name": "play_notification_bell", "docstring": "Play the terminal bell notification sound", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/util/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/util/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94e3a8b907fafa326eb506f13a7e890bc1b83675b5327f3f4df70b9124fe6002"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: should_play_bell\n\nDocumentation:\nDetermine if we should play the bell based on terminal type\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn should_play_bell() -> bool {\n // Get the TERM environment variable\n if let Ok(term) = std::env::var(\"TERM\") {\n // List of terminals known to handle bell character well\n let bell_compatible_terms = [\n \"xterm\",\n \"xterm-256color\",\n \"screen\",\n \"screen-256color\",\n \"tmux\",\n \"tmux-256color\",\n \"rxvt\",\n \"rxvt-unicode\",\n \"linux\",\n \"konsole\",\n \"gnome\",\n \"gnome-256color\",\n \"alacritty\",\n \"iterm2\",\n ];\n\n // Check if the current terminal is in the compatible list\n for compatible_term in bell_compatible_terms.iter() {\n if term.starts_with(compatible_term) {\n return true;\n }\n }\n\n // For other terminals, don't play the bell\n return false;\n }\n\n // If TERM is not set, default to not playing the bell\n false\n}\n```"}], "func_name": "should_play_bell", "docstring": "Determine if we should play the bell based on terminal type", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/cli/chat/util/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/cli/chat/util/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "164b46193b433fbfd510f8346623b113e9c5f80bc1f1f6a6bad916de129da1f2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_credentials_entry\n\nDocumentation:\nGet cognito credentials used by toolkit telemetry.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_credentials_entry(&mut self) -> Result, DatabaseError> {\n self.get_json_entry::(Table::State, CREDENTIALS_KEY)\n }\n```"}], "func_name": "get_credentials_entry", "docstring": "Get cognito credentials used by toolkit telemetry.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6de885f5f7a9906ee8d80820de99189a56720d99a9e20bae5ab5485a16245f1b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_credentials_entry\n\nDocumentation:\nSet cognito credentials used by toolkit telemetry.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_credentials_entry(&mut self, credentials: &Credentials) -> Result {\n self.set_json_entry(Table::State, CREDENTIALS_KEY, CredentialsJson {\n access_key_id: credentials.access_key_id.clone(),\n secret_key: credentials.secret_key.clone(),\n session_token: credentials.session_token.clone(),\n expiration: credentials\n .expiration\n .and_then(|t| t.fmt(DateTimeFormat::DateTime).ok()),\n })\n }\n```"}], "func_name": "set_credentials_entry", "docstring": "Set cognito credentials used by toolkit telemetry.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c485f7de5f5fea4a8c34866674f70dfd95eae2e21e2065fc86c3577c68c0053d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_auth_profile\n\nDocumentation:\nGet the current user profile used to determine API endpoints.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_auth_profile(&self) -> Result, DatabaseError> {\n self.get_json_entry(Table::State, CODEWHISPERER_PROFILE_KEY)\n }\n```"}], "func_name": "get_auth_profile", "docstring": "Get the current user profile used to determine API endpoints.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e3cc4ca25384d7b8718f4e36cd3a594eb963739047917a9da9d6d5288f356d90"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_auth_profile\n\nDocumentation:\nSet the current user profile used to determine API endpoints.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_auth_profile(&mut self, profile: &AuthProfile) -> Result<(), DatabaseError> {\n self.set_json_entry(Table::State, CODEWHISPERER_PROFILE_KEY, profile)?;\n self.delete_entry(Table::State, CUSTOMIZATION_STATE_KEY)\n }\n```"}], "func_name": "set_auth_profile", "docstring": "Set the current user profile used to determine API endpoints.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "75e5c9c9e6f7f22cd0484082acd7a87c9e563c8843ade1ad1dc1d8355d2a7f1a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unset_auth_profile\n\nDocumentation:\nUnset the current user profile used to determine API endpoints.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn unset_auth_profile(&mut self) -> Result<(), DatabaseError> {\n self.delete_entry(Table::State, CODEWHISPERER_PROFILE_KEY)?;\n self.delete_entry(Table::State, CUSTOMIZATION_STATE_KEY)\n }\n```"}], "func_name": "unset_auth_profile", "docstring": "Unset the current user profile used to determine API endpoints.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c860f708256fdf00056032d092b5aecd2ebe0b117efc4b9d0d2c4248307a68a4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_client_id\n\nDocumentation:\nGet the client ID used for telemetry requests.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_client_id(&mut self) -> Result, DatabaseError> {\n Ok(self\n .get_json_entry::(Table::State, CLIENT_ID_KEY)?\n .and_then(|s| Uuid::from_str(&s).ok()))\n }\n```"}], "func_name": "get_client_id", "docstring": "Get the client ID used for telemetry requests.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a32f9715c2b25bd40d6edefd5603c46ea91eb750cc9e43d7062ebc3d8c55908"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_client_id\n\nDocumentation:\nSet the client ID used for telemetry requests.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_client_id(&mut self, client_id: Uuid) -> Result {\n self.set_json_entry(Table::State, CLIENT_ID_KEY, client_id.to_string())\n }\n```"}], "func_name": "set_client_id", "docstring": "Set the client ID used for telemetry requests.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9e7ab30c29e72f51aee7e2c7946e026ec27b8459cb71699d1072ead78ce8082a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_start_url\n\nDocumentation:\nGet the start URL used for IdC login.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_start_url(&mut self) -> Result, DatabaseError> {\n self.get_json_entry::(Table::State, START_URL_KEY)\n }\n```"}], "func_name": "get_start_url", "docstring": "Get the start URL used for IdC login.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ce143a1ac8bd5e13eaf64cb969ba0878ca75d0ff001b0e9632f3ab6b9482b97c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_start_url\n\nDocumentation:\nSet the start URL used for IdC login.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_start_url(&mut self, start_url: String) -> Result {\n self.set_json_entry(Table::State, START_URL_KEY, start_url)\n }\n```"}], "func_name": "set_start_url", "docstring": "Set the start URL used for IdC login.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "53df594fea073b6f62a5d422819476ad4178d733b8ba25b81c67ba7a9b33c37f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_idc_region\n\nDocumentation:\nGet the region used for IdC login.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_idc_region(&mut self) -> Result, DatabaseError> {\n // Annoyingly, this is encoded as a JSON string on older clients\n self.get_json_entry::(Table::State, IDC_REGION_KEY)\n }\n```"}], "func_name": "get_idc_region", "docstring": "Get the region used for IdC login.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3eccfcc4c4bbd20b8f6a17b2a663aa117d5eb1bfa78bdee1509b6e7f6aa6ef77"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_idc_region\n\nDocumentation:\nSet the region used for IdC login.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_idc_region(&mut self, region: String) -> Result {\n // Annoyingly, this is encoded as a JSON string on older clients\n self.set_json_entry(Table::State, IDC_REGION_KEY, region)\n }\n```"}], "func_name": "set_idc_region", "docstring": "Set the region used for IdC login.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "59ec6c36f6c4abc2e308079103ffca14aacfee0f378f809adc5c65e81b5241a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_increment_rotating_tip\n\nDocumentation:\nGet the rotating tip used for chat then post increment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_increment_rotating_tip(&mut self) -> Result {\n let tip: usize = self.get_entry(Table::State, ROTATING_TIP_KEY)?.unwrap_or(0);\n self.set_entry(Table::State, ROTATING_TIP_KEY, tip.wrapping_add(1))?;\n Ok(tip)\n }\n```"}], "func_name": "get_increment_rotating_tip", "docstring": "Get the rotating tip used for chat then post increment.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "49da951d0dc4877966e47124c9ae2733b7fdf7f081bcdc78575fcb8b940e3554"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_conversation_by_path\n\nDocumentation:\nGet a chat conversation given a path to the conversation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_conversation_by_path(\n &mut self,\n path: impl AsRef,\n ) -> Result, DatabaseError> {\n // We would need to encode this to support non utf8 paths.\n let path = match path.as_ref().to_str() {\n Some(path) => path,\n None => return Ok(None),\n };\n\n self.get_json_entry(Table::Conversations, path)\n }\n```"}], "func_name": "get_conversation_by_path", "docstring": "Get a chat conversation given a path to the conversation.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c593132df124f3dae426432ee8fcb6c36388d80589a99f7b32681fec0a6b91cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_conversation_by_path\n\nDocumentation:\nSet a chat conversation given a path to the conversation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_conversation_by_path(\n &mut self,\n path: impl AsRef,\n state: &ConversationState,\n ) -> Result {\n // We would need to encode this to support non utf8 paths.\n let path = match path.as_ref().to_str() {\n Some(path) => path,\n None => return Ok(0),\n };\n\n self.set_json_entry(Table::Conversations, path, state)\n }\n```"}], "func_name": "set_conversation_by_path", "docstring": "Set a chat conversation given a path to the conversation.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/database/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/database/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "af35c1c3d47e2c642b6b45f42b0695eb28de8a7231ccd02717001daea4950775"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init\n\nDocumentation:\nExchange of information specified as per https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization\n\nAlso done are the following:\n- Spawns task for listening to server driven workflows\n- Spawns tasks to ask for relevant info such as tools and prompts in accordance to server\ncapabilities received\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn init(&self) -> Result {\n let transport_ref = self.transport.clone();\n let server_name = self.server_name.clone();\n\n // Spawning a task to listen and log stderr output\n tokio::spawn(async move {\n let mut log_listener = transport_ref.get_log_listener();\n loop {\n match log_listener.recv().await {\n Ok(msg) => {\n tracing::trace!(target: \"mcp\", \"{server_name} logged {}\", msg);\n },\n Err(e) => {\n tracing::error!(\n \"Error encountered while reading from stderr for {server_name}: {:?}\\nEnding stderr listening task.\",\n e\n );\n break;\n },\n }\n }\n });\n\n let init_params = Some({\n let client_cap = ClientCapabilities::from(self.client_info.clone());\n serde_json::json!(client_cap)\n });\n let init_resp = self.request(\"initialize\", init_params).await?;\n if let Err(e) = examine_server_capabilities(&init_resp) {\n return Err(ClientError::NegotiationError(format!(\n \"Client {} has failed to negotiate server capabilities with server: {:?}\",\n self.server_name, e\n )));\n }\n let cap = {\n let result = init_resp.result.ok_or(ClientError::NegotiationError(format!(\n \"Server {} init resp is missing result\",\n self.server_name\n )))?;\n let cap = result\n .get(\"capabilities\")\n .ok_or(ClientError::NegotiationError(format!(\n \"Server {} init resp result is missing capabilities\",\n self.server_name\n )))?\n .clone();\n serde_json::from_value::(cap)?\n };\n self.notify(\"initialized\", None).await?;\n\n // TODO: group this into examine_server_capabilities\n // Prefetch prompts in the background. We should only do this after the server has been\n // initialized\n if cap.prompts.is_some() {\n self.is_prompts_out_of_date.store(true, Ordering::Relaxed);\n let client_ref = (*self).clone();\n let messenger_ref = self.messenger.as_ref().map(|m| m.duplicate());\n tokio::spawn(async move {\n fetch_prompts_and_notify_with_messenger(&client_ref, messenger_ref.as_ref()).await;\n });\n }\n if cap.tools.is_some() {\n let client_ref = (*self).clone();\n let messenger_ref = self.messenger.as_ref().map(|m| m.duplicate());\n tokio::spawn(async move {\n fetch_tools_and_notify_with_messenger(&client_ref, messenger_ref.as_ref()).await;\n });\n }\n\n let transport_ref = self.transport.clone();\n let server_name = self.server_name.clone();\n let messenger_ref = self.messenger.as_ref().map(|m| m.duplicate());\n let client_ref = (*self).clone();\n\n let prompts_list_changed_supported = cap.prompts.as_ref().is_some_and(|p| p.get(\"listChanged\").is_some());\n let tools_list_changed_supported = cap.tools.as_ref().is_some_and(|t| t.get(\"listChanged\").is_some());\n tokio::spawn(async move {\n let mut listener = transport_ref.get_listener();\n loop {\n match listener.recv().await {\n Ok(msg) => {\n match msg {\n JsonRpcMessage::Request(_req) => {},\n JsonRpcMessage::Notification(notif) => {\n let JsonRpcNotification { method, params, .. } = notif;\n match method.as_str() {\n \"notifications/message\" | \"message\" => {\n let level = params\n .as_ref()\n .and_then(|p| p.get(\"level\"))\n .and_then(|v| serde_json::to_string(v).ok());\n let data = params\n .as_ref()\n .and_then(|p| p.get(\"data\"))\n .and_then(|v| serde_json::to_string(v).ok());\n if let (Some(level), Some(data)) = (level, data) {\n match level.to_lowercase().as_str() {\n \"error\" => {\n tracing::error!(target: \"mcp\", \"{}: {}\", server_name, data);\n },\n \"warn\" => {\n tracing::warn!(target: \"mcp\", \"{}: {}\", server_name, data);\n },\n \"info\" => {\n tracing::info!(target: \"mcp\", \"{}: {}\", server_name, data);\n },\n \"debug\" => {\n tracing::debug!(target: \"mcp\", \"{}: {}\", server_name, data);\n },\n \"trace\" => {\n tracing::trace!(target: \"mcp\", \"{}: {}\", server_name, data);\n },\n _ => {},\n }\n }\n },\n \"notifications/prompts/list_changed\" | \"prompts/list_changed\"\n if prompts_list_changed_supported =>\n {\n // TODO: after we have moved the prompts to the tool\n // manager we follow the same workflow as the list changed\n // for tools\n fetch_prompts_and_notify_with_messenger(&client_ref, messenger_ref.as_ref())\n .await;\n client_ref.is_prompts_out_of_date.store(true, Ordering::Release);\n },\n \"notifications/tools/list_changed\" | \"tools/list_changed\"\n if tools_list_changed_supported =>\n {\n fetch_tools_and_notify_with_messenger(&client_ref, messenger_ref.as_ref())\n .await;\n },\n _ => {},\n }\n },\n JsonRpcMessage::Response(_resp) => { /* noop since direct response is handled inside the request api */\n },\n }\n },\n Err(e) => {\n tracing::error!(\"Background listening thread for client {}: {:?}\", server_name, e);\n },\n }\n }\n });\n\n Ok(cap)\n }\n```"}], "func_name": "init", "docstring": "Exchange of information specified as per https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization\n\nAlso done are the following:\n- Spawns task for listening to server driven workflows\n- Spawns tasks to ask for relevant info such as tools and prompts in accordance to server\ncapabilities received", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/mcp_client/client.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/mcp_client/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e2f263c5111c6b34a0bffeac8383ad6c8874dbb52e7e6752b4ebfee4c5856906"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: request\n\nDocumentation:\nSends a request to the server associated.\nThis call will yield until a response is received.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn request(\n &self,\n method: &str,\n params: Option,\n ) -> Result {\n let send_map_err = |e: Elapsed| (e, method.to_string());\n let recv_map_err = |e: Elapsed| (e, format!(\"recv for {method}\"));\n let mut id = self.get_id();\n let request = JsonRpcRequest {\n jsonrpc: JsonRpcVersion::default(),\n id,\n method: method.to_owned(),\n params,\n };\n tracing::trace!(target: \"mcp\", \"To {}:\\n{:#?}\", self.server_name, request);\n let msg = JsonRpcMessage::Request(request);\n time::timeout(Duration::from_millis(self.timeout), self.transport.send(&msg))\n .await\n .map_err(send_map_err)??;\n let mut listener = self.transport.get_listener();\n let mut resp = time::timeout(Duration::from_millis(self.timeout), async {\n // we want to ignore all other messages sent by the server at this point and let the\n // background loop handle them\n // We also want to ignore all messages emitted by the server to its stdout that does\n // not deserialize into a valid JsonRpcMessage (they are not supposed to do this but\n // too many people complained about this so we are adding this safeguard in)\n loop {\n if let Ok(JsonRpcMessage::Response(resp)) = listener.recv().await {\n if resp.id == id {\n break Ok::(resp);\n }\n }\n }\n })\n .await\n .map_err(recv_map_err)??;\n // Pagination support: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/utilities/pagination/#pagination-model\n let mut next_cursor = resp.result.as_ref().and_then(|v| v.get(\"nextCursor\"));\n if next_cursor.is_some() {\n let mut current_resp = resp.clone();\n let mut results = Vec::::new();\n let pagination_supported_ops = {\n let maybe_pagination_supported_op: Result = method.try_into();\n maybe_pagination_supported_op.ok()\n };\n if let Some(ops) = pagination_supported_ops {\n loop {\n let result = current_resp.result.as_ref().cloned().unwrap();\n let mut list: Vec = match ops {\n PaginationSupportedOps::ResourcesList => {\n let ResourcesListResult { resources: list, .. } =\n serde_json::from_value::(result)\n .map_err(ClientError::Serialization)?;\n list\n },\n PaginationSupportedOps::ResourceTemplatesList => {\n let ResourceTemplatesListResult {\n resource_templates: list,\n ..\n } = serde_json::from_value::(result)\n .map_err(ClientError::Serialization)?;\n list\n },\n PaginationSupportedOps::PromptsList => {\n let PromptsListResult { prompts: list, .. } =\n serde_json::from_value::(result)\n .map_err(ClientError::Serialization)?;\n list\n },\n PaginationSupportedOps::ToolsList => {\n let ToolsListResult { tools: list, .. } = serde_json::from_value::(result)\n .map_err(ClientError::Serialization)?;\n list\n },\n };\n results.append(&mut list);\n if next_cursor.is_none() {\n break;\n }\n id = self.get_id();\n let next_request = JsonRpcRequest {\n jsonrpc: JsonRpcVersion::default(),\n id,\n method: method.to_owned(),\n params: Some(serde_json::json!({\n \"cursor\": next_cursor,\n })),\n };\n let msg = JsonRpcMessage::Request(next_request);\n time::timeout(Duration::from_millis(self.timeout), self.transport.send(&msg))\n .await\n .map_err(send_map_err)??;\n let resp = time::timeout(Duration::from_millis(self.timeout), async {\n loop {\n if let Ok(JsonRpcMessage::Response(resp)) = listener.recv().await {\n if resp.id == id {\n break Ok::(resp);\n }\n }\n }\n })\n .await\n .map_err(recv_map_err)??;\n current_resp = resp;\n next_cursor = current_resp.result.as_ref().and_then(|v| v.get(\"nextCursor\"));\n }\n resp.result = Some({\n let mut map = serde_json::Map::new();\n map.insert(ops.as_key().to_owned(), serde_json::to_value(results)?);\n serde_json::to_value(map)?\n });\n }\n }\n tracing::trace!(target: \"mcp\", \"From {}:\\n{:#?}\", self.server_name, resp);\n Ok(resp)\n }\n```"}], "func_name": "request", "docstring": "Sends a request to the server associated.\nThis call will yield until a response is received.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/mcp_client/client.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/mcp_client/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b5bd9aa2d2d4de564d42318c97db3c968a60ab93c9b186adc825bf25bf824b62"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: notify\n\nDocumentation:\nSends a notification to the server associated.\nNotifications are requests that expect no responses.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn notify(&self, method: &str, params: Option) -> Result<(), ClientError> {\n let send_map_err = |e: Elapsed| (e, method.to_string());\n let notification = JsonRpcNotification {\n jsonrpc: JsonRpcVersion::default(),\n method: format!(\"notifications/{}\", method),\n params,\n };\n let msg = JsonRpcMessage::Notification(notification);\n Ok(\n time::timeout(Duration::from_millis(self.timeout), self.transport.send(&msg))\n .await\n .map_err(send_map_err)??,\n )\n }\n```"}], "func_name": "notify", "docstring": "Sends a notification to the server associated.\nNotifications are requests that expect no responses.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/mcp_client/client.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/mcp_client/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "498f13c088ed88d7cd1883e7bd080a6ed9f0595177e63f4c30027b6f922662a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_slice\n\nDocumentation:\nCreate a fake process environment from a slice of tuples.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_slice(vars: &[(&str, &str)]) -> Self {\n use inner::Inner;\n let map: HashMap<_, _> = vars.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();\n Self(Inner::Fake(Arc::new(Mutex::new(inner::Fake {\n vars: map,\n ..Default::default()\n }))))\n }\n```"}], "func_name": "from_slice", "docstring": "Create a fake process environment from a slice of tuples.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/env.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/env.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca954c0de8386debebd25c17db84d56a9ef5869b3833576b1de6d37d2ceccddc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_var\n\nDocumentation:\nSets the environment variable `key` to the value `value` for the currently running\nprocess.\n\n# Safety\n\nSee [std::env::set_var] for the safety requirements.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub unsafe fn set_var(&self, key: impl AsRef, value: impl AsRef) {\n use inner::Inner;\n match &self.0 {\n Inner::Real => std::env::set_var(key, value),\n Inner::Fake(fake) => {\n fake.lock().unwrap().vars.insert(\n key.as_ref().to_str().expect(\"key must be valid str\").to_string(),\n value.as_ref().to_str().expect(\"key must be valid str\").to_string(),\n );\n },\n }\n }\n```"}], "func_name": "set_var", "docstring": "Sets the environment variable `key` to the value `value` for the currently running\nprocess.\n\n# Safety\n\nSee [std::env::set_var] for the safety requirements.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/env.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/env.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "da3536e776c345ab86f98cd055fee7f4e94441cb8f144d00d3586f254557b393"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open\n\nDocumentation:\nAttempts to open a file in read-only mode.\n\nThis is a proxy to [`tokio::fs::File::open`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn open(&self, path: impl AsRef) -> io::Result {\n use inner::Inner;\n match &self.0 {\n Inner::Real => fs::File::open(path).await,\n Inner::Chroot(root) => fs::File::open(append(root.path(), path)).await,\n Inner::Fake(_) => Err(io::Error::new(io::ErrorKind::Other, \"unimplemented\")),\n }\n }\n```"}], "func_name": "open", "docstring": "Attempts to open a file in read-only mode.\n\nThis is a proxy to [`tokio::fs::File::open`].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f414e718e2b0c17dadabadbd83bc69621dd484208df421878631feba52700657"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write\n\nDocumentation:\nCreates a future that will open a file for writing and write the entire\ncontents of `contents` to it.\n\nThis is a proxy to [`tokio::fs::write`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn write(&self, path: impl AsRef, contents: impl AsRef<[u8]>) -> io::Result<()> {\n use inner::Inner;\n match &self.0 {\n Inner::Real => fs::write(path, contents).await,\n Inner::Chroot(root) => fs::write(append(root.path(), path), contents).await,\n Inner::Fake(map) => {\n let Ok(mut lock) = map.lock() else {\n return Err(io::Error::new(io::ErrorKind::Other, \"poisoned lock\"));\n };\n lock.insert(path.as_ref().to_owned(), contents.as_ref().to_owned());\n Ok(())\n },\n }\n }\n```"}], "func_name": "write", "docstring": "Creates a future that will open a file for writing and write the entire\ncontents of `contents` to it.\n\nThis is a proxy to [`tokio::fs::write`].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48fb6fab5842e4ca61d73350d85683a213eb94bdda14fa7ee51b6d9ab3c56d2a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_file\n\nDocumentation:\nRemoves a file from the filesystem.\n\nNote that there is no guarantee that the file is immediately deleted (e.g.\ndepending on platform, other open file descriptors may prevent immediate\nremoval).\n\nThis is a proxy to [`tokio::fs::remove_file`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn remove_file(&self, path: impl AsRef) -> io::Result<()> {\n use inner::Inner;\n match &self.0 {\n Inner::Real => fs::remove_file(path).await,\n Inner::Chroot(root) => fs::remove_file(append(root.path(), path)).await,\n Inner::Fake(_) => panic!(\"unimplemented\"),\n }\n }\n```"}], "func_name": "remove_file", "docstring": "Removes a file from the filesystem.\n\nNote that there is no guarantee that the file is immediately deleted (e.g.\ndepending on platform, other open file descriptors may prevent immediate\nremoval).\n\nThis is a proxy to [`tokio::fs::remove_file`].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2398f424299adb4044b9988d5c9add77f878b4c49d5fc7cbaac0d098efec1705"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_dir_all\n\nDocumentation:\nRemoves a directory at this path, after removing all its contents. Use carefully!\n\nThis is a proxy to [`tokio::fs::remove_dir_all`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn remove_dir_all(&self, path: impl AsRef) -> io::Result<()> {\n use inner::Inner;\n match &self.0 {\n Inner::Real => fs::remove_dir_all(path).await,\n Inner::Chroot(root) => fs::remove_dir_all(append(root.path(), path)).await,\n Inner::Fake(_) => panic!(\"unimplemented\"),\n }\n }\n```"}], "func_name": "remove_dir_all", "docstring": "Removes a directory at this path, after removing all its contents. Use carefully!\n\nThis is a proxy to [`tokio::fs::remove_dir_all`].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba3cf2e2f37b5b03279286346a590db2b396186f9fc6e224ced9407273e67796"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: rename\n\nDocumentation:\nRenames a file or directory to a new name, replacing the original file if\n`to` already exists.\n\nThis will not work if the new name is on a different mount point.\n\nThis is a proxy to [`tokio::fs::rename`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn rename(&self, from: impl AsRef, to: impl AsRef) -> io::Result<()> {\n use inner::Inner;\n match &self.0 {\n Inner::Real => fs::rename(from, to).await,\n Inner::Chroot(root) => fs::rename(append(root.path(), from), append(root.path(), to)).await,\n Inner::Fake(_) => panic!(\"unimplemented\"),\n }\n }\n```"}], "func_name": "rename", "docstring": "Renames a file or directory to a new name, replacing the original file if\n`to` already exists.\n\nThis will not work if the new name is on a different mount point.\n\nThis is a proxy to [`tokio::fs::rename`].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a44832e6d7d022804aa92cd7cba2f605618e4ead5d4bfcc802988c5a8ae1c6ec"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: copy\n\nDocumentation:\nCopies the contents of one file to another. This function will also copy the permission bits\nof the original file to the destination file.\nThis function will overwrite the contents of to.\n\nThis is a proxy to [`tokio::fs::copy`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn copy(&self, from: impl AsRef, to: impl AsRef) -> io::Result {\n use inner::Inner;\n match &self.0 {\n Inner::Real => fs::copy(from, to).await,\n Inner::Chroot(root) => fs::copy(append(root.path(), from), append(root.path(), to)).await,\n Inner::Fake(_) => panic!(\"unimplemented\"),\n }\n }\n```"}], "func_name": "copy", "docstring": "Copies the contents of one file to another. This function will also copy the permission bits\nof the original file to the destination file.\nThis function will overwrite the contents of to.\n\nThis is a proxy to [`tokio::fs::copy`].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8413c627e18ee860cad86c996402df99d35679855d7efbb55a0a870f55794ef1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_exists\n\nDocumentation:\nReturns `Ok(true)` if the path points at an existing entity.\n\nThis function will traverse symbolic links to query information about the\ndestination file. In case of broken symbolic links this will return `Ok(false)`.\n\nThis is a proxy to [`tokio::fs::try_exists`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn try_exists(&self, path: impl AsRef) -> Result {\n use inner::Inner;\n match &self.0 {\n Inner::Real => fs::try_exists(path).await,\n Inner::Chroot(root) => fs::try_exists(append(root.path(), path)).await,\n Inner::Fake(_) => panic!(\"unimplemented\"),\n }\n }\n```"}], "func_name": "try_exists", "docstring": "Returns `Ok(true)` if the path points at an existing entity.\n\nThis function will traverse symbolic links to query information about the\ndestination file. In case of broken symbolic links this will return `Ok(false)`.\n\nThis is a proxy to [`tokio::fs::try_exists`].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c372c3372eb05a5a1d61d16304fc382d948bfe04b0dccdde32a0057a5b8f927"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: exists\n\nDocumentation:\nReturns `true` if the path points at an existing entity.\n\nThis is a proxy to [std::path::Path::exists]. See the related doc comment in std\non the pitfalls of using this versus [std::path::Path::try_exists].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn exists(&self, path: impl AsRef) -> bool {\n use inner::Inner;\n match &self.0 {\n Inner::Real => path.as_ref().exists(),\n Inner::Chroot(root) => append(root.path(), path).exists(),\n Inner::Fake(_) => panic!(\"unimplemented\"),\n }\n }\n```"}], "func_name": "exists", "docstring": "Returns `true` if the path points at an existing entity.\n\nThis is a proxy to [std::path::Path::exists]. See the related doc comment in std\non the pitfalls of using this versus [std::path::Path::try_exists].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "59f6f2d59828e7b1d155b29385f8c4dc24b3498576dc404ae6fb5e2aa9dad42e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: symlink_exists\n\nDocumentation:\nReturns `true` if the path points at an existing entity without following symlinks.\n\nThis does *not* guarantee that the path doesn't point to a symlink. For example, `false`\nwill be returned if the user doesn't have permission to perform a metadata operation on\n`path`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn symlink_exists(&self, path: impl AsRef) -> bool {\n match self.symlink_metadata(path).await {\n Ok(_) => true,\n Err(err) if err.kind() != std::io::ErrorKind::NotFound => true,\n Err(_) => false,\n }\n }\n```"}], "func_name": "symlink_exists", "docstring": "Returns `true` if the path points at an existing entity without following symlinks.\n\nThis does *not* guarantee that the path doesn't point to a symlink. For example, `false`\nwill be returned if the user doesn't have permission to perform a metadata operation on\n`path`.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9ab99ce165105b517b2a3e2b87cce0ad032a9c79fa22b4c7ce87519fd2bacacf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_link\n\nDocumentation:\nReads a symbolic link, returning the file that the link points to.\n\nThis is a proxy to [`tokio::fs::read_link`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn read_link(&self, path: impl AsRef) -> io::Result {\n use inner::Inner;\n match &self.0 {\n Inner::Real => fs::read_link(path).await,\n Inner::Chroot(root) => Ok(append(root.path(), fs::read_link(append(root.path(), path)).await?)),\n Inner::Fake(_) => panic!(\"unimplemented\"),\n }\n }\n```"}], "func_name": "read_link", "docstring": "Reads a symbolic link, returning the file that the link points to.\n\nThis is a proxy to [`tokio::fs::read_link`].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a578d6202bbd54b88885cfb4ccd81b608a01f77e65fff157000194bcec91f98a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_dir\n\nDocumentation:\nReturns a stream over the entries within a directory.\n\nThis is a proxy to [`tokio::fs::read_dir`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn read_dir(&self, path: impl AsRef) -> Result {\n use inner::Inner;\n match &self.0 {\n Inner::Real => fs::read_dir(path).await,\n Inner::Chroot(root) => fs::read_dir(append(root.path(), path)).await,\n Inner::Fake(_) => panic!(\"unimplemented\"),\n }\n }\n```"}], "func_name": "read_dir", "docstring": "Returns a stream over the entries within a directory.\n\nThis is a proxy to [`tokio::fs::read_dir`].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e9296ebbc74f91f65954a247820641c46de7e8f7f10295240cffcc1eac941bf3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: canonicalize\n\nDocumentation:\nReturns the canonical, absolute form of a path with all intermediate\ncomponents normalized and symbolic links resolved.\n\nThis is a proxy to [`tokio::fs::canonicalize`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn canonicalize(&self, path: impl AsRef) -> Result {\n use inner::Inner;\n match &self.0 {\n Inner::Real => fs::canonicalize(path).await,\n Inner::Chroot(root) => fs::canonicalize(append(root.path(), path)).await,\n Inner::Fake(_) => panic!(\"unimplemented\"),\n }\n }\n```"}], "func_name": "canonicalize", "docstring": "Returns the canonical, absolute form of a path with all intermediate\ncomponents normalized and symbolic links resolved.\n\nThis is a proxy to [`tokio::fs::canonicalize`].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b3b153b70de16c3669f50a5d7da32097694ceeab877f77edb1c209efe0b8e0c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_permissions\n\nDocumentation:\nChanges the permissions found on a file or a directory.\n\nThis is a proxy to [`tokio::fs::set_permissions`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn set_permissions(&self, path: impl AsRef, perm: Permissions) -> Result<(), io::Error> {\n use inner::Inner;\n match &self.0 {\n Inner::Real => fs::set_permissions(path, perm).await,\n Inner::Chroot(root) => fs::set_permissions(append(root.path(), path), perm).await,\n Inner::Fake(_) => panic!(\"unimplemented\"),\n }\n }\n```"}], "func_name": "set_permissions", "docstring": "Changes the permissions found on a file or a directory.\n\nThis is a proxy to [`tokio::fs::set_permissions`]", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "412643eabc8590c5e9ca202559d25cbb2dcdedfd19e9fd4a8d038bf5e1512244"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: chroot_path\n\nDocumentation:\nFor test [Fs]'s that use a different root, returns an absolute path.\n\nThis must be used for any paths indirectly used by code using a chroot\n[Fs].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn chroot_path(&self, path: impl AsRef) -> PathBuf {\n use inner::Inner;\n match &self.0 {\n Inner::Chroot(root) => append(root.path(), path),\n _ => path.as_ref().to_path_buf(),\n }\n }\n```"}], "func_name": "chroot_path", "docstring": "For test [Fs]'s that use a different root, returns an absolute path.\n\nThis must be used for any paths indirectly used by code using a chroot\n[Fs].", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/fs.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/fs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7a98b9c368418fafc6767a5908fc3b916310ca25e406f1a52e6050d80f315f79"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nReturns a new [Context] with real implementations of each OS shim.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new() -> Arc {\n match cfg!(test) {\n true => Arc::new(Self {\n fs: Fs::new(),\n env: Env::new(),\n sysinfo: SysInfo::new(),\n platform: Platform::new(),\n }),\n false => Arc::new_cyclic(|_| Self {\n fs: Default::default(),\n env: Default::default(),\n sysinfo: SysInfo::default(),\n platform: Platform::new(),\n }),\n }\n }\n```"}], "func_name": "new", "docstring": "Returns a new [Context] with real implementations of each OS shim.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "49fa087dea7bbf96667fbd9f2ab1ff81dd1f28f65ffcba52187cd79170fc0235"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nBuilds an immutable [Context] using real implementations for each field by default.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build(self) -> Arc {\n let fs = self.fs.unwrap_or_default();\n let env = self.env.unwrap_or_default();\n let sysinfo = self.sysinfo.unwrap_or_default();\n let platform = self.platform.unwrap_or_default();\n Arc::new_cyclic(|_| Context {\n fs,\n env,\n sysinfo,\n platform,\n })\n }\n```"}], "func_name": "build", "docstring": "Builds an immutable [Context] using real implementations for each field by default.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "58ca7b83c64fd698e7a7bd065f2a29d3c3465edd0142f035ca725c04047b05f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build_fake\n\nDocumentation:\nBuilds an immutable [Context] using fake implementations for each field by default.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn build_fake(self) -> Arc {\n let fs = self.fs.unwrap_or_default();\n let env = self.env.unwrap_or_default();\n let sysinfo = self.sysinfo.unwrap_or_default();\n let platform = self.platform.unwrap_or_default();\n Arc::new_cyclic(|_| Context {\n fs,\n env,\n sysinfo,\n platform,\n })\n }\n```"}], "func_name": "build_fake", "docstring": "Builds an immutable [Context] using fake implementations for each field by default.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "582bd700c3467d60cd6a40a5747d94805477421ddcbdd0e15f32a391ecdd3b44"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_process_running\n\nDocumentation:\nReturns whether the process containing `name` is running.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_process_running(&self, name: &str) -> bool {\n use inner::Inner;\n match &self.0 {\n Inner::Real => {\n let system = sysinfo::System::new_all();\n let is_running = system.processes_by_name(&OsString::from(name)).next().is_some();\n is_running\n },\n Inner::Fake(fake) => fake.lock().unwrap().process_names.contains(name),\n }\n }\n```"}], "func_name": "is_process_running", "docstring": "Returns whether the process containing `name` is running.", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/platform/sysinfo.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/platform/sysinfo.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3bc5ccfd4637d7c48a85fe3ccbd02e80d6097a5177dc951a6cbe6cb53380eaf5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: home_dir\n\nDocumentation:\nThe directory of the users home\n\n- Linux: /home/Alice\n- MacOS: /Users/Alice\n- Windows: C:\\Users\\Alice\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn home_dir(ctx: &Context) -> Result {\n #[cfg(unix)]\n match cfg!(test) {\n true => ctx\n .env()\n .get(\"HOME\")\n .map_err(|_err| DirectoryError::NoHomeDirectory)\n .and_then(|h| {\n if h.is_empty() {\n Err(DirectoryError::NoHomeDirectory)\n } else {\n Ok(h)\n }\n })\n .map(PathBuf::from)\n .map(|p| ctx.fs().chroot_path(p)),\n false => dirs::home_dir().ok_or(DirectoryError::NoHomeDirectory),\n }\n\n #[cfg(windows)]\n dirs::home_dir().ok_or(DirectoryError::NoHomeDirectory)\n}\n```"}], "func_name": "home_dir", "docstring": "The directory of the users home\n\n- Linux: /home/Alice\n- MacOS: /Users/Alice\n- Windows: C:\\Users\\Alice", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/util/directories.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/util/directories.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b7f514fe83cf34ec4049f38b6a9b52c74d60ae409cdaaf3c03934cab2bdaf2f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fig_data_dir\n\nDocumentation:\nThe q data directory\n\n- Linux: `$XDG_DATA_HOME/amazon-q` or `$HOME/.local/share/amazon-q`\n- MacOS: `$HOME/Library/Application Support/amazon-q`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fig_data_dir() -> Result {\n Ok(dirs::data_local_dir()\n .ok_or(DirectoryError::NoHomeDirectory)?\n .join(\"amazon-q\"))\n}\n```"}], "func_name": "fig_data_dir", "docstring": "The q data directory\n\n- Linux: `$XDG_DATA_HOME/amazon-q` or `$HOME/.local/share/amazon-q`\n- MacOS: `$HOME/Library/Application Support/amazon-q`", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/util/directories.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/util/directories.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93e513f5800d5f237e79e7126cf2a4bf4c55151b25235372ca668fd5d673f508"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: logs_dir\n\nDocumentation:\nThe directory to all the fig logs\n- Linux: `/tmp/fig/$USER/logs`\n- MacOS: `$TMPDIR/logs`\n- Windows: `%TEMP%\\fig\\logs`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn logs_dir() -> Result {\n cfg_if::cfg_if! {\n if #[cfg(unix)] {\n Ok(runtime_dir()?.join(\"qlog\"))\n } else if #[cfg(windows)] {\n Ok(std::env::temp_dir().join(\"amazon-q\").join(\"logs\"))\n }\n }\n}\n```"}], "func_name": "logs_dir", "docstring": "The directory to all the fig logs\n- Linux: `/tmp/fig/$USER/logs`\n- MacOS: `$TMPDIR/logs`\n- Windows: `%TEMP%\\fig\\logs`", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/util/directories.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/util/directories.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9bed96f3ae6767d0d95a2f6079ebad209314a1b87d15a60108a0b053af803090"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open_url_async\n\nDocumentation:\nReturns bool indicating whether the URL was opened successfully\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn open_url_async(url: impl AsRef) -> Result<(), Error> {\n cfg_if! {\n if #[cfg(target_os = \"macos\")] {\n open_macos(url)\n } else {\n match tokio::process::Command::from(open_command(url)).output().await {\n Ok(output) => {\n tracing::trace!(?output, \"open_url_async output\");\n if output.status.success() {\n Ok(())\n } else {\n Err(Error::Failed)\n }\n },\n Err(err) => Err(err.into()),\n }\n }\n }\n}\n```"}], "func_name": "open_url_async", "docstring": "Returns bool indicating whether the URL was opened successfully", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/util/open.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/util/open.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81cfcf2ad901e37ca141c2e82271a986a6edf64624b7c1c26c2ca544dc5ff641"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: terminate_process\n\nDocumentation:\nTerminate a process on Windows using the Windows API\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn terminate_process(pid: Pid) -> Result<(), String> {\n unsafe {\n // Open the process with termination rights\n let handle = OpenProcess(PROCESS_TERMINATE, false, pid.as_u32())\n .map_err(|e| format!(\"Failed to open process: {}\", e))?;\n\n // Create a safe handle that will be closed automatically when dropped\n let safe_handle = SafeHandle::new(handle).ok_or_else(|| \"Invalid process handle\".to_string())?;\n\n // Terminate the process with exit code 1\n TerminateProcess(*safe_handle, 1).map_err(|e| format!(\"Failed to terminate process: {}\", e))?;\n\n Ok(())\n }\n}\n```"}], "func_name": "terminate_process", "docstring": "Terminate a process on Windows using the Windows API", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/util/process/windows.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/util/process/windows.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5943a828adcd71590c853a63b53587a19b22189bb65a90c1dff1389966c4b924"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: in_wsl\n\nDocumentation:\nTest if the program is running under WSL\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn in_wsl() -> bool {\n cfg_if! {\n if #[cfg(target_os = \"linux\")] {\n static IN_WSL: OnceLock = OnceLock::new();\n *IN_WSL.get_or_init(|| {\n if let Ok(b) = std::fs::read(\"/proc/sys/kernel/osrelease\") {\n if let Ok(s) = std::str::from_utf8(&b) {\n let a = s.to_ascii_lowercase();\n return a.contains(\"microsoft\") || a.contains(\"wsl\");\n }\n }\n false\n })\n } else {\n false\n }\n }\n}\n```"}], "func_name": "in_wsl", "docstring": "Test if the program is running under WSL", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/util/system_info/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/util/system_info/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "744320fbafafb12782884b1cdcbd607ba9bf91e4c6b5af3c67feea2e9e3a29ee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_remote\n\nDocumentation:\nIs the calling binary running on a remote instance\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_remote() -> bool {\n // TODO(chay): Add detection for inside docker container\n in_ssh() || in_cloudshell() || in_wsl() || std::env::var_os(\"Q_FAKE_IS_REMOTE\").is_some()\n}\n```"}], "func_name": "is_remote", "docstring": "Is the calling binary running on a remote instance", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/util/system_info/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/util/system_info/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4cb3ff717c29ca354da4060ad2644a0ee9a4948d0665a87045de9bf16258e854"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: in_cloudshell\n\nDocumentation:\nThis true if the env var `AWS_EXECUTION_ENV=CloudShell`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn in_cloudshell() -> bool {\n static IN_CLOUDSHELL: OnceLock = OnceLock::new();\n *IN_CLOUDSHELL.get_or_init(|| Env::new().in_cloudshell())\n}\n```"}], "func_name": "in_cloudshell", "docstring": "This true if the env var `AWS_EXECUTION_ENV=CloudShell`", "repo": "aws/amazon-q-developer-cli", "path": "crates/cli/src/util/system_info/mod.rs", "url": "https://github.com/aws/amazon-q-developer-cli/blob/master/crates/cli/src/util/system_info/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9ce02efb6fa1ac017dee6c292127c2595d28cc0efaf1040135d1e45b9da49869"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn_exit_simple\n\nDocumentation:\nSame as above but fire & forget and without a forced stack trace collection\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn spawn_exit_simple(&self, future: F)\n where\n F: Future> + 'js,\n {\n let ctx = self.clone();\n self.spawn(async move {\n if let Err(err) = future.await.catch(&ctx) {\n handle_spawn_error(&ctx, err, None)\n }\n });\n }\n```"}], "func_name": "spawn_exit_simple", "docstring": "Same as above but fire & forget and without a forced stack trace collection", "repo": "awslabs/llrt", "path": "libs/llrt_context/src/lib.rs", "url": "https://github.com/awslabs/llrt/blob/master/libs/llrt_context/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "efafd0ad79d01f320c0fc7aee1119ea44a7bb869952f3a75daf4cf0e9bf26207"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: now_nanos\n\nDocumentation:\nGet the current time in nanoseconds.\n\n# Safety\n- Good until the year 2554\n- Always use a checked substraction since this can return 0\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn now_nanos() -> u64 {\n SystemTime::now()\n .duration_since(std::time::UNIX_EPOCH)\n .unwrap_or_default()\n .as_nanos() as u64\n}\n```"}], "func_name": "now_nanos", "docstring": "Get the current time in nanoseconds.\n\n# Safety\n- Good until the year 2554\n- Always use a checked substraction since this can return 0", "repo": "awslabs/llrt", "path": "libs/llrt_utils/src/time.rs", "url": "https://github.com/awslabs/llrt/blob/master/libs/llrt_utils/src/time.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c1742ea788d84f00fe0f66a58aa05f0edc4126c810354403291e25515240e21"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: now_millis\n\nDocumentation:\nGet the current time in millis.\n\n# Safety\n- Good until the year 2554\n- Always use a checked substraction since this can return 0\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn now_millis() -> i64 {\n SystemTime::now()\n .duration_since(std::time::UNIX_EPOCH)\n .unwrap_or_default()\n .as_millis() as i64\n}\n```"}], "func_name": "now_millis", "docstring": "Get the current time in millis.\n\n# Safety\n- Good until the year 2554\n- Always use a checked substraction since this can return 0", "repo": "awslabs/llrt", "path": "libs/llrt_utils/src/time.rs", "url": "https://github.com/awslabs/llrt/blob/master/libs/llrt_utils/src/time.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1cbfbda9e400c9f897c3d88077f6eec8c7622ea38151441c7b277fd9c9f531f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: as_bytes_mut\n\nDocumentation:\nMutable buffer for the view.\n\n# Safety\nThis is only safe if you have a lock on the runtime.\nDo not pass it directly to other threads.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn as_bytes_mut(&self) -> Option<&mut [u8]> {\n self.buffer\n .as_ref()\n .map(|b| unsafe { std::slice::from_raw_parts_mut(b.ptr.as_ptr(), b.len) })\n }\n```"}], "func_name": "as_bytes_mut", "docstring": "Mutable buffer for the view.\n\n# Safety\nThis is only safe if you have a lock on the runtime.\nDo not pass it directly to other threads.", "repo": "awslabs/llrt", "path": "modules/llrt_buffer/src/array_buffer_view.rs", "url": "https://github.com/awslabs/llrt/blob/master/modules/llrt_buffer/src/array_buffer_view.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f2da7c630311253d06b32ab86c3b8c17f0bce812efef14385c565a2324fb9a8d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decode_data\n\nDocumentation:\nTry to decode the given buffer and store the incomplete bytes.\nThe logic was adapted from the [Node implementation].\n\n[Node implementation]: https://github.com/nodejs/node/blob/ba06c5c509956dc413f91b755c1c93798bb700d4/src/string_decoder.cc#L66\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn decode_data(&mut self, ctx: &Ctx<'_>, mut data: &[u8]) -> Result {\n let mut result = String::new();\n\n if matches!(\n self.encoder,\n Encoder::Utf8 | Encoder::Utf16le | Encoder::Base64\n ) {\n // See if we want bytes to finish a character from the previous\n // chunk; if so, copy the new bytes to the missing bytes buffer\n // and create a string from it that is to be prepended to the main body.\n if self.missing_bytes > 0 {\n if matches!(self.encoder, Encoder::Utf8) {\n // For UTF-8, we need special alignment treatment:\n // If an incomplete character is found at a chunk boundary, we use\n // its remainder and try to decode it.\n let mut i = 0;\n while i < data.len() && i < self.missing_bytes {\n if (data[i] & 0xC0) != 0x80 {\n // This byte is not a continuation byte even though it should have\n // been one. We stop decoding of the incomplete character at this\n // point (but still use the rest of the incomplete bytes from this\n // chunk) and assume that the new, unexpected byte starts a new one.\n self.missing_bytes = 0;\n self.buffer.extend_from_slice(&data[..i]);\n self.buffered_bytes += i;\n data = &data[i..];\n break;\n }\n i += 1;\n }\n } else if matches!(self.encoder, Encoder::Utf16le) {\n // For UTF-16le, we need special alignment treatment:\n // If we have a high surrogate we need to extend the missing bytes\n // to 3 to get the low surrogate.\n let mut i = 0;\n while i < data.len() && i < self.missing_bytes {\n if (data[i] & 0xFC) == 0xD8 {\n self.missing_bytes = 3;\n break;\n }\n i += 1;\n }\n }\n\n let found_bytes = std::cmp::min(data.len(), self.missing_bytes);\n self.buffer.extend_from_slice(&data[..found_bytes]);\n\n data = &data[found_bytes..];\n\n self.missing_bytes -= found_bytes;\n self.buffered_bytes += found_bytes;\n if self.missing_bytes == 0 {\n // We have enough bytes to decode the buffered character\n result = self.make_string(ctx, &self.buffer)?;\n self.buffer.clear();\n self.buffered_bytes = 0;\n }\n }\n\n // It could be that trying to finish the previous chunk already\n // consumed all data that we received in this chunk.\n if data.is_empty() {\n return Ok(result);\n } else {\n // If not, that means is no character left to finish at this point.\n\n // See whether there is a character that we may have to cut off and\n // finish when receiving the next chunk.\n if matches!(self.encoder, Encoder::Utf8) && (data[data.len() - 1] & 0x80) != 0 {\n let mut i = data.len() - 1;\n loop {\n self.buffered_bytes += 1;\n if (data[i] & 0xC0) == 0x80 {\n // This byte does not start a character (a \"trailing\" byte).\n if self.buffered_bytes >= 4 || i == 0 {\n // We either have more then 4 trailing bytes (which means\n // the current character would not be inside the range for\n // valid Unicode, and in particular cannot be represented\n // through JavaScript's UTF-16-based approach to strings), or the\n // current buffer does not contain the start of an UTF-8 character\n // at all. Either way, this is invalid UTF8 and we can just\n // let the engine's decoder handle it.\n self.buffer.clear();\n self.buffered_bytes = 0;\n break;\n }\n } else {\n // Found the first byte of a UTF-8 character. By looking at the\n // upper bits we can tell how long the character *should* be.\n if (data[i] & 0xE0) == 0xC0 {\n self.missing_bytes = 2;\n } else if (data[i] & 0xF0) == 0xE0 {\n self.missing_bytes = 3;\n } else if (data[i] & 0xF8) == 0xF0 {\n self.missing_bytes = 4;\n } else {\n // This lead byte would indicate a character outside of the\n // representable range.\n self.buffered_bytes = 0;\n break;\n }\n\n if self.buffered_bytes >= self.missing_bytes {\n // Received more or exactly as many trailing bytes than the lead\n // character would indicate. In the \"==\" case, we have valid\n // data and don't need to slice anything off;\n // in the \">\" case, this is invalid UTF-8 anyway.\n self.missing_bytes = 0;\n self.buffered_bytes = 0;\n }\n\n self.missing_bytes -= self.buffered_bytes;\n break;\n }\n i -= 1;\n }\n } else if matches!(self.encoder, Encoder::Utf16le) {\n // WARN: For UTF-16LE we deviate from the specification when an invalid\n // high surrogate is found. The spec says we should keep it as is, but\n // there no way to encode in UTF-8 (required to interface with quickjs).\n // For now, we will replace it with a replacement character.\n // See https://github.com/quickjs-ng/quickjs/issues/992\n if (data.len() % 2) == 1 {\n // We got half a codepoint, and need the second byte of it.\n // But we need to avoid rendering high surrogates before we\n // have the full character.\n if data.len() >= 3 && (data[data.len() - 2] & 0xFC) == 0xD8 {\n self.buffered_bytes = 3;\n self.missing_bytes = 1;\n } else {\n self.buffered_bytes = 1;\n self.missing_bytes = 1;\n }\n } else if (data[data.len() - 1] & 0xFC) == 0xD8 {\n // Half a split UTF-16 character.\n self.buffered_bytes = 2;\n self.missing_bytes = 2;\n }\n } else if matches!(self.encoder, Encoder::Base64) {\n self.buffered_bytes = data.len() % 3;\n if self.buffered_bytes > 0 {\n self.missing_bytes = 3 - self.buffered_bytes;\n }\n }\n\n if self.buffered_bytes > 0 {\n // Copy the requested number of buffered bytes from the end of the\n // input into the incomplete character buffer.\n self.buffer\n .extend_from_slice(&data[data.len() - self.buffered_bytes..]);\n data = &data[..data.len() - self.buffered_bytes];\n }\n\n if !data.is_empty() {\n result.push_str(&self.make_string(ctx, data)?);\n }\n }\n\n Ok(result)\n } else {\n // For ASCII, HEX, and LATIN1, we can decode everything directly\n self.make_string(ctx, data)\n }\n }\n```"}], "func_name": "decode_data", "docstring": "Try to decode the given buffer and store the incomplete bytes.\nThe logic was adapted from the [Node implementation].\n\n[Node implementation]: https://github.com/nodejs/node/blob/ba06c5c509956dc413f91b755c1c93798bb700d4/src/string_decoder.cc#L66", "repo": "awslabs/llrt", "path": "modules/llrt_string_decoder/src/string_decoder.rs", "url": "https://github.com/awslabs/llrt/blob/master/modules/llrt_string_decoder/src/string_decoder.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "202b05775684247be4c1a547772a8fa8cf6bcead77eedc125cce3ecf6fa0f924"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bench_options_fn\n\nDocumentation:\nProduces a function expression for creating `LazyLock`.\n\nIf the `#[ignore]` attribute is specified, this be provided its\nidentifier to set `BenchOptions` using its span. Doing this instead of\ncreating the `ignore` identifier ourselves improves compiler error\ndiagnostics.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bench_options_fn(\n &self,\n ignore_attr_ident: Option<&syn::Path>,\n ) -> proc_macro2::TokenStream {\n fn is_lit_array(expr: &Expr) -> bool {\n let Expr::Array(expr) = expr else {\n return false;\n };\n expr.elems.iter().all(|elem| matches!(elem, Expr::Lit { .. }))\n }\n\n let private_mod = &self.private_mod;\n let option_some = tokens::option_some();\n\n // Directly set fields on `BenchOptions`. This simplifies things by:\n // - Having a single source of truth\n // - Making unknown options a compile error\n //\n // We use `..` (struct update syntax) to ensure that no option is set\n // twice, even if raw identifiers are used. This also has the accidental\n // benefit of Rust Analyzer recognizing fields and emitting suggestions\n // with docs and type info.\n if self.bench_options.is_empty()\n && self.counters.is_empty()\n && ignore_attr_ident.is_none()\n {\n tokens::option_none()\n } else {\n let options_iter = self.bench_options.iter().map(|(option, value)| {\n let option_name = option.to_string();\n let option_name = option_name.strip_prefix(\"r#\").unwrap_or(&option_name);\n\n let wrapped_value: proc_macro2::TokenStream;\n let value: &dyn ToTokens = match option_name {\n \"threads\" => {\n wrapped_value = if is_lit_array(value) {\n // If array of literals, just use `&[...]`.\n quote! { ::std::borrow::Cow::Borrowed(&#value) }\n } else {\n quote! { #private_mod::IntoThreads::into_threads(#value) }\n };\n\n &wrapped_value\n }\n\n // If the option is a `Duration`, use `IntoDuration` to be\n // polymorphic over `Duration` or `u64`/`f64` seconds.\n \"min_time\" | \"max_time\" => {\n wrapped_value =\n quote! { #private_mod::IntoDuration::into_duration(#value) };\n &wrapped_value\n }\n\n _ => value,\n };\n\n quote! { #option: #option_some(#value), }\n });\n\n let ignore = match ignore_attr_ident {\n Some(ignore_attr_ident) => {\n quote! { #ignore_attr_ident: #option_some(true), }\n }\n None => Default::default(),\n };\n\n let counters = &self.counters;\n\n quote! {\n #option_some(::std::sync::LazyLock::new(|| {\n #[allow(clippy::needless_update)]\n #private_mod::BenchOptions {\n #(#options_iter)*\n\n // Ignore comes after options so that options take\n // priority in compiler error diagnostics.\n #ignore\n\n #counters\n\n ..::std::default::Default::default()\n }\n }))\n }\n }\n }\n```"}], "func_name": "bench_options_fn", "docstring": "Produces a function expression for creating `LazyLock`.\n\nIf the `#[ignore]` attribute is specified, this be provided its\nidentifier to set `BenchOptions` using its span. Doing this instead of\ncreating the `ignore` identifier ourselves improves compiler error\ndiagnostics.", "repo": "nvzqz/divan", "path": "macros/src/attr_options.rs", "url": "https://github.com/nvzqz/divan/blob/master/macros/src/attr_options.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dccc39852a445c569667eb6e7bd144bfa50adcf835055c979873f6d228db637f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_empty\n\nDocumentation:\nReturns `true` if set exclusively to either:\n- `types = []`\n- `consts = []`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_empty(&self) -> bool {\n match (&self.types, &self.consts) {\n (Some(types), None) => types.is_empty(),\n (None, Some(Expr::Array(consts))) => consts.elems.is_empty(),\n _ => false,\n }\n }\n```"}], "func_name": "is_empty", "docstring": "Returns `true` if set exclusively to either:\n- `types = []`\n- `consts = []`", "repo": "nvzqz/divan", "path": "macros/src/attr_options.rs", "url": "https://github.com/nvzqz/divan/blob/master/macros/src/attr_options.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "13714673ce730c7bfa302575d4de1b8e5a66ccc1d7420dcc8961a22ad8c6d9f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: types_iter\n\nDocumentation:\nReturns an iterator of multiple `Some` for types, or a single `None` if\nthere are no types.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn types_iter(\n &self,\n ) -> Box> + '_> {\n match &self.types {\n None => Box::new(std::iter::once(None)),\n Some(GenericTypes::List(types)) => {\n Box::new(types.iter().map(|t| Some(t as &dyn ToTokens)))\n }\n }\n }\n```"}], "func_name": "types_iter", "docstring": "Returns an iterator of multiple `Some` for types, or a single `None` if\nthere are no types.", "repo": "nvzqz/divan", "path": "macros/src/attr_options.rs", "url": "https://github.com/nvzqz/divan/blob/master/macros/src/attr_options.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "976db393754e72cc84ebad5768a21af797fe5867528907806e8fefcfaad55f03"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pre_main_attrs\n\nDocumentation:\nAttributes applied to a `static` containing a pointer to a function to run\nbefore `main`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn pre_main_attrs() -> proc_macro2::TokenStream {\n let elf = systems::elf();\n let mach_o = systems::mach_o();\n\n quote! {\n #[used]\n #[cfg_attr(windows, link_section = \".CRT$XCU\")]\n #[cfg_attr(any(#elf), link_section = \".init_array\")]\n #[cfg_attr(any(#mach_o), link_section = \"__DATA,__mod_init_func,mod_init_funcs\")]\n }\n}\n```"}], "func_name": "pre_main_attrs", "docstring": "Attributes applied to a `static` containing a pointer to a function to run\nbefore `main`.", "repo": "nvzqz/divan", "path": "macros/src/lib.rs", "url": "https://github.com/nvzqz/divan/blob/master/macros/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17281b59de3f4dd9f90a32ebf6a245025b547a6ed994f584c37fdb290e790f70"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: runner\n\nDocumentation:\nInitializes `self` with the results of `make_args` and returns a\n`BenchArgsRunner` that will execute the benchmarking closure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn runner(\n &'static self,\n make_args: impl FnOnce() -> I,\n arg_to_string: impl Fn(&I::Item) -> String,\n _bench_impl: B,\n ) -> BenchArgsRunner\n where\n I: IntoIterator,\n I::Item: Any + Send + Sync,\n B: FnOnce(Bencher, &I::Item) + Copy,\n {\n let args = self.args.get_or_init(|| {\n let args_iter = make_args().into_iter();\n\n // Reuse arguments for names if already a slice of strings.\n //\n // NOTE: We do this over `I::IntoIter` instead of `I` since it works\n // for both slices and `slice::Iter`.\n let args_strings: Option<&'static [&str]> = args_iter\n .cast_ref::>()\n .map(|iter| iter.as_slice());\n\n // Collect arguments into leaked slice.\n //\n // Leaking the collected `args` simplifies memory management, such\n // as when reusing for `names`. We're leaking anyways since this is\n // accessed via a global `OnceLock`.\n //\n // PERF: We could optimize this to reuse arguments when users\n // provide slices. However, for slices its `Item` is a reference, so\n // `slice::Iter` would never match here. To make this\n // optimization, we would need to be able to get the referee type.\n let args: &'static [I::Item] = Box::leak(args_iter.collect());\n\n // Collect printable representations of arguments.\n //\n // PERF: We take multiple opportunities to reuse the provided\n // arguments buffer or individual strings' buffers:\n // - `&[&str]`\n // - `IntoIterator`\n // - `IntoIterator`\n // - `IntoIterator>`\n // - `IntoIterator>`\n let names: &'static [&str] = 'names: {\n // PERF: Reuse arguments strings slice.\n if let Some(args) = args_strings {\n break 'names args;\n }\n\n // PERF: Reuse our args slice allocation.\n if let Some(args) = args.cast_ref::<&[&str]>() {\n break 'names args;\n }\n\n Box::leak(\n args.iter()\n .map(|arg| -> &str {\n // PERF: Reuse strings as-is.\n if let Some(arg) = arg.cast_ref::() {\n return arg;\n }\n if let Some(arg) = arg.cast_ref::>() {\n return arg;\n }\n if let Some(arg) = arg.cast_ref::>() {\n return arg;\n }\n\n // Default to `arg_to_string`, which will format via\n // either `ToString` or `Debug`.\n Box::leak(arg_to_string(arg).into_boxed_str())\n })\n .collect(),\n )\n };\n\n ErasedArgsSlice {\n // We `black_box` arguments to prevent the compiler from\n // optimizing the benchmark for the provided values.\n args: crate::black_box(args.as_ptr().cast()),\n names: names.as_ptr(),\n len: args.len(),\n arg_type: TypeId::of::(),\n }\n });\n\n BenchArgsRunner { args, bench: bench:: }\n }\n```"}], "func_name": "runner", "docstring": "Initializes `self` with the results of `make_args` and returns a\n`BenchArgsRunner` that will execute the benchmarking closure.", "repo": "nvzqz/divan", "path": "src/benchmark/args.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/benchmark/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f182d2220d7d145c4f89439bf82c4548c43f864db7ae60f3aa8c8c5003d26eb5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: test_eq_ptr\n\nDocumentation:\nTests that two slices contain the same exact strings.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn test_eq_ptr, B: Borrow>(a: &[A], b: &[B]) {\n assert_eq!(a.len(), b.len());\n\n for (a, b) in a.iter().zip(b) {\n let a = a.borrow();\n let b = b.borrow();\n assert_eq!(a, b);\n assert_eq!(a.as_ptr(), b.as_ptr());\n }\n }\n```"}], "func_name": "test_eq_ptr", "docstring": "Tests that two slices contain the same exact strings.", "repo": "nvzqz/divan", "path": "src/benchmark/args.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/benchmark/args.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09c389324066c7c2073fe6ba888ea86363170522b1ec5b0610228e39313770cc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bench\n\nDocumentation:\nBenchmarks a function.\n\nThe function can be benchmarked in parallel using the [`threads`\noption](macro@crate::bench#threads). If the function is strictly\nsingle-threaded, use [`Bencher::bench_local`] instead.\n\n# Examples\n\n```\n#[divan::bench]\nfn bench(bencher: divan::Bencher) {\nbencher.bench(|| {\n// Benchmarked code...\n});\n}\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bench(self, benched: B)\n where\n B: Fn() -> O + Sync,\n {\n // Reusing `bench_values` for a zero-sized non-drop input type should\n // have no overhead.\n self.with_inputs(|| ()).bench_values(|_: ()| benched());\n }\n```"}], "func_name": "bench", "docstring": "Benchmarks a function.\n\nThe function can be benchmarked in parallel using the [`threads`\noption](macro@crate::bench#threads). If the function is strictly\nsingle-threaded, use [`Bencher::bench_local`] instead.\n\n# Examples\n\n```\n#[divan::bench]\nfn bench(bencher: divan::Bencher) {\nbencher.bench(|| {\n// Benchmarked code...\n});\n}\n```", "repo": "nvzqz/divan", "path": "src/benchmark/mod.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/benchmark/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "384fbee048cb9014e50e96f9ce0b75010a7fffc4b9f61437917c422a59272f5b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bench_local\n\nDocumentation:\nBenchmarks a function on the current thread.\n\n# Examples\n\n```\n#[divan::bench]\nfn bench(bencher: divan::Bencher) {\nbencher.bench_local(|| {\n// Benchmarked code...\n});\n}\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bench_local(self, mut benched: B)\n where\n B: FnMut() -> O,\n {\n // Reusing `bench_local_values` for a zero-sized non-drop input type\n // should have no overhead.\n self.with_inputs(|| ()).bench_local_values(|_: ()| benched());\n }\n```"}], "func_name": "bench_local", "docstring": "Benchmarks a function on the current thread.\n\n# Examples\n\n```\n#[divan::bench]\nfn bench(bencher: divan::Bencher) {\nbencher.bench_local(|| {\n// Benchmarked code...\n});\n}\n```", "repo": "nvzqz/divan", "path": "src/benchmark/mod.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/benchmark/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a6f0bed74712828f7776451132bf57a1f19c8a1e07fdd6a65554ae7c660b179"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_inputs\n\nDocumentation:\nGenerate inputs for the [benchmarked function](#input-bench).\n\nTime spent generating inputs does not affect benchmark timing.\n\nWhen [benchmarking in parallel](macro@crate::bench#threads), the input\ngenerator is called on the same thread as the sample loop that uses that\ninput.\n\n# Examples\n\n```\n#[divan::bench]\nfn bench(bencher: divan::Bencher) {\nbencher\n.with_inputs(|| {\n// Generate input:\nString::from(\"...\")\n})\n.bench_values(|s| {\n// Use input by-value:\ns + \"123\"\n});\n}\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_inputs(\n self,\n gen_input: G,\n ) -> Bencher<'a, 'b, BencherConfig> {\n Bencher { context: self.context, config: BencherConfig { gen_input } }\n }\n```"}], "func_name": "with_inputs", "docstring": "Generate inputs for the [benchmarked function](#input-bench).\n\nTime spent generating inputs does not affect benchmark timing.\n\nWhen [benchmarking in parallel](macro@crate::bench#threads), the input\ngenerator is called on the same thread as the sample loop that uses that\ninput.\n\n# Examples\n\n```\n#[divan::bench]\nfn bench(bencher: divan::Bencher) {\nbencher\n.with_inputs(|| {\n// Generate input:\nString::from(\"...\")\n})\n.bench_values(|s| {\n// Use input by-value:\ns + \"123\"\n});\n}\n```", "repo": "nvzqz/divan", "path": "src/benchmark/mod.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/benchmark/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca55851cc9ac82039c502f09f8d78c2cd5eefd636cd070f7c81c43735fc53111"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_match\n\nDocumentation:\nReturns `true` if a benchmark/group path matches these filters, and thus\nthe entry should be included.\n\nExclusive filters are prioritized over inclusive filters.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_match(&self, entry_path: &str) -> bool {\n let filters = self.filters.all();\n let inclusive_start = self.filters.split_index();\n\n // If any filter matches, return whether it was inclusive or exclusive.\n // Exclusive filters are checked before inclusive filters because they\n // have priority.\n if let Some(index) = filters.iter().position(|f| f.is_match(entry_path))\n {\n return index >= inclusive_start;\n }\n\n // Otherwise succeed only if there are no inclusive filters.\n filters.len() == inclusive_start\n }\n```"}], "func_name": "is_match", "docstring": "Returns `true` if a benchmark/group path matches these filters, and thus\nthe entry should be included.\n\nExclusive filters are prioritized over inclusive filters.", "repo": "nvzqz/divan", "path": "src/config/filter.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/config/filter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4640b8461cdc8c350bd1e4ad7cea30048ced917bbf9e544b09677ccbee620c3b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_tie_breakers\n\nDocumentation:\nReturns an array containing `self` along with other attributes that\nshould break ties if attributes are equal.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_tie_breakers(self) -> [Self; 3] {\n use SortingAttr::*;\n\n match self {\n Kind => [self, Name, Location],\n Name => [self, Location, Kind],\n Location => [self, Kind, Name],\n }\n }\n```"}], "func_name": "with_tie_breakers", "docstring": "Returns an array containing `self` along with other attributes that\nshould break ties if attributes are equal.", "repo": "nvzqz/divan", "path": "src/config/mod.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1fd3f7d257cf09f731247f2c9a525d09bd3b5bdd8a8bf754334005eaa6a6ee78"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cmp_bench_arg_names\n\nDocumentation:\nCompares benchmark runtime argument names.\n\nThis takes `&&str` to handle `SortingAttr::Location` since the strings\nare considered to be within the same `&[&str]`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn cmp_bench_arg_names(self, a: &&str, b: &&str) -> Ordering {\n for attr in self.with_tie_breakers() {\n let ordering = match attr {\n SortingAttr::Kind => Ordering::Equal,\n\n SortingAttr::Name => 'ordering: {\n // Compare as integers.\n match (a.parse::(), a.parse::()) {\n (Ok(a_u128), Ok(b_u128)) => {\n break 'ordering a_u128.cmp(&b_u128)\n }\n\n (Ok(_), Err(_)) => {\n if b.parse::().is_ok() {\n // a > b, because b is negative.\n break 'ordering Ordering::Greater;\n }\n }\n\n (Err(_), Ok(_)) => {\n if a.parse::().is_ok() {\n // a < b, because a is negative.\n break 'ordering Ordering::Less;\n }\n }\n\n (Err(_), Err(_)) => {\n if let (Ok(a_i128), Ok(b_i128)) =\n (a.parse::(), a.parse::())\n {\n break 'ordering a_i128.cmp(&b_i128);\n }\n }\n }\n\n // Compare as floats.\n if let (Ok(a), Ok(b)) = (a.parse::(), b.parse::())\n {\n if let Some(ordering) = a.partial_cmp(&b) {\n break 'ordering ordering;\n }\n }\n\n natural_cmp(a, b)\n }\n\n SortingAttr::Location => {\n let a: *const &str = a;\n let b: *const &str = b;\n a.cmp(&b)\n }\n };\n\n if ordering != Ordering::Equal {\n return ordering;\n }\n }\n\n Ordering::Equal\n }\n```"}], "func_name": "cmp_bench_arg_names", "docstring": "Compares benchmark runtime argument names.\n\nThis takes `&&str` to handle `SortingAttr::Location` since the strings\nare considered to be within the same `&[&str]`.", "repo": "nvzqz/divan", "path": "src/config/mod.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/config/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c760a51a3d454cbbb2b94fe43da450493adb876329dc17eb49fd082a91562a4c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_input_counter\n\nDocumentation:\nSet the input-based count generator function for a counter.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn set_input_counter(&mut self, make_counter: F)\n where\n F: Fn(&I) -> C + Sync + 'static,\n C: IntoCounter,\n {\n let info = self.info_mut(KnownCounterKind::of::());\n\n // Ignore previously-set counts.\n info.counts.clear();\n\n info.count_input = Some(Box::new(move |input: *const ()| {\n // SAFETY: Callers to `get_input_count` guarantee that the same `&I`\n // is passed.\n let counter = unsafe { make_counter(&*input.cast::()) };\n\n AnyCounter::new(counter).count()\n }));\n }\n```"}], "func_name": "set_input_counter", "docstring": "Set the input-based count generator function for a counter.", "repo": "nvzqz/divan", "path": "src/counter/collection.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/counter/collection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f6e1beae0f4751802fdbb11c866c91d62bb181c4c7c5e4dcccb2a0bc06ec02bb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_input_count\n\nDocumentation:\nCalls the user-provided closure to get the counter count for a given\ninput.\n\n# Safety\n\nThe `I` type must be the same as that used by `set_input_counter`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) unsafe fn get_input_count(\n &self,\n counter_kind: KnownCounterKind,\n input: &I,\n ) -> Option {\n let from_input = self.info(counter_kind).count_input.as_ref()?;\n\n // SAFETY: The caller ensures that this is called on the same input type\n // used for calling `set_input_counter`.\n Some(unsafe { from_input(input as *const I as *const ()) })\n }\n```"}], "func_name": "get_input_count", "docstring": "Calls the user-provided closure to get the counter count for a given\ninput.\n\n# Safety\n\nThe `I` type must be the same as that used by `set_input_counter`.", "repo": "nvzqz/divan", "path": "src/counter/collection.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/counter/collection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f1234e51ee4eae2913d9a67d150d00da45166e765f056b37b027fbd4c25613fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clear_input_counts\n\nDocumentation:\nRemoves counts that came from input.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn clear_input_counts(&mut self) {\n for info in &mut self.info {\n if info.count_input.is_some() {\n info.counts.clear();\n }\n }\n }\n```"}], "func_name": "clear_input_counts", "docstring": "Removes counts that came from input.", "repo": "nvzqz/divan", "path": "src/counter/collection.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/counter/collection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8d92e60ed5b9bb9ad6c11f45c348e5513ef9de94ed3dcec5bc436e6c67ee1ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: overwrite\n\nDocumentation:\nOverwrites `other` with values set in `self`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn overwrite(&self, other: &Self) -> Self {\n Self {\n counts: KnownCounterKind::ALL\n .map(|kind| self.get(kind).or(other.get(kind))),\n }\n }\n```"}], "func_name": "overwrite", "docstring": "Overwrites `other` with values set in `self`.", "repo": "nvzqz/divan", "path": "src/counter/collection.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/counter/collection.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a38afd88a65ef28a4fd7cf64bf8d5cdeac0ad46be6a57bf6de0f156c1ecbfb29"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates an instance for the given type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn new() -> Self {\n Self {\n get_type_name: std::any::type_name::,\n get_type_id: TypeId::of::,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates an instance for the given type.", "repo": "nvzqz/divan", "path": "src/entry/generic.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/entry/generic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "935f8eb113fa8c38127f2d149976f1eba67f0f6856104b061cc4a72508f7de85"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates entry data for a `const` values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn new(value: &'static T) -> Self\n where\n T: PartialOrd + ToString + Send + Sync,\n {\n unsafe fn partial_cmp(\n a: *const (),\n b: *const (),\n ) -> Option {\n T::partial_cmp(&*a.cast(), &*b.cast())\n }\n\n unsafe fn to_string(value: *const ()) -> String {\n T::to_string(&*value.cast())\n }\n\n Self {\n value: value as *const T as *const (),\n partial_cmp: partial_cmp::,\n to_string: to_string::,\n cached_string: ManuallyDrop::new(OnceLock::new()),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates entry data for a `const` values.", "repo": "nvzqz/divan", "path": "src/entry/generic.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/entry/generic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c52d2597fdc09cfe98fc7aae141d163e217cf5f1c2e20564a4ac9e5d6e8c8f2c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cmp_name\n\nDocumentation:\nReturns [`PartialOrd::partial_cmp`] ordering if `<` or `>, falling back\nto comparing [`ToString::to_string`] otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn cmp_name(&self, other: &Self) -> Ordering {\n // SAFETY: If both constants have the same `partial_cmp` function\n // pointer, they are safely comparable. In the context of how this\n // method is used, it is because the constants are of the same type.\n //\n // We don't need a type ID check because constants that are compared to\n // each other all come from the same code generation unit, so their\n // `partial_cmp` function pointers will never differ.\n #[allow(unpredictable_function_pointer_comparisons)]\n if self.partial_cmp == other.partial_cmp {\n if let Some(ordering) =\n unsafe { (self.partial_cmp)(self.value, other.value) }\n {\n if !ordering.is_eq() {\n return ordering;\n }\n }\n }\n\n // Fallback to name comparison.\n natural_cmp(self.name(), other.name())\n }\n```"}], "func_name": "cmp_name", "docstring": "Returns [`PartialOrd::partial_cmp`] ordering if `<` or `>, falling back\nto comparing [`ToString::to_string`] otherwise.", "repo": "nvzqz/divan", "path": "src/entry/generic.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/entry/generic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2811f5462e6fb464ed068c509d91dab30c04aa16dd08220cf46cbe5e72a3e047"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_benches\n\nDocumentation:\nConstructs a tree from an iterator of benchmark entries in the order\nthey're produced.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_benches(benches: I) -> Vec\n where\n I: IntoIterator>,\n {\n let mut result = Vec::::new();\n\n for bench in benches {\n let mut insert_entry = |path_iter| {\n Self::insert_entry(&mut result, bench, path_iter);\n };\n\n match bench {\n AnyBenchEntry::Bench(bench) => {\n insert_entry(&mut bench.meta.module_path_components());\n }\n AnyBenchEntry::GenericBench(bench) => {\n insert_entry(&mut bench.path_components());\n }\n }\n }\n\n result\n }\n```"}], "func_name": "from_benches", "docstring": "Constructs a tree from an iterator of benchmark entries in the order\nthey're produced.", "repo": "nvzqz/divan", "path": "src/entry/tree.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/entry/tree.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4387e98899b5c35a21ad455475c22fcb952bdb7ba92911e3ae3104792b8cf986"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_picos\n\nDocumentation:\nDetermines the scale of time for representing a number of picoseconds.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_picos(picos: u128) -> Self {\n use picos::*;\n\n if picos < NANOS {\n Self::PicoSec\n } else if picos < MICROS {\n Self::NanoSec\n } else if picos < MILLIS {\n Self::MicroSec\n } else if picos < SEC {\n Self::MilliSec\n } else if picos < MIN {\n Self::Sec\n } else if picos < HOUR {\n Self::Min\n } else if picos < DAY {\n Self::Hour\n } else {\n Self::Day\n }\n }\n```"}], "func_name": "from_picos", "docstring": "Determines the scale of time for representing a number of picoseconds.", "repo": "nvzqz/divan", "path": "src/time/fine_duration.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/time/fine_duration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "66b7d1017c0a99967fc08562a34423585a95a15d6581efd0c15c4ddc80880457"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: picos\n\nDocumentation:\nReturns the number of picoseconds needed to reach this scale.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn picos(self) -> u128 {\n use picos::*;\n\n match self {\n Self::PicoSec => 1,\n Self::NanoSec => NANOS,\n Self::MicroSec => MICROS,\n Self::MilliSec => MILLIS,\n Self::Sec => SEC,\n Self::Min => MIN,\n Self::Hour => HOUR,\n Self::Day => DAY,\n }\n }\n```"}], "func_name": "picos", "docstring": "Returns the number of picoseconds needed to reach this scale.", "repo": "nvzqz/divan", "path": "src/time/fine_duration.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/time/fine_duration.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "537d339f94046591506cbd9cfd3b23aa91deb27f9cfc44e3d52cf56e2016d716"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: precision\n\nDocumentation:\nReturns the smallest non-zero duration that this timer can measure.\n\nThe result is cached.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn precision(self) -> FineDuration {\n static CACHED: [OnceLock; Timer::COUNT] =\n [OnceLock::new(), OnceLock::new()];\n\n let cached = &CACHED[self.kind() as usize];\n\n *cached.get_or_init(|| self.measure_precision())\n }\n```"}], "func_name": "precision", "docstring": "Returns the smallest non-zero duration that this timer can measure.\n\nThe result is cached.", "repo": "nvzqz/divan", "path": "src/time/timer.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/time/timer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d54c51f02e2a726a247fac09ffc6b47ca2eaa1eaf9a315d3ab2aac5a324c46d6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bench_overheads\n\nDocumentation:\nReturns the overheads added by the benchmarker.\n\n`min_time` and `max_time` do not consider this as benchmarking time.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bench_overheads(self) -> &'static TimedOverhead {\n // Miri is slow, so don't waste time on this.\n if cfg!(miri) {\n return &TimedOverhead::ZERO;\n }\n\n static CACHED: [OnceLock; Timer::COUNT] =\n [OnceLock::new(), OnceLock::new()];\n\n let cached = &CACHED[self.kind() as usize];\n\n cached.get_or_init(|| TimedOverhead {\n sample_loop: self.sample_loop_overhead(),\n tally_alloc: self.measure_tally_alloc_overhead(),\n tally_dealloc: self.measure_tally_dealloc_overhead(),\n tally_realloc: self.measure_tally_realloc_overhead(),\n })\n }\n```"}], "func_name": "bench_overheads", "docstring": "Returns the overheads added by the benchmarker.\n\n`min_time` and `max_time` do not consider this as benchmarking time.", "repo": "nvzqz/divan", "path": "src/time/timer.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/time/timer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "60bca33a3fd1054e98e8b42b134c561c484bdb66afd11e5c9f69e5e35eb35459"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sample_loop_overhead\n\nDocumentation:\nReturns the per-iteration overhead of the benchmarking sample loop.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn sample_loop_overhead(self) -> FineDuration {\n // Miri is slow, so don't waste time on this.\n if cfg!(miri) {\n return FineDuration::default();\n }\n\n static CACHED: [OnceLock; Timer::COUNT] =\n [OnceLock::new(), OnceLock::new()];\n\n let cached = &CACHED[self.kind() as usize];\n\n *cached.get_or_init(|| self.measure_sample_loop_overhead())\n }\n```"}], "func_name": "sample_loop_overhead", "docstring": "Returns the per-iteration overhead of the benchmarking sample loop.", "repo": "nvzqz/divan", "path": "src/time/timer.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/time/timer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb2adcfdea1cb60b1e256befb780edd250a57cb5b2e525e79e6ad40e91617058"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: measure_sample_loop_overhead\n\nDocumentation:\nCalculates the per-iteration overhead of the benchmarking sample loop.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn measure_sample_loop_overhead(self) -> FineDuration {\n let timer_kind = self.kind();\n\n let sample_count: usize = 100;\n let sample_size: usize = 10_000;\n\n // The minimum non-zero sample.\n let mut min_sample = FineDuration::default();\n\n for _ in 0..sample_count {\n let start = UntaggedTimestamp::start(timer_kind);\n\n for i in 0..sample_size {\n _ = crate::black_box(i);\n }\n\n let end = UntaggedTimestamp::end(timer_kind);\n\n // SAFETY: These values are guaranteed to be the correct variant because\n // they were created from the same `timer_kind`.\n let [start, end] = unsafe {\n [\n start.into_timestamp(timer_kind),\n end.into_timestamp(timer_kind),\n ]\n };\n\n let mut sample = end.duration_since(start, self);\n sample.picos /= sample_size as u128;\n\n min_sample = min_sample.clamp_to_min(sample);\n }\n\n min_sample\n }\n```"}], "func_name": "measure_sample_loop_overhead", "docstring": "Calculates the per-iteration overhead of the benchmarking sample loop.", "repo": "nvzqz/divan", "path": "src/time/timer.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/time/timer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "874f64570d992d2667241f2218ff2240db2fb9f20881eb816ec226d2ba750b34"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: measure_min_time\n\nDocumentation:\nCalculates the smallest non-zero time to perform an operation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn measure_min_time(\n self,\n sample_count: usize,\n sample_size: usize,\n operation: impl Fn(),\n ) -> FineDuration {\n let timer_kind = self.kind();\n\n let loop_overhead = self.sample_loop_overhead();\n let mut min_sample = FineDuration::default();\n\n for _ in 0..sample_count {\n let start = UntaggedTimestamp::start(timer_kind);\n\n for _ in 0..sample_size {\n operation();\n }\n\n let end = UntaggedTimestamp::end(timer_kind);\n\n // SAFETY: These values are guaranteed to be the correct variant\n // because they were created from the same `timer_kind`.\n let [start, end] = unsafe {\n [\n start.into_timestamp(timer_kind),\n end.into_timestamp(timer_kind),\n ]\n };\n\n let mut sample = end.duration_since(start, self);\n sample.picos /= sample_size as u128;\n\n // Remove benchmarking loop overhead.\n sample.picos = sample.picos.saturating_sub(loop_overhead.picos);\n\n min_sample = min_sample.clamp_to_min(sample);\n }\n\n min_sample\n }\n```"}], "func_name": "measure_min_time", "docstring": "Calculates the smallest non-zero time to perform an operation.", "repo": "nvzqz/divan", "path": "src/time/timer.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/time/timer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aeafeea33b674b3c10eb5d8060ee54d83bf62c886924a19a281a31ffe9d02c8e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: nominal_frequency\n\nDocumentation:\nParses the CPU frequency in the brand name, e.g. \"2.50GHz\".\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn nominal_frequency() -> Option {\n let name = util::cpu_name()?;\n let name = {\n let len = name.iter().position(|&ch| ch == 0).unwrap_or(name.len());\n std::str::from_utf8(&name[..len]).ok()?\n };\n\n #[rustfmt::skip]\n let frequencies = [\n (\"MHz\", 1e6),\n (\"GHz\", 1e9),\n (\"THz\", 1e12),\n ];\n\n for (unit, scale) in frequencies {\n let Some(unit_start) = name.find(unit) else {\n continue;\n };\n\n let pre_unit = &name[..unit_start];\n let num = match pre_unit.rsplit_once(' ') {\n Some((_, num)) => num,\n None => pre_unit,\n };\n\n if let Ok(num) = num.parse::() {\n return Some(num * scale);\n };\n }\n\n None\n}\n```"}], "func_name": "nominal_frequency", "docstring": "Parses the CPU frequency in the brand name, e.g. \"2.50GHz\".", "repo": "nvzqz/divan", "path": "src/time/timestamp/tsc/x86.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/time/timestamp/tsc/x86.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "65e430c5f8ee302b7b6487c8cac9d8be1c4dea70c875f60279ce0a27b1d7d92b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cpu_name\n\nDocumentation:\nReturns the processor model name as a null-terminated ASCII string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn cpu_name() -> Option<[u8; 48]> {\n if !cpuid_has_leaf(0x8000_0004) {\n return None;\n }\n\n #[rustfmt::skip]\n let result = [\n cpuid_array(0x8000_0002),\n cpuid_array(0x8000_0003),\n cpuid_array(0x8000_0004),\n ];\n\n // SAFETY: Converting from `u32` to bytes.\n Some(unsafe { std::mem::transmute(result) })\n }\n```"}], "func_name": "cpu_name", "docstring": "Returns the processor model name as a null-terminated ASCII string.", "repo": "nvzqz/divan", "path": "src/time/timestamp/tsc/x86.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/time/timestamp/tsc/x86.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9c141305633d758d81bae8a65af9a656c941242954974e000705f6ead033f005"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: measure_frequency\n\nDocumentation:\nReturns the TSC frequency by measuring it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn measure_frequency() -> f64 {\n const TRIES: usize = 8;\n\n // Start with delay of 1ms up to 256ms (2^TRIES).\n let mut delay_ms = 1;\n\n let mut prev_measure = f64::NEG_INFINITY;\n let mut measures = [0.0; TRIES];\n\n for slot in &mut measures {\n let measure =\n measure_frequency_once(Duration::from_millis(delay_ms));\n\n // This measurement is sufficiently accurate if within 0.1% of the\n // previous.\n if measure * 0.999 < prev_measure && prev_measure < measure * 1.001\n {\n return measure;\n }\n\n *slot = measure;\n prev_measure = measure;\n\n delay_ms *= 2;\n }\n\n // If no frequencies were within 0.1% of each other, find the frequency\n // with the smallest delta.\n let mut min_delta = f64::INFINITY;\n let mut result_index = 0;\n\n for i in 0..TRIES {\n for j in (i + 1)..TRIES {\n let delta = (measures[i] - measures[j]).abs();\n\n if delta < min_delta {\n min_delta = delta;\n result_index = i;\n }\n }\n }\n\n measures[result_index]\n }\n```"}], "func_name": "measure_frequency", "docstring": "Returns the TSC frequency by measuring it.", "repo": "nvzqz/divan", "path": "src/time/timestamp/tsc/x86.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/time/timestamp/tsc/x86.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5033c30bca7e75aaef7d328e1e215ab383fdcae8c3d25a1fab1f1fc40166c0e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tsc_instant_pair\n\nDocumentation:\nReturns a timestamp/instant pair that has a small latency between\ngetting the two values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn tsc_instant_pair() -> (u64, Instant) {\n let mut best_latency = Duration::MAX;\n let mut best_pair = (0, Instant::now());\n\n // Make up to 100 attempts to get a low latency pair.\n for _ in 0..100 {\n let instant = Instant::now();\n let tsc = util::rdtsc();\n let latency = instant.elapsed();\n\n let pair = (tsc, instant);\n\n if latency.is_zero() {\n return pair;\n }\n\n if latency < best_latency {\n best_latency = latency;\n best_pair = pair;\n }\n }\n\n best_pair\n }\n```"}], "func_name": "tsc_instant_pair", "docstring": "Returns a timestamp/instant pair that has a small latency between\ngetting the two values.", "repo": "nvzqz/divan", "path": "src/time/timestamp/tsc/x86.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/time/timestamp/tsc/x86.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d4cc861ed918fd00274e5bf2d2f79bb599aac3e23f226de3b1487b6e28717731"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: format_f64\n\nDocumentation:\nFormats an `f64` to the given number of significant figures.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn format_f64(val: f64, sig_figs: usize) -> String {\n let mut str = val.to_string();\n\n if let Some(dot_index) = str.find('.') {\n let fract_digits = sig_figs.saturating_sub(dot_index);\n\n if fract_digits == 0 {\n str.truncate(dot_index);\n } else {\n let fract_start = dot_index + 1;\n let fract_end = fract_start + fract_digits;\n let fract_range = fract_start..fract_end;\n\n if let Some(fract_str) = str.get(fract_range) {\n // Get the offset from the end before all 0s.\n let pre_zero =\n fract_str.bytes().rev().enumerate().find_map(|(i, b)| {\n if b != b'0' {\n Some(i)\n } else {\n None\n }\n });\n\n if let Some(pre_zero) = pre_zero {\n str.truncate(fract_end - pre_zero);\n } else {\n str.truncate(dot_index);\n }\n }\n }\n }\n\n str\n}\n```"}], "func_name": "format_f64", "docstring": "Formats an `f64` to the given number of significant figures.", "repo": "nvzqz/divan", "path": "src/util/fmt.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/util/fmt.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "49631493571b310e0f3558adb2aac1daec421b545b301ad33c00a10a9bd8168e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: scale_value\n\nDocumentation:\nConverts a value to the appropriate scale.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn scale_value(value: f64, bytes_format: BytesFormat) -> (f64, Scale) {\n let starts = scale_starts(bytes_format);\n\n let scale = if value.is_infinite() || value < starts[1] {\n Scale::One\n } else if value < starts[2] {\n Scale::Kilo\n } else if value < starts[3] {\n Scale::Mega\n } else if value < starts[4] {\n Scale::Giga\n } else if value < starts[5] {\n Scale::Tera\n } else {\n Scale::Peta\n };\n\n (value / starts[scale as usize], scale)\n}\n```"}], "func_name": "scale_value", "docstring": "Converts a value to the appropriate scale.", "repo": "nvzqz/divan", "path": "src/util/fmt.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/util/fmt.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ede12bff5e118de435309dc591ee6efb9408b6a1e07c8afa6f0d1f1768d589b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_cargo_nextest\n\nDocumentation:\nReturns `true` if running under [`cargo-nextest`](https://nexte.st).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn is_cargo_nextest() -> bool {\n std::env::var_os(\"NEXTEST\").unwrap_or_default() == \"1\"\n}\n```"}], "func_name": "is_cargo_nextest", "docstring": "Returns `true` if running under [`cargo-nextest`](https://nexte.st).", "repo": "nvzqz/divan", "path": "src/util/mod.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/util/mod.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a2fc66d59bdb984cd5eff017fd97e982a511af640912084d1a52ebb005c3c840"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: natural_cmp\n\nDocumentation:\nCompares strings by treating internal integers as atomic units.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn natural_cmp(a: &str, b: &str) -> Ordering {\n Iterator::cmp(Tokenizer { input: a }, Tokenizer { input: b })\n}\n```"}], "func_name": "natural_cmp", "docstring": "Compares strings by treating internal integers as atomic units.", "repo": "nvzqz/divan", "path": "src/util/sort.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/util/sort.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a28c03e81d78410b4b9811aee8488c73c1ab506af6684432009c580ad05c7cc9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: broadcast_task\n\nDocumentation:\nType-erased monomorphized implementation for `broadcast`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nunsafe fn broadcast_task(&self, aux_threads: usize, task: Task) {\n // Send task to auxiliary threads.\n if aux_threads > 0 {\n let threads = &mut *self\n .threads\n .lock()\n .unwrap_or_else(PoisonError::into_inner);\n\n // Spawn more threads if necessary.\n if let Some(additional) =\n NonZeroUsize::new(aux_threads.saturating_sub(threads.len()))\n {\n spawn(additional, threads);\n }\n\n for thread in &threads[..aux_threads] {\n thread.send(task).unwrap();\n }\n }\n\n // Run the task on the main thread.\n let main_result =\n std::panic::catch_unwind(AssertUnwindSafe(|| task.run(0)));\n\n // Wait for other threads to finish writing their results.\n //\n // SAFETY: The acquire memory ordering ensures that all writes performed\n // by the task on other threads will become visible to this thread after\n // returning from `broadcast`.\n while task.shared.as_ref().ref_count.load(Ordering::Acquire) > 0 {\n std::thread::park();\n }\n\n // Don't drop our result until other threads finish, in case the panic\n // error's drop handler itself also panics.\n drop(main_result);\n }\n```"}], "func_name": "broadcast_task", "docstring": "Type-erased monomorphized implementation for `broadcast`.", "repo": "nvzqz/divan", "path": "src/util/thread/pool.rs", "url": "https://github.com/nvzqz/divan/blob/master/src/util/thread/pool.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81ec99222884078f0cee07c11b007763d718e489f53d703a3f0ebd331143c243"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: server\n\nDocumentation:\nTake the provided endpoint and run the server\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn server(endpoint: Endpoint, opt: Opt) -> Result<()> {\n let mut server_tasks = Vec::new();\n\n // Handle only the expected amount of clients\n for _ in 0..opt.clients {\n let incoming = endpoint.accept().await.unwrap();\n let connecting = match incoming.accept() {\n Ok(connecting) => connecting,\n Err(err) => {\n warn!(\"incoming connection failed: {err:#}\");\n // we can carry on in these cases:\n // this can be caused by retransmitted datagrams\n continue;\n }\n };\n let connection = connecting.await.context(\"handshake failed\")?;\n\n server_tasks.push(tokio::spawn(async move {\n loop {\n let (mut send_stream, mut recv_stream) = match connection.accept_bi().await {\n Err(ConnectionError::ApplicationClosed(_)) => break,\n Err(e) => {\n eprintln!(\"accepting stream failed: {e:?}\");\n break;\n }\n Ok(stream) => stream,\n };\n trace!(\"stream established\");\n\n tokio::spawn(async move {\n drain_stream(&mut recv_stream, opt.read_unordered).await?;\n send_data_on_stream(&mut send_stream, opt.download_size).await?;\n Ok::<_, n0_snafu::Error>(())\n });\n }\n\n if opt.stats {\n println!(\"\\nServer connection stats:\\n{:#?}\", connection.stats());\n }\n }));\n }\n\n // Await all the tasks. We have to do this to prevent the runtime getting dropped\n // and all server tasks to be cancelled\n for handle in server_tasks {\n if let Err(e) = handle.await {\n eprintln!(\"Server task error: {e:?}\");\n };\n }\n\n Ok(())\n}\n```"}], "func_name": "server", "docstring": "Take the provided endpoint and run the server", "repo": "n0-computer/iroh", "path": "iroh/bench/src/iroh.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/bench/src/iroh.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ad5c8ed324069e62a37f245de31c05152a33a4b9181a6f6fb294f76b1da1604"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: client_handler\n\nDocumentation:\nTake the provided endpoint and run the client benchmark\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn client_handler(\n endpoint: EndpointSelector,\n connection: ConnectionSelector,\n opt: Opt,\n) -> Result {\n let start = Instant::now();\n\n let connection = Arc::new(connection);\n\n let mut stats = ClientStats::default();\n let mut first_error = None;\n\n let sem = Arc::new(Semaphore::new(opt.max_streams));\n let results = Arc::new(Mutex::new(Vec::new()));\n for _ in 0..opt.streams {\n let permit = sem.clone().acquire_owned().await.unwrap();\n let results = results.clone();\n let connection = connection.clone();\n tokio::spawn(async move {\n let result = match &*connection {\n ConnectionSelector::Iroh(connection) => {\n iroh::handle_client_stream(connection, opt.upload_size, opt.read_unordered)\n .await\n }\n #[cfg(not(any(\n target_os = \"freebsd\",\n target_os = \"openbsd\",\n target_os = \"netbsd\"\n )))]\n ConnectionSelector::Quinn(connection) => {\n quinn::handle_client_stream(connection, opt.upload_size, opt.read_unordered)\n .await\n }\n };\n // handle_client_stream(connection, opt.upload_size, opt.read_unordered).await;\n info!(\"stream finished: {:?}\", result);\n results.lock().unwrap().push(result);\n drop(permit);\n });\n }\n\n // Wait for remaining streams to finish\n let _ = sem.acquire_many(opt.max_streams as u32).await.unwrap();\n\n stats.upload_stats.total_duration = start.elapsed();\n stats.download_stats.total_duration = start.elapsed();\n\n for result in results.lock().unwrap().drain(..) {\n match result {\n Ok((upload_result, download_result)) => {\n stats.upload_stats.stream_finished(upload_result);\n stats.download_stats.stream_finished(download_result);\n }\n Err(e) => {\n if first_error.is_none() {\n first_error = Some(e);\n }\n }\n }\n }\n\n // Explicit close of the connection, since handles can still be around due\n // to `Arc`ing them\n connection.close(0u32, b\"Benchmark done\");\n\n endpoint.close().await;\n\n if opt.stats {\n println!(\"\\nClient connection stats:\\n{:#?}\", connection.stats());\n }\n\n match first_error {\n None => Ok(stats),\n Some(e) => Err(e),\n }\n}\n```"}], "func_name": "client_handler", "docstring": "Take the provided endpoint and run the client benchmark", "repo": "n0-computer/iroh", "path": "iroh/bench/src/lib.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/bench/src/lib.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "99140cebcb7f8931cae1a13a871c93723bf5e12d10fe593af4419d2956ffdb6a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_or_generate_secret_key\n\nDocumentation:\nGets a secret key from the IROH_SECRET environment variable or generates a new random one.\nIf the environment variable is set, it must be a valid string representation of a secret key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_or_generate_secret_key() -> n0_snafu::Result {\n if let Ok(secret) = env::var(\"IROH_SECRET\") {\n // Parse the secret key from string\n SecretKey::from_str(&secret).context(\"Invalid secret key format\")\n } else {\n // Generate a new random key\n let secret_key = SecretKey::generate(&mut thread_rng());\n println!(\"Generated new secret key: {}\", secret_key);\n println!(\"To reuse this key, set the IROH_SECRET environment variable to this value\");\n Ok(secret_key)\n }\n}\n```"}], "func_name": "get_or_generate_secret_key", "docstring": "Gets a secret key from the IROH_SECRET environment variable or generates a new random one.\nIf the environment variable is set, it must be a valid string representation of a secret key.", "repo": "n0-computer/iroh", "path": "iroh/examples/0rtt.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/examples/0rtt.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "479998edb95371234d083da4ca8cbfa4144637c4c0807552e306aebd867526b8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pingpong\n\nDocumentation:\nDo a simple ping-pong with the given connection.\n\nWe send the data on the connection. If `proceed` resolves to true,\nread the response immediately. Otherwise, the stream pair is bad and we need\nto open a new stream pair.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn pingpong(\n connection: &Connection,\n proceed: impl Future,\n x: u64,\n) -> n0_snafu::Result<()> {\n let (mut send, recv) = connection.open_bi().await.e()?;\n let data = x.to_be_bytes();\n send.write_all(&data).await.e()?;\n send.finish().e()?;\n let mut recv = if proceed.await {\n // use recv directly if we can proceed\n recv\n } else {\n // proceed returned false, so we have learned that the 0-RTT send was rejected.\n // at this point we have a fully handshaked connection, so we try again.\n let (mut send, recv) = connection.open_bi().await.e()?;\n send.write_all(&data).await.e()?;\n send.finish().e()?;\n recv\n };\n let echo = recv.read_to_end(8).await.e()?;\n assert!(echo == data);\n Ok(())\n}\n```"}], "func_name": "pingpong", "docstring": "Do a simple ping-pong with the given connection.\n\nWe send the data on the connection. If `proceed` resolves to true,\nread the response immediately. Otherwise, the stream pair is bad and we need\nto open a new stream pair.", "repo": "n0-computer/iroh", "path": "iroh/examples/0rtt.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/examples/0rtt.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c42b3d58dbb9f4070f0095d0575f0e24501b9883b4e6a925fd36be83de8bfc9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accept\n\nDocumentation:\nThe `accept` method is called for each incoming connection for our ALPN.\n\nThe returned future runs on a newly spawned tokio task, so it can run as long as\nthe connection lasts.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn accept(&self, connection: Connection) -> Result<(), AcceptError> {\n // We can get the remote's node id from the connection.\n let node_id = connection.remote_node_id()?;\n println!(\"accepted connection from {node_id}\");\n\n // Our protocol is a simple request-response protocol, so we expect the\n // connecting peer to open a single bi-directional stream.\n let (mut send, mut recv) = connection.accept_bi().await?;\n\n // Echo any bytes received back directly.\n // This will keep copying until the sender signals the end of data on the stream.\n let bytes_sent = tokio::io::copy(&mut recv, &mut send).await?;\n println!(\"Copied over {bytes_sent} byte(s)\");\n\n // By calling `finish` on the send stream we signal that we will not send anything\n // further, which makes the receive stream on the other end terminate.\n send.finish()?;\n\n // Wait until the remote closes the connection, which it does once it\n // received the response.\n connection.closed().await;\n\n Ok(())\n }\n```"}], "func_name": "accept", "docstring": "The `accept` method is called for each incoming connection for our ALPN.\n\nThe returned future runs on a newly spawned tokio task, so it can run as long as\nthe connection lasts.", "repo": "n0-computer/iroh", "path": "iroh/examples/echo.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/examples/echo.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f9bb98ecb702a8ae450e9dcc8429c5ef2f9ee5e7944110801c0dd70b83b83abb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: query_remote\n\nDocumentation:\nQuery a remote node, download all matching blobs and print the results.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn query_remote(&self, node_id: NodeId, query: &str) -> Result {\n // Establish a connection to our node.\n // We use the default node discovery in iroh, so we can connect by node id without\n // providing further information.\n let conn = self.endpoint.connect(node_id, ALPN).await?;\n\n // Open a bi-directional in our connection.\n let (mut send, mut recv) = conn.open_bi().await.e()?;\n\n // Send our query.\n send.write_all(query.as_bytes()).await.e()?;\n\n // Finish the send stream, signalling that no further data will be sent.\n // This makes the `read_to_end` call on the accepting side terminate.\n send.finish().e()?;\n\n // The response is a 64 bit integer\n // We simply read it into a byte buffer.\n let mut num_matches = [0u8; 8];\n\n // Read 8 bytes from the stream.\n recv.read_exact(&mut num_matches).await.e()?;\n\n let num_matches = u64::from_le_bytes(num_matches);\n\n // Dropping the connection here will close it.\n\n Ok(num_matches)\n }\n```"}], "func_name": "query_remote", "docstring": "Query a remote node, download all matching blobs and print the results.", "repo": "n0-computer/iroh", "path": "iroh/examples/search.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/examples/search.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "57254d259dc750945bb1bfc8b30233b97465b88fcc7245a28f6560dd35784e1c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: query_local\n\nDocumentation:\nQuery the local database.\n\nReturns how many matches were found.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn query_local(&self, query: &str) -> u64 {\n let guard = self.blobs.lock().await;\n let count: usize = guard.iter().filter(|text| text.contains(query)).count();\n count as u64\n }\n```"}], "func_name": "query_local", "docstring": "Query the local database.\n\nReturns how many matches were found.", "repo": "n0-computer/iroh", "path": "iroh/examples/search.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/examples/search.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0ad089ad462e802c8db7239aafa00dd48d66695b8f316b81bab975735cab505"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nInsert a text string into the database.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn insert(&self, text: String) -> Result<()> {\n let mut guard = self.blobs.lock().await;\n guard.insert(text);\n Ok(())\n }\n```"}], "func_name": "insert", "docstring": "Insert a text string into the database.", "repo": "n0-computer/iroh", "path": "iroh/examples/search.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/examples/search.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c667db8a4bfe82cba1beebc81e5f4833b4ef2a034c071b7f44f7e192ef97e15"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: setup_logging\n\nDocumentation:\nSet the RUST_LOG env var to one of {debug,info,warn} to see logging.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn setup_logging() {\n tracing_subscriber::registry()\n .with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr))\n .with(EnvFilter::from_default_env())\n .try_init()\n .ok();\n}\n```"}], "func_name": "setup_logging", "docstring": "Set the RUST_LOG env var to one of {debug,info,warn} to see logging.", "repo": "n0-computer/iroh", "path": "iroh/examples/search.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/examples/search.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "13f744e452326982602fd3db4e08f9c2cd8c84ed85b1e110cb3075abb0f5f3e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_na_relay_node\n\nDocumentation:\nGet the default [`RelayNode`] for NA.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn default_na_relay_node() -> RelayNode {\n // The default NA relay server run by number0.\n let url: Url = format!(\"https://{NA_RELAY_HOSTNAME}\")\n .parse()\n .expect(\"default url\");\n RelayNode {\n url: url.into(),\n stun_only: false,\n stun_port: DEFAULT_STUN_PORT,\n quic: Some(RelayQuicConfig::default()),\n }\n }\n```"}], "func_name": "default_na_relay_node", "docstring": "Get the default [`RelayNode`] for NA.", "repo": "n0-computer/iroh", "path": "iroh/src/defaults.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/defaults.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e97d8717850882ae0e6cbcd8ddd735d7a22b2510e9cef105b7a888af603dfac4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_eu_relay_node\n\nDocumentation:\nGet the default [`RelayNode`] for EU.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn default_eu_relay_node() -> RelayNode {\n // The default EU relay server run by number0.\n let url: Url = format!(\"https://{EU_RELAY_HOSTNAME}\")\n .parse()\n .expect(\"default_url\");\n RelayNode {\n url: url.into(),\n stun_only: false,\n stun_port: DEFAULT_STUN_PORT,\n quic: Some(RelayQuicConfig::default()),\n }\n }\n```"}], "func_name": "default_eu_relay_node", "docstring": "Get the default [`RelayNode`] for EU.", "repo": "n0-computer/iroh", "path": "iroh/src/defaults.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/defaults.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b4c47c53501524964592191c5b9fa77a898ebea6dc31f68d90c5872421c64b02"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default_ap_relay_node\n\nDocumentation:\nGet the default [`RelayNode`] for Asia-Pacific\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn default_ap_relay_node() -> RelayNode {\n // The default Asia-Pacific relay server run by number0.\n let url: Url = format!(\"https://{AP_RELAY_HOSTNAME}\")\n .parse()\n .expect(\"default_url\");\n RelayNode {\n url: url.into(),\n stun_only: false,\n stun_port: DEFAULT_STUN_PORT,\n quic: Some(RelayQuicConfig::default()),\n }\n }\n```"}], "func_name": "default_ap_relay_node", "docstring": "Get the default [`RelayNode`] for Asia-Pacific", "repo": "n0-computer/iroh", "path": "iroh/src/defaults.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/defaults.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6cfc64295cf156eb18d8e4dac7517db7ee4a1f82ab02ddcf70553ddf9594ffb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_err\n\nDocumentation:\nCreates a new user error from an arbitrary error type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_err(\n provenance: &'static str,\n source: T,\n ) -> Self {\n UserSnafu { provenance }.into_error(Box::new(source))\n }\n```"}], "func_name": "from_err", "docstring": "Creates a new user error from an arbitrary error type.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a77f63a76cd4a924f97b20e8c68009408c6637a668838db67f2ea11cfa873bc3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_err_box\n\nDocumentation:\nCreates a new user error from an arbitrary boxed error type.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_err_box(\n provenance: &'static str,\n source: Box,\n ) -> Self {\n UserSnafu { provenance }.into_error(source)\n }\n```"}], "func_name": "from_err_box", "docstring": "Creates a new user error from an arbitrary boxed error type.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7f61d3783a0d086958804c1766ad344cb9f244f9d34cd435de74454421813a76"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve\n\nDocumentation:\nResolves the [`DiscoveryItem`] for the given [`NodeId`].\n\nOnce the returned [`BoxStream`] is dropped, the service should stop any pending\nwork.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn resolve(\n &self,\n _endpoint: Endpoint,\n _node_id: NodeId,\n ) -> Option>> {\n None\n }\n```"}], "func_name": "resolve", "docstring": "Resolves the [`DiscoveryItem`] for the given [`NodeId`].\n\nOnce the returned [`BoxStream`] is dropped, the service should stop any pending\nwork.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c836e89def0a9ca4e7ee588e422b308f4ca7e0beb3f68d7b29d42e14e35a15c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: maybe_start_after_delay\n\nDocumentation:\nStarts a discovery task after a delay and only if no path to the node was recently active.\n\nThis returns `None` if we received data or control messages from the remote endpoint\nrecently enough. If not it returns a [`DiscoveryTask`].\n\nIf `delay` is set, the [`DiscoveryTask`] will first wait for `delay` and then check again\nif we recently received messages from remote endpoint. If true, the task will abort.\nOtherwise, or if no `delay` is set, the discovery will be started.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn maybe_start_after_delay(\n ep: &Endpoint,\n node_id: NodeId,\n delay: Option,\n ) -> Result, DiscoveryError> {\n // If discovery is not needed, don't even spawn a task.\n if !Self::needs_discovery(ep, node_id) {\n return Ok(None);\n }\n ensure!(ep.discovery().is_some(), NoServiceConfiguredSnafu);\n let (on_first_tx, on_first_rx) = oneshot::channel();\n let ep = ep.clone();\n let me = ep.node_id();\n let task = task::spawn(\n async move {\n // If delay is set, wait and recheck if discovery is needed. If not, early-exit.\n if let Some(delay) = delay {\n time::sleep(delay).await;\n if !Self::needs_discovery(&ep, node_id) {\n debug!(\"no discovery needed, abort\");\n on_first_tx.send(Ok(())).ok();\n return;\n }\n }\n Self::run(ep, node_id, on_first_tx).await\n }\n .instrument(\n error_span!(\"discovery\", me = %me.fmt_short(), node = %node_id.fmt_short()),\n ),\n );\n Ok(Some(Self {\n _task: AbortOnDropHandle::new(task),\n on_first_rx,\n }))\n }\n```"}], "func_name": "maybe_start_after_delay", "docstring": "Starts a discovery task after a delay and only if no path to the node was recently active.\n\nThis returns `None` if we received data or control messages from the remote endpoint\nrecently enough. If not it returns a [`DiscoveryTask`].\n\nIf `delay` is set, the [`DiscoveryTask`] will first wait for `delay` and then check again\nif we recently received messages from remote endpoint. If true, the task will abort.\nOtherwise, or if no `delay` is set, the discovery will be started.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9091a7a2d2e0e29a3da25f9f3b0b5ea81479ee46513d8cf4adf43f4ba3724d6b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: first_arrived\n\nDocumentation:\nWaits until the discovery task produced at least one result.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn first_arrived(&mut self) -> Result<(), DiscoveryError> {\n let fut = &mut self.on_first_rx;\n fut.await.expect(\"sender dropped\")?;\n Ok(())\n }\n```"}], "func_name": "first_arrived", "docstring": "Waits until the discovery task produced at least one result.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "03b3e6d2a8a827cb4d86b97a9538cb0445d0f6b4fae75fb60df7b66e45feb674"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: needs_discovery\n\nDocumentation:\nWe need discovery if we have no paths to the node, or if the paths we do have\nhave timed out.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn needs_discovery(ep: &Endpoint, node_id: NodeId) -> bool {\n match ep.remote_info(node_id) {\n // No info means no path to node -> start discovery.\n None => true,\n Some(info) => {\n match (\n info.last_received(),\n info.relay_url.as_ref().and_then(|r| r.last_alive),\n ) {\n // No path to node -> start discovery.\n (None, None) => true,\n // If we haven't received on direct addresses or the relay for MAX_AGE,\n // start discovery.\n (Some(elapsed), Some(elapsed_relay)) => {\n elapsed > MAX_AGE && elapsed_relay > MAX_AGE\n }\n (Some(elapsed), _) | (_, Some(elapsed)) => elapsed > MAX_AGE,\n }\n }\n }\n }\n```"}], "func_name": "needs_discovery", "docstring": "We need discovery if we have no paths to the node, or if the paths we do have\nhave timed out.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5fb62a3ce0d081a59a397758646bdc65fb375046c0e89e04d0b535f06940745f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bind_addr_v4\n\nDocumentation:\nSets the IPv4 bind address.\n\nSetting the port to `0` will use a random port.\nIf the port specified is already in use, it will fallback to choosing a random port.\n\nBy default will use `0.0.0.0:0` to bind to.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bind_addr_v4(mut self, addr: SocketAddrV4) -> Self {\n self.addr_v4.replace(addr);\n self\n }\n```"}], "func_name": "bind_addr_v4", "docstring": "Sets the IPv4 bind address.\n\nSetting the port to `0` will use a random port.\nIf the port specified is already in use, it will fallback to choosing a random port.\n\nBy default will use `0.0.0.0:0` to bind to.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d1da15df97618134107e118d007de39076f8e4ed36edadae9f4d8b6a5a57a47c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bind_addr_v6\n\nDocumentation:\nSets the IPv6 bind address.\n\nSetting the port to `0` will use a random port.\nIf the port specified is already in use, it will fallback to choosing a random port.\n\nBy default will use `[::]:0` to bind to.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bind_addr_v6(mut self, addr: SocketAddrV6) -> Self {\n self.addr_v6.replace(addr);\n self\n }\n```"}], "func_name": "bind_addr_v6", "docstring": "Sets the IPv6 bind address.\n\nSetting the port to `0` will use a random port.\nIf the port specified is already in use, it will fallback to choosing a random port.\n\nBy default will use `[::]:0` to bind to.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ba3250da7c81c7e680be3ed768316198e00943b1ae5f3281b600d5882d09edbb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: secret_key\n\nDocumentation:\nSets a secret key to authenticate with other peers.\n\nThis secret key's public key will be the [`PublicKey`] of this endpoint and thus\nalso its [`NodeId`]\n\nIf not set, a new secret key will be generated.\n\n[`PublicKey`]: iroh_base::PublicKey\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn secret_key(mut self, secret_key: SecretKey) -> Self {\n self.secret_key = Some(secret_key);\n self\n }\n```"}], "func_name": "secret_key", "docstring": "Sets a secret key to authenticate with other peers.\n\nThis secret key's public key will be the [`PublicKey`] of this endpoint and thus\nalso its [`NodeId`]\n\nIf not set, a new secret key will be generated.\n\n[`PublicKey`]: iroh_base::PublicKey", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f1694b504397ece505b23cafcd386f295e8ba39a7836dc9e43fbb21dcebdef48"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: alpns\n\nDocumentation:\nSets the [ALPN] protocols that this endpoint will accept on incoming connections.\n\nNot setting this will still allow creating connections, but to accept incoming\nconnections at least one [ALPN] must be set.\n\n[ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn alpns(mut self, alpn_protocols: Vec>) -> Self {\n self.alpn_protocols = alpn_protocols;\n self\n }\n```"}], "func_name": "alpns", "docstring": "Sets the [ALPN] protocols that this endpoint will accept on incoming connections.\n\nNot setting this will still allow creating connections, but to accept incoming\nconnections at least one [ALPN] must be set.\n\n[ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "16d53b39304e297a709548af0c493250942978488419f7314a0e1f89cd49b161"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: relay_mode\n\nDocumentation:\nSets the relay servers to assist in establishing connectivity.\n\nRelay servers are used to establish initial connection with another iroh node.\nThey also perform various functions related to hole punching, see the [crate docs]\nfor more details.\n\nBy default the [number 0] relay servers are used, see [`RelayMode::Default`].\n\nWhen using [RelayMode::Custom], the provided `relay_map` must contain at least one\nconfigured relay node. If an invalid RelayMap is provided [`bind`]\nwill result in an error.\n\n[`bind`]: Builder::bind\n[crate docs]: crate\n[number 0]: https://n0.computer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn relay_mode(mut self, relay_mode: RelayMode) -> Self {\n self.relay_mode = relay_mode;\n self\n }\n```"}], "func_name": "relay_mode", "docstring": "Sets the relay servers to assist in establishing connectivity.\n\nRelay servers are used to establish initial connection with another iroh node.\nThey also perform various functions related to hole punching, see the [crate docs]\nfor more details.\n\nBy default the [number 0] relay servers are used, see [`RelayMode::Default`].\n\nWhen using [RelayMode::Custom], the provided `relay_map` must contain at least one\nconfigured relay node. If an invalid RelayMap is provided [`bind`]\nwill result in an error.\n\n[`bind`]: Builder::bind\n[crate docs]: crate\n[number 0]: https://n0.computer", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "76737071757fc6fea65e5b304011f0af7ff9a53f4eb0884a9db77af71a729a0b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: relay_conn_protocol\n\nDocumentation:\nSets the protocol to use for relay connections.\n\nOptions are either [`RelayProtocol::Websocket`] or [`RelayProtocol::Relay`].\n\n`Websocket` is considered unstable between iroh versions at the moment.\nThe protocol can change in compatibility-breaking ways before iroh 1.0.\n\nDefault is set to `Relay` at the moment, until we've stabilized the websocket protocol.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn relay_conn_protocol(mut self, protocol: RelayProtocol) -> Self {\n self.relay_protocol = protocol;\n self\n }\n```"}], "func_name": "relay_conn_protocol", "docstring": "Sets the protocol to use for relay connections.\n\nOptions are either [`RelayProtocol::Websocket`] or [`RelayProtocol::Relay`].\n\n`Websocket` is considered unstable between iroh versions at the moment.\nThe protocol can change in compatibility-breaking ways before iroh 1.0.\n\nDefault is set to `Relay` at the moment, until we've stabilized the websocket protocol.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "576d50652c859dbbfb576478b6a85411f4ded8fd589eccdcb23a2a3abdf0805f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clear_discovery\n\nDocumentation:\nRemoves all discovery services from the builder.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clear_discovery(mut self) -> Self {\n self.discovery.clear();\n self\n }\n```"}], "func_name": "clear_discovery", "docstring": "Removes all discovery services from the builder.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "01526d2050eed730318f61d73d90c207e38f9774d126adbde30fda59eea82c65"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: discovery\n\nDocumentation:\nOptionally sets a discovery mechanism for this endpoint.\n\nIf you want to combine multiple discovery services, you can use\n[`Builder::add_discovery`] instead. This will internally create a\n[`crate::discovery::ConcurrentDiscovery`].\n\nIf no discovery service is set, connecting to a node without providing its\ndirect addresses or relay URLs will fail.\n\nSee the documentation of the [`Discovery`] trait for details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn discovery(mut self, discovery: Box) -> Self {\n self.discovery.clear();\n self.discovery.push(Box::new(move |_| Some(discovery)));\n self\n }\n```"}], "func_name": "discovery", "docstring": "Optionally sets a discovery mechanism for this endpoint.\n\nIf you want to combine multiple discovery services, you can use\n[`Builder::add_discovery`] instead. This will internally create a\n[`crate::discovery::ConcurrentDiscovery`].\n\nIf no discovery service is set, connecting to a node without providing its\ndirect addresses or relay URLs will fail.\n\nSee the documentation of the [`Discovery`] trait for details.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "784cab12b4ec70c0466a6de885917321eda55b111a3772acb82a77a4cd32b3dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_discovery\n\nDocumentation:\nAdds a discovery mechanism for this endpoint.\n\nThe function `discovery`\nwill be called on endpoint creation with the configured secret key of\nthe endpoint. Discovery services that need to publish information need\nto use this secret key to sign the information.\n\nIf you add multiple discovery services, they will be combined using a\n[`crate::discovery::ConcurrentDiscovery`].\n\nIf no discovery service is set, connecting to a node without providing its\ndirect addresses or relay URLs will fail.\n\nTo clear all discovery services, use [`Builder::clear_discovery`].\n\nSee the documentation of the [`Discovery`] trait for details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_discovery(mut self, discovery: F) -> Self\n where\n F: FnOnce(&SecretKey) -> Option + Send + Sync + 'static,\n D: Discovery + 'static,\n {\n let discovery: DiscoveryBuilder =\n Box::new(move |secret_key| discovery(secret_key).map(|x| Box::new(x) as _));\n self.discovery.push(discovery);\n self\n }\n```"}], "func_name": "add_discovery", "docstring": "Adds a discovery mechanism for this endpoint.\n\nThe function `discovery`\nwill be called on endpoint creation with the configured secret key of\nthe endpoint. Discovery services that need to publish information need\nto use this secret key to sign the information.\n\nIf you add multiple discovery services, they will be combined using a\n[`crate::discovery::ConcurrentDiscovery`].\n\nIf no discovery service is set, connecting to a node without providing its\ndirect addresses or relay URLs will fail.\n\nTo clear all discovery services, use [`Builder::clear_discovery`].\n\nSee the documentation of the [`Discovery`] trait for details.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8778b302cf98e638894cd5a2c66e09b2b463a7b238b8b500e18f9888a7dff868"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: discovery_n0\n\nDocumentation:\nConfigures the endpoint to use the default n0 DNS discovery service.\n\nThe default discovery service publishes to and resolves from the\nn0.computer dns server `iroh.link`.\n\nThis is equivalent to adding both a [`crate::discovery::pkarr::PkarrPublisher`]\nand a [`crate::discovery::dns::DnsDiscovery`], both configured to use the\nn0.computer dns server.\n\nThis will by default use [`N0_DNS_PKARR_RELAY_PROD`].\nWhen in tests, or when the `test-utils` feature is enabled, this will use the\n[`N0_DNS_PKARR_RELAY_STAGING`].\n\n[`N0_DNS_PKARR_RELAY_PROD`]: crate::discovery::pkarr::N0_DNS_PKARR_RELAY_PROD\n[`N0_DNS_PKARR_RELAY_STAGING`]: crate::discovery::pkarr::N0_DNS_PKARR_RELAY_STAGING\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn discovery_n0(mut self) -> Self {\n self.discovery.push(Box::new(|secret_key| {\n Some(Box::new(PkarrPublisher::n0_dns(secret_key.clone())))\n }));\n // Resolve using HTTPS requests to our DNS server's /pkarr path in browsers\n #[cfg(wasm_browser)]\n {\n self.discovery\n .push(Box::new(|_| Some(Box::new(PkarrResolver::n0_dns()))));\n }\n // Resolve using DNS queries outside browsers.\n #[cfg(not(wasm_browser))]\n {\n self.discovery\n .push(Box::new(|_| Some(Box::new(DnsDiscovery::n0_dns()))));\n }\n self\n }\n```"}], "func_name": "discovery_n0", "docstring": "Configures the endpoint to use the default n0 DNS discovery service.\n\nThe default discovery service publishes to and resolves from the\nn0.computer dns server `iroh.link`.\n\nThis is equivalent to adding both a [`crate::discovery::pkarr::PkarrPublisher`]\nand a [`crate::discovery::dns::DnsDiscovery`], both configured to use the\nn0.computer dns server.\n\nThis will by default use [`N0_DNS_PKARR_RELAY_PROD`].\nWhen in tests, or when the `test-utils` feature is enabled, this will use the\n[`N0_DNS_PKARR_RELAY_STAGING`].\n\n[`N0_DNS_PKARR_RELAY_PROD`]: crate::discovery::pkarr::N0_DNS_PKARR_RELAY_PROD\n[`N0_DNS_PKARR_RELAY_STAGING`]: crate::discovery::pkarr::N0_DNS_PKARR_RELAY_STAGING", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "68dfd4908ef6d08b96ee99208d621f0167f1691680c83baa43087cf2ee54951c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: discovery_dht\n\nDocumentation:\nConfigures the endpoint to also use the mainline DHT with default settings.\n\nThis is equivalent to adding a [`crate::discovery::pkarr::dht::DhtDiscovery`]\nwith default settings. Note that DhtDiscovery has various more advanced\nconfiguration options. If you need any of those, you should manually\ncreate a DhtDiscovery and add it with [`Builder::add_discovery`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn discovery_dht(mut self) -> Self {\n use crate::discovery::pkarr::dht::DhtDiscovery;\n self.discovery.push(Box::new(|secret_key| {\n match DhtDiscovery::builder()\n .secret_key(secret_key.clone())\n .build()\n {\n Ok(discovery) => Some(Box::new(discovery)),\n Err(err) => {\n tracing::error!(\"failed to build discovery: {:?}\", err);\n None\n }\n }\n }));\n self\n }\n```"}], "func_name": "discovery_dht", "docstring": "Configures the endpoint to also use the mainline DHT with default settings.\n\nThis is equivalent to adding a [`crate::discovery::pkarr::dht::DhtDiscovery`]\nwith default settings. Note that DhtDiscovery has various more advanced\nconfiguration options. If you need any of those, you should manually\ncreate a DhtDiscovery and add it with [`Builder::add_discovery`].", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d78142ec31994d606388f905b5a9e669bb59139f78c954b68efdf89d85db1efc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: discovery_local_network\n\nDocumentation:\nConfigures the endpoint to also use local network discovery.\n\nThis is equivalent to adding a [`crate::discovery::mdns::MdnsDiscovery`]\nwith default settings. Note that MdnsDiscovery has various more advanced\nconfiguration options. If you need any of those, you should manually\ncreate a MdnsDiscovery and add it with [`Builder::add_discovery`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn discovery_local_network(mut self) -> Self {\n use crate::discovery::mdns::MdnsDiscovery;\n self.discovery.push(Box::new(|secret_key| {\n MdnsDiscovery::new(secret_key.public())\n .map(|x| Box::new(x) as _)\n .ok()\n }));\n self\n }\n```"}], "func_name": "discovery_local_network", "docstring": "Configures the endpoint to also use local network discovery.\n\nThis is equivalent to adding a [`crate::discovery::mdns::MdnsDiscovery`]\nwith default settings. Note that MdnsDiscovery has various more advanced\nconfiguration options. If you need any of those, you should manually\ncreate a MdnsDiscovery and add it with [`Builder::add_discovery`].", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "60f63e4fa4e3bab5f1246b2f1758c337bba48b2982b464ba405e09517e3d3bdd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: user_data_for_discovery\n\nDocumentation:\nSets the initial user-defined data to be published in discovery services for this node.\n\nWhen using discovery services, this string of [`UserData`] will be published together\nwith the node's addresses and relay URL. When other nodes discover this node,\nthey retrieve the [`UserData`] in addition to the addressing info.\n\nIroh itself does not interpret the user-defined data in any way, it is purely left\nfor applications to parse and use.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn user_data_for_discovery(mut self, user_data: UserData) -> Self {\n self.discovery_user_data = Some(user_data);\n self\n }\n```"}], "func_name": "user_data_for_discovery", "docstring": "Sets the initial user-defined data to be published in discovery services for this node.\n\nWhen using discovery services, this string of [`UserData`] will be published together\nwith the node's addresses and relay URL. When other nodes discover this node,\nthey retrieve the [`UserData`] in addition to the addressing info.\n\nIroh itself does not interpret the user-defined data in any way, it is purely left\nfor applications to parse and use.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "df539287676de38275d654aed4513fcfacd6eb10ed48077c191c9875ec66ea66"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: known_nodes\n\nDocumentation:\nOptionally set a list of known nodes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn known_nodes(mut self, nodes: Vec) -> Self {\n self.node_map = Some(nodes);\n self\n }\n```"}], "func_name": "known_nodes", "docstring": "Optionally set a list of known nodes.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "88811afee6631358bd1eb2cd66d642a2683e492fa7cb260dddbdf89a7701c410"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: transport_config\n\nDocumentation:\nSets a custom [`quinn::TransportConfig`] for this endpoint.\n\nThe transport config contains parameters governing the QUIC state machine.\n\nIf unset, the default config is used. Default values should be suitable for most\ninternet applications. Applications protocols which forbid remotely-initiated\nstreams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to\nzero.\n\nPlease be aware that changing some settings may have adverse effects on establishing\nand maintaining direct connections.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn transport_config(mut self, transport_config: quinn::TransportConfig) -> Self {\n self.transport_config = transport_config;\n self\n }\n```"}], "func_name": "transport_config", "docstring": "Sets a custom [`quinn::TransportConfig`] for this endpoint.\n\nThe transport config contains parameters governing the QUIC state machine.\n\nIf unset, the default config is used. Default values should be suitable for most\ninternet applications. Applications protocols which forbid remotely-initiated\nstreams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to\nzero.\n\nPlease be aware that changing some settings may have adverse effects on establishing\nand maintaining direct connections.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8de27c111332f38d4e60b49458f8c54bfecf6e2fc88d973cfb6fe9861a461a62"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: proxy_url\n\nDocumentation:\nSets an explicit proxy url to proxy all HTTP(S) traffic through.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn proxy_url(mut self, url: Url) -> Self {\n self.proxy_url.replace(url);\n self\n }\n```"}], "func_name": "proxy_url", "docstring": "Sets an explicit proxy url to proxy all HTTP(S) traffic through.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "621a1f0586735ea17dd22f087a82d6fe4cd432e2df1765da032530891bb8b2dd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: proxy_from_env\n\nDocumentation:\nSets the proxy url from the environment, in this order:\n\n- `HTTP_PROXY`\n- `http_proxy`\n- `HTTPS_PROXY`\n- `https_proxy`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn proxy_from_env(mut self) -> Self {\n self.proxy_url = proxy_url_from_env();\n self\n }\n```"}], "func_name": "proxy_from_env", "docstring": "Sets the proxy url from the environment, in this order:\n\n- `HTTP_PROXY`\n- `http_proxy`\n- `HTTPS_PROXY`\n- `https_proxy`", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e9a6cb5c1b569ddcd8d5558ffa9eb9f293da2fc62f7200dfc1e57927b2d4296"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: keylog\n\nDocumentation:\nEnables saving the TLS pre-master key for connections.\n\nThis key should normally remain secret but can be useful to debug networking issues\nby decrypting captured traffic.\n\nIf *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a\nfilename will result in this file being used to log the TLS pre-master keys.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn keylog(mut self, keylog: bool) -> Self {\n self.keylog = keylog;\n self\n }\n```"}], "func_name": "keylog", "docstring": "Enables saving the TLS pre-master key for connections.\n\nThis key should normally remain secret but can be useful to debug networking issues\nby decrypting captured traffic.\n\nIf *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a\nfilename will result in this file being used to log the TLS pre-master keys.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a74f9ecd9a208da05869d8bb306b7278f041e5ef4ad8108e5b031f4c0768c5a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_server_config\n\nDocumentation:\nCreate a [`quinn::ServerConfig`] with the specified ALPN protocols.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn create_server_config(&self, alpn_protocols: Vec>) -> ServerConfig {\n let quic_server_config = self\n .tls_config\n .make_server_config(alpn_protocols, self.keylog);\n let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));\n server_config.transport_config(self.transport_config.clone());\n\n server_config\n }\n```"}], "func_name": "create_server_config", "docstring": "Create a [`quinn::ServerConfig`] with the specified ALPN protocols.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8506eb0ffb588d4be4def9701f73769b52ba982a320c570117c3dff80a1bde15"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_alpns\n\nDocumentation:\nSets the list of accepted ALPN protocols.\n\nThis will only affect new incoming connections.\nNote that this *overrides* the current list of ALPNs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_alpns(&self, alpns: Vec>) {\n let server_config = self.static_config.create_server_config(alpns);\n self.msock.endpoint().set_server_config(Some(server_config));\n }\n```"}], "func_name": "set_alpns", "docstring": "Sets the list of accepted ALPN protocols.\n\nThis will only affect new incoming connections.\nNote that this *overrides* the current list of ALPNs.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "483cf23db4b90c7f13abe211347ebe219fe4861fb876e5b26d134fa1b124b947"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nConnects to a remote [`Endpoint`].\n\nA value that can be converted into a [`NodeAddr`] is required. This can be either a\n[`NodeAddr`], a [`NodeId`] or a [`iroh_base::ticket::NodeTicket`].\n\nThe [`NodeAddr`] must contain the [`NodeId`] to dial and may also contain a [`RelayUrl`]\nand direct addresses. If direct addresses are provided, they will be used to try and\nestablish a direct connection without involving a relay server.\n\nIf neither a [`RelayUrl`] or direct addresses are configured in the [`NodeAddr`] it\nmay still be possible a connection can be established. This depends on other calls\nto [`Endpoint::add_node_addr`] which may provide contact information, or via the\n[`Discovery`] service configured using [`Builder::discovery`]. The discovery\nservice will also be used if the remote node is not reachable on the provided direct\naddresses and there is no [`RelayUrl`].\n\nIf addresses or relay servers are neither provided nor can be discovered, the\nconnection attempt will fail with an error.\n\nThe `alpn`, or application-level protocol identifier, is also required. The remote\nendpoint must support this `alpn`, otherwise the connection attempt will fail with\nan error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn connect(\n &self,\n node_addr: impl Into,\n alpn: &[u8],\n ) -> Result {\n let node_addr = node_addr.into();\n let remote = node_addr.node_id;\n let connecting = self\n .connect_with_opts(node_addr, alpn, Default::default())\n .await?;\n let conn = connecting.await?;\n\n debug!(\n me = %self.node_id().fmt_short(),\n remote = %remote.fmt_short(),\n alpn = %String::from_utf8_lossy(alpn),\n \"Connection established.\"\n );\n Ok(conn)\n }\n```"}], "func_name": "connect", "docstring": "Connects to a remote [`Endpoint`].\n\nA value that can be converted into a [`NodeAddr`] is required. This can be either a\n[`NodeAddr`], a [`NodeId`] or a [`iroh_base::ticket::NodeTicket`].\n\nThe [`NodeAddr`] must contain the [`NodeId`] to dial and may also contain a [`RelayUrl`]\nand direct addresses. If direct addresses are provided, they will be used to try and\nestablish a direct connection without involving a relay server.\n\nIf neither a [`RelayUrl`] or direct addresses are configured in the [`NodeAddr`] it\nmay still be possible a connection can be established. This depends on other calls\nto [`Endpoint::add_node_addr`] which may provide contact information, or via the\n[`Discovery`] service configured using [`Builder::discovery`]. The discovery\nservice will also be used if the remote node is not reachable on the provided direct\naddresses and there is no [`RelayUrl`].\n\nIf addresses or relay servers are neither provided nor can be discovered, the\nconnection attempt will fail with an error.\n\nThe `alpn`, or application-level protocol identifier, is also required. The remote\nendpoint must support this `alpn`, otherwise the connection attempt will fail with\nan error.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fb1c5f533e325cf2b3087f4e442de6bd8eebdcc660ab8d3e57d040e73a43574c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accept\n\nDocumentation:\nAccepts an incoming connection on the endpoint.\n\nOnly connections with the ALPNs configured in [`Builder::alpns`] will be accepted.\nIf multiple ALPNs have been configured the ALPN can be inspected before accepting\nthe connection using [`Connecting::alpn`].\n\nThe returned future will yield `None` if the endpoint is closed by calling\n[`Endpoint::close`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn accept(&self) -> Accept<'_> {\n Accept {\n inner: self.msock.endpoint().accept(),\n ep: self.clone(),\n }\n }\n```"}], "func_name": "accept", "docstring": "Accepts an incoming connection on the endpoint.\n\nOnly connections with the ALPNs configured in [`Builder::alpns`] will be accepted.\nIf multiple ALPNs have been configured the ALPN can be inspected before accepting\nthe connection using [`Connecting::alpn`].\n\nThe returned future will yield `None` if the endpoint is closed by calling\n[`Endpoint::close`].", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "af02fc377c911e6e70c516a9ed3f61c2e4405f4eea7778f6a300ccbbce3c967f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_node_addr\n\nDocumentation:\nInforms this [`Endpoint`] about addresses of the iroh node.\n\nThis updates the local state for the remote node. If the provided [`NodeAddr`]\ncontains a [`RelayUrl`] this will be used as the new relay server for this node. If\nit contains any new IP endpoints they will also be stored and tried when next\nconnecting to this node. Any address that matches this node's direct addresses will be\nsilently ignored.\n\nSee also [`Endpoint::add_node_addr_with_source`].\n\n# Using node discovery instead\n\nIt is strongly advised to use node discovery using the [`StaticProvider`] instead.\nThis provides more flexibility and future proofing.\n\n# Errors\n\nWill return an error if we attempt to add our own [`NodeId`] to the node map or\nif the direct addresses are a subset of ours.\n\n[`StaticProvider`]: crate::discovery::static_provider::StaticProvider\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_node_addr(&self, node_addr: NodeAddr) -> Result<(), AddNodeAddrError> {\n self.add_node_addr_inner(node_addr, magicsock::Source::App)\n }\n```"}], "func_name": "add_node_addr", "docstring": "Informs this [`Endpoint`] about addresses of the iroh node.\n\nThis updates the local state for the remote node. If the provided [`NodeAddr`]\ncontains a [`RelayUrl`] this will be used as the new relay server for this node. If\nit contains any new IP endpoints they will also be stored and tried when next\nconnecting to this node. Any address that matches this node's direct addresses will be\nsilently ignored.\n\nSee also [`Endpoint::add_node_addr_with_source`].\n\n# Using node discovery instead\n\nIt is strongly advised to use node discovery using the [`StaticProvider`] instead.\nThis provides more flexibility and future proofing.\n\n# Errors\n\nWill return an error if we attempt to add our own [`NodeId`] to the node map or\nif the direct addresses are a subset of ours.\n\n[`StaticProvider`]: crate::discovery::static_provider::StaticProvider", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ad71e4c1904a9c15a44d36347db9875f9a03120a9d3dacc3f35d3e28ba77132a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_node_addr_with_source\n\nDocumentation:\nInforms this [`Endpoint`] about addresses of the iroh node, noting the source.\n\nThis updates the local state for the remote node. If the provided [`NodeAddr`] contains a\n[`RelayUrl`] this will be used as the new relay server for this node. If it contains any\nnew IP endpoints they will also be stored and tried when next connecting to this node. Any\naddress that matches this node's direct addresses will be silently ignored. The *source* is\nused for logging exclusively and will not be stored.\n\n# Using node discovery instead\n\nIt is strongly advised to use node discovery using the [`StaticProvider`] instead.\nThis provides more flexibility and future proofing.\n\n# Errors\n\nWill return an error if we attempt to add our own [`NodeId`] to the node map or\nif the direct addresses are a subset of ours.\n\n[`StaticProvider`]: crate::discovery::static_provider::StaticProvider\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_node_addr_with_source(\n &self,\n node_addr: NodeAddr,\n source: &'static str,\n ) -> Result<(), AddNodeAddrError> {\n self.add_node_addr_inner(\n node_addr,\n magicsock::Source::NamedApp {\n name: source.into(),\n },\n )\n }\n```"}], "func_name": "add_node_addr_with_source", "docstring": "Informs this [`Endpoint`] about addresses of the iroh node, noting the source.\n\nThis updates the local state for the remote node. If the provided [`NodeAddr`] contains a\n[`RelayUrl`] this will be used as the new relay server for this node. If it contains any\nnew IP endpoints they will also be stored and tried when next connecting to this node. Any\naddress that matches this node's direct addresses will be silently ignored. The *source* is\nused for logging exclusively and will not be stored.\n\n# Using node discovery instead\n\nIt is strongly advised to use node discovery using the [`StaticProvider`] instead.\nThis provides more flexibility and future proofing.\n\n# Errors\n\nWill return an error if we attempt to add our own [`NodeId`] to the node map or\nif the direct addresses are a subset of ours.\n\n[`StaticProvider`]: crate::discovery::static_provider::StaticProvider", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c3c3c37193869b1ba06f14003fae95930cf9afe18093e8f043ba9040ef1bc3b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bound_sockets\n\nDocumentation:\nReturns the local socket addresses on which the underlying sockets are bound.\n\nThe [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6\naddress if available.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bound_sockets(&self) -> Vec {\n self.msock\n .local_addr()\n .into_iter()\n .filter_map(|addr| addr.into_socket_addr())\n .collect()\n }\n```"}], "func_name": "bound_sockets", "docstring": "Returns the local socket addresses on which the underlying sockets are bound.\n\nThe [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6\naddress if available.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e350e054ed5f7fbe2573b7e9ec8ccb4e36b36b7d149886b4983b89ba6c220a3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_mapping_addr_and_maybe_start_discovery\n\nDocumentation:\nReturn the quic mapped address for this `node_id` and possibly start discovery\nservices if discovery is enabled on this magic endpoint.\n\nThis will launch discovery in all cases except if:\n1) we do not have discovery enabled\n2) we have discovery enabled, but already have at least one verified, unexpired\naddresses for this `node_id`\n\n# Errors\n\nThis method may fail if we have no way of dialing the node. This can occur if\nwe were given no dialing information in the [`NodeAddr`] and no discovery\nservices were configured or if discovery failed to fetch any dialing information.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn get_mapping_addr_and_maybe_start_discovery(\n &self,\n node_addr: NodeAddr,\n ) -> Result<(NodeIdMappedAddr, Option), GetMappingAddressError> {\n let node_id = node_addr.node_id;\n\n // Only return a mapped addr if we have some way of dialing this node, in other\n // words, we have either a relay URL or at least one direct address.\n let addr = if self.msock.has_send_address(node_id) {\n self.msock.get_mapping_addr(node_id)\n } else {\n None\n };\n match addr {\n Some(addr) => {\n // We have some way of dialing this node, but that doesn't actually mean\n // we can actually connect to any of these addresses.\n // Therefore, we will invoke the discovery service if we haven't received from the\n // endpoint on any of the existing paths recently.\n // If the user provided addresses in this connect call, we will add a delay\n // followed by a recheck before starting the discovery, to give the magicsocket a\n // chance to test the newly provided addresses.\n let delay = (!node_addr.is_empty()).then_some(DISCOVERY_WAIT_PERIOD);\n let discovery = DiscoveryTask::maybe_start_after_delay(self, node_id, delay)\n .ok()\n .flatten();\n Ok((addr, discovery))\n }\n\n None => {\n // We have no known addresses or relay URLs for this node.\n // So, we start a discovery task and wait for the first result to arrive, and\n // only then continue, because otherwise we wouldn't have any\n // path to the remote endpoint.\n let res = DiscoveryTask::start(self.clone(), node_id);\n let mut discovery = res.context(get_mapping_address_error::DiscoveryStartSnafu)?;\n discovery\n .first_arrived()\n .await\n .context(get_mapping_address_error::DiscoverSnafu)?;\n if let Some(addr) = self.msock.get_mapping_addr(node_id) {\n Ok((addr, Some(discovery)))\n } else {\n Err(get_mapping_address_error::NoAddressSnafu.build())\n }\n }\n }\n }\n```"}], "func_name": "get_mapping_addr_and_maybe_start_discovery", "docstring": "Return the quic mapped address for this `node_id` and possibly start discovery\nservices if discovery is enabled on this magic endpoint.\n\nThis will launch discovery in all cases except if:\n1) we do not have discovery enabled\n2) we have discovery enabled, but already have at least one verified, unexpired\naddresses for this `node_id`\n\n# Errors\n\nThis method may fail if we have no way of dialing the node. This can occur if\nwe were given no dialing information in the [`NodeAddr`] and no discovery\nservices were configured or if discovery failed to fetch any dialing information.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b335b049758b9691041abf552d62b5bacd27478cb235f46a8c7a17cba55c2046"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_transport_config\n\nDocumentation:\nSets the QUIC transport config options for this connection.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_transport_config(mut self, transport_config: Arc) -> Self {\n self.transport_config = Some(transport_config);\n self\n }\n```"}], "func_name": "with_transport_config", "docstring": "Sets the QUIC transport config options for this connection.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "71d68979c355f9ef6cbd45d35713d0074ea67cf9d48a80d36e44a7eee82c7c08"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_additional_alpns\n\nDocumentation:\nSets [ALPN] identifiers that should be signaled as supported on connection, *in\naddition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`].\n\nThis allows connecting to servers that may only support older versions of your\nprotocol. In this case, you would add the older [ALPN] identifiers with this\nfunction.\n\nYou'll know the final negotiated [ALPN] identifier once your connection was\nestablished using [`Connection::alpn`], or even slightly earlier in the\nhandshake by using [`Connecting::alpn`].\nThe negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this\nlist or the main [ALPN] used in [`Endpoint::connect_with_opts`].\n\nThe [ALPN] identifier order on the connect side doesn't matter, since it's the\naccept side that determines the protocol.\n\nFor setting the supported [ALPN] identifiers on the accept side, see the endpoint\nbuilder's [`Builder::alpns`] function.\n\n[ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_additional_alpns(mut self, alpns: Vec>) -> Self {\n self.additional_alpns = alpns;\n self\n }\n```"}], "func_name": "with_additional_alpns", "docstring": "Sets [ALPN] identifiers that should be signaled as supported on connection, *in\naddition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`].\n\nThis allows connecting to servers that may only support older versions of your\nprotocol. In this case, you would add the older [ALPN] identifiers with this\nfunction.\n\nYou'll know the final negotiated [ALPN] identifier once your connection was\nestablished using [`Connection::alpn`], or even slightly earlier in the\nhandshake by using [`Connecting::alpn`].\nThe negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this\nlist or the main [ALPN] used in [`Endpoint::connect_with_opts`].\n\nThe [ALPN] identifier order on the connect side doesn't matter, since it's the\naccept side that determines the protocol.\n\nFor setting the supported [ALPN] identifiers on the accept side, see the endpoint\nbuilder's [`Builder::alpns`] function.\n\n[ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ed00fd1832b9c92ed0897f3a9e296cd9a20cbf51fbdd1e3b63c0cc75d1625177"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accept\n\nDocumentation:\nAttempts to accept this incoming connection (an error may still occur).\n\nErrors occurring here are likely not caused by the application or remote. The QUIC\nconnection listens on a normal UDP socket and any reachable network endpoint can\nsend datagrams to it, solicited or not. Even if the first few bytes look like a\nQUIC packet, it might not even be a QUIC packet that is being received.\n\nThus it is common to simply log the errors here and accept them as something which\ncan happen.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn accept(self) -> Result {\n self.inner.accept().map(|conn| Connecting {\n inner: conn,\n ep: self.ep,\n remote_node_id: None,\n _discovery_drop_guard: None,\n })\n }\n```"}], "func_name": "accept", "docstring": "Attempts to accept this incoming connection (an error may still occur).\n\nErrors occurring here are likely not caused by the application or remote. The QUIC\nconnection listens on a normal UDP socket and any reachable network endpoint can\nsend datagrams to it, solicited or not. Even if the first few bytes look like a\nQUIC packet, it might not even be a QUIC packet that is being received.\n\nThus it is common to simply log the errors here and accept them as something which\ncan happen.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d7bbc0b980056046e4c1ce07f39725b6d326e4405fbfb6d7f52e6835bd104683"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accept_with\n\nDocumentation:\nAccepts this incoming connection using a custom configuration.\n\nSee [`accept()`] for more details.\n\n[`accept()`]: Incoming::accept\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn accept_with(\n self,\n server_config: Arc,\n ) -> Result {\n self.inner\n .accept_with(server_config)\n .map(|conn| Connecting {\n inner: conn,\n ep: self.ep,\n remote_node_id: None,\n _discovery_drop_guard: None,\n })\n }\n```"}], "func_name": "accept_with", "docstring": "Accepts this incoming connection using a custom configuration.\n\nSee [`accept()`] for more details.\n\n[`accept()`]: Incoming::accept", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8a679cfceb5147158ba43617ea2d26bb6c87ca1b2a5fab4086eb093aaf1e02e7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: alpn\n\nDocumentation:\nExtracts the ALPN protocol from the peer's handshake data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn alpn(&mut self) -> Result, AlpnError> {\n let data = self.handshake_data().await?;\n match data.downcast::() {\n Ok(data) => match data.protocol {\n Some(protocol) => Ok(protocol),\n None => Err(UnavailableSnafu.build()),\n },\n Err(_) => Err(UnknownHandshakeSnafu.build()),\n }\n }\n```"}], "func_name": "alpn", "docstring": "Extracts the ALPN protocol from the peer's handshake data.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "92345c1dd6a33d2fbd3d39a3b4a1ee7b85249d869263324c02d47addc9259d72"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open\n\nDocumentation:\nOpens the ciphertext, which must have been created using `Self::seal`, and places the clear text into the provided buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn open(&self, buffer: &mut dyn Buffer) -> Result<(), DecryptionError> {\n use aead::AeadInPlace;\n ensure!(buffer.len() >= NONCE_LEN, InvalidNonceSnafu);\n\n let offset = buffer.len() - NONCE_LEN;\n let nonce: [u8; NONCE_LEN] = buffer.as_ref()[offset..]\n .try_into()\n .map_err(|_| InvalidNonceSnafu.build())?;\n\n buffer.truncate(offset);\n self.0\n .decrypt_in_place(&nonce.into(), &[], buffer)\n .context(AeadSnafu)?;\n\n Ok(())\n }\n```"}], "func_name": "open", "docstring": "Opens the ciphertext, which must have been created using `Self::seal`, and places the clear text into the provided buffer.", "repo": "n0-computer/iroh", "path": "iroh/src/key.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/key.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dec26768f2da07d582dbc17854a75b77178ed440b438f88743eac956cc24d7a3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: my_relay\n\nDocumentation:\nReturns the relay node we are connected to, that has the best latency.\n\nIf `None`, then we are not connected to any relay nodes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn my_relay(&self) -> Option {\n self.local_addr().into_iter().find_map(|a| {\n if let transports::Addr::Relay(url, _) = a {\n Some(url)\n } else {\n None\n }\n })\n }\n```"}], "func_name": "my_relay", "docstring": "Returns the relay node we are connected to, that has the best latency.\n\nIf `None`, then we are not connected to any relay nodes.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aec56dcdf44ac6ddb293cc4de90159b2618572344df5993fa0677564a00ae59f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_send_address\n\nDocumentation:\nReturns `true` if we have at least one candidate address where we can send packets to.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn has_send_address(&self, node_key: PublicKey) -> bool {\n self.remote_info(node_key)\n .map(|info| info.has_send_address())\n .unwrap_or(false)\n }\n```"}], "func_name": "has_send_address", "docstring": "Returns `true` if we have at least one candidate address where we can send packets to.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5ce9994aef4e78483cd17017dc1ee7631488e446ae86ce90ff1752acff16618"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: home_relay\n\nDocumentation:\nWatch for changes to the home relay.\n\nNote that this can be used to wait for the initial home relay to be known using\n[`Watcher::initialized`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn home_relay(&self) -> impl Watcher> {\n let res = self.local_addrs_watch.clone().map(|addrs| {\n addrs\n .into_iter()\n .filter_map(|addr| {\n if let transports::Addr::Relay(url, _) = addr {\n Some(url)\n } else {\n None\n }\n })\n .collect()\n });\n res.expect(\"disconnected\")\n }\n```"}], "func_name": "home_relay", "docstring": "Watch for changes to the home relay.\n\nNote that this can be used to wait for the initial home relay to be known using\n[`Watcher::initialized`].", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ccf47c2e91f5cccad5bcde945bf5bd9a293a32a7f7a937f6c932e78cea81e1a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: store_direct_addresses\n\nDocumentation:\nStores a new set of direct addresses.\n\nIf the direct addresses have changed from the previous set, they are published to\ndiscovery.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn store_direct_addresses(&self, addrs: BTreeSet) {\n let updated = self.direct_addrs.update(addrs);\n if updated {\n self.node_map\n .on_direct_addr_discovered(self.direct_addrs.sockaddrs());\n self.publish_my_addr();\n }\n }\n```"}], "func_name": "store_direct_addresses", "docstring": "Stores a new set of direct addresses.\n\nIf the direct addresses have changed from the previous set, they are published to\ndiscovery.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f06f3faef51183b4a6055bce9b33f77b62e8b901dedbf86476b42db89ad3586"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_user_data_for_discovery\n\nDocumentation:\nUpdates the user-defined discovery data for this node.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn set_user_data_for_discovery(&self, user_data: Option) {\n let mut guard = self.discovery_user_data.write().expect(\"lock poisened\");\n if *guard != user_data {\n *guard = user_data;\n drop(guard);\n self.publish_my_addr();\n }\n }\n```"}], "func_name": "set_user_data_for_discovery", "docstring": "Updates the user-defined discovery data for this node.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "836ce4c2cfc9a306593dcf8318b3b37474a9cd03fac2bdc90b7d44fe6bd0dad0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: network_change\n\nDocumentation:\nCall to notify the system of potential network changes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn network_change(&self) {\n self.actor_sender\n .send(ActorMessage::NetworkChange)\n .await\n .ok();\n }\n```"}], "func_name": "network_change", "docstring": "Call to notify the system of potential network changes.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f84bb490c7d4b806f863842824b9f642a63d7eefe84158eba7551c5a872bc0aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: process_datagrams\n\nDocumentation:\nProcess datagrams received from UDP sockets.\n\nAll the `bufs` and `metas` should have initialized packets in them.\n\nThis fixes up the datagrams to use the correct [`NodeIdMappedAddr`] and extracts DISCO\npackets, processing them inside the magic socket.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn process_datagrams(\n &self,\n bufs: &mut [io::IoSliceMut<'_>],\n metas: &mut [quinn_udp::RecvMeta],\n source_addrs: &[transports::Addr],\n ) {\n debug_assert_eq!(bufs.len(), metas.len(), \"non matching bufs & metas\");\n debug_assert_eq!(\n bufs.len(),\n source_addrs.len(),\n \"non matching bufs & source_addrs\"\n );\n\n // Adding the IP address we received something on results in Quinn using this\n // address on the send path to send from. However we let Quinn use a\n // NodeIdMappedAddress, not a real address. So we used to substitute our bind address\n // here so that Quinn would send on the right address. But that would sometimes\n // result in the wrong address family and Windows trips up on that.\n //\n // What should be done is that this dst_ip from the RecvMeta is stored in the\n // NodeState/PathState. Then on the send path it should be retrieved from the\n // NodeState/PathSate together with the send address and substituted at send time.\n // This is relevant for IPv6 link-local addresses where the OS otherwise does not\n // know which interface to send from.\n #[cfg(not(windows))]\n let dst_ip = self.normalized_local_addr().ok().map(|addr| addr.ip());\n // Reasoning for this here:\n // https://github.com/n0-computer/iroh/pull/2595#issuecomment-2290947319\n #[cfg(windows)]\n let dst_ip = None;\n\n let mut quic_packets_total = 0;\n\n for ((quinn_meta, buf), source_addr) in metas\n .iter_mut()\n .zip(bufs.iter_mut())\n .zip(source_addrs.iter())\n {\n let mut buf_contains_quic_datagrams = false;\n let mut quic_datagram_count = 0;\n if quinn_meta.len > quinn_meta.stride {\n trace!(%quinn_meta.len, %quinn_meta.stride, \"GRO datagram received\");\n self.metrics.magicsock.recv_gro_datagrams.inc();\n }\n\n // Chunk through the datagrams in this GRO payload to find disco and stun\n // packets and forward them to the actor\n for datagram in buf[..quinn_meta.len].chunks_mut(quinn_meta.stride) {\n if datagram.len() < quinn_meta.stride {\n trace!(\n len = %datagram.len(),\n %quinn_meta.stride,\n \"Last GRO datagram smaller than stride\",\n );\n }\n\n // Detect DISCO and STUN datagrams and process them. Overwrite the first\n // byte of those packets with zero to make Quinn ignore the packet. This\n // relies on quinn::EndpointConfig::grease_quic_bit being set to `false`,\n // which we do in Endpoint::bind.\n if source_addr.is_ip() && stun::is(datagram) {\n trace!(src = ?source_addr, len = %quinn_meta.stride, \"UDP recv: stun packet\");\n let packet2 = Bytes::copy_from_slice(datagram);\n self.net_reporter.receive_stun_packet(\n packet2,\n source_addr.clone().into_socket_addr().expect(\"checked\"),\n );\n datagram[0] = 0u8;\n } else if let Some((sender, sealed_box)) = disco::source_and_box(datagram) {\n trace!(src = ?source_addr, len = %quinn_meta.stride, \"UDP recv: disco packet\");\n self.handle_disco_message(sender, sealed_box, source_addr);\n datagram[0] = 0u8;\n } else {\n trace!(src = ?source_addr, len = %quinn_meta.stride, \"UDP recv: quic packet\");\n match source_addr {\n transports::Addr::Ip(SocketAddr::V4(..)) => {\n self.metrics\n .magicsock\n .recv_data_ipv4\n .inc_by(datagram.len() as _);\n }\n transports::Addr::Ip(SocketAddr::V6(..)) => {\n self.metrics\n .magicsock\n .recv_data_ipv6\n .inc_by(datagram.len() as _);\n }\n transports::Addr::Relay(..) => {\n self.metrics\n .magicsock\n .recv_data_relay\n .inc_by(datagram.len() as _);\n }\n }\n\n quic_datagram_count += 1;\n buf_contains_quic_datagrams = true;\n }\n }\n\n if buf_contains_quic_datagrams {\n match source_addr {\n #[cfg(wasm_browser)]\n transports::Addr::Ip(_addr) => {\n panic!(\"cannot use IP based addressing in the browser\");\n }\n #[cfg(not(wasm_browser))]\n transports::Addr::Ip(addr) => {\n // UDP\n\n // Update the NodeMap and remap RecvMeta to the NodeIdMappedAddr.\n match self.node_map.receive_udp(*addr) {\n None => {\n // Check if this address is mapped to an IpMappedAddr\n if let Some(ip_mapped_addr) =\n self.ip_mapped_addrs.get_mapped_addr(addr)\n {\n trace!(\n src = %addr,\n count = %quic_datagram_count,\n len = quinn_meta.len,\n \"UDP recv QUIC address discovery packets\",\n );\n quic_packets_total += quic_datagram_count;\n quinn_meta.addr = ip_mapped_addr.private_socket_addr();\n } else {\n warn!(\n src = %addr,\n count = %quic_datagram_count,\n len = quinn_meta.len,\n \"UDP recv quic packets: no node state found, skipping\",\n );\n // If we have no node state for the from addr, set len to 0 to make\n // quinn skip the buf completely.\n quinn_meta.len = 0;\n }\n }\n Some((node_id, quic_mapped_addr)) => {\n trace!(\n src = %addr,\n node = %node_id.fmt_short(),\n count = %quic_datagram_count,\n len = quinn_meta.len,\n \"UDP recv quic packets\",\n );\n quic_packets_total += quic_datagram_count;\n quinn_meta.addr = quic_mapped_addr.private_socket_addr();\n }\n }\n }\n transports::Addr::Relay(src_url, src_node) => {\n // Relay\n let quic_mapped_addr = self.node_map.receive_relay(src_url, *src_node);\n quinn_meta.addr = quic_mapped_addr.private_socket_addr();\n }\n }\n } else {\n // If all datagrams in this buf are DISCO or STUN, set len to zero to make\n // Quinn skip the buf completely.\n quinn_meta.len = 0;\n }\n // Normalize local_ip\n quinn_meta.dst_ip = dst_ip;\n }\n\n if quic_packets_total > 0 {\n self.metrics\n .magicsock\n .recv_datagrams\n .inc_by(quic_packets_total as _);\n trace!(\"UDP recv: {} packets\", quic_packets_total);\n }\n }\n```"}], "func_name": "process_datagrams", "docstring": "Process datagrams received from UDP sockets.\n\nAll the `bufs` and `metas` should have initialized packets in them.\n\nThis fixes up the datagrams to use the correct [`NodeIdMappedAddr`] and extracts DISCO\npackets, processing them inside the magic socket.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2bda48fe67b67c4381979150cf11f5089d461db513d263f56dd0568dc09ed07a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_ping_actions\n\nDocumentation:\nTries to send the ping actions.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn send_ping_actions(&self, sender: &UdpSender, msgs: Vec) -> io::Result<()> {\n for msg in msgs {\n // Abort sending as soon as we know we are shutting down.\n if self.is_closing() || self.is_closed() {\n return Ok(());\n }\n match msg {\n PingAction::SendCallMeMaybe {\n ref relay_url,\n dst_node,\n } => {\n self.send_or_queue_call_me_maybe(relay_url, dst_node);\n }\n PingAction::SendPing(ping) => {\n self.send_ping(sender, ping).await?;\n }\n }\n }\n Ok(())\n }\n```"}], "func_name": "send_ping_actions", "docstring": "Tries to send the ping actions.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "da029b5b53a24a3af025be5381626be1a2af3e5bdd67ab6dd31dcfe8c0256c87"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_disco_message\n\nDocumentation:\nSend a disco message. UDP messages will be polled to send directly on the UDP socket.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn send_disco_message(\n &self,\n sender: &UdpSender,\n dst: SendAddr,\n dst_key: PublicKey,\n msg: disco::Message,\n ) -> io::Result<()> {\n let dst = match dst {\n SendAddr::Udp(addr) => transports::Addr::Ip(addr),\n SendAddr::Relay(url) => transports::Addr::Relay(url, dst_key),\n };\n\n trace!(?dst, %msg, \"send disco message (UDP)\");\n if self.is_closed() {\n return Err(io::Error::new(\n io::ErrorKind::NotConnected,\n \"connection closed\",\n ));\n }\n let pkt = self.encode_disco_message(dst_key, &msg);\n\n let transmit = transports::Transmit {\n contents: &pkt,\n ecn: None,\n segment_size: None,\n };\n\n let dst2 = dst.clone();\n match sender.send(&dst2, None, &transmit).await {\n Ok(()) => {\n trace!(?dst, %msg, \"sent disco message\");\n self.metrics.magicsock.sent_disco_udp.inc();\n disco_message_sent(&msg, &self.metrics.magicsock);\n Ok(())\n }\n Err(err) => {\n warn!(?dst, ?msg, ?err, \"failed to send disco message\");\n Err(err)\n }\n }\n }\n```"}], "func_name": "send_disco_message", "docstring": "Send a disco message. UDP messages will be polled to send directly on the UDP socket.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fbd86e5f0083453a9b7693895c462a2cc06a80ba65cc6980841ee05157f4d5da"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_or_queue_call_me_maybe\n\nDocumentation:\nSends the call-me-maybe DISCO message, queuing if addresses are too stale.\n\nTo send the call-me-maybe message, we need to know our current direct addresses. If\nthis information is too stale, the call-me-maybe is queued while a net_report run is\nscheduled. Once this run finishes, the call-me-maybe will be sent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn send_or_queue_call_me_maybe(&self, url: &RelayUrl, dst_node: NodeId) {\n match self.direct_addrs.fresh_enough() {\n Ok(()) => {\n let msg = self.direct_addrs.to_call_me_maybe_message();\n let msg = disco::Message::CallMeMaybe(msg);\n if self\n .disco_sender\n .try_send((SendAddr::Relay(url.clone()), dst_node, msg.clone()))\n .is_err()\n {\n warn!(dstkey = %dst_node.fmt_short(), relayurl = %url,\n \"relay channel full, dropping call-me-maybe\");\n } else {\n debug!(dstkey = %dst_node.fmt_short(), relayurl = %url, \"call-me-maybe sent\");\n }\n }\n Err(last_refresh_ago) => {\n self.pending_call_me_maybes\n .lock()\n .expect(\"poisoned\")\n .insert(dst_node, url.clone());\n debug!(\n ?last_refresh_ago,\n \"want call-me-maybe but direct addrs stale; queuing after restun\",\n );\n self.re_stun(\"refresh-for-peering\");\n }\n }\n }\n```"}], "func_name": "send_or_queue_call_me_maybe", "docstring": "Sends the call-me-maybe DISCO message, queuing if addresses are too stale.\n\nTo send the call-me-maybe message, we need to know our current direct addresses. If\nthis information is too stale, the call-me-maybe is queued while a net_report run is\nscheduled. Once this run finishes, the call-me-maybe will be sent.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d3ad7d53df343c269be8239a23e178059fed0ba8558d7c63b45006bae284d65e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: publish_my_addr\n\nDocumentation:\nPublishes our address to a discovery service, if configured.\n\nCalled whenever our addresses or home relay node changes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn publish_my_addr(&self) {\n if let Some(ref discovery) = self.discovery {\n let relay_url = self.my_relay();\n let direct_addrs = self.direct_addrs.sockaddrs();\n\n let user_data = self\n .discovery_user_data\n .read()\n .expect(\"lock poisened\")\n .clone();\n if relay_url.is_none() && direct_addrs.is_empty() && user_data.is_none() {\n // do not bother publishing if we don't have any information\n return;\n }\n\n let data = NodeData::new(relay_url, direct_addrs).with_user_data(user_data);\n discovery.publish(&data);\n }\n }\n```"}], "func_name": "publish_my_addr", "docstring": "Publishes our address to a discovery service, if configured.\n\nCalled whenever our addresses or home relay node changes.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a7908337265f1ab4e25844cb5cdb8d9521beb82c37dec3e42bb138ecb24ed1e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: schedule_run\n\nDocumentation:\nSchedules a new run, either starting it immediately if none is running or\nscheduling it for later.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn schedule_run(&self, why: &'static str) {\n if self.is_running() {\n let _ = self.want_update.lock().expect(\"poisoned\").insert(why);\n } else {\n self.run(why);\n }\n }\n```"}], "func_name": "schedule_run", "docstring": "Schedules a new run, either starting it immediately if none is running or\nscheduling it for later.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bba55f0301c14e8d0e8aa10af9592f536dc6f2b4cdc1bbb62e2c0bec5c4718b8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a magic [`MagicSock`] listening on [`Options::addr_v4`] and [`Options::addr_v6`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn new(opts: Options) -> Result {\n let me = opts.secret_key.public().fmt_short();\n\n Self::with_name(me, opts)\n .instrument(error_span!(\"magicsock\"))\n .await\n }\n```"}], "func_name": "new", "docstring": "Creates a magic [`MagicSock`] listening on [`Options::addr_v4`] and [`Options::addr_v6`].", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c11e63d2a3f4807e78ed984f7bf109e019c0daa780056f36d46df0231e9852f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: poll_recv\n\nDocumentation:\nNOTE: Receiving on a closed socket will return [`Poll::Pending`] indefinitely.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn poll_recv(\n &mut self,\n cx: &mut Context,\n bufs: &mut [io::IoSliceMut<'_>],\n metas: &mut [quinn_udp::RecvMeta],\n ) -> Poll> {\n self.transports.poll_recv(cx, bufs, metas, &self.socket)\n }\n```"}], "func_name": "poll_recv", "docstring": "NOTE: Receiving on a closed socket will return [`Poll::Pending`] indefinitely.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3b11cf6c9eeed554b4b02164efabaef204bac5e371770021fb6f149848c0b94e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_actor_message\n\nDocumentation:\nProcesses an incoming actor message.\n\nReturns `true` if it was a shutdown.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_actor_message(&mut self, msg: ActorMessage, sender: &UdpSender) -> bool {\n match msg {\n ActorMessage::Shutdown => {\n debug!(\"shutting down\");\n\n self.msock.node_map.notify_shutdown();\n #[cfg(not(wasm_browser))]\n self.port_mapper.deactivate();\n\n debug!(\"shutdown complete\");\n return true;\n }\n ActorMessage::EndpointPingExpired(id, txid) => {\n self.msock.node_map.notify_ping_timeout(id, txid);\n }\n ActorMessage::NetReport(report, why) => {\n match report {\n Ok(report) => {\n self.handle_net_report_report(report).await;\n }\n Err(err) => {\n warn!(\n \"failed to generate net_report report for: {}: {:?}\",\n why, err\n );\n }\n }\n self.finalize_direct_addrs_update(why);\n }\n ActorMessage::NetworkChange => {\n self.network_monitor.network_change().await.ok();\n }\n #[cfg(test)]\n ActorMessage::ForceNetworkChange(is_major) => {\n self.handle_network_change(is_major);\n }\n ActorMessage::PingActions(ping_actions) => {\n self.handle_ping_actions(sender, ping_actions).await;\n }\n }\n\n false\n }\n```"}], "func_name": "handle_actor_message", "docstring": "Processes an incoming actor message.\n\nReturns `true` if it was a shutdown.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ff535e9f2b8f6ae8ac642766b9cd60ce17c5efa7bfa73e531e3d0b753866ebdb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finalize_direct_addrs_update\n\nDocumentation:\nCalled when a direct addr update is done, no matter if it was successful or not.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn finalize_direct_addrs_update(&mut self, why: &'static str) {\n let new_why = self.msock.direct_addr_update_state.next_update();\n if !self.msock.is_closed() {\n if let Some(new_why) = new_why {\n self.msock.direct_addr_update_state.run(new_why);\n return;\n }\n #[cfg(not(wasm_browser))]\n {\n self.periodic_re_stun_timer = new_re_stun_timer(true);\n }\n }\n\n self.msock.direct_addr_update_state.finish_run();\n debug!(\"direct addr update done ({})\", why);\n }\n```"}], "func_name": "finalize_direct_addrs_update", "docstring": "Called when a direct addr update is done, no matter if it was successful or not.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "875f3496cb427a5fb1649142d4e19931cc5c327c3c5e98901fc7a7f70b0416cb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pick_relay_fallback\n\nDocumentation:\nReturns a deterministic relay node to connect to. This is only used if net_report\ncouldn't find the nearest one, for instance, if UDP is blocked and thus STUN\nlatency checks aren't working.\n\nIf no the [`RelayMap`] is empty, returns `0`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn pick_relay_fallback(&self) -> Option {\n // TODO: figure out which relay node most of our nodes are using,\n // and use that region as our fallback.\n //\n // If we already had selected something in the past and it has any\n // nodes, we want to stay on it. If there are no nodes at all,\n // stay on whatever relay we previously picked. If we need to pick\n // one and have no node info, pick a node randomly.\n //\n // We used to do the above for legacy clients, but never updated it for disco.\n\n let my_relay = self.msock.my_relay();\n if my_relay.is_some() {\n return my_relay;\n }\n\n let ids = self.msock.relay_map.urls().collect::>();\n let mut rng = rand::rngs::StdRng::seed_from_u64(0);\n ids.choose(&mut rng).map(|c| (*c).clone())\n }\n```"}], "func_name": "pick_relay_fallback", "docstring": "Returns a deterministic relay node to connect to. This is only used if net_report\ncouldn't find the nearest one, for instance, if UDP is blocked and thus STUN\nlatency checks aren't working.\n\nIf no the [`RelayMap`] is empty, returns `0`.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "15761d57367e88eff0d93e9fd905f5ec49a29ed4514e3336ecc59f39db96f9ef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update\n\nDocumentation:\nUpdates the direct addresses, returns `true` if they changed, `false` if not.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn update(&self, addrs: BTreeSet) -> bool {\n *self.updated_at.write().expect(\"poisoned\") = Some(Instant::now());\n let updated = self.addrs.set(Some(addrs)).is_ok();\n if updated {\n event!(\n target: \"iroh::_events::direct_addrs\",\n Level::DEBUG,\n addrs = ?self.addrs.get(),\n );\n }\n updated\n }\n```"}], "func_name": "update", "docstring": "Updates the direct addresses, returns `true` if they changed, `false` if not.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2d9e3c0b4efd623b2b4ae0ae90b83340f396b74a47535866b6aea56ba595da81"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fresh_enough\n\nDocumentation:\nWhether the direct addr information is considered \"fresh\".\n\nIf not fresh you should probably update the direct addresses before using this info.\n\nReturns `Ok(())` if fresh enough and `Err(elapsed)` if not fresh enough.\n`elapsed` is the time elapsed since the direct addresses were last updated.\n\nIf there is no direct address information `Err(Duration::ZERO)` is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fresh_enough(&self) -> Result<(), Duration> {\n match *self.updated_at.read().expect(\"poisoned\") {\n None => Err(Duration::ZERO),\n Some(time) => {\n let elapsed = time.elapsed();\n if elapsed <= ENDPOINTS_FRESH_ENOUGH_DURATION {\n Ok(())\n } else {\n Err(elapsed)\n }\n }\n }\n }\n```"}], "func_name": "fresh_enough", "docstring": "Whether the direct addr information is considered \"fresh\".\n\nIf not fresh you should probably update the direct addresses before using this info.\n\nReturns `Ok(())` if fresh enough and `Err(elapsed)` if not fresh enough.\n`elapsed` is the time elapsed since the direct addresses were last updated.\n\nIf there is no direct address information `Err(Duration::ZERO)` is returned.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b18a9a21268126ee6bb10f28e8af6182f8d0cf1739c5d64c72b57038e0349f2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate\n\nDocumentation:\nGenerates a globally unique fake UDP address.\n\nThis generates and IPv6 Unique Local Address according to RFC 4193.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn generate() -> Self {\n let mut addr = [0u8; 16];\n addr[0] = Self::ADDR_PREFIXL;\n addr[1..6].copy_from_slice(&Self::ADDR_GLOBAL_ID);\n addr[6..8].copy_from_slice(&Self::ADDR_SUBNET);\n\n let counter = NODE_ID_ADDR_COUNTER.fetch_add(1, Ordering::Relaxed);\n addr[8..16].copy_from_slice(&counter.to_be_bytes());\n\n Self(Ipv6Addr::from(addr))\n }\n```"}], "func_name": "generate", "docstring": "Generates a globally unique fake UDP address.\n\nThis generates and IPv6 Unique Local Address according to RFC 4193.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f37237aa0d42c5b988132fe8f0dc29ea2b71819974a93d7d7b0db7d1a740d581"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: private_socket_addr\n\nDocumentation:\nReturns a consistent [`SocketAddr`] for the [`NodeIdMappedAddr`].\n\nThis socket address does not have a routable IP address.\n\nThis uses a made-up port number, since the port does not play a role in looking up\nthe node in the [`NodeMap`]. This socket address is only to be used to pass into\nQuinn.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn private_socket_addr(&self) -> SocketAddr {\n SocketAddr::new(IpAddr::from(self.0), Self::NODE_ID_MAPPED_PORT)\n }\n```"}], "func_name": "private_socket_addr", "docstring": "Returns a consistent [`SocketAddr`] for the [`NodeIdMappedAddr`].\n\nThis socket address does not have a routable IP address.\n\nThis uses a made-up port number, since the port does not play a role in looking up\nthe node in the [`NodeMap`]. This socket address is only to be used to pass into\nQuinn.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bbbfedaa537a2c680551f87f22b3b104e19276ed7cb88c854a30160cf7345f52"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: basically_equal\n\nDocumentation:\nChecks if this is probably still the same network as *other*.\n\nThis tries to compare the network situation, without taking into account things\nexpected to change a little like e.g. latency to the relay server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn basically_equal(&self, other: &Self) -> bool {\n let eq_icmp_v4 = match (self.working_icmp_v4, other.working_icmp_v4) {\n (Some(slf), Some(other)) => slf == other,\n _ => true, // ignore for comparison if only one report had this info\n };\n let eq_icmp_v6 = match (self.working_icmp_v6, other.working_icmp_v6) {\n (Some(slf), Some(other)) => slf == other,\n _ => true, // ignore for comparison if only one report had this info\n };\n\n #[cfg(not(wasm_browser))]\n let probe_eq = self.portmap_probe == other.portmap_probe;\n #[cfg(wasm_browser)]\n let probe_eq = true;\n\n self.mapping_varies_by_dest_ip == other.mapping_varies_by_dest_ip\n && self.hair_pinning == other.hair_pinning\n && self.working_ipv6 == other.working_ipv6\n && self.os_has_ipv6 == other.os_has_ipv6\n && self.working_udp == other.working_udp\n && eq_icmp_v4\n && eq_icmp_v6\n && self.have_port_map == other.have_port_map\n && probe_eq\n && self.preferred_relay == other.preferred_relay\n }\n```"}], "func_name": "basically_equal", "docstring": "Checks if this is probably still the same network as *other*.\n\nThis tries to compare the network situation, without taking into account things\nexpected to change a little like e.g. latency to the relay server.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3995d79effb2d28e2919f32ce27df74be037bc598a8ccae09a0c88479510ff15"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_default_server_config\n\nDocumentation:\nGenerate a server config with no ALPNS and a default transport configuration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn make_default_server_config(secret_key: &SecretKey) -> ServerConfig {\n let quic_server_config =\n crate::tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![], false);\n let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));\n server_config.transport_config(Arc::new(quinn::TransportConfig::default()));\n server_config\n }\n```"}], "func_name": "make_default_server_config", "docstring": "Generate a server config with no ALPNS and a default transport configuration", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "08ec8e8eb2bfc8cd253270cc32b4d7a34a0aab27669250956f2b9d46ff03e00f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_direct_addrs\n\nDocumentation:\nRegisters endpoint addresses of a node to all other nodes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn update_direct_addrs(\n stacks: &[MagicStack],\n my_idx: usize,\n new_addrs: BTreeSet,\n ) {\n let me = &stacks[my_idx];\n for (i, m) in stacks.iter().enumerate() {\n if i == my_idx {\n continue;\n }\n\n let addr = NodeAddr {\n node_id: me.public(),\n relay_url: None,\n direct_addresses: new_addrs.iter().map(|ep| ep.addr).collect(),\n };\n m.endpoint.magic_sock().add_test_addr(addr);\n }\n }\n```"}], "func_name": "update_direct_addrs", "docstring": "Registers endpoint addresses of a node to all other nodes.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "414926cc0a584638c31df7a7eda8babba19a85efd67923c251ea990415dfc683"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: test_two_devices_roundtrip_network_change_impl\n\nDocumentation:\nSame structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly\nwith (simulated) network changes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn test_two_devices_roundtrip_network_change_impl() -> Result {\n let m1 = MagicStack::new(RelayMode::Disabled).await;\n let m2 = MagicStack::new(RelayMode::Disabled).await;\n\n let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;\n\n let offset = || {\n let delay = rand::thread_rng().gen_range(10..=500);\n Duration::from_millis(delay)\n };\n let rounds = 5;\n\n // Regular network changes to m1 only.\n let m1_network_change_guard = {\n let m1 = m1.clone();\n let task = tokio::spawn(async move {\n loop {\n println!(\"[m1] network change\");\n m1.endpoint.magic_sock().force_network_change(true).await;\n time::sleep(offset()).await;\n }\n });\n AbortOnDropHandle::new(task)\n };\n\n for i in 0..rounds {\n println!(\"-- [m1 changes] round {}\", i + 1);\n run_roundtrip(m1.clone(), m2.clone(), b\"hello m1\", ExpectedLoss::YeahSure).await;\n run_roundtrip(m2.clone(), m1.clone(), b\"hello m2\", ExpectedLoss::YeahSure).await;\n\n println!(\"-- [m1 changes] larger data\");\n let mut data = vec![0u8; 10 * 1024];\n rand::thread_rng().fill_bytes(&mut data);\n run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;\n run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;\n }\n\n std::mem::drop(m1_network_change_guard);\n\n // Regular network changes to m2 only.\n let m2_network_change_guard = {\n let m2 = m2.clone();\n let task = tokio::spawn(async move {\n loop {\n println!(\"[m2] network change\");\n m2.endpoint.magic_sock().force_network_change(true).await;\n time::sleep(offset()).await;\n }\n });\n AbortOnDropHandle::new(task)\n };\n\n for i in 0..rounds {\n println!(\"-- [m2 changes] round {}\", i + 1);\n run_roundtrip(m1.clone(), m2.clone(), b\"hello m1\", ExpectedLoss::YeahSure).await;\n run_roundtrip(m2.clone(), m1.clone(), b\"hello m2\", ExpectedLoss::YeahSure).await;\n\n println!(\"-- [m2 changes] larger data\");\n let mut data = vec![0u8; 10 * 1024];\n rand::thread_rng().fill_bytes(&mut data);\n run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;\n run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;\n }\n\n std::mem::drop(m2_network_change_guard);\n\n // Regular network changes to both m1 and m2 only.\n let m1_m2_network_change_guard = {\n let m1 = m1.clone();\n let m2 = m2.clone();\n let task = tokio::spawn(async move {\n println!(\"-- [m1] network change\");\n m1.endpoint.magic_sock().force_network_change(true).await;\n println!(\"-- [m2] network change\");\n m2.endpoint.magic_sock().force_network_change(true).await;\n time::sleep(offset()).await;\n });\n AbortOnDropHandle::new(task)\n };\n\n for i in 0..rounds {\n println!(\"-- [m1 & m2 changes] round {}\", i + 1);\n run_roundtrip(m1.clone(), m2.clone(), b\"hello m1\", ExpectedLoss::YeahSure).await;\n run_roundtrip(m2.clone(), m1.clone(), b\"hello m2\", ExpectedLoss::YeahSure).await;\n\n println!(\"-- [m1 & m2 changes] larger data\");\n let mut data = vec![0u8; 10 * 1024];\n rand::thread_rng().fill_bytes(&mut data);\n run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;\n run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;\n }\n\n std::mem::drop(m1_m2_network_change_guard);\n Ok(())\n }\n```"}], "func_name": "test_two_devices_roundtrip_network_change_impl", "docstring": "Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly\nwith (simulated) network changes.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8b7400585e26cd0dbddcb8bf624fe17defc1de79f81a9ece173853f5cef160b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_relay\n\nDocumentation:\nUpdates a relay's latency, if it is faster than before.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn update_relay(&mut self, url: RelayUrl, latency: Duration) {\n let val = self.0.entry(url).or_insert(latency);\n if latency < *val {\n *val = latency;\n }\n }\n```"}], "func_name": "update_relay", "docstring": "Updates a relay's latency, if it is faster than before.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "abf649267c6471b73748f08f24dd8bd81712edabf54410e5fa43875cd3dc5cf7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: merge\n\nDocumentation:\nMerges another [`RelayLatencies`] into this one.\n\nFor each relay the latency is updated using [`RelayLatencies::update_relay`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn merge(&mut self, other: &RelayLatencies) {\n for (url, latency) in other.iter() {\n self.update_relay(url.clone(), latency);\n }\n }\n```"}], "func_name": "merge", "docstring": "Merges another [`RelayLatencies`] into this one.\n\nFor each relay the latency is updated using [`RelayLatencies::update_relay`].", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e234704f869c50615ac3553df45f41572b515e7a98bcd8cf11050a0f3f43040c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: max_latency\n\nDocumentation:\nReturns the maximum latency for all relays.\n\nIf there are not yet any latencies this will return [`DEFAULT_MAX_LATENCY`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn max_latency(&self) -> Duration {\n self.0\n .values()\n .max()\n .copied()\n .unwrap_or(DEFAULT_MAX_LATENCY)\n }\n```"}], "func_name": "max_latency", "docstring": "Returns the maximum latency for all relays.\n\nIf there are not yet any latencies this will return [`DEFAULT_MAX_LATENCY`].", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "11092c0a0d158884599d5347673bef3a2392c9115974999eab07d58301423027"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: iter\n\nDocumentation:\nReturns an iterator over all the relays and their latencies.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn iter(&self) -> impl Iterator + '_ {\n self.0.iter().map(|(k, v)| (k, *v))\n }\n```"}], "func_name": "iter", "docstring": "Returns an iterator over all the relays and their latencies.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "19e8a2e4e76c69c7a194361dc5ea8e11ccf04dd5868b933a08cedc93a6ff5c29"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new net_report client.\n\nThis starts a connected actor in the background. Once the client is dropped it will\nstop running.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n #[cfg(not(wasm_browser))] port_mapper: Option,\n #[cfg(not(wasm_browser))] dns_resolver: DnsResolver,\n #[cfg(not(wasm_browser))] ip_mapped_addrs: Option,\n metrics: Arc,\n ) -> Self {\n let mut actor = Actor::new(\n #[cfg(not(wasm_browser))]\n port_mapper,\n #[cfg(not(wasm_browser))]\n dns_resolver,\n #[cfg(not(wasm_browser))]\n ip_mapped_addrs,\n metrics,\n );\n let addr = actor.addr();\n let task = task::spawn(\n async move { actor.run().await }.instrument(info_span!(\"net_report.actor\")),\n );\n let drop_guard = AbortOnDropHandle::new(task);\n Client {\n addr,\n _drop_guard: Arc::new(drop_guard),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new net_report client.\n\nThis starts a connected actor in the background. Once the client is dropped it will\nstop running.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0085e6e1c487346bab7731248a923f43a42d94ed71df5926c78441b5afbc6a42"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_report\n\nDocumentation:\nRuns a net_report, returning the report.\n\nIt may not be called concurrently with itself, `&mut self` takes care of that.\n\nLook at [`Options`] for the different configuration options.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_report(\n &mut self,\n relay_map: RelayMap,\n opts: Options,\n ) -> Result, ReportError> {\n let rx = self.get_report_channel(relay_map, opts).await?;\n match rx.await {\n Ok(res) => res,\n Err(_) => Err(ActorGoneSnafu.build()),\n }\n }\n```"}], "func_name": "get_report", "docstring": "Runs a net_report, returning the report.\n\nIt may not be called concurrently with itself, `&mut self` takes care of that.\n\nLook at [`Options`] for the different configuration options.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a978667f1eb11022f65a955db789855f4245b7f6a9cab0bbb9d197be51567889"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_report_channel\n\nDocumentation:\nGet report with channel\n\nLook at [`Options`] for the different configuration options.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn get_report_channel(\n &mut self,\n relay_map: RelayMap,\n opts: Options,\n ) -> Result, ReportError>>, ReportError> {\n let (tx, rx) = oneshot::channel();\n self.addr\n .send(Message::RunCheck {\n relay_map,\n opts,\n response_tx: tx,\n })\n .await\n .map_err(|_| ActorGoneSnafu.build())?;\n Ok(rx)\n }\n```"}], "func_name": "get_report_channel", "docstring": "Get report with channel\n\nLook at [`Options`] for the different configuration options.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fb76fe2fe73400c7fcfec8993c2f1c17a631dca04fbbf142d1742a5263bb459f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: receive_stun_packet\n\nDocumentation:\nPass a received STUN packet to the net_reporter.\n\nNormally the UDP sockets to send STUN messages from are passed in so that STUN\npackets are sent from the sockets that carry the real traffic. However because\nthese sockets carry real traffic they will also receive non-STUN traffic, thus the\nnet_report actor does not read from the sockets directly. If you receive a STUN\npacket on the socket you should pass it to this method.\n\nIt is safe to call this even when the net_report actor does not currently have any\nin-flight STUN probes. The actor will simply ignore any stray STUN packets.\n\nThere is an implicit queue here which may drop packets if the actor does not keep up\nconsuming them.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn receive_stun_packet(&self, payload: Bytes, src: SocketAddr) {\n if let Err(mpsc::error::TrySendError::Full(_)) = self.sender.try_send(Message::StunPacket {\n payload,\n from_addr: src,\n }) {\n self.metrics.stun_packets_dropped.inc();\n warn!(\"dropping stun packet from {}\", src);\n }\n }\n```"}], "func_name": "receive_stun_packet", "docstring": "Pass a received STUN packet to the net_reporter.\n\nNormally the UDP sockets to send STUN messages from are passed in so that STUN\npackets are sent from the sockets that carry the real traffic. However because\nthese sockets carry real traffic they will also receive non-STUN traffic, thus the\nnet_report actor does not read from the sockets directly. If you receive a STUN\npacket on the socket you should pass it to this method.\n\nIt is safe to call this even when the net_report actor does not currently have any\nin-flight STUN probes. The actor will simply ignore any stray STUN packets.\n\nThere is an implicit queue here which may drop packets if the actor does not keep up\nconsuming them.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "33eb72a40a250a43d47697c014540d6b387c1b785a89e88b8896184c58b5c961"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new actor.\n\nThis does not start the actor, see [`Actor::run`] for this. You should not\nnormally create this directly but rather create a [`Client`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(\n #[cfg(not(wasm_browser))] port_mapper: Option,\n #[cfg(not(wasm_browser))] dns_resolver: DnsResolver,\n #[cfg(not(wasm_browser))] ip_mapped_addrs: Option,\n metrics: Arc,\n ) -> Self {\n // TODO: consider an instrumented flume channel so we have metrics.\n let (sender, receiver) = mpsc::channel(32);\n Self {\n receiver,\n sender,\n reports: Default::default(),\n #[cfg(not(wasm_browser))]\n port_mapper,\n in_flight_stun_requests: Default::default(),\n current_report_run: None,\n #[cfg(not(wasm_browser))]\n dns_resolver,\n #[cfg(not(wasm_browser))]\n ip_mapped_addrs,\n metrics,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new actor.\n\nThis does not start the actor, see [`Actor::run`] for this. You should not\nnormally create this directly but rather create a [`Client`].", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0843096b2daa9d0b38b1de77a23bd5232a6fb8bcc5335197d01b0a2a9d8921fd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: addr\n\nDocumentation:\nReturns the channel to send messages to the actor.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn addr(&self) -> Addr {\n Addr {\n sender: self.sender.clone(),\n metrics: self.metrics.clone(),\n }\n }\n```"}], "func_name": "addr", "docstring": "Returns the channel to send messages to the actor.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8febd3873746676f77e6de5dff846e59032dd9741344f5efecb668fbacba0fc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRun the actor.\n\nIt will now run and handle messages. Once the connected [`Client`] (including all\nits clones) is dropped this will terminate.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run(&mut self) {\n debug!(\"net_report actor starting\");\n while let Some(msg) = self.receiver.recv().await {\n trace!(?msg, \"handling message\");\n match msg {\n Message::RunCheck {\n relay_map,\n opts,\n response_tx,\n } => {\n self.handle_run_check(relay_map, opts, response_tx);\n }\n Message::ReportReady { report } => {\n self.handle_report_ready(*report);\n }\n Message::ReportAborted { reason: err } => {\n self.handle_report_aborted(err);\n }\n Message::StunPacket { payload, from_addr } => {\n self.handle_stun_packet(&payload, from_addr);\n }\n Message::InFlightStun(inflight, response_tx) => {\n self.handle_in_flight_stun(inflight, response_tx);\n }\n }\n }\n }\n```"}], "func_name": "run", "docstring": "Run the actor.\n\nIt will now run and handle messages. Once the connected [`Client`] (including all\nits clones) is dropped this will terminate.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44c2d48368b5c483acb8fc9b741b24cf8d455b9e66a967dc8994b4564bfda532"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_run_check\n\nDocumentation:\nStarts a check run as requested by the [`Message::RunCheck`] message.\n\nIf *stun_sock_v4* or *stun_sock_v6* are not provided this will bind the sockets\nitself. This is not ideal since really you want to send STUN probes from the\nsockets you will be using.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_run_check(\n &mut self,\n relay_map: RelayMap,\n opts: Options,\n response_tx: oneshot::Sender, ReportError>>,\n ) {\n let protocols = opts.to_protocols();\n #[cfg(not(wasm_browser))]\n let socket_state = SocketState {\n port_mapper: self.port_mapper.clone(),\n stun_sock4: opts.stun_sock_v4,\n stun_sock6: opts.stun_sock_v6,\n quic_config: opts.quic_config,\n dns_resolver: self.dns_resolver.clone(),\n ip_mapped_addrs: self.ip_mapped_addrs.clone(),\n };\n trace!(\"Attempting probes for protocols {protocols:#?}\");\n if self.current_report_run.is_some() {\n response_tx.send(Err(AlreadyRunningSnafu.build())).ok();\n return;\n }\n\n let now = Instant::now();\n\n let mut do_full = self.reports.next_full\n || now.duration_since(self.reports.last_full) > FULL_REPORT_INTERVAL;\n\n // If the last report had a captive portal and reported no UDP access,\n // it's possible that we didn't get a useful net_report due to the\n // captive portal blocking us. If so, make this report a full (non-incremental) one.\n if !do_full {\n if let Some(ref last) = self.reports.last {\n do_full = !last.udp && last.captive_portal.unwrap_or_default();\n }\n }\n if do_full {\n self.reports.last = None; // causes ProbePlan::new below to do a full (initial) plan\n self.reports.next_full = false;\n self.reports.last_full = now;\n self.metrics.reports_full.inc();\n }\n self.metrics.reports.inc();\n\n let actor = reportgen::Client::new(\n self.addr(),\n self.reports.last.clone(),\n relay_map,\n protocols,\n self.metrics.clone(),\n #[cfg(not(wasm_browser))]\n socket_state,\n #[cfg(any(test, feature = \"test-utils\"))]\n opts.insecure_skip_relay_cert_verify,\n );\n\n self.current_report_run = Some(ReportRun {\n _reportgen: actor,\n report_tx: response_tx,\n });\n }\n```"}], "func_name": "handle_run_check", "docstring": "Starts a check run as requested by the [`Message::RunCheck`] message.\n\nIf *stun_sock_v4* or *stun_sock_v6* are not provided this will bind the sockets\nitself. This is not ideal since really you want to send STUN probes from the\nsockets you will be using.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "37eed8134f162cb99c8e2f640af24c102136bb1f21dfc1b03935df0739cd5dd9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_stun_packet\n\nDocumentation:\nHandles [`Message::StunPacket`].\n\nIf there are currently no in-flight stun requests registered this is dropped,\notherwise forwarded to the probe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_stun_packet(&mut self, pkt: &[u8], src: SocketAddr) {\n trace!(%src, \"received STUN packet\");\n if self.in_flight_stun_requests.is_empty() {\n return;\n }\n\n #[cfg(feature = \"metrics\")]\n match &src {\n SocketAddr::V4(_) => {\n self.metrics.stun_packets_recv_ipv4.inc();\n }\n SocketAddr::V6(_) => {\n self.metrics.stun_packets_recv_ipv6.inc();\n }\n }\n\n match stun::parse_response(pkt) {\n Ok((txn, addr_port)) => match self.in_flight_stun_requests.remove(&txn) {\n Some(inf) => {\n debug!(%src, %txn, \"received known STUN packet\");\n let elapsed = inf.start.elapsed();\n inf.s.send((elapsed, addr_port)).ok();\n }\n None => {\n debug!(%src, %txn, \"received unexpected STUN message response\");\n }\n },\n Err(err) => {\n match stun::parse_binding_request(pkt) {\n Ok(txn) => {\n // Is this our hairpin request?\n match self.in_flight_stun_requests.remove(&txn) {\n Some(inf) => {\n debug!(%src, %txn, \"received our hairpin STUN request\");\n let elapsed = inf.start.elapsed();\n inf.s.send((elapsed, src)).ok();\n }\n None => {\n debug!(%src, %txn, \"unknown STUN request\");\n }\n }\n }\n Err(_) => {\n debug!(%src, \"received invalid STUN response: {err:#}\");\n }\n }\n }\n }\n }\n```"}], "func_name": "handle_stun_packet", "docstring": "Handles [`Message::StunPacket`].\n\nIf there are currently no in-flight stun requests registered this is dropped,\notherwise forwarded to the probe.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f744996e6b7f646e298f6a6f0ab866872200e151d13c4020f43b914d467f662"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_in_flight_stun\n\nDocumentation:\nHandles [`Message::InFlightStun`].\n\nThe in-flight request is added to [`Actor::in_flight_stun_requests`] so that\n[`Actor::handle_stun_packet`] can forward packets correctly.\n\n*response_tx* is to signal the actor message has been handled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_in_flight_stun(&mut self, inflight: Inflight, response_tx: oneshot::Sender<()>) {\n self.in_flight_stun_requests.insert(inflight.txn, inflight);\n response_tx.send(()).ok();\n }\n```"}], "func_name": "handle_in_flight_stun", "docstring": "Handles [`Message::InFlightStun`].\n\nThe in-flight request is added to [`Actor::in_flight_stun_requests`] so that\n[`Actor::handle_stun_packet`] can forward packets correctly.\n\n*response_tx* is to signal the actor message has been handled.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d5f73b63ad3a87c67537c11b2b4ec339e0ed7ea2c0d422331b117a79495b4188"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_report_history_and_set_preferred_relay\n\nDocumentation:\nAdds `r` to the set of recent Reports and mutates `r.preferred_relay` to contain the best recent one.\n`r` is stored ref counted and a reference is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_report_history_and_set_preferred_relay(&mut self, mut r: Report) -> Arc {\n let mut prev_relay = None;\n if let Some(ref last) = self.reports.last {\n prev_relay.clone_from(&last.preferred_relay);\n }\n let now = Instant::now();\n const MAX_AGE: Duration = Duration::from_secs(5 * 60);\n\n // relay ID => its best recent latency in last MAX_AGE\n let mut best_recent = RelayLatencies::new();\n\n // chain the current report as we are still mutating it\n let prevs_iter = self\n .reports\n .prev\n .iter()\n .map(|(a, b)| -> (&Instant, &Report) { (a, b) })\n .chain(std::iter::once((&now, &r)));\n\n let mut to_remove = Vec::new();\n for (t, pr) in prevs_iter {\n if now.duration_since(*t) > MAX_AGE {\n to_remove.push(*t);\n continue;\n }\n best_recent.merge(&pr.relay_latency);\n }\n\n for t in to_remove {\n self.reports.prev.remove(&t);\n }\n\n // Then, pick which currently-alive relay server from the\n // current report has the best latency over the past MAX_AGE.\n let mut best_any = Duration::default();\n let mut old_relay_cur_latency = Duration::default();\n {\n for (url, duration) in r.relay_latency.iter() {\n if Some(url) == prev_relay.as_ref() {\n old_relay_cur_latency = duration;\n }\n if let Some(best) = best_recent.get(url) {\n if r.preferred_relay.is_none() || best < best_any {\n best_any = best;\n r.preferred_relay.replace(url.clone());\n }\n }\n }\n\n // If we're changing our preferred relay but the old one's still\n // accessible and the new one's not much better, just stick with\n // where we are.\n if prev_relay.is_some()\n && r.preferred_relay != prev_relay\n && !old_relay_cur_latency.is_zero()\n && best_any > old_relay_cur_latency / 3 * 2\n {\n r.preferred_relay = prev_relay;\n }\n }\n\n let r = Arc::new(r);\n self.reports.prev.insert(now, r.clone());\n self.reports.last = Some(r.clone());\n\n r\n }\n```"}], "func_name": "add_report_history_and_set_preferred_relay", "docstring": "Adds `r` to the set of recent Reports and mutates `r.preferred_relay` to contain the best recent one.\n`r` is stored ref counted and a reference is returned.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a96d5a1322d3979d4748c9805ad858c7c1d013c8e85de2b2107b3e91b1c2e405"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bind_local_stun_socket\n\nDocumentation:\nAttempts to bind a local socket to send STUN packets from.\n\nIf successful this returns the bound socket and will forward STUN responses to the\nprovided *actor_addr*. The *cancel_token* serves to stop the packet forwarding when the\nsocket is no longer needed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bind_local_stun_socket(\n network: IpFamily,\n actor_addr: Addr,\n cancel_token: CancellationToken,\n ) -> Option> {\n let sock = match UdpSocket::bind(network, 0) {\n Ok(sock) => Arc::new(sock),\n Err(err) => {\n debug!(\"failed to bind STUN socket: {}\", err);\n return None;\n }\n };\n let span = info_span!(\n \"stun_udp_listener\",\n local_addr = sock\n .local_addr()\n .map(|a| a.to_string())\n .unwrap_or(String::from(\"-\")),\n );\n {\n let sock = sock.clone();\n task::spawn(\n async move {\n debug!(\"udp stun socket listener started\");\n // TODO: Can we do better for buffers here? Probably doesn't matter much.\n let mut buf = vec![0u8; 64 << 10];\n loop {\n tokio::select! {\n biased;\n _ = cancel_token.cancelled() => break,\n res = recv_stun_once(&sock, &mut buf, &actor_addr) => {\n if let Err(err) = res {\n warn!(%err, \"stun recv failed\");\n break;\n }\n }\n }\n }\n debug!(\"udp stun socket listener stopped\");\n }\n .instrument(span),\n );\n }\n Some(sock)\n }\n```"}], "func_name": "bind_local_stun_socket", "docstring": "Attempts to bind a local socket to send STUN packets from.\n\nIf successful this returns the bound socket and will forward STUN responses to the\nprovided *actor_addr*. The *cancel_token* serves to stop the packet forwarding when the\nsocket is no longer needed.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6024d62d2a7529a328730d83ee86a3bcb33f029ca742aeb1c2619b8a8a96783c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: recv_stun_once\n\nDocumentation:\nReceive STUN response from a UDP socket, pass it to the actor.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn recv_stun_once(\n sock: &UdpSocket,\n buf: &mut [u8],\n actor_addr: &Addr,\n ) -> Result<(), RecvStunError> {\n let (count, mut from_addr) = sock.recv_from(buf).await?;\n\n let payload = &buf[..count];\n from_addr.set_ip(from_addr.ip().to_canonical());\n let msg = Message::StunPacket {\n payload: Bytes::from(payload.to_vec()),\n from_addr,\n };\n actor_addr\n .send(msg)\n .await\n .map_err(|_| ActorGoneSnafu.build())\n }\n```"}], "func_name": "recv_stun_once", "docstring": "Receive STUN response from a UDP socket, pass it to the actor.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc8c78ea37e5593c82513a8db1d9ac452f9fd5b7b2702a5840b96030c89e649b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: relay_map\n\nDocumentation:\nCreate a [`crate::RelayMap`] of the given size.\n\nThis function uses [`relay`]. Note that the returned map uses internal order that will\noften _not_ match the order of the servers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn relay_map(relays: usize) -> (Vec, crate::RelayMap) {\n let mut servers = Vec::with_capacity(relays);\n let mut nodes = Vec::with_capacity(relays);\n for _ in 0..relays {\n let (relay_server, node) = relay().await;\n servers.push(relay_server);\n nodes.push(node);\n }\n (servers, crate::RelayMap::from_iter(nodes))\n }\n```"}], "func_name": "relay_map", "docstring": "Create a [`crate::RelayMap`] of the given size.\n\nThis function uses [`relay`]. Note that the returned map uses internal order that will\noften _not_ match the order of the servers.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ee731ded8d02ae45e3c983d2ac1c9a8a79227179daa5c6cc6a3fcc7ba2e7898"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: serve_v4\n\nDocumentation:\nSets up a simple STUN server binding to `0.0.0.0:0`.\n\nSee [`serve`] for more details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn serve_v4() -> std::io::Result<(SocketAddr, StunStats, CleanupDropGuard)>\n {\n serve(std::net::Ipv4Addr::UNSPECIFIED.into()).await\n }\n```"}], "func_name": "serve_v4", "docstring": "Sets up a simple STUN server binding to `0.0.0.0:0`.\n\nSee [`serve`] for more details.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e07cf5d40fb5bf81baab618bf77188e5347819029337285bb08c73460ec12ec"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_connecting\n\nDocumentation:\nOptional interception point to handle the `Connecting` state.\n\nCan be implemented as `async fn on_connecting(&self, connecting: Connecting) -> Result`.\n\nThis enables accepting 0-RTT data from clients, among other things.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn on_connecting(\n &self,\n connecting: Connecting,\n ) -> impl Future> + Send {\n async move {\n let conn = connecting.await?;\n Ok(conn)\n }\n }\n```"}], "func_name": "on_connecting", "docstring": "Optional interception point to handle the `Connecting` state.\n\nCan be implemented as `async fn on_connecting(&self, connecting: Connecting) -> Result`.\n\nThis enables accepting 0-RTT data from clients, among other things.", "repo": "n0-computer/iroh", "path": "iroh/src/protocol.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/protocol.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a06b1776680ee88466f5bbcb638071a63d7c79f61edb4fff585597938daf8b3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shutdown\n\nDocumentation:\nCalled when the router shuts down.\n\nCan be implemented as `async fn shutdown(&self)`.\n\nThis is called from [`Router::shutdown`]. The returned future is awaited before\nthe router closes the endpoint.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn shutdown(&self) -> impl Future + Send {\n async move {}\n }\n```"}], "func_name": "shutdown", "docstring": "Called when the router shuts down.\n\nCan be implemented as `async fn shutdown(&self)`.\n\nThis is called from [`Router::shutdown`]. The returned future is awaited before\nthe router closes the endpoint.", "repo": "n0-computer/iroh", "path": "iroh/src/protocol.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/protocol.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "97067ddc9f4b4b80320367b945d0acf61ad09f7ab664a4f448c2ddd0565f8991"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturns the registered protocol handler for an ALPN as a [`Arc`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn get(&self, alpn: &[u8]) -> Option<&dyn DynProtocolHandler> {\n self.0.get(alpn).map(|p| &**p)\n }\n```"}], "func_name": "get", "docstring": "Returns the registered protocol handler for an ALPN as a [`Arc`].", "repo": "n0-computer/iroh", "path": "iroh/src/protocol.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/protocol.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9171d81d2ae1f6e132aa0520e9409df4cdbf9de35ab6e8726234347b681a028b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shutdown\n\nDocumentation:\nShuts down all protocol handlers.\n\nCalls and awaits [`ProtocolHandler::shutdown`] for all registered handlers concurrently.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn shutdown(&self) {\n let handlers = self.0.values().map(|p| p.shutdown());\n join_all(handlers).await;\n }\n```"}], "func_name": "shutdown", "docstring": "Shuts down all protocol handlers.\n\nCalls and awaits [`ProtocolHandler::shutdown`] for all registered handlers concurrently.", "repo": "n0-computer/iroh", "path": "iroh/src/protocol.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/protocol.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f445f348fde42d26b44abf992365324a7403df903877e02b3a2bb64abda6d284"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shutdown\n\nDocumentation:\nShuts down the accept loop cleanly.\n\nWhen this function returns, all [`ProtocolHandler`]s will be shutdown and\n`Endpoint::close` will have been called.\n\nIf already shutdown, it returns `Ok`.\n\nIf some [`ProtocolHandler`] panicked in the accept loop, this will propagate\nthat panic into the result here.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn shutdown(&self) -> Result<(), n0_future::task::JoinError> {\n if self.is_shutdown() {\n return Ok(());\n }\n\n // Trigger shutdown of the main run task by activating the cancel token.\n self.cancel_token.cancel();\n\n // Wait for the main task to terminate.\n if let Some(task) = self.task.lock().await.take() {\n task.await?;\n }\n\n Ok(())\n }\n```"}], "func_name": "shutdown", "docstring": "Shuts down the accept loop cleanly.\n\nWhen this function returns, all [`ProtocolHandler`]s will be shutdown and\n`Endpoint::close` will have been called.\n\nIf already shutdown, it returns `Ok`.\n\nIf some [`ProtocolHandler`] panicked in the accept loop, this will propagate\nthat panic into the result here.", "repo": "n0-computer/iroh", "path": "iroh/src/protocol.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/protocol.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4585510087191df2d83ccb1615c29a5082c5853e4fe3afd73b432d46ca3cd4d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new router builder using given [`Endpoint`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(endpoint: Endpoint) -> Self {\n Self {\n endpoint,\n protocols: ProtocolMap::default(),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new router builder using given [`Endpoint`].", "repo": "n0-computer/iroh", "path": "iroh/src/protocol.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/protocol.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f24103a86f73c0b3b2e14dff7e61a83f832f9acc1a0866ddbbb0ce5a91d44f7b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accept\n\nDocumentation:\nConfigures the router to accept the [`ProtocolHandler`] when receiving a connection\nwith this `alpn`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn accept(mut self, alpn: impl AsRef<[u8]>, handler: impl ProtocolHandler) -> Self {\n self.protocols.insert(alpn.as_ref().to_vec(), handler);\n self\n }\n```"}], "func_name": "accept", "docstring": "Configures the router to accept the [`ProtocolHandler`] when receiving a connection\nwith this `alpn`.", "repo": "n0-computer/iroh", "path": "iroh/src/protocol.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/protocol.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5f4b95e022d635f07c1a6a8fdc4275d3941d39c4431b2f0967241e92dd81dbb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn\n\nDocumentation:\nSpawns an accept loop and returns a handle to it encapsulated as the [`Router`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn spawn(self) -> Router {\n // Update the endpoint with our alpns.\n let alpns = self\n .protocols\n .alpns()\n .map(|alpn| alpn.to_vec())\n .collect::>();\n\n let protocols = Arc::new(self.protocols);\n self.endpoint.set_alpns(alpns);\n\n let mut join_set = JoinSet::new();\n let endpoint = self.endpoint.clone();\n\n // Our own shutdown works with a cancellation token.\n let cancel = CancellationToken::new();\n let cancel_token = cancel.clone();\n\n let run_loop_fut = async move {\n // Make sure to cancel the token, if this future ever exits.\n let _cancel_guard = cancel_token.clone().drop_guard();\n // We create a separate cancellation token to stop any `ProtocolHandler::accept` futures\n // that are still running after `ProtocolHandler::shutdown` was called.\n let handler_cancel_token = CancellationToken::new();\n\n loop {\n tokio::select! {\n biased;\n _ = cancel_token.cancelled() => {\n break;\n },\n // handle task terminations and quit on panics.\n Some(res) = join_set.join_next() => {\n match res {\n Err(outer) => {\n if outer.is_panic() {\n error!(\"Task panicked: {outer:?}\");\n break;\n } else if outer.is_cancelled() {\n trace!(\"Task cancelled: {outer:?}\");\n } else {\n error!(\"Task failed: {outer:?}\");\n break;\n }\n }\n Ok(Some(())) => {\n trace!(\"Task finished\");\n }\n Ok(None) => {\n trace!(\"Task cancelled\");\n }\n }\n },\n\n // handle incoming p2p connections.\n incoming = endpoint.accept() => {\n let Some(incoming) = incoming else {\n break; // Endpoint is closed.\n };\n\n let protocols = protocols.clone();\n let token = handler_cancel_token.child_token();\n join_set.spawn(async move {\n token.run_until_cancelled(handle_connection(incoming, protocols)).await\n }.instrument(info_span!(\"router.accept\")));\n },\n }\n }\n\n // We first shutdown the protocol handlers to give them a chance to close connections gracefully.\n protocols.shutdown().await;\n // We now cancel the remaining `ProtocolHandler::accept` futures.\n handler_cancel_token.cancel();\n // Now we close the endpoint. This will force-close all connections that are not yet closed.\n endpoint.close().await;\n // Finally, we abort the remaining accept tasks. This should be a noop because we already cancelled\n // the futures above.\n tracing::debug!(\"Shutting down remaining tasks\");\n join_set.abort_all();\n while let Some(res) = join_set.join_next().await {\n match res {\n Err(err) if err.is_panic() => error!(\"Task panicked: {err:?}\"),\n _ => {}\n }\n }\n };\n let task = task::spawn(run_loop_fut);\n let task = AbortOnDropHandle::new(task);\n\n Router {\n endpoint: self.endpoint,\n task: Arc::new(Mutex::new(Some(task))),\n cancel_token: cancel,\n }\n }\n```"}], "func_name": "spawn", "docstring": "Spawns an accept loop and returns a handle to it encapsulated as the [`Router`].", "repo": "n0-computer/iroh", "path": "iroh/src/protocol.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/protocol.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d6278560390a98361e84ad36be3a1ebf51d99d8b8acd95a6ed3e95df6dfe277"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_relay_server\n\nDocumentation:\nRuns a relay server with STUN and QUIC enabled suitable for tests.\n\nThe returned `Url` is the url of the relay server in the returned [`RelayMap`].\nWhen dropped, the returned [`Server`] does will stop running.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_relay_server() -> Result<(RelayMap, RelayUrl, Server), SpawnError> {\n run_relay_server_with(\n Some(StunConfig {\n bind_addr: (Ipv4Addr::LOCALHOST, 0).into(),\n }),\n true,\n )\n .await\n}\n```"}], "func_name": "run_relay_server", "docstring": "Runs a relay server with STUN and QUIC enabled suitable for tests.\n\nThe returned `Url` is the url of the relay server in the returned [`RelayMap`].\nWhen dropped, the returned [`Server`] does will stop running.", "repo": "n0-computer/iroh", "path": "iroh/src/test_utils.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "26490ce81da41b2ba752782ecba2c9007cf76f49617f59267daf77c0ac8044cd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_relay_server_with_stun\n\nDocumentation:\nRuns a relay server with STUN enabled suitable for tests.\n\nThe returned `Url` is the url of the relay server in the returned [`RelayMap`].\nWhen dropped, the returned [`Server`] does will stop running.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_relay_server_with_stun() -> Result<(RelayMap, RelayUrl, Server), SpawnError> {\n run_relay_server_with(\n Some(StunConfig {\n bind_addr: (Ipv4Addr::LOCALHOST, 0).into(),\n }),\n false,\n )\n .await\n}\n```"}], "func_name": "run_relay_server_with_stun", "docstring": "Runs a relay server with STUN enabled suitable for tests.\n\nThe returned `Url` is the url of the relay server in the returned [`RelayMap`].\nWhen dropped, the returned [`Server`] does will stop running.", "repo": "n0-computer/iroh", "path": "iroh/src/test_utils.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf2b9caaba36106dafdc7c67136de65e4f20976dc5addd8ea0ca9cc704995ac0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_relay_server_with\n\nDocumentation:\nRuns a relay server.\n\n`stun` can be set to `None` to disable stun, or set to `Some` `StunConfig`,\nto enable stun on a specific socket.\n\nIf `quic` is set to `true`, it will make the appropriate [`QuicConfig`] from the generated tls certificates and run the quic server at a random free port.\n\n\nThe return value is similar to [`run_relay_server`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_relay_server_with(\n stun: Option,\n quic: bool,\n) -> Result<(RelayMap, RelayUrl, Server), SpawnError> {\n let (certs, server_config) = iroh_relay::server::testing::self_signed_tls_certs_and_config();\n\n let tls = TlsConfig {\n cert: CertConfig::<(), ()>::Manual { certs },\n https_bind_addr: (Ipv4Addr::LOCALHOST, 0).into(),\n quic_bind_addr: (Ipv4Addr::LOCALHOST, 0).into(),\n server_config,\n };\n let quic = if quic {\n Some(QuicConfig {\n server_config: tls.server_config.clone(),\n bind_addr: tls.quic_bind_addr,\n })\n } else {\n None\n };\n let config = ServerConfig {\n relay: Some(RelayConfig {\n http_bind_addr: (Ipv4Addr::LOCALHOST, 0).into(),\n tls: Some(tls),\n limits: Default::default(),\n key_cache_capacity: Some(1024),\n access: AccessConfig::Everyone,\n }),\n quic,\n stun,\n ..Default::default()\n };\n let server = Server::spawn(config).await?;\n let url: RelayUrl = format!(\"https://{}\", server.https_addr().expect(\"configured\"))\n .parse()\n .expect(\"invalid relay url\");\n\n let quic = server\n .quic_addr()\n .map(|addr| RelayQuicConfig { port: addr.port() });\n let n: RelayMap = RelayNode {\n url: url.clone(),\n stun_only: false,\n stun_port: server.stun_addr().map_or(DEFAULT_STUN_PORT, |s| s.port()),\n quic,\n }\n .into();\n Ok((n, url, server))\n}\n```"}], "func_name": "run_relay_server_with", "docstring": "Runs a relay server.\n\n`stun` can be set to `None` to disable stun, or set to `Some` `StunConfig`,\nto enable stun on a specific socket.\n\nIf `quic` is set to `true`, it will make the appropriate [`QuicConfig`] from the generated tls certificates and run the quic server at a random free port.\n\n\nThe return value is similar to [`run_relay_server`].", "repo": "n0-computer/iroh", "path": "iroh/src/test_utils.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e1a21479fc74d84d91ed4031f224901f8f9effe63f9c24bd90d338f0a6a27e6a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_with_origin\n\nDocumentation:\nRun DNS and Pkarr servers on localhost with the specified `node_origin` domain.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_with_origin(node_origin: String) -> std::io::Result {\n let state = State::new(node_origin.clone());\n let (nameserver, dns_drop_guard) = run_dns_server(state.clone()).await?;\n let (pkarr_url, pkarr_drop_guard) = run_pkarr_relay(state.clone()).await?;\n Ok(Self {\n node_origin,\n nameserver,\n pkarr_url,\n state,\n _dns_drop_guard: dns_drop_guard,\n _pkarr_drop_guard: pkarr_drop_guard,\n })\n }\n```"}], "func_name": "run_with_origin", "docstring": "Run DNS and Pkarr servers on localhost with the specified `node_origin` domain.", "repo": "n0-computer/iroh", "path": "iroh/src/test_utils.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c2283e17d371b30e2f089ff774c6defa52ef698d277b39295795968db74415f9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: discovery\n\nDocumentation:\nCreate a [`ConcurrentDiscovery`] with [`DnsDiscovery`] and [`PkarrPublisher`]\nconfigured to use the test servers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn discovery(&self, secret_key: SecretKey) -> Box {\n Box::new(ConcurrentDiscovery::from_services(vec![\n // Enable DNS discovery by default\n Box::new(DnsDiscovery::new(self.node_origin.clone())),\n // Enable pkarr publishing by default\n Box::new(PkarrPublisher::new(secret_key, self.pkarr_url.clone())),\n ]))\n }\n```"}], "func_name": "discovery", "docstring": "Create a [`ConcurrentDiscovery`] with [`DnsDiscovery`] and [`PkarrPublisher`]\nconfigured to use the test servers.", "repo": "n0-computer/iroh", "path": "iroh/src/test_utils.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e366e1cd87bc2fb4920e6df02073b486bb1ecf1fc907e0a1804333dafad71929"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_node\n\nDocumentation:\nWait until a Pkarr announce for a node is published to the server.\n\nIf `timeout` elapses an error is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn on_node(&self, node_id: &NodeId, timeout: Duration) -> std::io::Result<()> {\n self.state.on_node(node_id, timeout).await\n }\n```"}], "func_name": "on_node", "docstring": "Wait until a Pkarr announce for a node is published to the server.\n\nIf `timeout` elapses an error is returned.", "repo": "n0-computer/iroh", "path": "iroh/src/test_utils.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0667d75e25dd1a8a16ce3960e164c8a70539cb70084a7bebb3807ef3b77c5ec0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_dns_server\n\nDocumentation:\nRun a DNS server.\n\nMust pass a [`QueryHandler`] that answers queries.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_dns_server(\n resolver: impl QueryHandler,\n ) -> std::io::Result<(SocketAddr, CleanupDropGuard)> {\n let bind_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 0));\n let socket = UdpSocket::bind(bind_addr).await?;\n let bound_addr = socket.local_addr()?;\n let s = TestDnsServer { socket, resolver };\n let (tx, mut rx) = oneshot::channel();\n tokio::task::spawn(async move {\n tokio::select! {\n _ = &mut rx => {\n debug!(\"shutting down dns server\");\n }\n res = s.run() => {\n if let Err(e) = res {\n error!(\"error running dns server {e:?}\");\n }\n }\n }\n });\n Ok((bound_addr, CleanupDropGuard(tx)))\n }\n```"}], "func_name": "run_dns_server", "docstring": "Run a DNS server.\n\nMust pass a [`QueryHandler`] that answers queries.", "repo": "n0-computer/iroh", "path": "iroh/src/test_utils.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "52fef76a4b991bce4fa139114e99975fd12be7fc4dc10308c61b31cf1015ff9f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturns a mutex guard, do not hold over await points\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(&self, node_id: &NodeId, cb: F) -> T\n where\n F: FnOnce(Option<&mut SignedPacket>) -> T,\n {\n let mut map = self.packets.lock().expect(\"poisoned\");\n let packet = map.get_mut(node_id);\n cb(packet)\n }\n```"}], "func_name": "get", "docstring": "Returns a mutex guard, do not hold over await points", "repo": "n0-computer/iroh", "path": "iroh/src/test_utils.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aa35163236a0e23f6a9e8d340bd3a37a195c1069f0307a82f630c9c7710a24de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: node_id_from_domain_name\n\nDocumentation:\nParses a [`NodeId`] from a DNS domain name.\n\nSplits the domain name into labels on each dot. Expects the first label to be\n[`IROH_TXT_NAME`] and the second label to be a z32 encoded [`NodeId`]. Ignores\nsubsequent labels.\n\nReturns a [`NodeId`] if parsed successfully, otherwise `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn node_id_from_domain_name(name: &str) -> Option {\n let mut labels = name.split(\".\");\n let label = labels.next()?;\n if label != IROH_TXT_NAME {\n return None;\n }\n let label = labels.next()?;\n let node_id = NodeId::from_z32(label).ok()?;\n Some(node_id)\n }\n```"}], "func_name": "node_id_from_domain_name", "docstring": "Parses a [`NodeId`] from a DNS domain name.\n\nSplits the domain name into labels on each dot. Expects the first label to be\n[`IROH_TXT_NAME`] and the second label to be a z32 encoded [`NodeId`]. Ignores\nsubsequent labels.\n\nReturns a [`NodeId`] if parsed successfully, otherwise `None`.", "repo": "n0-computer/iroh", "path": "iroh/src/test_utils.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "800094e150da2da7da8e400b512944884475c0fdd2b2071828417780543f9864"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: node_info_to_hickory_records\n\nDocumentation:\nConverts a [`NodeInfo`]into a [`hickory_resolver::proto::rr::Record`] DNS record.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn node_info_to_hickory_records(\n node_info: &NodeInfo,\n origin: &str,\n ttl: u32,\n ) -> impl Iterator + 'static {\n let txt_strings = node_info.to_txt_strings();\n let records = to_hickory_records(txt_strings, node_info.node_id, origin, ttl);\n records.collect::>().into_iter()\n }\n```"}], "func_name": "node_info_to_hickory_records", "docstring": "Converts a [`NodeInfo`]into a [`hickory_resolver::proto::rr::Record`] DNS record.", "repo": "n0-computer/iroh", "path": "iroh/src/test_utils.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0bdc25a1117d9d9efb73fd14adfba93ad02c78e3471fe1be496f980ae15f051c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_hickory_records\n\nDocumentation:\nConverts to a list of [`hickory_resolver::proto::rr::Record`] resource records.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn to_hickory_records(\n txt_strings: Vec,\n node_id: NodeId,\n origin: &str,\n ttl: u32,\n ) -> impl Iterator + '_ {\n use hickory_resolver::proto::rr;\n let name = format!(\"{}.{}.{}\", IROH_TXT_NAME, node_id.to_z32(), origin);\n let name = rr::Name::from_utf8(name).expect(\"invalid name\");\n txt_strings.into_iter().map(move |s| {\n let txt = rr::rdata::TXT::new(vec![s]);\n let rdata = rr::RData::TXT(txt);\n rr::Record::from_rdata(name.clone(), ttl, rdata)\n })\n }\n```"}], "func_name": "to_hickory_records", "docstring": "Converts to a list of [`hickory_resolver::proto::rr::Record`] resource records.", "repo": "n0-computer/iroh", "path": "iroh/src/test_utils.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/test_utils.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fbffdd00682f8949a9f5f5ab6d112902cede1190c615d475bbefc7ad9a091d01"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_client_config\n\nDocumentation:\nCreate a TLS client configuration.\n\nIf *keylog* is `true` this will enable logging of the pre-master key to the file in the\n`SSLKEYLOGFILE` environment variable. This can be used to inspect the traffic for\ndebugging purposes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn make_client_config(\n &self,\n alpn_protocols: Vec>,\n keylog: bool,\n ) -> QuicClientConfig {\n let mut crypto = rustls::ClientConfig::builder_with_provider(Arc::new(\n rustls::crypto::ring::default_provider(),\n ))\n .with_protocol_versions(verifier::PROTOCOL_VERSIONS)\n .expect(\"version supported by ring\")\n .dangerous()\n .with_custom_certificate_verifier(self.server_verifier.clone())\n .with_client_cert_resolver(self.cert_resolver.clone());\n crypto.alpn_protocols = alpn_protocols;\n\n // TODO: enable/disable 0-RTT/storing tickets\n crypto.resumption = rustls::client::Resumption::store(self.session_store.clone());\n crypto.enable_early_data = true;\n\n if keylog {\n warn!(\"enabling SSLKEYLOGFILE for TLS pre-master keys\");\n crypto.key_log = Arc::new(rustls::KeyLogFile::new());\n }\n\n crypto\n .try_into()\n .expect(\"expected to have a TLS1.3-compatible crypto provider set (hardcoded)\")\n }\n```"}], "func_name": "make_client_config", "docstring": "Create a TLS client configuration.\n\nIf *keylog* is `true` this will enable logging of the pre-master key to the file in the\n`SSLKEYLOGFILE` environment variable. This can be used to inspect the traffic for\ndebugging purposes.", "repo": "n0-computer/iroh", "path": "iroh/src/tls.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/tls.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3af9599672e8c506429ea3151a1f4d17331af96619540e5edb38fe3ebb0f9f15"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_server_config\n\nDocumentation:\nCreate a TLS server configuration.\n\nIf *keylog* is `true` this will enable logging of the pre-master key to the file in the\n`SSLKEYLOGFILE` environment variable. This can be used to inspect the traffic for\ndebugging purposes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn make_server_config(\n &self,\n alpn_protocols: Vec>,\n keylog: bool,\n ) -> QuicServerConfig {\n let mut crypto = rustls::ServerConfig::builder_with_provider(Arc::new(\n rustls::crypto::ring::default_provider(),\n ))\n .with_protocol_versions(verifier::PROTOCOL_VERSIONS)\n .expect(\"fixed config\")\n .with_client_cert_verifier(self.client_verifier.clone())\n .with_cert_resolver(self.cert_resolver.clone());\n crypto.alpn_protocols = alpn_protocols;\n if keylog {\n warn!(\"enabling SSLKEYLOGFILE for TLS pre-master keys\");\n crypto.key_log = Arc::new(rustls::KeyLogFile::new());\n }\n\n // must be u32::MAX or 0 (the default). Any other value panics with QUIC\n // This is specified in RFC 9001: https://www.rfc-editor.org/rfc/rfc9001#section-4.6.1\n crypto.max_early_data_size = u32::MAX;\n crypto\n .try_into()\n .expect(\"expected to have a TLS1.3-compatible crypto provider set (hardcoded)\")\n }\n```"}], "func_name": "make_server_config", "docstring": "Create a TLS server configuration.\n\nIf *keylog* is `true` this will enable logging of the pre-master key to the file in the\n`SSLKEYLOGFILE` environment variable. This can be used to inspect the traffic for\ndebugging purposes.", "repo": "n0-computer/iroh", "path": "iroh/src/tls.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/tls.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9eafa1b881dbdbcb27b17eb4662d78b73a12534f5b7e6f95d3d2c74f5c28cfe5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_none\n\nDocumentation:\nReturns `true` if the inner is empty.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn is_none(&self) -> bool {\n matches!(self, Self::None)\n }\n```"}], "func_name": "is_none", "docstring": "Returns `true` if the inner is empty.", "repo": "n0-computer/iroh", "path": "iroh/src/util.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/util.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ed2c2b7a6c580171daf95d58d12c55b4ccd92ee856717c828f30ff3bc07a8f09"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_some\n\nDocumentation:\nReturns `true` if the inner contains a future.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn is_some(&self) -> bool {\n matches!(self, Self::Some(_))\n }\n```"}], "func_name": "is_some", "docstring": "Returns `true` if the inner contains a future.", "repo": "n0-computer/iroh", "path": "iroh/src/util.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/util.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "46f227501cbd1f0deb2729e015b369fe8561bad4a36967252fb750650b2d91b3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: n0_dns\n\nDocumentation:\nCreates a new DNS discovery using the `iroh.link` domain.\n\nThis uses the [`N0_DNS_NODE_ORIGIN_PROD`] domain.\n\n# Usage during tests\n\nFor testing it is possible to use the [`N0_DNS_NODE_ORIGIN_STAGING`] domain\nwith [`DnsDiscovery::new`]. This would then use a hosted staging discovery\nservice for testing purposes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn n0_dns() -> Self {\n if force_staging_infra() {\n Self::new(N0_DNS_NODE_ORIGIN_STAGING.to_string())\n } else {\n Self::new(N0_DNS_NODE_ORIGIN_PROD.to_string())\n }\n }\n```"}], "func_name": "n0_dns", "docstring": "Creates a new DNS discovery using the `iroh.link` domain.\n\nThis uses the [`N0_DNS_NODE_ORIGIN_PROD`] domain.\n\n# Usage during tests\n\nFor testing it is possible to use the [`N0_DNS_NODE_ORIGIN_STAGING`] domain\nwith [`DnsDiscovery::new`]. This would then use a hosted staging discovery\nservice for testing purposes.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "42539127047cb2dc847c903f268ffeb11d709c6099c136283d12ff803033d7a1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send\n\nDocumentation:\nSends the `node_id` and `item` to each subscriber.\n\nCleans up any subscribers that have been dropped.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn send(&mut self, item: DiscoveryItem) {\n let mut clean_up = vec![];\n for (i, subscriber) in self.0.iter().enumerate() {\n // assume subscriber was dropped\n if let Err(err) = subscriber.try_send(item.clone()) {\n match err {\n TrySendError::Full(_) => {\n warn!(\n ?item,\n idx = i,\n \"local swarm discovery subscriber is blocked, dropping item\"\n )\n }\n TrySendError::Closed(_) => clean_up.push(i),\n }\n }\n }\n for i in clean_up.into_iter().rev() {\n self.0.swap_remove(i);\n }\n }\n```"}], "func_name": "send", "docstring": "Sends the `node_id` and `item` to each subscriber.\n\nCleans up any subscribers that have been dropped.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/mdns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/mdns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f613b747b3b12aea7cd823c510c3483d2f742e80110d20317f417fe09a8532fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new [`MdnsDiscovery`] Service.\n\nThis starts a [`Discoverer`] that broadcasts your addresses and receives addresses from other nodes in your local network.\n\n# Errors\nReturns an error if the network does not allow ipv4 OR ipv6.\n\n# Panics\nThis relies on [`tokio::runtime::Handle::current`] and will panic if called outside of the context of a tokio runtime.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(node_id: NodeId) -> Result {\n debug!(\"Creating new MdnsDiscovery service\");\n let (send, mut recv) = mpsc::channel(64);\n let task_sender = send.clone();\n let rt = tokio::runtime::Handle::current();\n let discovery =\n MdnsDiscovery::spawn_discoverer(node_id, task_sender.clone(), BTreeSet::new(), &rt)?;\n\n let local_addrs: Watchable> = Watchable::default();\n let mut addrs_change = local_addrs.watch();\n let discovery_fut = async move {\n let mut node_addrs: HashMap = HashMap::default();\n let mut subscribers = Subscribers::new();\n let mut last_id = 0;\n let mut senders: HashMap<\n PublicKey,\n HashMap>>,\n > = HashMap::default();\n let mut timeouts = JoinSet::new();\n loop {\n trace!(?node_addrs, \"MdnsDiscovery Service loop tick\");\n let msg = tokio::select! {\n msg = recv.recv() => {\n msg\n }\n Ok(Some(data)) = addrs_change.updated() => {\n tracing::trace!(?data, \"MdnsDiscovery address changed\");\n discovery.remove_all();\n let addrs =\n MdnsDiscovery::socketaddrs_to_addrs(data.direct_addresses());\n for addr in addrs {\n discovery.add(addr.0, addr.1)\n }\n if let Some(user_data) = data.user_data() {\n if let Err(err) = discovery.set_txt_attribute(USER_DATA_ATTRIBUTE.to_string(), Some(user_data.to_string())) {\n warn!(\"Failed to set the user-defined data in local swarm discovery: {err:?}\");\n }\n }\n continue;\n }\n };\n let msg = match msg {\n None => {\n error!(\"MdnsDiscovery channel closed\");\n error!(\"closing MdnsDiscovery\");\n timeouts.abort_all();\n return;\n }\n Some(msg) => msg,\n };\n match msg {\n Message::Discovery(discovered_node_id, peer_info) => {\n trace!(\n ?discovered_node_id,\n ?peer_info,\n \"MdnsDiscovery Message::Discovery\"\n );\n let discovered_node_id = match PublicKey::from_str(&discovered_node_id) {\n Ok(node_id) => node_id,\n Err(e) => {\n warn!(\n discovered_node_id,\n \"couldn't parse node_id from mdns discovery service: {e:?}\"\n );\n continue;\n }\n };\n\n if discovered_node_id == node_id {\n continue;\n }\n\n if peer_info.is_expiry() {\n trace!(\n ?discovered_node_id,\n \"removing node from MdnsDiscovery address book\"\n );\n node_addrs.remove(&discovered_node_id);\n continue;\n }\n\n let entry = node_addrs.entry(discovered_node_id);\n if let std::collections::hash_map::Entry::Occupied(ref entry) = entry {\n if entry.get() == &peer_info {\n // this is a republish we already know about\n continue;\n }\n }\n\n debug!(\n ?discovered_node_id,\n ?peer_info,\n \"adding node to MdnsDiscovery address book\"\n );\n\n let mut resolved = false;\n let item = peer_to_discovery_item(&peer_info, &discovered_node_id);\n if let Some(senders) = senders.get(&discovered_node_id) {\n trace!(?item, senders = senders.len(), \"sending DiscoveryItem\");\n resolved = true;\n for sender in senders.values() {\n sender.send(Ok(item.clone())).await.ok();\n }\n }\n entry.or_insert(peer_info);\n\n // only send nodes to the `subscriber` if they weren't explicitly resolved\n // in other words, nodes sent to the `subscribers` should only be the ones that\n // have been \"passively\" discovered\n if !resolved {\n subscribers.send(item);\n }\n }\n Message::Resolve(node_id, sender) => {\n let id = last_id + 1;\n last_id = id;\n trace!(?node_id, \"MdnsDiscovery Message::SendAddrs\");\n if let Some(peer_info) = node_addrs.get(&node_id) {\n let item = peer_to_discovery_item(peer_info, &node_id);\n debug!(?item, \"sending DiscoveryItem\");\n sender.send(Ok(item)).await.ok();\n }\n if let Some(senders_for_node_id) = senders.get_mut(&node_id) {\n senders_for_node_id.insert(id, sender);\n } else {\n let mut senders_for_node_id = HashMap::new();\n senders_for_node_id.insert(id, sender);\n senders.insert(node_id, senders_for_node_id);\n }\n let timeout_sender = task_sender.clone();\n timeouts.spawn(async move {\n time::sleep(DISCOVERY_DURATION).await;\n trace!(?node_id, \"discovery timeout\");\n timeout_sender\n .send(Message::Timeout(node_id, id))\n .await\n .ok();\n });\n }\n Message::Timeout(node_id, id) => {\n trace!(?node_id, \"MdnsDiscovery Message::Timeout\");\n if let Some(senders_for_node_id) = senders.get_mut(&node_id) {\n senders_for_node_id.remove(&id);\n if senders_for_node_id.is_empty() {\n senders.remove(&node_id);\n }\n }\n }\n Message::Subscribe(subscriber) => {\n trace!(\"MdnsDiscovery Message::Subscribe\");\n subscribers.push(subscriber);\n }\n }\n }\n };\n let handle = task::spawn(discovery_fut.instrument(info_span!(\"swarm-discovery.actor\")));\n Ok(Self {\n handle: AbortOnDropHandle::new(handle),\n sender: send,\n local_addrs,\n })\n }\n```"}], "func_name": "new", "docstring": "Create a new [`MdnsDiscovery`] Service.\n\nThis starts a [`Discoverer`] that broadcasts your addresses and receives addresses from other nodes in your local network.\n\n# Errors\nReturns an error if the network does not allow ipv4 OR ipv6.\n\n# Panics\nThis relies on [`tokio::runtime::Handle::current`] and will panic if called outside of the context of a tokio runtime.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/mdns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/mdns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a0192cc74bd8ef38af2179fea847fee343cf553833a5491214f84f895499931"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new publisher for the [`SecretKey`].\n\nThis publisher will be able to publish [pkarr] records for [`SecretKey`]. It will\nuse [`DEFAULT_PKARR_TTL`] as the time-to-live value for the published packets. Will\nrepublish discovery information every [`DEFAULT_REPUBLISH_INTERVAL`], even if the\ninformation is unchanged.\n\n[pkarr]: https://pkarr.org\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(secret_key: SecretKey, pkarr_relay: Url) -> Self {\n Self::with_options(\n secret_key,\n pkarr_relay,\n DEFAULT_PKARR_TTL,\n DEFAULT_REPUBLISH_INTERVAL,\n )\n }\n```"}], "func_name": "new", "docstring": "Creates a new publisher for the [`SecretKey`].\n\nThis publisher will be able to publish [pkarr] records for [`SecretKey`]. It will\nuse [`DEFAULT_PKARR_TTL`] as the time-to-live value for the published packets. Will\nrepublish discovery information every [`DEFAULT_REPUBLISH_INTERVAL`], even if the\ninformation is unchanged.\n\n[pkarr]: https://pkarr.org", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8d46587bf617c3f572b8e77d471fd392a0147b5cc5662b867478085cca4bac85"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_options\n\nDocumentation:\nCreates a new [`PkarrPublisher`] with a custom TTL and republish intervals.\n\nThis allows creating the publisher with custom time-to-live values of the\n[`pkarr::SignedPacket`]s and well as a custom republish interval.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_options(\n secret_key: SecretKey,\n pkarr_relay: Url,\n ttl: u32,\n republish_interval: Duration,\n ) -> Self {\n debug!(\"creating pkarr publisher that publishes to {pkarr_relay}\");\n let node_id = secret_key.public();\n let pkarr_client = PkarrRelayClient::new(pkarr_relay);\n let watchable = Watchable::default();\n let service = PublisherService {\n ttl,\n watcher: watchable.watch(),\n secret_key,\n pkarr_client,\n republish_interval,\n };\n let join_handle = task::spawn(\n service\n .run()\n .instrument(error_span!(\"pkarr_publish\", me=%node_id.fmt_short())),\n );\n Self {\n watchable,\n node_id,\n _drop_guard: Arc::new(AbortOnDropHandle::new(join_handle)),\n }\n }\n```"}], "func_name": "with_options", "docstring": "Creates a new [`PkarrPublisher`] with a custom TTL and republish intervals.\n\nThis allows creating the publisher with custom time-to-live values of the\n[`pkarr::SignedPacket`]s and well as a custom republish interval.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "84814ffb679c99231c99ec536fd6bd436e4176066075ce98354fe3f39dad78dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: n0_dns\n\nDocumentation:\nCreates a pkarr publisher which uses the [number 0] pkarr relay server.\n\nThis uses the pkarr relay server operated by [number 0], at\n[`N0_DNS_PKARR_RELAY_PROD`].\n\nWhen running with the environment variable\n`IROH_FORCE_STAGING_RELAYS` set to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`]\nserver is used instead.\n\n[number 0]: https://n0.computer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn n0_dns(secret_key: SecretKey) -> Self {\n let pkarr_relay = match force_staging_infra() {\n true => N0_DNS_PKARR_RELAY_STAGING,\n false => N0_DNS_PKARR_RELAY_PROD,\n };\n\n let pkarr_relay: Url = pkarr_relay.parse().expect(\"url is valid\");\n Self::new(secret_key, pkarr_relay)\n }\n```"}], "func_name": "n0_dns", "docstring": "Creates a pkarr publisher which uses the [number 0] pkarr relay server.\n\nThis uses the pkarr relay server operated by [number 0], at\n[`N0_DNS_PKARR_RELAY_PROD`].\n\nWhen running with the environment variable\n`IROH_FORCE_STAGING_RELAYS` set to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`]\nserver is used instead.\n\n[number 0]: https://n0.computer", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b35319c4a992a0da98954ada0d40a690644791308ed6470b5832a16eee4f14dd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update_node_data\n\nDocumentation:\nPublishes the addressing information about this node to a pkarr relay.\n\nThis is a nonblocking function, the actual update is performed in the background.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn update_node_data(&self, data: &NodeData) {\n let mut data = data.clone();\n if data.relay_url().is_some() {\n // If relay url is set: only publish relay url, and no direct addrs.\n data.clear_direct_addresses();\n }\n let info = NodeInfo::from_parts(self.node_id, data);\n self.watchable.set(Some(info)).ok();\n }\n```"}], "func_name": "update_node_data", "docstring": "Publishes the addressing information about this node to a pkarr relay.\n\nThis is a nonblocking function, the actual update is performed in the background.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc2e3c403e3ba83e8c8072dd2ae2ba1b3590ee8bd3cb6ef23e6d36e2c4e44893"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new publisher using the pkarr relay server at the URL.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(pkarr_relay: Url) -> Self {\n Self {\n pkarr_client: PkarrRelayClient::new(pkarr_relay),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new publisher using the pkarr relay server at the URL.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "746da3aab89f242920f0d587e66051776e237133ccdc384d069eb1a3d84051b7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: n0_dns\n\nDocumentation:\nCreates a pkarr resolver which uses the [number 0] pkarr relay server.\n\nThis uses the pkarr relay server operated by [number 0] at\n[`N0_DNS_PKARR_RELAY_PROD`].\n\nWhen running with the environment variable `IROH_FORCE_STAGING_RELAYS`\nset to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`]\nserver is used instead.\n\n[number 0]: https://n0.computer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn n0_dns() -> Self {\n let pkarr_relay = match force_staging_infra() {\n true => N0_DNS_PKARR_RELAY_STAGING,\n false => N0_DNS_PKARR_RELAY_PROD,\n };\n\n let pkarr_relay: Url = pkarr_relay.parse().expect(\"url is valid\");\n Self::new(pkarr_relay)\n }\n```"}], "func_name": "n0_dns", "docstring": "Creates a pkarr resolver which uses the [number 0] pkarr relay server.\n\nThis uses the pkarr relay server operated by [number 0] at\n[`N0_DNS_PKARR_RELAY_PROD`].\n\nWhen running with the environment variable `IROH_FORCE_STAGING_RELAYS`\nset to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`]\nserver is used instead.\n\n[number 0]: https://n0.computer", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc0896139ab18b781c9ffd05a0277234e4dd6371d907bad157ba6608ab7f3325"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve\n\nDocumentation:\nResolves a [`SignedPacket`] for the given [`NodeId`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn resolve(&self, node_id: NodeId) -> Result {\n // We map the error to string, as in browsers the error is !Send\n let public_key = pkarr::PublicKey::try_from(node_id.as_bytes()).context(PublicKeySnafu)?;\n\n let mut url = self.pkarr_relay_url.clone();\n url.path_segments_mut()\n .map_err(|_| {\n InvalidRelayUrlSnafu {\n url: self.pkarr_relay_url.clone(),\n }\n .build()\n })?\n .push(&public_key.to_z32());\n\n let response = self\n .http_client\n .get(url)\n .send()\n .await\n .context(HttpSendSnafu)?;\n\n if !response.status().is_success() {\n return Err(HttpRequestSnafu {\n status: response.status(),\n }\n .build()\n .into());\n }\n\n let payload = response.bytes().await.context(HttpPayloadSnafu)?;\n // We map the error to string, as in browsers the error is !Send\n let packet =\n SignedPacket::from_relay_payload(&public_key, &payload).context(VerifySnafu)?;\n Ok(packet)\n }\n```"}], "func_name": "resolve", "docstring": "Resolves a [`SignedPacket`] for the given [`NodeId`].", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f85b6e29ecd99ef992781baf68b1b7f0db37bc9bbb5698a4820f65c8156d0e6d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_node_info\n\nDocumentation:\nCreates a static discovery instance from node addresses.\n\n# Examples\n\n```rust\nuse std::{net::SocketAddr, str::FromStr};\n\nuse iroh::{discovery::static_provider::StaticProvider, Endpoint, NodeAddr};\n\n# fn get_addrs() -> Vec {\n# Vec::new()\n# }\n# #[tokio::main]\n# async fn main() -> n0_snafu::Result<()> {\n// get addrs from somewhere\nlet addrs = get_addrs();\n\n// create a StaticProvider from the list of addrs.\nlet discovery = StaticProvider::from_node_info(addrs);\n// create an endpoint with the discovery\nlet endpoint = Endpoint::builder()\n.add_discovery(|_| Some(discovery))\n.bind()\n.await?;\n# Ok(())\n# }\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_node_info(infos: impl IntoIterator>) -> Self {\n let res = Self::default();\n for info in infos {\n res.add_node_info(info);\n }\n res\n }\n```"}], "func_name": "from_node_info", "docstring": "Creates a static discovery instance from node addresses.\n\n# Examples\n\n```rust\nuse std::{net::SocketAddr, str::FromStr};\n\nuse iroh::{discovery::static_provider::StaticProvider, Endpoint, NodeAddr};\n\n# fn get_addrs() -> Vec {\n# Vec::new()\n# }\n# #[tokio::main]\n# async fn main() -> n0_snafu::Result<()> {\n// get addrs from somewhere\nlet addrs = get_addrs();\n\n// create a StaticProvider from the list of addrs.\nlet discovery = StaticProvider::from_node_info(addrs);\n// create an endpoint with the discovery\nlet endpoint = Endpoint::builder()\n.add_discovery(|_| Some(discovery))\n.bind()\n.await?;\n# Ok(())\n# }\n```", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/static_provider.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/static_provider.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "22e1202306c1d7c4ee4910910ddb0a00032784e2b49484a0d7bbafc9a1092a32"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_node_info\n\nDocumentation:\nSets node addressing information for the given node ID.\n\nThis will completely overwrite any existing info for the node.\n\nReturns the [`NodeData`] of the previous entry, or `None` if there was no previous\nentry for this node ID.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_node_info(&self, node_info: impl Into) -> Option {\n let last_updated = SystemTime::now();\n let NodeInfo { node_id, data } = node_info.into();\n let mut guard = self.nodes.write().expect(\"poisoned\");\n let previous = guard.insert(node_id, StoredNodeInfo { data, last_updated });\n previous.map(|x| x.data)\n }\n```"}], "func_name": "set_node_info", "docstring": "Sets node addressing information for the given node ID.\n\nThis will completely overwrite any existing info for the node.\n\nReturns the [`NodeData`] of the previous entry, or `None` if there was no previous\nentry for this node ID.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/static_provider.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/static_provider.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c8b54153c90fa6300fb5e997c10eacc9f7e6ebff87251042eab256a69b0e7e5f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_node_info\n\nDocumentation:\nAugments node addressing information for the given node ID.\n\nThe provided addressing information is combined with the existing info in the static\nprovider. Any new direct addresses are added to those already present while the\nrelay URL is overwritten.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_node_info(&self, node_info: impl Into) {\n let last_updated = SystemTime::now();\n let NodeInfo { node_id, data } = node_info.into();\n let mut guard = self.nodes.write().expect(\"poisoned\");\n match guard.entry(node_id) {\n Entry::Occupied(mut entry) => {\n let existing = entry.get_mut();\n existing\n .data\n .add_direct_addresses(data.direct_addresses().iter().copied());\n existing.data.set_relay_url(data.relay_url().cloned());\n existing.data.set_user_data(data.user_data().cloned());\n existing.last_updated = last_updated;\n }\n Entry::Vacant(entry) => {\n entry.insert(StoredNodeInfo { data, last_updated });\n }\n }\n }\n```"}], "func_name": "add_node_info", "docstring": "Augments node addressing information for the given node ID.\n\nThe provided addressing information is combined with the existing info in the static\nprovider. Any new direct addresses are added to those already present while the\nrelay URL is overwritten.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/static_provider.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/static_provider.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a3f16fa99f90c11149835e13db7aecd0cc9ef01cc2fd4fc908b7809648d80ae8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_node_info\n\nDocumentation:\nReturns node addressing information for the given node ID.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_node_info(&self, node_id: NodeId) -> Option {\n let guard = self.nodes.read().expect(\"poisoned\");\n let info = guard.get(&node_id)?;\n Some(NodeInfo::from_parts(node_id, info.data.clone()))\n }\n```"}], "func_name": "get_node_info", "docstring": "Returns node addressing information for the given node ID.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/static_provider.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/static_provider.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d1eac55cf4b9c73eb47bb6309dad00d9054eea92e5ef85b8dc40d3bc4dcb3768"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_node_info\n\nDocumentation:\nRemoves all node addressing information for the given node ID.\n\nAny removed information is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn remove_node_info(&self, node_id: NodeId) -> Option {\n let mut guard = self.nodes.write().expect(\"poisoned\");\n let info = guard.remove(&node_id)?;\n Some(NodeInfo::from_parts(node_id, info.data))\n }\n```"}], "func_name": "remove_node_info", "docstring": "Removes all node addressing information for the given node ID.\n\nAny removed information is returned.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/static_provider.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/static_provider.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9ee21933ab97efeb6b73a5233e05292495c8350cf9cecd06a3e3eea7fca3ba04"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: client\n\nDocumentation:\nExplicitly sets the pkarr client to use.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn client(mut self, client: PkarrClient) -> Self {\n self.client = Some(client);\n self\n }\n```"}], "func_name": "client", "docstring": "Explicitly sets the pkarr client to use.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr/dht.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr/dht.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3bbc58191e38ca432acb653d0fa736739743b2d0b5f36874dd0073a9c597299c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pkarr_relay\n\nDocumentation:\nSets the pkarr relay URL to use.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pkarr_relay(mut self, pkarr_relay: Url) -> Self {\n self.pkarr_relay = Some(pkarr_relay);\n self\n }\n```"}], "func_name": "pkarr_relay", "docstring": "Sets the pkarr relay URL to use.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr/dht.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr/dht.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca042defeaa1f67e7b5cd00d1f95af8baa433802de7fe03e6e902e8697ad0b5f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: n0_dns_pkarr_relay\n\nDocumentation:\nUses the default [number 0] pkarr relay URL.\n\n[number 0]: https://n0.computer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn n0_dns_pkarr_relay(mut self) -> Self {\n self.pkarr_relay = Some(N0_DNS_PKARR_RELAY_PROD.parse().expect(\"valid URL\"));\n self\n }\n```"}], "func_name": "n0_dns_pkarr_relay", "docstring": "Uses the default [number 0] pkarr relay URL.\n\n[number 0]: https://n0.computer", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr/dht.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr/dht.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3e694b76d8ca4f896bbb6539e5a977cbbaf5d39ce31081a3a1992a8e373f3b1b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: dht\n\nDocumentation:\nSets whether to publish to the Mainline DHT.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn dht(mut self, dht: bool) -> Self {\n self.dht = dht;\n self\n }\n```"}], "func_name": "dht", "docstring": "Sets whether to publish to the Mainline DHT.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr/dht.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr/dht.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dfd8e923dc871edab1a86dba02a46394fa0e3314f4beacb33840be4bc46da48a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: include_direct_addresses\n\nDocumentation:\nSets whether to include the direct addresses in the DNS packet.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn include_direct_addresses(mut self, include_direct_addresses: bool) -> Self {\n self.include_direct_addresses = include_direct_addresses;\n self\n }\n```"}], "func_name": "include_direct_addresses", "docstring": "Sets whether to include the direct addresses in the DNS packet.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr/dht.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr/dht.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a4c055498940992b34f8a2b0f91e8e9ef9ff09102c37fffa6f483706ba6182a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: initial_publish_delay\n\nDocumentation:\nSets the initial delay before the first publish.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn initial_publish_delay(mut self, initial_publish_delay: Duration) -> Self {\n self.initial_publish_delay = initial_publish_delay;\n self\n }\n```"}], "func_name": "initial_publish_delay", "docstring": "Sets the initial delay before the first publish.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr/dht.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr/dht.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "808c28fa7fa1bc98535ddd263e8549d2c517a907f0bb047c5ffa6245e59780e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: republish_delay\n\nDocumentation:\nSets the republish delay for the DHT.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn republish_delay(mut self, republish_delay: Duration) -> Self {\n self.republish_delay = republish_delay;\n self\n }\n```"}], "func_name": "republish_delay", "docstring": "Sets the republish delay for the DHT.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr/dht.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr/dht.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "92f0d903b8a82f31f71e2eb41db5236150ac5cee2de81cd83a048872c42805c8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: publish_loop\n\nDocumentation:\nPeriodically publishes the node address to the DHT and/or relay.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn publish_loop(self, keypair: SecretKey, signed_packet: SignedPacket) {\n let this = self;\n let z32 = pkarr::PublicKey::try_from(keypair.public().as_bytes())\n .expect(\"valid public key\")\n .to_z32();\n // initial delay. If the task gets aborted before this delay is over,\n // we have not published anything to the DHT yet.\n time::sleep(this.0.initial_publish_delay).await;\n loop {\n // TODO: publish takes a compare-and-swap timestamp, make use of that.\n let res = this.0.pkarr.publish(&signed_packet, None).await;\n match res {\n Ok(()) => {\n tracing::debug!(\"pkarr publish success. published under {z32}\",);\n }\n Err(e) => {\n // we could do a smaller delay here, but in general DHT publish\n // not working is due to a network issue, and if the network changes\n // the task will be restarted anyway.\n //\n // Being unable to publish to the DHT is something that is expected\n // to happen from time to time, so this does not warrant a error log.\n tracing::warn!(\"pkarr publish error: {}\", e);\n }\n }\n time::sleep(this.0.republish_delay).await;\n }\n }\n```"}], "func_name": "publish_loop", "docstring": "Periodically publishes the node address to the DHT and/or relay.", "repo": "n0-computer/iroh", "path": "iroh/src/discovery/pkarr/dht.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/discovery/pkarr/dht.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "de6dd57a22e8a61c981c4ac8aeca0e27502be1e1c61f3f190117c806026739b9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: poll_next\n\nDocumentation:\nPerforms the congestion controller reset for a magic socket path change.\n\nRegardless of which kind of path we are changed to, the congestion controller needs\nresetting. Even when switching to mixed we should reset the state as e.g. switching\nfrom direct to mixed back to direct should be a rare exception and is a bug if this\nhappens commonly.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn poll_next(\n mut self: Pin<&mut Self>,\n cx: &mut std::task::Context<'_>,\n ) -> Poll> {\n match Pin::new(&mut self.stream).poll_next(cx) {\n Poll::Ready(Some(new_conn_type)) => {\n let mut became_direct = false;\n if self.connection.network_path_changed() {\n debug!(\n node_id = %self.node_id.fmt_short(),\n new_type = ?new_conn_type,\n \"Congestion controller state reset\",\n );\n if !self.was_direct_before && matches!(new_conn_type, ConnectionType::Direct(_))\n {\n self.was_direct_before = true;\n became_direct = true\n }\n };\n Poll::Ready(Some(ConnectionEvent { became_direct }))\n }\n Poll::Ready(None) => Poll::Ready(None),\n Poll::Pending => Poll::Pending,\n }\n }\n```"}], "func_name": "poll_next", "docstring": "Performs the congestion controller reset for a magic socket path change.\n\nRegardless of which kind of path we are changed to, the congestion controller needs\nresetting. Even when switching to mixed we should reset the state as e.g. switching\nfrom direct to mixed back to direct should be a rare exception and is a bug if this\nhappens commonly.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint/rtt_actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint/rtt_actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8f24362bae7dde4f4f602aa831e333de18ff2aa626e42267dbcf5a98ab61429e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nRuns the actor main loop.\n\nThe main loop will finish when the sender is dropped.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run(&mut self, mut msg_rx: mpsc::Receiver) {\n loop {\n tokio::select! {\n biased;\n msg = msg_rx.recv() => {\n match msg {\n Some(msg) => self.handle_msg(msg),\n None => break,\n }\n }\n event = self.connection_events.next(), if !self.connection_events.is_empty() => {\n if event.map(|e| e.became_direct).unwrap_or(false) {\n self.metrics.connection_became_direct.inc();\n }\n }\n }\n }\n debug!(\"rtt-actor finished\");\n }\n```"}], "func_name": "run", "docstring": "Runs the actor main loop.\n\nThe main loop will finish when the sender is dropped.", "repo": "n0-computer/iroh", "path": "iroh/src/endpoint/rtt_actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/endpoint/rtt_actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e6084d55c2bad04a2c6213e20887f5cad3b19b2ada5b59c1ee22a5d6250c423"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_from_vec\n\nDocumentation:\nCreate a new [`NodeMap`] from a list of [`NodeAddr`]s.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn load_from_vec(nodes: Vec, metrics: &Metrics) -> Self {\n Self::from_inner(NodeMapInner::load_from_vec(nodes, metrics))\n }\n```"}], "func_name": "load_from_vec", "docstring": "Create a new [`NodeMap`] from a list of [`NodeAddr`]s.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "10c864a5eb6fbf71c6587bc44b7000c5009ca15619e94cffb17edcc41c2c5fc3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_node_addr\n\nDocumentation:\nAdd the contact information for a node.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn add_node_addr(&self, node_addr: NodeAddr, source: Source, metrics: &Metrics) {\n self.inner\n .lock()\n .expect(\"poisoned\")\n .add_node_addr(node_addr, source, metrics)\n }\n```"}], "func_name": "add_node_addr", "docstring": "Add the contact information for a node.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "730baca1e5a3547128b52c4fd57def3fe3307fec0f416db1757af55cbff71088"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_ping\n\nDocumentation:\nInsert a received ping into the node map, and return whether a ping with this tx_id was already\nreceived.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn handle_ping(\n &self,\n sender: PublicKey,\n src: SendAddr,\n tx_id: TransactionId,\n ) -> PingHandled {\n self.inner\n .lock()\n .expect(\"poisoned\")\n .handle_ping(sender, src, tx_id)\n }\n```"}], "func_name": "handle_ping", "docstring": "Insert a received ping into the node map, and return whether a ping with this tx_id was already\nreceived.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "150d2707061255ac9e3ece3c7c95f7a433b9bc18c4536a29b4bbdbedfa8cd47a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: list_remote_infos\n\nDocumentation:\nReturns the [`RemoteInfo`]s for each node in the node map.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn list_remote_infos(&self, now: Instant) -> Vec {\n // NOTE: calls to this method will often call `into_iter` (or similar methods). Note that\n // we can't avoid `collect` here since it would hold a lock for an indefinite time. Even if\n // we were to find this acceptable, dealing with the lifetimes of the mutex's guard and the\n // internal iterator will be a hassle, if possible at all.\n self.inner\n .lock()\n .expect(\"poisoned\")\n .remote_infos_iter(now)\n .collect()\n }\n```"}], "func_name": "list_remote_infos", "docstring": "Returns the [`RemoteInfo`]s for each node in the node map.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "89a2648a0bd571bd376143937572846e2a8441826da1072a1b1ac23c24e34a47"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: on_direct_addr_discovered\n\nDocumentation:\nPrunes direct addresses from nodes that claim to share an address we know points to us.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn on_direct_addr_discovered(&mut self, discovered: BTreeSet) {\n for addr in discovered {\n self.remove_by_ipp(addr.into(), ClearReason::MatchesOurLocalAddr)\n }\n }\n```"}], "func_name": "on_direct_addr_discovered", "docstring": "Prunes direct addresses from nodes that claim to share an address we know points to us.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8e70c2ef38b2efde1a7075529c751d65da2998334f450aaf282df96618d09207"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remote_infos_iter\n\nDocumentation:\nGet the [`RemoteInfo`]s for all nodes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn remote_infos_iter(&self, now: Instant) -> impl Iterator + '_ {\n self.node_states().map(move |(_, ep)| ep.info(now))\n }\n```"}], "func_name": "remote_infos_iter", "docstring": "Get the [`RemoteInfo`]s for all nodes.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d917c22ca7bf18155c0f830201f158c39dfd03cffaf71d2d3f0bc5d6504a21f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remote_info\n\nDocumentation:\nGet the [`RemoteInfo`]s for each node.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn remote_info(&self, node_id: NodeId) -> Option {\n self.get(NodeStateKey::NodeId(node_id))\n .map(|ep| ep.info(Instant::now()))\n }\n```"}], "func_name": "remote_info", "docstring": "Get the [`RemoteInfo`]s for each node.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bcbc7c64d90b7141b2e40e28b04c20de94cb7c970274d4940510cbae67ee5218"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: conn_type\n\nDocumentation:\nReturns a stream of [`ConnectionType`].\n\nSends the current [`ConnectionType`] whenever any changes to the\nconnection type for `public_key` has occurred.\n\n# Errors\n\nWill return `None` if there is not an entry in the [`NodeMap`] for\nthe `public_key`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn conn_type(&self, node_id: NodeId) -> Option> {\n self.get(NodeStateKey::NodeId(node_id))\n .map(|ep| ep.conn_type())\n }\n```"}], "func_name": "conn_type", "docstring": "Returns a stream of [`ConnectionType`].\n\nSends the current [`ConnectionType`] whenever any changes to the\nconnection type for `public_key` has occurred.\n\n# Errors\n\nWill return `None` if there is not an entry in the [`NodeMap`] for\nthe `public_key`", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c8c2b39b9c350d4ac703be4735bb1c447b776f8e62aa7e66229480ce8aadb9b9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert_node\n\nDocumentation:\nInserts a new node into the [`NodeMap`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn insert_node(&mut self, options: Options) -> &mut NodeState {\n info!(\n node = %options.node_id.fmt_short(),\n relay_url = ?options.relay_url,\n source = %options.source,\n \"inserting new node in NodeMap\",\n );\n let id = self.next_id;\n self.next_id = self.next_id.wrapping_add(1);\n let node_state = NodeState::new(id, options);\n\n // update indices\n self.by_quic_mapped_addr\n .insert(*node_state.quic_mapped_addr(), id);\n self.by_node_key.insert(*node_state.public_key(), id);\n\n self.by_id.insert(id, node_state);\n self.by_id.get_mut(&id).expect(\"just inserted\")\n }\n```"}], "func_name": "insert_node", "docstring": "Inserts a new node into the [`NodeMap`].", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6aff3a7f95bc2e74b86d0c8a817a0cfee008ca3606f84f587841182cd01fc1e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_node_key_for_ip_port\n\nDocumentation:\nMakes future node lookups by ipp return the same endpoint as a lookup by nk.\n\nThis should only be called with a fully verified mapping of ipp to\nnk, because calling this function defines the endpoint we hand to\nWireGuard for packets received from ipp.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn set_node_key_for_ip_port(&mut self, ipp: impl Into, nk: &PublicKey) {\n let ipp = ipp.into();\n if let Some(id) = self.by_ip_port.get(&ipp) {\n if !self.by_node_key.contains_key(nk) {\n self.by_node_key.insert(*nk, *id);\n }\n self.by_ip_port.remove(&ipp);\n }\n if let Some(id) = self.by_node_key.get(nk) {\n trace!(\"insert ip -> id: {:?} -> {}\", ipp, id);\n self.by_ip_port.insert(ipp, *id);\n }\n }\n```"}], "func_name": "set_node_key_for_ip_port", "docstring": "Makes future node lookups by ipp return the same endpoint as a lookup by nk.\n\nThis should only be called with a fully verified mapping of ipp to\nnk, because calling this function defines the endpoint we hand to\nWireGuard for packets received from ipp.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e31fe4eed4c6a141e267fdb93356a0ef3fb1248d48605c5ea7e59cc0a46a65df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prune_inactive\n\nDocumentation:\nPrunes nodes without recent activity so that at most [`MAX_INACTIVE_NODES`] are kept.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn prune_inactive(&mut self) {\n let now = Instant::now();\n let mut prune_candidates: Vec<_> = self\n .by_id\n .values()\n .filter(|node| !node.is_active(&now))\n .map(|node| (*node.public_key(), node.last_used()))\n .collect();\n\n let prune_count = prune_candidates.len().saturating_sub(MAX_INACTIVE_NODES);\n if prune_count == 0 {\n // within limits\n return;\n }\n\n prune_candidates.sort_unstable_by_key(|(_pk, last_used)| *last_used);\n prune_candidates.truncate(prune_count);\n for (public_key, last_used) in prune_candidates.into_iter() {\n let node = public_key.fmt_short();\n match last_used.map(|instant| instant.elapsed()) {\n Some(last_used) => trace!(%node, ?last_used, \"pruning inactive\"),\n None => trace!(%node, last_used=%\"never\", \"pruning inactive\"),\n }\n\n let Some(id) = self.by_node_key.remove(&public_key) else {\n debug_assert!(false, \"missing by_node_key entry for pk in by_id\");\n continue;\n };\n\n let Some(ep) = self.by_id.remove(&id) else {\n debug_assert!(false, \"missing by_id entry for id in by_node_key\");\n continue;\n };\n\n for ip_port in ep.direct_addresses() {\n self.by_ip_port.remove(&ip_port);\n }\n\n self.by_quic_mapped_addr.remove(ep.quic_mapped_addr());\n }\n }\n```"}], "func_name": "prune_inactive", "docstring": "Prunes nodes without recent activity so that at most [`MAX_INACTIVE_NODES`] are kept.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f64bfe94a63e170772ff8e732496646927075c865a181b410b5f721aa741204"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: inner_poll_recv\n\nDocumentation:\nTries to recv data, on all available transports.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn inner_poll_recv(\n &mut self,\n cx: &mut Context,\n bufs: &mut [IoSliceMut<'_>],\n metas: &mut [quinn_udp::RecvMeta],\n source_addrs: &mut [Addr],\n ) -> Poll> {\n debug_assert_eq!(bufs.len(), metas.len(), \"non matching bufs & metas\");\n\n macro_rules! poll_transport {\n ($socket:expr) => {\n match $socket.poll_recv(cx, bufs, metas, source_addrs)? {\n Poll::Pending | Poll::Ready(0) => {}\n Poll::Ready(n) => {\n return Poll::Ready(Ok(n));\n }\n }\n };\n }\n\n // To improve fairness, every other call reverses the ordering of polling.\n\n let counter = self\n .poll_recv_counter\n .fetch_add(1, std::sync::atomic::Ordering::Relaxed);\n\n if counter % 2 == 0 {\n #[cfg(not(wasm_browser))]\n for transport in &mut self.ip {\n poll_transport!(transport);\n }\n for transport in &mut self.relay {\n poll_transport!(transport);\n }\n } else {\n for transport in self.relay.iter_mut().rev() {\n poll_transport!(transport);\n }\n #[cfg(not(wasm_browser))]\n for transport in self.ip.iter_mut().rev() {\n poll_transport!(transport);\n }\n }\n\n Poll::Pending\n }\n```"}], "func_name": "inner_poll_recv", "docstring": "Tries to recv data, on all available transports.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3acc24671bc64e9bce9db1a55ca0332f89e622af3a725dabd3f2358e8500937f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: local_addrs\n\nDocumentation:\nReturns a list of all currently known local addresses.\n\nFor IP based transports this is the [`SocketAddr`] of the socket,\nfor relay transports, this is the home relay.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn local_addrs(&self) -> Vec {\n self.local_addrs_watch().get().expect(\"not disconnected\")\n }\n```"}], "func_name": "local_addrs", "docstring": "Returns a list of all currently known local addresses.\n\nFor IP based transports this is the [`SocketAddr`] of the socket,\nfor relay transports, this is the home relay.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69fe7895af8c8fa385a8fd78b936c2bfd4e3aa1b5ce33cb168db1c4d3a42a557"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: create_network_change_sender\n\nDocumentation:\nHandles potential changes to the underlying network conditions.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn create_network_change_sender(&self) -> NetworkChangeSender {\n NetworkChangeSender {\n #[cfg(not(wasm_browser))]\n ip: self\n .ip\n .iter()\n .map(|t| t.create_network_change_sender())\n .collect(),\n relay: self\n .relay\n .iter()\n .map(|t| t.create_network_change_sender())\n .collect(),\n }\n }\n```"}], "func_name": "create_network_change_sender", "docstring": "Handles potential changes to the underlying network conditions.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a9839a292b50b3957670e951a220c143b70b3307c820f987f420c458be528b4c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_socket_addr\n\nDocumentation:\nReturns `None` if not an `Ip`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn into_socket_addr(self) -> Option {\n match self {\n Self::Ip(ip) => Some(ip),\n Self::Relay(..) => None,\n }\n }\n```"}], "func_name": "into_socket_addr", "docstring": "Returns `None` if not an `Ip`.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b8d99773d2a36392c073ccc190206f8ae9241e13c3ef1d32921a367fbe83590"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clear_if_equals\n\nDocumentation:\nClears the best address if equal to `addr`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clear_if_equals(&mut self, addr: SocketAddr, reason: ClearReason, has_relay: bool) {\n if self.addr() == Some(addr) {\n self.clear(reason, has_relay)\n }\n }\n```"}], "func_name": "clear_if_equals", "docstring": "Clears the best address if equal to `addr`.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/best_addr.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/best_addr.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d97892d052b92a4a0772bfc3243c33969dbd91f91f63cf0008a65b578191146f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_better_than\n\nDocumentation:\nReports whether `self` is a better addr to use than `other`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_better_than(&self, other: &Self) -> bool {\n if self.addr == other.addr {\n return false;\n }\n if self.addr.is_ipv6() && other.addr.is_ipv4() {\n // Prefer IPv6 for being a bit more robust, as long as\n // the latencies are roughly equivalent.\n if self.latency / 10 * 9 < other.latency {\n return true;\n }\n } else if self.addr.is_ipv4() && other.addr.is_ipv6() && other.is_better_than(self) {\n return false;\n }\n self.latency < other.latency\n }\n```"}], "func_name": "is_better_than", "docstring": "Reports whether `self` is a better addr to use than `other`.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/best_addr.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/best_addr.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "58a88c99b5cb09f3992ab738eb70690de63a8a363c57b31e00418fcae1038d20"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: relay_url\n\nDocumentation:\nReturns the relay url of this endpoint\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn relay_url(&self) -> Option {\n self.relay_url.as_ref().map(|(url, _state)| url.clone())\n }\n```"}], "func_name": "relay_url", "docstring": "Returns the relay url of this endpoint", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/node_state.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/node_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e1e5dcde7fb599126a3b3e68674dcb613c56238fd0bbffb4c24fa5c74e429204"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: addr_for_send\n\nDocumentation:\nReturns the address(es) that should be used for sending the next packet.\n\nThis may return to send on one, both or no paths.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn addr_for_send(\n &mut self,\n now: &Instant,\n have_ipv6: bool,\n metrics: &MagicsockMetrics,\n ) -> (Option, Option) {\n #[cfg(any(test, feature = \"test-utils\"))]\n if self.path_selection == PathSelection::RelayOnly {\n debug!(\"in `RelayOnly` mode, giving the relay address as the only viable address for this endpoint\");\n return (None, self.relay_url());\n }\n let (best_addr, relay_url) = match self.udp_paths.send_addr(*now, have_ipv6) {\n UdpSendAddr::Valid(addr) => {\n // If we have a valid address we use it.\n trace!(%addr, \"UdpSendAddr is valid, use it\");\n (Some(addr), None)\n }\n UdpSendAddr::Outdated(addr) => {\n // If the address is outdated we use it, but send via relay at the same time.\n // We also send disco pings so that it will become valid again if it still\n // works (i.e. we don't need to holepunch again).\n trace!(%addr, \"UdpSendAddr is outdated, use it together with relay\");\n (Some(addr), self.relay_url())\n }\n UdpSendAddr::Unconfirmed(addr) => {\n trace!(%addr, \"UdpSendAddr is unconfirmed, use it together with relay\");\n (Some(addr), self.relay_url())\n }\n UdpSendAddr::None => {\n trace!(\"No UdpSendAddr, use relay\");\n (None, self.relay_url())\n }\n };\n let typ = match (best_addr, relay_url.clone()) {\n (Some(best_addr), Some(relay_url)) => ConnectionType::Mixed(best_addr, relay_url),\n (Some(best_addr), None) => ConnectionType::Direct(best_addr),\n (None, Some(relay_url)) => ConnectionType::Relay(relay_url),\n (None, None) => ConnectionType::None,\n };\n if !self.has_been_direct && matches!(&typ, ConnectionType::Direct(_)) {\n self.has_been_direct = true;\n metrics.nodes_contacted_directly.inc();\n }\n if let Ok(prev_typ) = self.conn_type.set(typ.clone()) {\n // The connection type has changed.\n event!(\n target: \"iroh::_events::conn_type::changed\",\n Level::DEBUG,\n remote_node = %self.node_id.fmt_short(),\n conn_type = ?typ,\n );\n info!(%typ, \"new connection type\");\n\n // Update some metrics\n match (prev_typ, typ) {\n (ConnectionType::Relay(_), ConnectionType::Direct(_))\n | (ConnectionType::Mixed(_, _), ConnectionType::Direct(_)) => {\n metrics.num_direct_conns_added.inc();\n metrics.num_relay_conns_removed.inc();\n }\n (ConnectionType::Direct(_), ConnectionType::Relay(_))\n | (ConnectionType::Direct(_), ConnectionType::Mixed(_, _)) => {\n metrics.num_direct_conns_removed.inc();\n metrics.num_relay_conns_added.inc();\n }\n (ConnectionType::None, ConnectionType::Direct(_)) => {\n metrics.num_direct_conns_added.inc();\n }\n (ConnectionType::Direct(_), ConnectionType::None) => {\n metrics.num_direct_conns_removed.inc();\n }\n (ConnectionType::None, ConnectionType::Relay(_))\n | (ConnectionType::None, ConnectionType::Mixed(_, _)) => {\n metrics.num_relay_conns_added.inc();\n }\n (ConnectionType::Relay(_), ConnectionType::None)\n | (ConnectionType::Mixed(_, _), ConnectionType::None) => {\n metrics.num_relay_conns_removed.inc();\n }\n _ => (),\n }\n }\n (best_addr, relay_url)\n }\n```"}], "func_name": "addr_for_send", "docstring": "Returns the address(es) that should be used for sending the next packet.\n\nThis may return to send on one, both or no paths.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/node_state.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/node_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "790470890757062469ea1698efa12839708cf9a698f3f6a516abf5df9d0e0e7b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove_direct_addr\n\nDocumentation:\nRemoves a direct address for this node.\n\nIf this is also the best address, it will be cleared as well.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn remove_direct_addr(&mut self, ip_port: &IpPort, reason: ClearReason) {\n let Some(state) = self.udp_paths.paths.remove(ip_port) else {\n return;\n };\n\n match state.last_alive().map(|instant| instant.elapsed()) {\n Some(last_alive) => debug!(%ip_port, ?last_alive, ?reason, \"pruning address\"),\n None => debug!(%ip_port, last_seen=%\"never\", ?reason, \"pruning address\"),\n }\n\n self.udp_paths.best_addr.clear_if_equals(\n (*ip_port).into(),\n reason,\n self.relay_url.is_some(),\n );\n }\n```"}], "func_name": "remove_direct_addr", "docstring": "Removes a direct address for this node.\n\nIf this is also the best address, it will be cleared as well.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/node_state.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/node_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dfc1ff0768d85eaec617218086ea06c0be355f58b52afc75688b4ba82ae2b8ae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ping_sent\n\nDocumentation:\nRecord the fact that a ping has been sent out.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn ping_sent(\n &mut self,\n to: SendAddr,\n tx_id: stun::TransactionId,\n purpose: DiscoPingPurpose,\n sender: mpsc::Sender,\n ) {\n trace!(%to, tx = %HEXLOWER.encode(&tx_id), ?purpose, \"record ping sent\");\n\n let now = Instant::now();\n let mut path_found = false;\n match to {\n SendAddr::Udp(addr) => {\n if let Some(st) = self.udp_paths.paths.get_mut(&addr.into()) {\n st.last_ping.replace(now);\n path_found = true\n }\n }\n SendAddr::Relay(ref url) => {\n if let Some((home_relay, relay_state)) = self.relay_url.as_mut() {\n if home_relay == url {\n relay_state.last_ping.replace(now);\n path_found = true\n }\n }\n }\n }\n if !path_found {\n // Shouldn't happen. But don't ping an endpoint that's not active for us.\n warn!(%to, ?purpose, \"unexpected attempt to ping no longer live path\");\n return;\n }\n\n let id = self.id;\n let _expiry_task = AbortOnDropHandle::new(task::spawn(async move {\n time::sleep(PING_TIMEOUT_DURATION).await;\n sender\n .send(ActorMessage::EndpointPingExpired(id, tx_id))\n .await\n .ok();\n }));\n self.sent_pings.insert(\n tx_id,\n SentPing {\n to,\n at: now,\n purpose,\n _expiry_task,\n },\n );\n }\n```"}], "func_name": "ping_sent", "docstring": "Record the fact that a ping has been sent out.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/node_state.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/node_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "231b01f4145e5c9994e20579d3f60afb02df2f76902aaa53e2400620a981ae0a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_ping\n\nDocumentation:\nHandle a received Disco Ping.\n\n- Ensures the paths the ping was received on is a known path for this endpoint.\n\n- If there is no best_addr for this endpoint yet, sends a ping itself to try and\nestablish one.\n\nThis is called once we've already verified that we got a valid discovery message\nfrom `self` via ep.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn handle_ping(\n &mut self,\n path: SendAddr,\n tx_id: stun::TransactionId,\n ) -> PingHandled {\n let now = Instant::now();\n\n let role = match path {\n SendAddr::Udp(addr) => match self.udp_paths.paths.entry(addr.into()) {\n Entry::Occupied(mut occupied) => occupied.get_mut().handle_ping(tx_id, now),\n Entry::Vacant(vacant) => {\n info!(%addr, \"new direct addr for node\");\n vacant.insert(PathState::with_ping(\n self.node_id,\n path.clone(),\n tx_id,\n Source::Udp,\n now,\n ));\n PingRole::NewPath\n }\n },\n SendAddr::Relay(ref url) => {\n match self.relay_url.as_mut() {\n Some((home_url, _state)) if home_url != url => {\n // either the node changed relays or we didn't have a relay address for the\n // node. In both cases, trust the new confirmed url\n info!(%url, \"new relay addr for node\");\n self.relay_url = Some((\n url.clone(),\n PathState::with_ping(\n self.node_id,\n path.clone(),\n tx_id,\n Source::Relay,\n now,\n ),\n ));\n PingRole::NewPath\n }\n Some((_home_url, state)) => state.handle_ping(tx_id, now),\n None => {\n info!(%url, \"new relay addr for node\");\n self.relay_url = Some((\n url.clone(),\n PathState::with_ping(\n self.node_id,\n path.clone(),\n tx_id,\n Source::Relay,\n now,\n ),\n ));\n PingRole::NewPath\n }\n }\n }\n };\n event!(\n target: \"iroh::_events::ping::recv\",\n Level::DEBUG,\n remote_node = %self.node_id.fmt_short(),\n src = ?path,\n txn = ?tx_id,\n ?role,\n );\n\n if matches!(path, SendAddr::Udp(_)) && matches!(role, PingRole::NewPath) {\n self.prune_direct_addresses();\n }\n\n // if the endpoint does not yet have a best_addrr\n let needs_ping_back = if matches!(path, SendAddr::Udp(_))\n && matches!(\n self.udp_paths.best_addr.state(now),\n best_addr::State::Empty | best_addr::State::Outdated(_)\n ) {\n // We also need to send a ping to make this path available to us as well. This\n // is always sent together with a pong. So in the worst case the pong gets lost\n // and this ping does not. In that case we ping-pong until both sides have\n // received at least one pong. Once both sides have received one pong they both\n // have a best_addr and this ping will stop being sent.\n self.start_ping(path, DiscoPingPurpose::PingBack)\n } else {\n None\n };\n\n debug!(\n ?role,\n needs_ping_back = ?needs_ping_back.is_some(),\n paths = %summarize_node_paths(&self.udp_paths.paths),\n \"endpoint handled ping\",\n );\n PingHandled {\n role,\n needs_ping_back,\n }\n }\n```"}], "func_name": "handle_ping", "docstring": "Handle a received Disco Ping.\n\n- Ensures the paths the ping was received on is a known path for this endpoint.\n\n- If there is no best_addr for this endpoint yet, sends a ping itself to try and\nestablish one.\n\nThis is called once we've already verified that we got a valid discovery message\nfrom `self` via ep.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/node_state.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/node_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0aaa3e394952ddd39e5cbdaf1c079d8a0188e90c51b452d5a55d62a42d02ac44"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prune_direct_addresses\n\nDocumentation:\nPrune inactive paths.\n\nThis trims the list of inactive paths for an endpoint. At most\n[`MAX_INACTIVE_DIRECT_ADDRESSES`] are kept.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn prune_direct_addresses(&mut self) {\n // prune candidates are addresses that are not active\n let mut prune_candidates: Vec<_> = self\n .udp_paths\n .paths\n .iter()\n .filter(|(_ip_port, state)| !state.is_active())\n .map(|(ip_port, state)| (*ip_port, state.last_alive()))\n .filter(|(_ipp, last_alive)| match last_alive {\n Some(last_seen) => last_seen.elapsed() > LAST_ALIVE_PRUNE_DURATION,\n None => true,\n })\n .collect();\n let prune_count = prune_candidates\n .len()\n .saturating_sub(MAX_INACTIVE_DIRECT_ADDRESSES);\n if prune_count == 0 {\n // nothing to do, within limits\n debug!(\n paths = %summarize_node_paths(&self.udp_paths.paths),\n \"prune addresses: {prune_count} pruned\",\n );\n return;\n }\n\n // sort leaving the worst addresses first (never contacted) and better ones (most recently\n // used ones) last\n prune_candidates.sort_unstable_by_key(|(_ip_port, last_alive)| *last_alive);\n prune_candidates.truncate(prune_count);\n for (ip_port, _last_alive) in prune_candidates.into_iter() {\n self.remove_direct_addr(&ip_port, ClearReason::Inactive)\n }\n debug!(\n paths = %summarize_node_paths(&self.udp_paths.paths),\n \"prune addresses: {prune_count} pruned\",\n );\n }\n```"}], "func_name": "prune_direct_addresses", "docstring": "Prune inactive paths.\n\nThis trims the list of inactive paths for an endpoint. At most\n[`MAX_INACTIVE_DIRECT_ADDRESSES`] are kept.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/node_state.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/node_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0f97ee2ea41daf26bf309ccc87c0a3a966d8efcecd955bc657b4259741df95d6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_call_me_maybe\n\nDocumentation:\nHandles a DISCO CallMeMaybe discovery message.\n\nThe contract for use of this message is that the node has already pinged to us via\nUDP, so their stateful firewall should be open. Now we can Ping back and make it\nthrough.\n\nHowever if the remote side has no direct path information to us, they would not have\nhad any [`IpPort`]s to send pings to and our pings might end up blocked. But at\nleast open the firewalls on our side, giving the other side another change of making\nit through when it pings in response.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn handle_call_me_maybe(&mut self, m: disco::CallMeMaybe) -> Vec {\n let now = Instant::now();\n let mut call_me_maybe_ipps = BTreeSet::new();\n\n for peer_sockaddr in &m.my_numbers {\n if let IpAddr::V6(ip) = peer_sockaddr.ip() {\n if netwatch::ip::is_unicast_link_local(ip) {\n // We send these out, but ignore them for now.\n // TODO: teach the ping code to ping on all interfaces for these.\n continue;\n }\n }\n let ipp = IpPort::from(*peer_sockaddr);\n call_me_maybe_ipps.insert(ipp);\n self.udp_paths\n .paths\n .entry(ipp)\n .or_insert_with(|| {\n PathState::new(\n self.node_id,\n SendAddr::from(*peer_sockaddr),\n Source::Relay,\n now,\n )\n })\n .call_me_maybe_time\n .replace(now);\n }\n\n // Zero out all the last_ping times to force send_pings to send new ones, even if\n // it's been less than 5 seconds ago. Also clear pongs for direct addresses not\n // included in the updated set.\n for (ipp, st) in self.udp_paths.paths.iter_mut() {\n st.last_ping = None;\n if !call_me_maybe_ipps.contains(ipp) {\n // TODO: This seems like a weird way to signal that the endpoint no longer\n // thinks it has this IpPort as an available path.\n if st.recent_pong.is_some() {\n debug!(path=?ipp ,\"clearing recent pong\");\n st.recent_pong = None;\n }\n }\n }\n // Clear trust on our best_addr if it is not included in the updated set. Also\n // clear the last call-me-maybe send time so we will send one again.\n if let Some(addr) = self.udp_paths.best_addr.addr() {\n let ipp: IpPort = addr.into();\n if !call_me_maybe_ipps.contains(&ipp) {\n self.udp_paths\n .best_addr\n .clear_trust(\"best_addr not in new call-me-maybe\");\n self.last_call_me_maybe = None;\n }\n }\n debug!(\n paths = %summarize_node_paths(&self.udp_paths.paths),\n \"updated endpoint paths from call-me-maybe\",\n );\n self.send_pings(now)\n }\n```"}], "func_name": "handle_call_me_maybe", "docstring": "Handles a DISCO CallMeMaybe discovery message.\n\nThe contract for use of this message is that the node has already pinged to us via\nUDP, so their stateful firewall should be open. Now we can Ping back and make it\nthrough.\n\nHowever if the remote side has no direct path information to us, they would not have\nhad any [`IpPort`]s to send pings to and our pings might end up blocked. But at\nleast open the firewalls on our side, giving the other side another change of making\nit through when it pings in response.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/node_state.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/node_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b6a053430ba50222672ae19791b1dcae1170b756f767db27c454c41d1f91ae4a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_active\n\nDocumentation:\nChecks if this `Endpoint` is currently actively being used.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn is_active(&self, now: &Instant) -> bool {\n match self.last_used {\n Some(last_active) => now.duration_since(last_active) <= SESSION_ACTIVE_TIMEOUT,\n None => false,\n }\n }\n```"}], "func_name": "is_active", "docstring": "Checks if this `Endpoint` is currently actively being used.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/node_state.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/node_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a741f3f9d188dd3af71d1fbd312a69b1aaea0ac2305d9ffe4c5c0fde3c216f6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_active\n\nDocumentation:\nCheck whether this path is considered active.\n\nActive means the path has received payload messages within the last\n[`SESSION_ACTIVE_TIMEOUT`].\n\nNote that a path might be alive but not active if it's contactable but not in\nuse.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn is_active(&self) -> bool {\n self.last_payload_msg\n .as_ref()\n .map(|instant| instant.elapsed() <= SESSION_ACTIVE_TIMEOUT)\n .unwrap_or(false)\n }\n```"}], "func_name": "is_active", "docstring": "Check whether this path is considered active.\n\nActive means the path has received payload messages within the last\n[`SESSION_ACTIVE_TIMEOUT`].\n\nNote that a path might be alive but not active if it's contactable but not in\nuse.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/path_state.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/path_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f75e3f87af83e4ad540754874ced8de7ff877a6459158fe3ca4ee475cd60cd48"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: last_incoming_ping\n\nDocumentation:\nReturns the instant the last incoming ping was received.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn last_incoming_ping(&self) -> Option<&Instant> {\n self.last_got_ping.as_ref().map(|(time, _tx_id)| time)\n }\n```"}], "func_name": "last_incoming_ping", "docstring": "Returns the instant the last incoming ping was received.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/path_state.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/path_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ce354e979c9d7be062945cc893d34e33db9f221b90e442a00e40f545590c5fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: last_alive\n\nDocumentation:\nReports the last instant this path was considered alive.\n\nAlive means the path is considered in use by the remote endpoint. Either because we\nreceived a payload message, a DISCO message (ping, pong) or it was advertised in a\ncall-me-maybe message.\n\nThis is the most recent instant between:\n- when last pong was received.\n- when this path was last advertised in a received CallMeMaybe message.\n- When the last payload transmission occurred.\n- when the last ping from them was received.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn last_alive(&self) -> Option {\n self.recent_pong\n .as_ref()\n .map(|pong| &pong.pong_at)\n .into_iter()\n .chain(self.last_payload_msg.as_ref())\n .chain(self.call_me_maybe_time.as_ref())\n .chain(self.last_incoming_ping())\n .max()\n .copied()\n }\n```"}], "func_name": "last_alive", "docstring": "Reports the last instant this path was considered alive.\n\nAlive means the path is considered in use by the remote endpoint. Either because we\nreceived a payload message, a DISCO message (ping, pong) or it was advertised in a\ncall-me-maybe message.\n\nThis is the most recent instant between:\n- when last pong was received.\n- when this path was last advertised in a received CallMeMaybe message.\n- When the last payload transmission occurred.\n- when the last ping from them was received.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/path_state.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/path_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "888c6cd0f35e2b13f7c8733d1cfa261f4994645d2c19a04804ce50564c9f1a98"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: last_control_msg\n\nDocumentation:\nThe last control or DISCO message **about** this path.\n\nThis is the most recent instant among:\n- when last pong was received.\n- when this path was last advertised in a received CallMeMaybe message.\n- when the last ping from them was received.\n\nReturns the time elapsed since the last control message, and the type of control message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn last_control_msg(&self, now: Instant) -> Option<(Duration, ControlMsg)> {\n // get every control message and assign it its kind\n let last_pong = self\n .recent_pong\n .as_ref()\n .map(|pong| (pong.pong_at, ControlMsg::Pong));\n let last_call_me_maybe = self\n .call_me_maybe_time\n .as_ref()\n .map(|call_me| (*call_me, ControlMsg::CallMeMaybe));\n let last_ping = self\n .last_incoming_ping()\n .map(|ping| (*ping, ControlMsg::Ping));\n\n last_pong\n .into_iter()\n .chain(last_call_me_maybe)\n .chain(last_ping)\n .max_by_key(|(instant, _kind)| *instant)\n .map(|(instant, kind)| (now.duration_since(instant), kind))\n }\n```"}], "func_name": "last_control_msg", "docstring": "The last control or DISCO message **about** this path.\n\nThis is the most recent instant among:\n- when last pong was received.\n- when this path was last advertised in a received CallMeMaybe message.\n- when the last ping from them was received.\n\nReturns the time elapsed since the last control message, and the type of control message.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/path_state.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/path_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "902701c6ee094453523f7e02b114770acdf41b0c1ed4f94647a419037537ae1e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: latency\n\nDocumentation:\nReturns the latency from the most recent pong, if available.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn latency(&self) -> Option {\n self.recent_pong.as_ref().map(|p| p.latency)\n }\n```"}], "func_name": "latency", "docstring": "Returns the latency from the most recent pong, if available.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/path_state.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/path_state.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be46c791da2a40852a87ec7cfdb63c4c8d1008c96b6cf671ab2a96296683af53"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_addr\n\nDocumentation:\nReturns the current UDP address to send on.\n\nTODO: The goal here is for this to simply return the already known send address, so\nit should be `&self` and not `&mut self`. This is only possible once the state from\n[`NodeUdpPaths`] is no longer modified from outside.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn send_addr(&mut self, now: Instant, have_ipv6: bool) -> UdpSendAddr {\n self.assign_best_addr_from_candidates_if_empty();\n match self.best_addr.state(now) {\n best_addr::State::Valid(addr) => UdpSendAddr::Valid(addr.addr),\n best_addr::State::Outdated(addr) => UdpSendAddr::Outdated(addr.addr),\n best_addr::State::Empty => {\n // No direct connection has been used before. If we know of any possible\n // candidate addresses, randomly try to use one. This path is most\n // effective when folks use a NodeAddr with exactly one direct address which\n // they know to work, effectively like using a traditional socket or QUIC\n // endpoint.\n let addr = self\n .chosen_candidate\n .and_then(|ipp| self.paths.get(&ipp))\n .and_then(|path| path.udp_addr())\n .filter(|addr| addr.is_ipv4() || have_ipv6)\n .or_else(|| {\n // Look for a new candidate in all the known paths. This may look\n // like a RNG use on the hot-path but this is normally invoked at\n // most most once at startup.\n let addr = self\n .paths\n .values()\n .filter_map(|path| path.udp_addr())\n .filter(|addr| addr.is_ipv4() || have_ipv6)\n .choose(&mut rand::thread_rng());\n self.chosen_candidate = addr.map(IpPort::from);\n addr\n });\n match addr {\n Some(addr) => UdpSendAddr::Unconfirmed(addr),\n None => UdpSendAddr::None,\n }\n }\n }\n }\n```"}], "func_name": "send_addr", "docstring": "Returns the current UDP address to send on.\n\nTODO: The goal here is for this to simply return the already known send address, so\nit should be `&self` and not `&mut self`. This is only possible once the state from\n[`NodeUdpPaths`] is no longer modified from outside.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/udp_paths.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/udp_paths.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb4e935a24fefd2cc15ccbdb547f97e215cf036b6cf402854abc1aeb9f425de4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: assign_best_addr_from_candidates_if_empty\n\nDocumentation:\nFixup best_addr from candidates.\n\nIf somehow we end up in a state where we failed to set a best_addr, while we do have\nvalid candidates, this will chose a candidate and set best_addr again. Most likely\nthis is a bug elsewhere though.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn assign_best_addr_from_candidates_if_empty(&mut self) {\n if !self.best_addr.is_empty() {\n return;\n }\n\n // The highest acceptable latency for an endpoint path. If the latency is higher\n // then this the path will be ignored.\n const MAX_LATENCY: Duration = Duration::from_secs(60 * 60);\n let best_pong = self.paths.iter().fold(None, |best_pong, (ipp, state)| {\n let best_latency = best_pong\n .map(|p: &PongReply| p.latency)\n .unwrap_or(MAX_LATENCY);\n match state.recent_pong {\n // This pong is better if it has a lower latency, or if it has the same\n // latency but on an IPv6 path.\n Some(ref pong)\n if pong.latency < best_latency\n || (pong.latency == best_latency && ipp.ip().is_ipv6()) =>\n {\n Some(pong)\n }\n _ => best_pong,\n }\n });\n\n // If we found a candidate, set to best addr\n if let Some(pong) = best_pong {\n if let SendAddr::Udp(addr) = pong.from {\n warn!(%addr, \"No best_addr was set, choose candidate with lowest latency\");\n self.best_addr.insert_if_better_or_reconfirm(\n addr,\n pong.latency,\n best_addr::Source::BestCandidate,\n pong.pong_at,\n )\n }\n }\n }\n```"}], "func_name": "assign_best_addr_from_candidates_if_empty", "docstring": "Fixup best_addr from candidates.\n\nIf somehow we end up in a state where we failed to set a best_addr, while we do have\nvalid candidates, this will chose a candidate and set best_addr again. Most likely\nthis is a bug elsewhere though.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/node_map/udp_paths.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/node_map/udp_paths.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2d9fe2604a6b920a1a697982c1677f0d09a398ffe180d88dfe7f4789ac258e86"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run\n\nDocumentation:\nThe main actor run loop.\n\nPrimarily switches between the dialing and connected states.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run(mut self) {\n // TODO(frando): decide what this metric means, it's either wrong here or in node_state.rs.\n // From the existing description, it is wrong here.\n // self.metrics.num_relay_conns_added.inc();\n\n let mut backoff = Self::build_backoff();\n\n while let Err(err) = self.run_once().await {\n warn!(\"{err}\");\n match err {\n RelayConnectionError::Dial { .. } | RelayConnectionError::Handshake { .. } => {\n // If dialing failed, or if the relay connection failed before we received a pong,\n // we wait an exponentially increasing time until we attempt to reconnect again.\n let Some(delay) = backoff.next() else {\n warn!(\"retries exceeded\");\n break;\n };\n debug!(\"retry in {delay:?}\");\n time::sleep(delay).await;\n }\n RelayConnectionError::Established { .. } => {\n // If the relay connection remained established long enough so that we received a pong\n // from the relay server, we reset the backoff and attempt to reconnect immediately.\n backoff = Self::build_backoff();\n }\n }\n }\n debug!(\"exiting\");\n // TODO(frando): decide what this metric means, it's either wrong here or in node_state.rs.\n // From the existing description, it is wrong here.\n // self.metrics.num_relay_conns_removed.inc();\n }\n```"}], "func_name": "run", "docstring": "The main actor run loop.\n\nPrimarily switches between the dialing and connected states.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports/relay/actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports/relay/actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e3408b1ecb0cca8ef2b6bb5ad7407ea8647cb70b71a45e2ffd3e265ff2c261a1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_once\n\nDocumentation:\nAttempt to connect to the relay, and run the connected actor loop.\n\nReturns `Ok(())` if the actor loop should shut down. Returns an error if dialing failed,\nor if the relay connection failed while connected. In both cases, the connection should\nbe retried with a backoff.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_once(&mut self) -> Result<(), RelayConnectionError> {\n let client = match self.run_dialing().instrument(info_span!(\"dialing\")).await {\n Some(client_res) => client_res.context(DialSnafu)?,\n None => return Ok(()),\n };\n self.run_connected(client)\n .instrument(info_span!(\"connected\"))\n .await\n }\n```"}], "func_name": "run_once", "docstring": "Attempt to connect to the relay, and run the connected actor loop.\n\nReturns `Ok(())` if the actor loop should shut down. Returns an error if dialing failed,\nor if the relay connection failed while connected. In both cases, the connection should\nbe retried with a backoff.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports/relay/actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports/relay/actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0a725ad1b007b67b23cd76d115dd53c80023b686d79f48c21cd5ebb0474e0c0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_dialing\n\nDocumentation:\nActor loop when connecting to the relay server.\n\nReturns `None` if the actor needs to shut down. Returns `Some(Ok(client))` when the\nconnection is established, and `Some(Err(err))` if dialing the relay failed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_dialing(&mut self) -> Option> {\n debug!(\"Actor loop: connecting to relay.\");\n\n // We regularly flush the relay_datagrams_send queue so it is not full of stale\n // packets while reconnecting. Those datagrams are dropped and the QUIC congestion\n // controller will have to handle this (DISCO packets do not yet have retry). This\n // is not an ideal mechanism, an alternative approach would be to use\n // e.g. ConcurrentQueue with force_push, though now you might still send very stale\n // packets when eventually connected. So perhaps this is a reasonable compromise.\n let mut send_datagram_flush = time::interval(UNDELIVERABLE_DATAGRAM_TIMEOUT);\n send_datagram_flush.set_missed_tick_behavior(MissedTickBehavior::Delay);\n send_datagram_flush.reset(); // Skip the immediate interval\n\n let dialing_fut = self.dial_relay();\n tokio::pin!(dialing_fut);\n loop {\n tokio::select! {\n biased;\n _ = self.stop_token.cancelled() => {\n debug!(\"Shutdown.\");\n break None;\n }\n msg = self.prio_inbox.recv() => {\n let Some(msg) = msg else {\n warn!(\"Priority inbox closed, shutdown.\");\n break None;\n };\n match msg {\n ActiveRelayPrioMessage::HasNodeRoute(_peer, sender) => {\n sender.send(false).ok();\n }\n }\n }\n res = &mut dialing_fut => {\n match res {\n Ok(client) => {\n break Some(Ok(client));\n }\n Err(err) => {\n break Some(Err(err));\n }\n }\n }\n msg = self.inbox.recv() => {\n let Some(msg) = msg else {\n debug!(\"Inbox closed, shutdown.\");\n break None;\n };\n match msg {\n ActiveRelayMessage::SetHomeRelay(is_home) => {\n self.set_home_relay(is_home);\n }\n ActiveRelayMessage::CheckConnection(_local_ips) => {}\n #[cfg(test)]\n ActiveRelayMessage::GetLocalAddr(sender) => {\n sender.send(None).ok();\n }\n #[cfg(test)]\n ActiveRelayMessage::PingServer(sender) => {\n drop(sender);\n }\n }\n }\n _ = send_datagram_flush.tick() => {\n self.reset_inactive_timeout();\n let mut logged = false;\n while self.relay_datagrams_send.try_recv().is_ok() {\n if !logged {\n debug!(?UNDELIVERABLE_DATAGRAM_TIMEOUT, \"Dropping datagrams to send.\");\n logged = true;\n }\n }\n }\n _ = &mut self.inactive_timeout, if !self.is_home_relay => {\n debug!(?RELAY_INACTIVE_CLEANUP_TIME, \"Inactive, exiting.\");\n break None;\n }\n }\n }\n }\n```"}], "func_name": "run_dialing", "docstring": "Actor loop when connecting to the relay server.\n\nReturns `None` if the actor needs to shut down. Returns `Some(Ok(client))` when the\nconnection is established, and `Some(Err(err))` if dialing the relay failed.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports/relay/actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports/relay/actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cc19c6fd276f6013741f3ed8213217727747b2f72524e531520dc526aee5c9a0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_connected\n\nDocumentation:\nRuns the actor loop when connected to a relay server.\n\nReturns `Ok` if the actor needs to shut down. `Err` is returned if the connection\nto the relay server is lost.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_connected(\n &mut self,\n client: iroh_relay::client::Client,\n ) -> Result<(), RelayConnectionError> {\n debug!(\"Actor loop: connected to relay\");\n event!(\n target: \"iroh::_events::relay::connected\",\n Level::DEBUG,\n url = %self.url,\n home_relay = self.is_home_relay,\n );\n\n let (mut client_stream, client_sink) = client.split();\n let mut client_sink = client_sink.sink_map_err(|e| ClientStreamWriteSnafu.into_error(e));\n\n let mut state = ConnectedRelayState {\n ping_tracker: PingTracker::default(),\n nodes_present: BTreeSet::new(),\n last_packet_src: None,\n pong_pending: None,\n established: false,\n #[cfg(test)]\n test_pong: None,\n };\n\n // A buffer to pass through multiple datagrams at once as an optimisation.\n let mut send_datagrams_buf = Vec::with_capacity(SEND_DATAGRAM_BATCH_SIZE);\n\n // Regularly send pings so we know the connection is healthy.\n // The first ping will be sent immediately.\n let mut ping_interval = time::interval(PING_INTERVAL);\n ping_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);\n\n let res = loop {\n if let Some(data) = state.pong_pending.take() {\n let fut = client_sink.send(SendMessage::Pong(data));\n self.run_sending(fut, &mut state, &mut client_stream)\n .await?;\n }\n tokio::select! {\n biased;\n _ = self.stop_token.cancelled() => {\n debug!(\"Shutdown.\");\n break Ok(());\n }\n msg = self.prio_inbox.recv() => {\n let Some(msg) = msg else {\n warn!(\"Priority inbox closed, shutdown.\");\n break Ok(());\n };\n match msg {\n ActiveRelayPrioMessage::HasNodeRoute(peer, sender) => {\n let has_peer = state.nodes_present.contains(&peer);\n sender.send(has_peer).ok();\n }\n }\n }\n _ = state.ping_tracker.timeout() => {\n break Err(PingTimeoutSnafu.build());\n }\n _ = ping_interval.tick() => {\n let data = state.ping_tracker.new_ping();\n let fut = client_sink.send(SendMessage::Ping(data));\n self.run_sending(fut, &mut state, &mut client_stream).await?;\n }\n msg = self.inbox.recv() => {\n let Some(msg) = msg else {\n warn!(\"Inbox closed, shutdown.\");\n break Ok(());\n };\n match msg {\n ActiveRelayMessage::SetHomeRelay(is_home) => {\n self.set_home_relay(is_home);\n }\n ActiveRelayMessage::CheckConnection(local_ips) => {\n match client_stream.local_addr() {\n Some(addr) if local_ips.contains(&addr.ip()) => {\n let data = state.ping_tracker.new_ping();\n let fut = client_sink.send(SendMessage::Ping(data));\n self.run_sending(fut, &mut state, &mut client_stream).await?;\n }\n Some(_) => break Err(LocalIpInvalidSnafu.build()),\n None => break Err(LocalAddrMissingSnafu.build()),\n }\n }\n #[cfg(test)]\n ActiveRelayMessage::GetLocalAddr(sender) => {\n let addr = client_stream.local_addr();\n sender.send(addr).ok();\n }\n #[cfg(test)]\n ActiveRelayMessage::PingServer(sender) => {\n let data = rand::random();\n state.test_pong = Some((data, sender));\n let fut = client_sink.send(SendMessage::Ping(data));\n self.run_sending(fut, &mut state, &mut client_stream).await?;\n }\n }\n }\n count = self.relay_datagrams_send.recv_many(\n &mut send_datagrams_buf,\n SEND_DATAGRAM_BATCH_SIZE,\n ) => {\n if count == 0 {\n warn!(\"Datagram inbox closed, shutdown\");\n break Ok(());\n };\n self.reset_inactive_timeout();\n // TODO: This allocation is *very* unfortunate. But so is the\n // allocation *inside* of PacketizeIter...\n let dgrams = std::mem::replace(\n &mut send_datagrams_buf,\n Vec::with_capacity(SEND_DATAGRAM_BATCH_SIZE),\n );\n // TODO(frando): can we avoid the clone here?\n let metrics = self.metrics.clone();\n let packet_iter = dgrams.into_iter().flat_map(|datagrams| {\n PacketizeIter::<_, MAX_PAYLOAD_SIZE>::new(\n datagrams.remote_node,\n datagrams.datagrams.clone(),\n )\n .map(|p| {\n Ok(SendMessage::SendPacket(p.node_id, p.payload))\n })\n });\n let mut packet_stream = n0_future::stream::iter(packet_iter).inspect(|m| {\n if let Ok(SendMessage::SendPacket(_node_id, payload)) = m {\n metrics.send_relay.inc_by(payload.len() as _);\n }\n });\n let fut = client_sink.send_all(&mut packet_stream);\n self.run_sending(fut, &mut state, &mut client_stream).await?;\n }\n msg = client_stream.next() => {\n let Some(msg) = msg else {\n break Err(StreamClosedServerSnafu.build());\n };\n match msg {\n Ok(msg) => {\n self.handle_relay_msg(msg, &mut state);\n // reset the ping timer, we have just received a message\n ping_interval.reset();\n },\n Err(err) => break Err(ClientStreamReadSnafu.into_error(err)),\n }\n }\n _ = &mut self.inactive_timeout, if !self.is_home_relay => {\n debug!(\"Inactive for {RELAY_INACTIVE_CLEANUP_TIME:?}, exiting.\");\n break Ok(());\n }\n }\n };\n\n if res.is_ok() {\n if let Err(err) = client_sink.close().await {\n debug!(\"Failed to close client sink gracefully: {err:#}\");\n }\n }\n\n res.map_err(|err| state.map_err(err))\n }\n```"}], "func_name": "run_connected", "docstring": "Runs the actor loop when connected to a relay server.\n\nReturns `Ok` if the actor needs to shut down. `Err` is returned if the connection\nto the relay server is lost.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports/relay/actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports/relay/actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e2e2e72790fb956b3fe46a825370b9cd96aae85f5636839af9ea7ac3e00c7db7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_send_datagram\n\nDocumentation:\nSends datagrams to the correct [`ActiveRelayActor`], or returns a future.\n\nIf the datagram can not be sent immediately, because the destination channel is\nfull, a future is returned that will complete once the datagrams have been sent to\nthe [`ActiveRelayActor`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn try_send_datagram(&mut self, item: RelaySendItem) -> Option> {\n let url = item.url.clone();\n let handle = self\n .active_relay_handle_for_node(&item.url, &item.remote_node)\n .await;\n match handle.datagrams_send_queue.try_send(item) {\n Ok(()) => None,\n Err(mpsc::error::TrySendError::Closed(_)) => {\n warn!(?url, \"Dropped datagram(s): ActiveRelayActor closed.\");\n None\n }\n Err(mpsc::error::TrySendError::Full(item)) => {\n let sender = handle.datagrams_send_queue.clone();\n let fut = async move {\n if sender.send(item).await.is_err() {\n warn!(?url, \"Dropped datagram(s): ActiveRelayActor closed.\");\n }\n };\n Some(fut)\n }\n }\n }\n```"}], "func_name": "try_send_datagram", "docstring": "Sends datagrams to the correct [`ActiveRelayActor`], or returns a future.\n\nIf the datagram can not be sent immediately, because the destination channel is\nfull, a future is returned that will complete once the datagrams have been sent to\nthe [`ActiveRelayActor`].", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports/relay/actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports/relay/actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2965bb82d5713dceb80c2cc6089206d41f3a371ec7d52b7569655bb8140162de"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: active_relay_handle_for_node\n\nDocumentation:\nReturns the handle for the [`ActiveRelayActor`] to reach `remote_node`.\n\nThe node is expected to be reachable on `url`, but if no [`ActiveRelayActor`] for\n`url` exists but another existing [`ActiveRelayActor`] already knows about the node,\nthat other node is used.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn active_relay_handle_for_node(\n &mut self,\n url: &RelayUrl,\n remote_node: &NodeId,\n ) -> ActiveRelayHandle {\n if let Some(handle) = self.active_relays.get(url) {\n return handle.clone();\n }\n\n let mut found_relay: Option = None;\n // If we don't have an open connection to the remote node's home relay, see if\n // we have an open connection to a relay node where we'd heard from that peer\n // already. E.g. maybe they dialed our home relay recently.\n {\n // Futures which return Some(RelayUrl) if the relay knows about the remote node.\n let check_futs = self.active_relays.iter().map(|(url, handle)| async move {\n let (tx, rx) = oneshot::channel();\n handle\n .prio_inbox_addr\n .send(ActiveRelayPrioMessage::HasNodeRoute(*remote_node, tx))\n .await\n .ok();\n match rx.await {\n Ok(true) => Some(url.clone()),\n _ => None,\n }\n });\n let mut futures = FuturesUnorderedBounded::from_iter(check_futs);\n while let Some(maybe_url) = futures.next().await {\n if maybe_url.is_some() {\n found_relay = maybe_url;\n break;\n }\n }\n }\n let url = found_relay.unwrap_or(url.clone());\n self.active_relay_handle(url)\n }\n```"}], "func_name": "active_relay_handle_for_node", "docstring": "Returns the handle for the [`ActiveRelayActor`] to reach `remote_node`.\n\nThe node is expected to be reachable on `url`, but if no [`ActiveRelayActor`] for\n`url` exists but another existing [`ActiveRelayActor`] already knows about the node,\nthat other node is used.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports/relay/actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports/relay/actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8371a3cfed9df1faba769743f22b82d74edbecd737b8ba7c1e8873d3251cbe95"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: active_relay_handle\n\nDocumentation:\nReturns the handle of the [`ActiveRelayActor`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn active_relay_handle(&mut self, url: RelayUrl) -> ActiveRelayHandle {\n match self.active_relays.get(&url) {\n Some(e) => e.clone(),\n None => {\n let handle = self.start_active_relay(url.clone());\n if Some(&url) == self.config.my_relay.get().as_ref() {\n if let Err(err) = handle\n .inbox_addr\n .try_send(ActiveRelayMessage::SetHomeRelay(true))\n {\n error!(\"Home relay not set, send to new actor failed: {err:#}.\");\n }\n }\n self.active_relays.insert(url, handle.clone());\n self.log_active_relay();\n handle\n }\n }\n }\n```"}], "func_name": "active_relay_handle", "docstring": "Returns the handle of the [`ActiveRelayActor`].", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports/relay/actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports/relay/actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "882431d7bf8120a068a0e218db8083feb9af49f57a0bcc7c81d3481373b7fde3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: maybe_close_relays_on_rebind\n\nDocumentation:\nCloses the relay connections not originating from a local IP address.\n\nCalled in response to a rebind, any relay connection originating from an address\nthat's not known to be currently a local IP address should be closed. All the other\nrelay connections are pinged.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn maybe_close_relays_on_rebind(&mut self) {\n #[cfg(not(wasm_browser))]\n let ifs = interfaces::State::new().await;\n #[cfg(not(wasm_browser))]\n let local_ips: Vec<_> = ifs\n .interfaces\n .values()\n .flat_map(|netif| netif.addrs())\n .map(|ipnet| ipnet.addr())\n .collect();\n // In browsers, we don't have this information. This will do the right thing in the ActiveRelayActor, though.\n #[cfg(wasm_browser)]\n let local_ips = Vec::new();\n let send_futs = self.active_relays.values().map(|handle| {\n let local_ips = local_ips.clone();\n async move {\n handle\n .inbox_addr\n .send(ActiveRelayMessage::CheckConnection(local_ips))\n .await\n .ok();\n }\n });\n n0_future::join_all(send_futs).await;\n self.log_active_relay();\n }\n```"}], "func_name": "maybe_close_relays_on_rebind", "docstring": "Closes the relay connections not originating from a local IP address.\n\nCalled in response to a rebind, any relay connection originating from an address\nthat's not known to be currently a local IP address should be closed. All the other\nrelay connections are pinged.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports/relay/actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports/relay/actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "90dea086db642d3a41bb93353c81c24f46df63133af9d9badbd10dd4734f0419"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reap_active_relays\n\nDocumentation:\nCleans up [`ActiveRelayActor`]s which have stopped running.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn reap_active_relays(&mut self) {\n self.active_relays\n .retain(|_url, handle| !handle.inbox_addr.is_closed());\n\n // Make sure home relay exists\n if let Some(url) = self.config.my_relay.get() {\n self.active_relay_handle(url);\n }\n self.log_active_relay();\n }\n```"}], "func_name": "reap_active_relays", "docstring": "Cleans up [`ActiveRelayActor`]s which have stopped running.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports/relay/actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports/relay/actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "309e4a63906529750de4d7f0a23ce3a2f22d3aff1eed5d216494bbbb52d73d76"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: close_all_active_relays\n\nDocumentation:\nStops all [`ActiveRelayActor`]s and awaits for them to finish.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn close_all_active_relays(&mut self) {\n self.cancel_token.cancel();\n let tasks = std::mem::take(&mut self.active_relay_tasks);\n tasks.join_all().await;\n\n self.log_active_relay();\n }\n```"}], "func_name": "close_all_active_relays", "docstring": "Stops all [`ActiveRelayActor`]s and awaits for them to finish.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports/relay/actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports/relay/actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2091a59d269194262d9b74297fe967ca64d9be25c280f2c32fc0363fa75fa17b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new new PacketizeIter from something that can be turned into an\niterator of slices, like a `Vec`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(node_id: NodeId, iter: impl IntoIterator) -> Self {\n Self {\n node_id,\n iter: iter.into_iter().peekable(),\n buffer: BytesMut::with_capacity(N),\n }\n }\n```"}], "func_name": "new", "docstring": "Create a new new PacketizeIter from something that can be turned into an\niterator of slices, like a `Vec`.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports/relay/actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports/relay/actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "19df852e6b3a85f64ea8e4a3d7393c1d10f4d390a1f59ba69199819201d47358"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_echo_node\n\nDocumentation:\nStarts an [`ActiveRelayActor`] as an \"iroh echo node\".\n\nThis actor will connect to the relay server, pretending to be an iroh node, and echo\nback any datagram it receives from the relay. This is used by the\n[`ActiveRelayNode`] under test to check connectivity works.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn start_echo_node(relay_url: RelayUrl) -> (NodeId, AbortOnDropHandle<()>) {\n let secret_key = SecretKey::from_bytes(&[8u8; 32]);\n let (recv_datagram_tx, mut recv_datagram_rx) = mpsc::channel(16);\n let (send_datagram_tx, send_datagram_rx) = mpsc::channel(16);\n let (prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);\n let (inbox_tx, inbox_rx) = mpsc::channel(16);\n let cancel_token = CancellationToken::new();\n let actor_task = start_active_relay_actor(\n secret_key.clone(),\n cancel_token.clone(),\n relay_url.clone(),\n prio_inbox_rx,\n inbox_rx,\n send_datagram_rx,\n recv_datagram_tx,\n info_span!(\"echo-node\"),\n );\n let echo_task = tokio::spawn({\n let relay_url = relay_url.clone();\n async move {\n loop {\n let datagram = recv_datagram_rx.recv().await;\n if let Some(recv) = datagram {\n let RelayRecvDatagram { url: _, src, buf } = recv;\n info!(from = src.fmt_short(), \"Received datagram\");\n let send = RelaySendItem {\n remote_node: src,\n url: relay_url.clone(),\n datagrams: smallvec![buf],\n };\n send_datagram_tx.send(send).await.ok();\n }\n }\n }\n .instrument(info_span!(\"echo-task\"))\n });\n let echo_task = AbortOnDropHandle::new(echo_task);\n let supervisor_task = tokio::spawn(async move {\n let _guard = cancel_token.drop_guard();\n // move the inboxes here so it is not dropped, as this stops the actor.\n let _prio_inbox_tx = prio_inbox_tx;\n let _inbox_tx = inbox_tx;\n tokio::select! {\n biased;\n _ = actor_task => (),\n _ = echo_task => (),\n };\n });\n let supervisor_task = AbortOnDropHandle::new(supervisor_task);\n (secret_key.public(), supervisor_task)\n }\n```"}], "func_name": "start_echo_node", "docstring": "Starts an [`ActiveRelayActor`] as an \"iroh echo node\".\n\nThis actor will connect to the relay server, pretending to be an iroh node, and echo\nback any datagram it receives from the relay. This is used by the\n[`ActiveRelayNode`] under test to check connectivity works.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports/relay/actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports/relay/actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cbdfd0b8082a4826abc7fd374aa3acb980ecfb64e9e1ca4603e70337322e1154"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_recv_echo\n\nDocumentation:\nSends a message to the echo node, receives the response.\n\nThis takes care of retry and timeout. Because we don't know when both the\nnode-under-test and the echo node will be ready and datagrams aren't queued to send\nforever, we have to retry a few times.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn send_recv_echo(\n item: RelaySendItem,\n tx: &mpsc::Sender,\n rx: &mut mpsc::Receiver,\n ) -> Result<()> {\n assert!(item.datagrams.len() == 1);\n tokio::time::timeout(Duration::from_secs(10), async move {\n loop {\n let res = tokio::time::timeout(UNDELIVERABLE_DATAGRAM_TIMEOUT, async {\n tx.send(item.clone()).await.context(\"send item\")?;\n let RelayRecvDatagram {\n url: _,\n src: _,\n buf,\n } = rx.recv().await.unwrap();\n\n assert_eq!(buf.as_ref(), item.datagrams[0]);\n\n Ok::<_, Error>(())\n })\n .await;\n if res.is_ok() {\n break;\n }\n }\n })\n .await\n .expect(\"overall timeout exceeded\");\n Ok(())\n }\n```"}], "func_name": "send_recv_echo", "docstring": "Sends a message to the echo node, receives the response.\n\nThis takes care of retry and timeout. Because we don't know when both the\nnode-under-test and the echo node will be ready and datagrams aren't queued to send\nforever, we have to retry a few times.", "repo": "n0-computer/iroh", "path": "iroh/src/magicsock/transports/relay/actor.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/magicsock/transports/relay/actor.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "35475cd0e0213aea5dad855f39e624c2a04c9b60af49988c5f4506e12f17a219"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate\n\nDocumentation:\nGenerates a globally unique fake UDP address.\n\nThis generates a new IPv6 address in the Unique Local Address range (RFC 4193)\nwhich is recognised by iroh as an IP mapped address.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate() -> Self {\n let mut addr = [0u8; 16];\n addr[0] = Self::ADDR_PREFIXL;\n addr[1..6].copy_from_slice(&Self::ADDR_GLOBAL_ID);\n addr[6..8].copy_from_slice(&Self::ADDR_SUBNET);\n\n let counter = IP_ADDR_COUNTER.fetch_add(1, Ordering::Relaxed);\n addr[8..16].copy_from_slice(&counter.to_be_bytes());\n\n Self(Ipv6Addr::from(addr))\n }\n```"}], "func_name": "generate", "docstring": "Generates a globally unique fake UDP address.\n\nThis generates a new IPv6 address in the Unique Local Address range (RFC 4193)\nwhich is recognised by iroh as an IP mapped address.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/ip_mapped_addrs.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/ip_mapped_addrs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fd58fd82d0073038e05e59a7c5ad31587cf4397346ea626e4304375af547ccc3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: private_socket_addr\n\nDocumentation:\nReturns a consistent [`SocketAddr`] for the [`IpMappedAddr`].\n\nThis does not have a routable IP address.\n\nThis uses a made-up, but fixed port number. The [IpMappedAddresses`] map this is\nmade for creates a unique [`IpMappedAddr`] for each IP+port and thus does not use\nthe port to map back to the original [`SocketAddr`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn private_socket_addr(&self) -> SocketAddr {\n SocketAddr::new(IpAddr::from(self.0), Self::MAPPED_ADDR_PORT)\n }\n```"}], "func_name": "private_socket_addr", "docstring": "Returns a consistent [`SocketAddr`] for the [`IpMappedAddr`].\n\nThis does not have a routable IP address.\n\nThis uses a made-up, but fixed port number. The [IpMappedAddresses`] map this is\nmade for creates a unique [`IpMappedAddr`] for each IP+port and thus does not use\nthe port to map back to the original [`SocketAddr`].", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/ip_mapped_addrs.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/ip_mapped_addrs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "80e58c447ec96a0ea77a5838780243bd549513ab8cdd9788e2064eefb9810e01"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_or_register\n\nDocumentation:\nAdds a [`SocketAddr`] to the map and returns the generated [`IpMappedAddr`].\n\nIf this [`SocketAddr`] already exists in the map, it returns its\nassociated [`IpMappedAddr`].\n\nOtherwise a new [`IpMappedAddr`] is generated for it and returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_or_register(&self, socket_addr: SocketAddr) -> IpMappedAddr {\n let ip_port = (socket_addr.ip(), socket_addr.port());\n let mut inner = self.0.lock().expect(\"poisoned\");\n if let Some(mapped_addr) = inner.by_ip_port.get(&ip_port) {\n return *mapped_addr;\n }\n let ip_mapped_addr = IpMappedAddr::generate();\n inner.by_mapped_addr.insert(ip_mapped_addr, socket_addr);\n inner.by_ip_port.insert(ip_port, ip_mapped_addr);\n ip_mapped_addr\n }\n```"}], "func_name": "get_or_register", "docstring": "Adds a [`SocketAddr`] to the map and returns the generated [`IpMappedAddr`].\n\nIf this [`SocketAddr`] already exists in the map, it returns its\nassociated [`IpMappedAddr`].\n\nOtherwise a new [`IpMappedAddr`] is generated for it and returned.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/ip_mapped_addrs.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/ip_mapped_addrs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c9744eac71d018d1053149b7379f79da646235a64eac8761a8f22601b70f135d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_mapped_addr\n\nDocumentation:\nReturns the [`IpMappedAddr`] for the given [`SocketAddr`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_mapped_addr(&self, socket_addr: &SocketAddr) -> Option {\n let ip_port = (socket_addr.ip(), socket_addr.port());\n let inner = self.0.lock().expect(\"poisoned\");\n inner.by_ip_port.get(&ip_port).copied()\n }\n```"}], "func_name": "get_mapped_addr", "docstring": "Returns the [`IpMappedAddr`] for the given [`SocketAddr`].", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/ip_mapped_addrs.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/ip_mapped_addrs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2418b9a801c9b8f4fed9869ece33ce8925b77281ec847aabfeadb67f3232bffe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_ip_addr\n\nDocumentation:\nReturns the [`SocketAddr`] for the given [`IpMappedAddr`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_ip_addr(&self, mapped_addr: &IpMappedAddr) -> Option {\n let inner = self.0.lock().expect(\"poisoned\");\n inner.by_mapped_addr.get(mapped_addr).copied()\n }\n```"}], "func_name": "get_ip_addr", "docstring": "Returns the [`SocketAddr`] for the given [`IpMappedAddr`].", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/ip_mapped_addrs.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/ip_mapped_addrs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f16c916358f3bfc90de21ba8b23b9cb1b740d16e4f86da714f34c95f0e22b198"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: disabled\n\nDocumentation:\nCreate an [`Options`] that disables all probes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn disabled() -> Self {\n Self {\n stun_sock_v4: None,\n stun_sock_v6: None,\n quic_config: None,\n icmp_v4: false,\n icmp_v6: false,\n https: false,\n #[cfg(any(test, feature = \"test-utils\"))]\n insecure_skip_relay_cert_verify: false,\n }\n }\n```"}], "func_name": "disabled", "docstring": "Create an [`Options`] that disables all probes", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/options.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/options.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2a9ca03e31f4c9321ea9920e0b387355f1ecea8f4d0efea1e4c034efccafcd1b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stun_v4\n\nDocumentation:\nSet the ipv4 stun socket and enable ipv4 stun probes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stun_v4(mut self, sock: Option>) -> Self {\n self.stun_sock_v4 = sock;\n self\n }\n```"}], "func_name": "stun_v4", "docstring": "Set the ipv4 stun socket and enable ipv4 stun probes", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/options.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/options.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0a1b152664f102c276f7f7f2b8616fa3e5f8e33b6baaf53d4d6f5071bb9ca0d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stun_v6\n\nDocumentation:\nSet the ipv6 stun socket and enable ipv6 stun probes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stun_v6(mut self, sock: Option>) -> Self {\n self.stun_sock_v6 = sock;\n self\n }\n```"}], "func_name": "stun_v6", "docstring": "Set the ipv6 stun socket and enable ipv6 stun probes", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/options.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/options.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "db141794ca3f4458c3f4fdf7d95810b041ebd52c5e0088c0a862c01d0fd45b7f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_protocols\n\nDocumentation:\nTurn the options into set of valid protocols\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn to_protocols(&self) -> BTreeSet {\n let mut protocols = BTreeSet::new();\n if self.stun_sock_v4.is_some() {\n protocols.insert(ProbeProto::StunIpv4);\n }\n if self.stun_sock_v6.is_some() {\n protocols.insert(ProbeProto::StunIpv6);\n }\n if let Some(ref quic) = self.quic_config {\n if quic.ipv4 {\n protocols.insert(ProbeProto::QuicIpv4);\n }\n if quic.ipv6 {\n protocols.insert(ProbeProto::QuicIpv6);\n }\n }\n if self.icmp_v4 {\n protocols.insert(ProbeProto::IcmpV4);\n }\n if self.icmp_v6 {\n protocols.insert(ProbeProto::IcmpV6);\n }\n if self.https {\n protocols.insert(ProbeProto::Https);\n }\n protocols\n }\n```"}], "func_name": "to_protocols", "docstring": "Turn the options into set of valid protocols", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/options.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/options.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e302dba1c0c75bf1c6bf9e97909555a7c7ec3c05ea15f63578864b60c7c5d8b1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_client\n\nDocumentation:\nLazily create the ping client.\n\nWe do this because it means we do not bind a socket until we really try to send a\nping. It makes it more transparent to use the pinger.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_client(&self, kind: ICMP) -> Result {\n let client = match kind {\n ICMP::V4 => {\n let mut opt_client = self.0.client_v4.lock().expect(\"poisoned\");\n match *opt_client {\n Some(ref client) => client.clone(),\n None => {\n let cfg = Config::builder().kind(kind).build();\n let client = Client::new(&cfg).context(CreateClientIpv4Snafu)?;\n *opt_client = Some(client.clone());\n client\n }\n }\n }\n ICMP::V6 => {\n let mut opt_client = self.0.client_v6.lock().expect(\"poisoned\");\n match *opt_client {\n Some(ref client) => client.clone(),\n None => {\n let cfg = Config::builder().kind(kind).build();\n let client = Client::new(&cfg).context(CreateClientIpv6Snafu)?;\n *opt_client = Some(client.clone());\n client\n }\n }\n }\n };\n Ok(client)\n }\n```"}], "func_name": "get_client", "docstring": "Lazily create the ping client.\n\nWe do this because it means we do not bind a socket until we really try to send a\nping. It makes it more transparent to use the pinger.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/ping.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/ping.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b2cbca5fb414e75206e159982e5b7053cda0e75af2b95c758b54e5ba1c3da2c6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send\n\nDocumentation:\nSend a ping request with associated data, returning the perceived latency.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn send(&self, addr: IpAddr, data: &[u8]) -> Result {\n let client = match addr {\n IpAddr::V4(_) => self.get_client(ICMP::V4)?,\n IpAddr::V6(_) => self.get_client(ICMP::V6)?,\n };\n let ident = PingIdentifier(rand::random());\n debug!(%addr, %ident, \"Creating pinger\");\n let mut pinger = client.pinger(addr, ident).await;\n pinger.timeout(DEFAULT_TIMEOUT); // todo: timeout too large for net_report\n match pinger\n .ping(PingSequence(0), data)\n .await\n .context(PingSnafu)?\n {\n (IcmpPacket::V4(packet), dur) => {\n debug!(\n \"{} bytes from {}: icmp_seq={} ttl={:?} time={:0.2?}\",\n packet.get_size(),\n packet.get_source(),\n packet.get_sequence(),\n packet.get_ttl(),\n dur\n );\n Ok(dur)\n }\n\n (IcmpPacket::V6(packet), dur) => {\n debug!(\n \"{} bytes from {}: icmp_seq={} hlim={} time={:0.2?}\",\n packet.get_size(),\n packet.get_source(),\n packet.get_sequence(),\n packet.get_max_hop_limit(),\n dur\n );\n Ok(dur)\n }\n }\n }\n```"}], "func_name": "send", "docstring": "Send a ping request with associated data, returning the perceived latency.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/ping.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/ping.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "846758af7a8c0e14b4d43f74f2d3ac39e847f24287290cc85e77c834b9484820"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new actor generating a single report.\n\nThe actor starts running immediately and only generates a single report, after which\nit shuts down. Dropping this handle will abort the actor.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn new(\n net_report: net_report::Addr,\n last_report: Option>,\n relay_map: RelayMap,\n protocols: BTreeSet,\n metrics: Arc,\n #[cfg(not(wasm_browser))] socket_state: SocketState,\n #[cfg(any(test, feature = \"test-utils\"))] insecure_skip_relay_cert_verify: bool,\n ) -> Self {\n let (msg_tx, msg_rx) = mpsc::channel(32);\n let addr = Addr {\n sender: msg_tx.clone(),\n };\n let mut actor = Actor {\n msg_tx,\n msg_rx,\n net_report: net_report.clone(),\n last_report,\n relay_map,\n report: Report::default(),\n outstanding_tasks: OutstandingTasks::default(),\n protocols,\n #[cfg(not(wasm_browser))]\n socket_state,\n #[cfg(not(wasm_browser))]\n hairpin_actor: hairpin::Client::new(net_report, addr),\n metrics,\n #[cfg(any(test, feature = \"test-utils\"))]\n insecure_skip_relay_cert_verify,\n };\n let task =\n task::spawn(async move { actor.run().await }.instrument(info_span!(\"reportgen.actor\")));\n Self {\n _drop_guard: AbortOnDropHandle::new(task),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new actor generating a single report.\n\nThe actor starts running immediately and only generates a single report, after which\nit shuts down. Dropping this handle will abort the actor.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f5a3b34083cd02289f8beda9d06723b5ff7de6a0a9602f32f4d17d7497613339"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send\n\nDocumentation:\nBlocking send to the actor, to be used from a non-actor future.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn send(&self, msg: Message) -> Result<(), mpsc::error::SendError> {\n trace!(\n \"sending {:?} to channel with cap {}\",\n msg,\n self.sender.capacity()\n );\n self.sender.send(msg).await\n }\n```"}], "func_name": "send", "docstring": "Blocking send to the actor, to be used from a non-actor future.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7b211836a5f24199cf1575c6f50060bf44733cb00e05baab9db17aabe0ba2539"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_inner\n\nDocumentation:\nRuns the main reportgen actor logic.\n\nThis actor runs by:\n\n- Creates a hairpin actor.\n- Creates a captive portal future.\n- Creates ProbeSet futures in a group of futures.\n- Runs a main loop:\n- Drives all the above futures.\n- Receives actor messages (sent by those futures).\n- Updates the report, cancels unneeded futures.\n- Sends the report to the net_report actor.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_inner(&mut self) -> Result<(), ActorRunError> {\n #[cfg(not(wasm_browser))]\n let port_mapper = self.socket_state.port_mapper.is_some();\n #[cfg(wasm_browser)]\n let port_mapper = false;\n debug!(%port_mapper, \"reportstate actor starting\");\n\n self.report.os_has_ipv6 = super::os_has_ipv6();\n\n let mut port_mapping = self.prepare_portmapper_task();\n let mut captive_task = self.prepare_captive_portal_task();\n let mut probes = self.spawn_probes_task().await;\n\n let total_timer = time::sleep(OVERALL_REPORT_TIMEOUT);\n tokio::pin!(total_timer);\n let probe_timer = time::sleep(PROBES_TIMEOUT);\n tokio::pin!(probe_timer);\n\n loop {\n trace!(awaiting = ?self.outstanding_tasks, \"tick; awaiting tasks\");\n if self.outstanding_tasks.all_done() {\n debug!(\"all tasks done\");\n break;\n }\n tokio::select! {\n biased;\n _ = &mut total_timer => {\n trace!(\"tick: total_timer expired\");\n return Err(TimeoutSnafu.build());\n }\n\n _ = &mut probe_timer => {\n warn!(\"tick: probes timed out\");\n // Set new timeout to not go into this branch multiple times. We need\n // the abort to finish all probes normally. PROBES_TIMEOUT is\n // sufficiently far in the future.\n probe_timer.as_mut().reset(Instant::now() + PROBES_TIMEOUT);\n probes.abort_all();\n self.handle_abort_probes();\n }\n\n // Drive the portmapper.\n pm = &mut port_mapping, if self.outstanding_tasks.port_mapper => {\n debug!(report=?pm, \"tick: portmapper probe report\");\n self.report.portmap_probe = pm;\n port_mapping.inner = None;\n self.outstanding_tasks.port_mapper = false;\n }\n\n // Check for probes finishing.\n set_result = probes.join_next(), if self.outstanding_tasks.probes => {\n trace!(\"tick: probes done: {:?}\", set_result);\n match set_result {\n Some(Ok(Ok(report))) => self.handle_probe_report(report),\n Some(Ok(Err(_))) => (),\n Some(Err(e)) => {\n warn!(\"probes task error: {:?}\", e);\n }\n None => {\n self.handle_abort_probes();\n }\n }\n trace!(\"tick: probes handled\");\n }\n\n // Drive the captive task.\n found = &mut captive_task, if self.outstanding_tasks.captive_task => {\n trace!(\"tick: captive portal task done\");\n self.report.captive_portal = found;\n captive_task.inner = None;\n self.outstanding_tasks.captive_task = false;\n }\n\n // Handle actor messages.\n msg = self.msg_rx.recv() => {\n trace!(\"tick: msg recv: {:?}\", msg);\n match msg {\n Some(msg) => self.handle_message(msg),\n None => {\n return Err(ClientGoneSnafu.build());\n }\n }\n }\n }\n }\n\n if !probes.is_empty() {\n debug!(\n \"aborting {} probe sets, already have enough reports\",\n probes.len()\n );\n drop(probes);\n }\n\n debug!(\"Sending report to net_report actor\");\n self.net_report\n .send(net_report::Message::ReportReady {\n report: Box::new(self.report.clone()),\n })\n .await\n .map_err(|_| ActorGoneSnafu.build())?;\n\n Ok(())\n }\n```"}], "func_name": "run_inner", "docstring": "Runs the main reportgen actor logic.\n\nThis actor runs by:\n\n- Creates a hairpin actor.\n- Creates a captive portal future.\n- Creates ProbeSet futures in a group of futures.\n- Runs a main loop:\n- Drives all the above futures.\n- Receives actor messages (sent by those futures).\n- Updates the report, cancels unneeded futures.\n- Sends the report to the net_report actor.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2764a593dfd66caa3f9b81ca40cf8ed6f956f98473a172a125c865a8c01d0ccf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_message\n\nDocumentation:\nHandles an actor message.\n\nReturns `true` if all the probes need to be aborted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_message(&mut self, msg: Message) {\n trace!(?msg, \"handling message\");\n match msg {\n Message::HairpinResult(works) => {\n self.report.hair_pinning = Some(works);\n self.outstanding_tasks.hairpin = false;\n }\n Message::ProbeWouldHelp(probe, relay_node, response_tx) => {\n let res = self.probe_would_help(probe, relay_node);\n if response_tx.send(res).is_err() {\n debug!(\"probe dropped before ProbeWouldHelp response sent\");\n }\n }\n Message::AbortProbes => {\n self.handle_abort_probes();\n }\n }\n }\n```"}], "func_name": "handle_message", "docstring": "Handles an actor message.\n\nReturns `true` if all the probes need to be aborted.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a04c28f06bc9430a07c9e02ada41e36ee6747d9e5711008eaba9f84cfcadb17c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: probe_would_help\n\nDocumentation:\nWhether running this probe would still improve our report.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn probe_would_help(&mut self, probe: Probe, relay_node: Arc) -> bool {\n // If the probe is for a relay we don't yet know about, that would help.\n if self.report.relay_latency.get(&relay_node.url).is_none() {\n return true;\n }\n\n // If the probe is for IPv6 and we don't yet have an IPv6 report, that would help.\n #[cfg(not(wasm_browser))]\n if probe.proto() == ProbeProto::StunIpv6 && self.report.relay_v6_latency.is_empty() {\n return true;\n }\n\n // For IPv4, we need at least two IPv4 results overall to\n // determine whether we're behind a NAT that shows us as\n // different source IPs and/or ports depending on who we're\n // talking to. If we don't yet have two results yet\n // (`mapping_varies_by_dest_ip` is blank), then another IPv4 probe\n // would be good.\n #[cfg(not(wasm_browser))]\n if probe.proto() == ProbeProto::StunIpv4 && self.report.mapping_varies_by_dest_ip.is_none()\n {\n return true;\n }\n\n // Otherwise not interesting.\n false\n }\n```"}], "func_name": "probe_would_help", "docstring": "Whether running this probe would still improve our report.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "97b6f159e88772882e59eef1afcaea62fcc5a20df40386adc85bc2b1cac1b5e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_abort_probes\n\nDocumentation:\nStops further probes.\n\nThis makes sure that no further probes are run and also cancels the captive portal\nand portmapper tasks if there were successful probes. Be sure to only handle this\nafter all the required [`ProbeReport`]s have been processed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_abort_probes(&mut self) {\n trace!(\"handle abort probes\");\n self.outstanding_tasks.probes = false;\n if self.report.udp {\n self.outstanding_tasks.port_mapper = false;\n self.outstanding_tasks.captive_task = false;\n }\n }\n```"}], "func_name": "handle_abort_probes", "docstring": "Stops further probes.\n\nThis makes sure that no further probes are run and also cancels the captive portal\nand portmapper tasks if there were successful probes. Be sure to only handle this\nafter all the required [`ProbeReport`]s have been processed.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b9ba41f444b8f671c5106bc001b86fc9825b0aaa7af5fd4945cb9533eafe0f3b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prepare_portmapper_task\n\nDocumentation:\nCreates the future which will perform the portmapper task.\n\nThe returned future will run the portmapper, if enabled, resolving to it's result.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn prepare_portmapper_task(\n &mut self,\n ) -> MaybeFuture>>>> {\n // In the browser, the compiler struggles to infer the type of future inside, because it's never set.\n #[cfg(wasm_browser)]\n let port_mapping: MaybeFuture>>>> =\n MaybeFuture::default();\n\n #[cfg(not(wasm_browser))]\n let mut port_mapping = MaybeFuture::default();\n\n #[cfg(not(wasm_browser))]\n if let Some(port_mapper) = self.socket_state.port_mapper.clone() {\n port_mapping.inner = Some(Box::pin(async move {\n match port_mapper.probe().await {\n Ok(Ok(res)) => Some(res),\n Ok(Err(err)) => {\n debug!(\"skipping port mapping: {err:?}\");\n None\n }\n Err(recv_err) => {\n warn!(\"skipping port mapping: {recv_err:?}\");\n None\n }\n }\n }));\n self.outstanding_tasks.port_mapper = true;\n }\n port_mapping\n }\n```"}], "func_name": "prepare_portmapper_task", "docstring": "Creates the future which will perform the portmapper task.\n\nThe returned future will run the portmapper, if enabled, resolving to it's result.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8a6f6414b11a8eb6a9b4751099d1c824ccc70dac9cbe21fe768a0b63839f449"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prepare_captive_portal_task\n\nDocumentation:\nCreates the future which will perform the captive portal check.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn prepare_captive_portal_task(\n &mut self,\n ) -> MaybeFuture>>>> {\n // In the browser case the compiler cannot infer the type of the future, because it's never set:\n #[cfg(wasm_browser)]\n let captive_task: MaybeFuture>>>> = MaybeFuture::default();\n\n #[cfg(not(wasm_browser))]\n let mut captive_task = MaybeFuture::default();\n\n // If we're doing a full probe, also check for a captive portal. We\n // delay by a bit to wait for UDP STUN to finish, to avoid the probe if\n // it's unnecessary.\n #[cfg(not(wasm_browser))]\n if self.last_report.is_none() {\n // Even if we're doing a non-incremental update, we may want to try our\n // preferred relay for captive portal detection.\n let preferred_relay = self\n .last_report\n .as_ref()\n .and_then(|l| l.preferred_relay.clone());\n\n let dns_resolver = self.socket_state.dns_resolver.clone();\n let dm = self.relay_map.clone();\n self.outstanding_tasks.captive_task = true;\n captive_task.inner = Some(Box::pin(async move {\n time::sleep(CAPTIVE_PORTAL_DELAY).await;\n debug!(\"Captive portal check started after {CAPTIVE_PORTAL_DELAY:?}\");\n let captive_portal_check = time::timeout(\n CAPTIVE_PORTAL_TIMEOUT,\n check_captive_portal(&dns_resolver, &dm, preferred_relay)\n .instrument(debug_span!(\"captive-portal\")),\n );\n match captive_portal_check.await {\n Ok(Ok(found)) => Some(found),\n Ok(Err(err)) => {\n match err {\n CaptivePortalError::CreateReqwestClient { ref source }\n | CaptivePortalError::HttpRequest { ref source } => {\n if source.is_connect() {\n debug!(\"check_captive_portal failed: {err:#}\");\n }\n }\n _ => warn!(\"check_captive_portal error: {err:#}\"),\n }\n None\n }\n Err(_) => {\n warn!(\"check_captive_portal timed out\");\n None\n }\n }\n }));\n }\n\n self.outstanding_tasks.captive_task = false;\n captive_task\n }\n```"}], "func_name": "prepare_captive_portal_task", "docstring": "Creates the future which will perform the captive portal check.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c725e4565468d32e0b48c0c56d115a435cd0ff87068043d04b521104705b72a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn_probes_task\n\nDocumentation:\nPrepares the future which will run all the probes as per generated ProbePlan.\n\nProbes operate like the following:\n\n- A future is created for each probe in all probe sets.\n- All probes in a set are grouped in [`JoinSet`].\n- All those probe sets are grouped in one overall [`JoinSet`].\n- This future is polled by the main actor loop to make progress.\n- Once a probe future is polled:\n- Many probes start with a delay, they sleep during this time.\n- When a probe starts it first asks the reportgen [`Actor`] if it is still useful\nto run. If not it aborts the entire probe set.\n- When a probe finishes, its [`ProbeReport`] is yielded to the reportgen actor.\n- Probes get aborted in several ways:\n- A running it can fail and abort the entire probe set if it deems the\nfailure permanent. Probes in a probe set are essentially retries.\n- Once there are [`ProbeReport`]s from enough nodes, all remaining probes are\naborted. That is, the main actor loop stops polling them.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn spawn_probes_task(&mut self) -> JoinSet> {\n #[cfg(not(wasm_browser))]\n let if_state = interfaces::State::new().await;\n #[cfg(not(wasm_browser))]\n debug!(%if_state, \"Local interfaces\");\n let plan = match self.last_report {\n Some(ref report) => ProbePlan::with_last_report(\n &self.relay_map,\n report,\n &self.protocols,\n #[cfg(not(wasm_browser))]\n &if_state,\n ),\n None => ProbePlan::initial(\n &self.relay_map,\n &self.protocols,\n #[cfg(not(wasm_browser))]\n &if_state,\n ),\n };\n trace!(%plan, \"probe plan\");\n\n // The pinger is created here so that any sockets that might be bound for it are\n // shared between the probes that use it. It binds sockets lazily, so we can always\n // create it.\n #[cfg(not(wasm_browser))]\n let pinger = Pinger::new();\n\n // A collection of futures running probe sets.\n let mut probes = JoinSet::default();\n for probe_set in plan.iter() {\n let mut set = JoinSet::default();\n for probe in probe_set {\n let reportstate = self.addr();\n let relay_node = probe.node().clone();\n let probe = probe.clone();\n let net_report = self.net_report.clone();\n\n #[cfg(not(wasm_browser))]\n let pinger = pinger.clone();\n #[cfg(not(wasm_browser))]\n let socket_state = self.socket_state.clone();\n\n let metrics = self.metrics.clone();\n set.spawn(\n run_probe(\n reportstate,\n relay_node,\n probe.clone(),\n net_report,\n metrics,\n #[cfg(not(wasm_browser))]\n pinger,\n #[cfg(not(wasm_browser))]\n socket_state,\n #[cfg(any(test, feature = \"test-utils\"))]\n self.insecure_skip_relay_cert_verify,\n )\n .instrument(debug_span!(\"run_probe\", %probe)),\n );\n }\n\n // Add the probe set to all futures of probe sets. Handle aborting a probe set\n // if needed, only normal errors means the set continues.\n probes.spawn(\n async move {\n // Hack because ProbeSet is not it's own type yet.\n let mut probe_proto = None;\n while let Some(res) = set.join_next().await {\n match res {\n Ok(Ok(report)) => return Ok(report),\n Ok(Err(ProbeErrorWithProbe::Error(err, probe))) => {\n probe_proto = Some(probe.proto());\n warn!(?probe, \"probe failed: {:#}\", err);\n continue;\n }\n Ok(Err(ProbeErrorWithProbe::AbortSet(err, probe))) => {\n debug!(?probe, \"probe set aborted: {:#}\", err);\n set.abort_all();\n return Err(ProbeFailureSnafu.into_error(err));\n }\n Err(err) => {\n warn!(\"fatal probe set error, aborting: {:#}\", err);\n continue;\n }\n }\n }\n warn!(?probe_proto, \"no successful probes in ProbeSet\");\n Err(AllProbesFailedSnafu.build())\n }\n .instrument(info_span!(\"probe\")),\n );\n }\n self.outstanding_tasks.probes = true;\n\n probes\n }\n```"}], "func_name": "spawn_probes_task", "docstring": "Prepares the future which will run all the probes as per generated ProbePlan.\n\nProbes operate like the following:\n\n- A future is created for each probe in all probe sets.\n- All probes in a set are grouped in [`JoinSet`].\n- All those probe sets are grouped in one overall [`JoinSet`].\n- This future is polled by the main actor loop to make progress.\n- Once a probe future is polled:\n- Many probes start with a delay, they sleep during this time.\n- When a probe starts it first asks the reportgen [`Actor`] if it is still useful\nto run. If not it aborts the entire probe set.\n- When a probe finishes, its [`ProbeReport`] is yielded to the reportgen actor.\n- Probes get aborted in several ways:\n- A running it can fail and abort the entire probe set if it deems the\nfailure permanent. Probes in a probe set are essentially retries.\n- Once there are [`ProbeReport`]s from enough nodes, all remaining probes are\naborted. That is, the main actor loop stops polling them.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f7b6a2ec84c04e45207693118e60cd8ba946d99faba977d3b1ed9a693da4af57"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_port\n\nDocumentation:\nReturns the proper port based on the protocol of the probe.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_port(relay_node: &RelayNode, proto: &ProbeProto) -> Option {\n match proto {\n #[cfg(not(wasm_browser))]\n ProbeProto::QuicIpv4 | ProbeProto::QuicIpv6 => {\n if let Some(ref quic) = relay_node.quic {\n if quic.port == 0 {\n Some(DEFAULT_RELAY_QUIC_PORT)\n } else {\n Some(quic.port)\n }\n } else {\n None\n }\n }\n _ => {\n if relay_node.stun_port == 0 {\n Some(DEFAULT_STUN_PORT)\n } else {\n Some(relay_node.stun_port)\n }\n }\n }\n}\n```"}], "func_name": "get_port", "docstring": "Returns the proper port based on the protocol of the probe.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "84963ec0b5915f37201b03c1d4cd558526cf457bcc6f689494ab7e5d2118e3a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_check\n\nDocumentation:\nStarts the hairpin check.\n\n*dst* should be our own address as discovered by STUN. Hairpin detection works by\nsending a new STUN request to our own public address, if we receive this request\nback then hairpinning works, otherwise it does not.\n\nWill do nothing if this actor is already finished or a check has already started.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn start_check(&mut self, dst: SocketAddrV4) {\n if let Some(addr) = self.addr.take() {\n addr.send(Message::StartCheck(dst)).ok();\n }\n }\n```"}], "func_name": "start_check", "docstring": "Starts the hairpin check.\n\n*dst* should be our own address as discovered by STUN. Hairpin detection works by\nsending a new STUN request to our own public address, if we receive this request\nback then hairpinning works, otherwise it does not.\n\nWill do nothing if this actor is already finished or a check has already started.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen/hairpin.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen/hairpin.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "492e16333e496ff708089cd66380784bab5e9d80a1ea9df0eb917545e85d0a3a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_if_enabled\n\nDocumentation:\nAdds a [`ProbeSet`] if it contains probes and the protocol indicated in\nthe [`ProbeSet] matches a protocol in our set of [`ProbeProto`]s.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_if_enabled(&mut self, set: ProbeSet) {\n if !set.is_empty() && self.protocols.contains(&set.proto) {\n self.set.insert(set);\n }\n }\n```"}], "func_name": "add_if_enabled", "docstring": "Adds a [`ProbeSet`] if it contains probes and the protocol indicated in\nthe [`ProbeSet] matches a protocol in our set of [`ProbeProto`]s.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen/probes.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen/probes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "53e8a304ed887021b285a5418702f9f8e3e669a4c2e33134055acea5140c5147"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: max_delay\n\nDocumentation:\nReturns the delay of the last probe in the probe plan.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn max_delay(&self) -> Duration {\n self.set\n .iter()\n .flatten()\n .map(|probe| probe.delay())\n .max()\n .unwrap_or_default()\n }\n```"}], "func_name": "max_delay", "docstring": "Returns the delay of the last probe in the probe plan.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen/probes.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen/probes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7015ef03c37f44577afbdd5b149bc5b1a05c78e13c56c73b76c87e7389b994a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_priority_probes\n\nDocumentation:\nStun & Quic probes are \"priority\" probes\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn has_priority_probes(&self) -> bool {\n #[cfg(not(wasm_browser))]\n for probe in &self.set {\n if matches!(\n probe.proto,\n ProbeProto::StunIpv4\n | ProbeProto::StunIpv6\n | ProbeProto::QuicIpv4\n | ProbeProto::QuicIpv6\n ) {\n return true;\n }\n }\n false\n }\n```"}], "func_name": "has_priority_probes", "docstring": "Stun & Quic probes are \"priority\" probes", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen/probes.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen/probes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "edb57b00150281db2dae099e3e7c0178ff8d26327b5866aa12b766e8ec383590"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sort_relays\n\nDocumentation:\nSorts the nodes in the [`RelayMap`] from fastest to slowest.\n\nThis uses the latencies from the last report to determine the order. Relay Nodes with no\ndata are at the end.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn sort_relays<'a>(\n relay_map: &'a RelayMap,\n last_report: &Report,\n) -> Vec<(&'a RelayUrl, &'a Arc)> {\n let mut prev: Vec<_> = relay_map.nodes().collect();\n prev.sort_by(|a, b| {\n let latencies_a = last_report.relay_latency.get(&a.url);\n let latencies_b = last_report.relay_latency.get(&b.url);\n match (latencies_a, latencies_b) {\n (Some(_), None) => {\n // Non-zero sorts before zero.\n std::cmp::Ordering::Less\n }\n (None, Some(_)) => {\n // Zero can't sort before anything else.\n std::cmp::Ordering::Greater\n }\n (None, None) => {\n // For both empty latencies sort by relay_id.\n a.url.cmp(&b.url)\n }\n (Some(_), Some(_)) => match latencies_a.cmp(&latencies_b) {\n std::cmp::Ordering::Equal => a.url.cmp(&b.url),\n x => x,\n },\n }\n });\n\n prev.into_iter().map(|n| (&n.url, n)).collect()\n}\n```"}], "func_name": "sort_relays", "docstring": "Sorts the nodes in the [`RelayMap`] from fastest to slowest.\n\nThis uses the latencies from the last report to determine the order. Relay Nodes with no\ndata are at the end.", "repo": "n0-computer/iroh", "path": "iroh/src/net_report/reportgen/probes.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh/src/net_report/reportgen/probes.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9d8633e0c4273b895f7518680a1029cf4b6efc03846eede3e0c19895eae2a34a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: public\n\nDocumentation:\nReturns the [`VerifyingKey`] for this `PublicKey`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn public(&self) -> VerifyingKey {\n VerifyingKey::from_bytes(self.0.as_bytes()).expect(\"already verified\")\n }\n```"}], "func_name": "public", "docstring": "Returns the [`VerifyingKey`] for this `PublicKey`.", "repo": "n0-computer/iroh", "path": "iroh-base/src/key.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-base/src/key.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8c4ea8afbd35f78c7f0e551fe57c2c2d8aa06e9b6eedc1c90b97be1e57c85db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_bytes\n\nDocumentation:\nConstruct a `PublicKey` from a slice of bytes.\n\n# Warning\n\nThis will return a [`SignatureError`] if the bytes passed into this method do not represent\na valid `ed25519_dalek` curve point. Will never fail for bytes return from [`Self::as_bytes`].\nSee [`VerifyingKey::from_bytes`] for details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_bytes(bytes: &[u8; 32]) -> Result {\n let key = VerifyingKey::from_bytes(bytes)?;\n let y = CompressedEdwardsY(key.to_bytes());\n Ok(Self(y))\n }\n```"}], "func_name": "from_bytes", "docstring": "Construct a `PublicKey` from a slice of bytes.\n\n# Warning\n\nThis will return a [`SignatureError`] if the bytes passed into this method do not represent\na valid `ed25519_dalek` curve point. Will never fail for bytes return from [`Self::as_bytes`].\nSee [`VerifyingKey::from_bytes`] for details.", "repo": "n0-computer/iroh", "path": "iroh-base/src/key.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-base/src/key.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "52c2a6db9b3994b228a7c243c9cb0d674c0139cb9d49328194aec43e49d56d14"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: verify\n\nDocumentation:\nVerify a signature on a message with this secret key's public key.\n\n# Return\n\nReturns `Ok(())` if the signature is valid, and `Err` otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn verify(&self, message: &[u8], signature: &Signature) -> Result<(), SignatureError> {\n self.public().verify_strict(message, signature)\n }\n```"}], "func_name": "verify", "docstring": "Verify a signature on a message with this secret key's public key.\n\n# Return\n\nReturns `Ok(())` if the signature is valid, and `Err` otherwise.", "repo": "n0-computer/iroh", "path": "iroh-base/src/key.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-base/src/key.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f37f065d73d044e48cbef1c8cf0ef784600950fa306318318a1165cbfb2902e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate\n\nDocumentation:\nGenerate a new [`SecretKey`] with a randomness generator.\n\n```rust\n// use the OsRng option for OS depedndent most secure RNG.\nlet mut rng = rand::rngs::OsRng;\nlet _key = iroh_base::SecretKey::generate(&mut rng);\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn generate(mut csprng: R) -> Self {\n let secret = SigningKey::generate(&mut csprng);\n\n Self { secret }\n }\n```"}], "func_name": "generate", "docstring": "Generate a new [`SecretKey`] with a randomness generator.\n\n```rust\n// use the OsRng option for OS depedndent most secure RNG.\nlet mut rng = rand::rngs::OsRng;\nlet _key = iroh_base::SecretKey::generate(&mut rng);\n```", "repo": "n0-computer/iroh", "path": "iroh-base/src/key.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-base/src/key.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b4ab088627350f8879c7dfdc563e65a972e851580635c728ed3ca59d08372bbc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sign\n\nDocumentation:\nSign the given message and return a digital signature\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sign(&self, msg: &[u8]) -> Signature {\n use ed25519_dalek::Signer;\n\n self.secret.sign(msg)\n }\n```"}], "func_name": "sign", "docstring": "Sign the given message and return a digital signature", "repo": "n0-computer/iroh", "path": "iroh-base/src/key.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-base/src/key.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "063b32fcd248e22a29031ae830f3ab0a37b9bfebb7bc02cdd702e69308137519"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_bytes\n\nDocumentation:\nCreate a secret key from its byte representation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_bytes(bytes: &[u8; 32]) -> Self {\n let secret = SigningKey::from_bytes(bytes);\n secret.into()\n }\n```"}], "func_name": "from_bytes", "docstring": "Create a secret key from its byte representation.", "repo": "n0-computer/iroh", "path": "iroh-base/src/key.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-base/src/key.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dc6603f876a80f25550090599acffd92bd4487796074043c3872e9721d448d87"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new [`NodeAddr`] with no `relay_url` and no `direct_addresses`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(node_id: PublicKey) -> Self {\n NodeAddr {\n node_id,\n relay_url: None,\n direct_addresses: Default::default(),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new [`NodeAddr`] with no `relay_url` and no `direct_addresses`.", "repo": "n0-computer/iroh", "path": "iroh-base/src/node_addr.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-base/src/node_addr.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a4d0dfafaa705227286bf157fbd4e76d43768b6ce0f6329516d449b28158f8bf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_parts\n\nDocumentation:\nCreates a new [`NodeAddr`] from its parts.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_parts(\n node_id: PublicKey,\n relay_url: Option,\n direct_addresses: impl IntoIterator,\n ) -> Self {\n Self {\n node_id,\n relay_url,\n direct_addresses: direct_addresses.into_iter().collect(),\n }\n }\n```"}], "func_name": "from_parts", "docstring": "Creates a new [`NodeAddr`] from its parts.", "repo": "n0-computer/iroh", "path": "iroh-base/src/node_addr.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-base/src/node_addr.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93d2a700a8d692f92a741fa04397f821c0a827538435a5363f40dd5b69a6b56b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_empty\n\nDocumentation:\nReturns true, if only a [`NodeId`] is present.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_empty(&self) -> bool {\n self.relay_url.is_none() && self.direct_addresses.is_empty()\n }\n```"}], "func_name": "is_empty", "docstring": "Returns true, if only a [`NodeId`] is present.", "repo": "n0-computer/iroh", "path": "iroh-base/src/node_addr.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-base/src/node_addr.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1762bf1ed4c6f912d1c9b2c4f3189fee3fff634adfd32b57698f494aa0d4e234"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nCreates a ticket from given addressing info.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from(addr: NodeAddr) -> Self {\n Self { node: addr }\n }\n```"}], "func_name": "from", "docstring": "Creates a ticket from given addressing info.", "repo": "n0-computer/iroh", "path": "iroh-base/src/ticket/node.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-base/src/ticket/node.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5e7a6757ae61e2d04ba349eeaed441fcaf00f4297c729bb608e1e8cd716b2ed5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: metrics_addr\n\nDocumentation:\nGet the address where the metrics server should be bound, if set.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn metrics_addr(&self) -> Option {\n match &self.metrics {\n None => Some(DEFAULT_METRICS_ADDR),\n Some(conf) => match conf.disabled {\n true => None,\n false => Some(conf.bind_addr.unwrap_or(DEFAULT_METRICS_ADDR)),\n },\n }\n }\n```"}], "func_name": "metrics_addr", "docstring": "Get the address where the metrics server should be bound, if set.", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/config.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/config.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d8011036f2ac381d6b2b5ccd1fe3cd05e04ed60aa0eb7f9f8965a01169008bc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shutdown\n\nDocumentation:\nShutdown the server an wait for all tasks to complete.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn shutdown(mut self) -> Result<()> {\n self.server.shutdown_gracefully().await.e()?;\n Ok(())\n }\n```"}], "func_name": "shutdown", "docstring": "Shutdown the server an wait for all tasks to complete.", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9fcd29a63c4836bcda11f6f9cc594b5084f62e855b2f9d4b81a2946610a8cbbb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_until_done\n\nDocumentation:\nWait for all tasks to complete.\n\nRuns forever unless tasks fail.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_until_done(mut self) -> Result<()> {\n self.server.block_until_done().await.e()?;\n Ok(())\n }\n```"}], "func_name": "run_until_done", "docstring": "Wait for all tasks to complete.\n\nRuns forever unless tasks fail.", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9600a33211050904fbf5b107ac62f65bd5170168d0a3ab6aad4986810d0f0cd6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a DNS server given some settings, a connection to the DB for DID-by-username lookups\nand the server DID to serve under `_did.`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(zone_store: ZoneStore, config: &DnsConfig, metrics: Arc) -> Result {\n let origins = config\n .origins\n .iter()\n .map(Name::from_utf8)\n .collect::, _>>()\n .e()?;\n\n let (static_authority, serial) = create_static_authority(&origins, config)?;\n let authority = Arc::new(NodeAuthority::new(\n zone_store,\n static_authority,\n origins,\n serial,\n )?);\n\n let mut catalog = Catalog::new();\n for origin in authority.origins() {\n catalog.upsert(LowerName::from(origin), vec![authority.clone()]);\n }\n\n Ok(Self {\n catalog: Arc::new(catalog),\n metrics,\n })\n }\n```"}], "func_name": "new", "docstring": "Create a DNS server given some settings, a connection to the DB for DID-by-username lookups\nand the server DID to serve under `_did.`.", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e0e81f867838e28f1f78f2199069ae9f9de93be7337c1ea807f6c6067eca3174"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shutdown\n\nDocumentation:\nShutdown the server and wait for all tasks to complete.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn shutdown(mut self) -> Result<()> {\n // TODO: Graceful cancellation.\n self.tasks.abort_all();\n self.run_until_done().await?;\n Ok(())\n }\n```"}], "func_name": "shutdown", "docstring": "Shutdown the server and wait for all tasks to complete.", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/http.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/http.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e58a60a7b8eeee8d4c2fc3ccee287aa422f0685315e137dee1cf7116bdc9a2c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_with_config_until_ctrl_c\n\nDocumentation:\nSpawn the server and run until the `Ctrl-C` signal is received, then shutdown.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_with_config_until_ctrl_c(config: Config) -> Result<()> {\n let metrics = Arc::new(Metrics::default());\n let zone_store_options = config.zone_store.clone().unwrap_or_default();\n let mut store = ZoneStore::persistent(\n Config::signed_packet_store_path()?,\n zone_store_options.into(),\n metrics.clone(),\n )?;\n if let Some(bootstrap) = config.mainline_enabled() {\n info!(\"mainline fallback enabled\");\n store = store.with_mainline_fallback(bootstrap);\n };\n let server = Server::spawn(config, store, metrics).await?;\n tokio::signal::ctrl_c().await.e()?;\n info!(\"shutdown\");\n server.shutdown().await?;\n Ok(())\n}\n```"}], "func_name": "run_with_config_until_ctrl_c", "docstring": "Spawn the server and run until the `Ctrl-C` signal is received, then shutdown.", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ab8566129e9b00689b4319e4bba57a210d1fbddf7ebe42680bca177d1ee5e65b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn\n\nDocumentation:\nSpawn the server.\n\nThis will spawn several background tasks:\n* A DNS server task\n* A HTTP server task, if `config.http` is not empty\n* A HTTPS server task, if `config.https` is not empty\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn spawn(config: Config, store: ZoneStore, metrics: Arc) -> Result {\n let dns_handler = DnsHandler::new(store.clone(), &config.dns, metrics.clone())?;\n\n let state = AppState {\n store,\n dns_handler,\n metrics: metrics.clone(),\n };\n\n let metrics_addr = config.metrics_addr();\n let metrics_task = tokio::task::spawn(async move {\n if let Some(addr) = metrics_addr {\n let mut registry = iroh_metrics::Registry::default();\n registry.register(metrics);\n start_metrics_server(addr, Arc::new(registry)).await.e()?;\n }\n Ok(())\n });\n let http_server = HttpServer::spawn(\n config.http,\n config.https,\n config.pkarr_put_rate_limit,\n state.clone(),\n )\n .await?;\n let dns_server = DnsServer::spawn(config.dns, state.dns_handler.clone()).await?;\n Ok(Self {\n http_server,\n dns_server,\n metrics_task,\n })\n }\n```"}], "func_name": "spawn", "docstring": "Spawn the server.\n\nThis will spawn several background tasks:\n* A DNS server task\n* A HTTP server task, if `config.http` is not empty\n* A HTTPS server task, if `config.https` is not empty", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a4383c6e18668671372b80ccb84420d1d8e2e59f817a3b077c8dbad646dafc74"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shutdown\n\nDocumentation:\nCancel the server tasks and wait for all tasks to complete.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn shutdown(self) -> Result<()> {\n self.metrics_task.abort();\n let (res1, res2) = tokio::join!(self.dns_server.shutdown(), self.http_server.shutdown(),);\n res1?;\n res2?;\n Ok(())\n }\n```"}], "func_name": "shutdown", "docstring": "Cancel the server tasks and wait for all tasks to complete.", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5bdf892b9c1aefd4cd6bf0a9df33fff20e60bf8cd4d53e22d934e7200cba4efd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_until_error\n\nDocumentation:\nWait for all tasks to complete.\n\nThis will run forever unless all tasks close with an error, or `Self::cancel` is called.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn run_until_error(self) -> Result<()> {\n tokio::select! {\n res = self.dns_server.run_until_done() => res?,\n res = self.http_server.run_until_done() => res?,\n }\n self.metrics_task.abort();\n Ok(())\n }\n```"}], "func_name": "run_until_error", "docstring": "Wait for all tasks to complete.\n\nThis will run forever unless all tasks close with an error, or `Self::cancel` is called.", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b558e4736a9fadad7b50437ce9e64d4d5a965b73e7d2fbf41358bf852275565a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_mainline_fallback\n\nDocumentation:\nConfigure a pkarr client for resolution of packets from the bittorrent mainline DHT.\n\nThis will be used only as a fallback if there is no local info available.\n\nOptionally set custom bootstrap nodes. If `bootstrap` is empty it will use the default\nmainline bootstrap nodes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_mainline_fallback(self, bootstrap: BootstrapOption) -> Self {\n let pkarr_client = match bootstrap {\n BootstrapOption::Default => PkarrClient::builder().build().unwrap(),\n BootstrapOption::Custom(bootstrap) => PkarrClient::builder()\n .dht(|builder| builder.bootstrap(&bootstrap))\n .build()\n .unwrap(),\n };\n Self {\n pkarr: Some(Arc::new(pkarr_client)),\n ..self\n }\n }\n```"}], "func_name": "with_mainline_fallback", "docstring": "Configure a pkarr client for resolution of packets from the bittorrent mainline DHT.\n\nThis will be used only as a fallback if there is no local info available.\n\nOptionally set custom bootstrap nodes. If `bootstrap` is empty it will use the default\nmainline bootstrap nodes.", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/store.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/store.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c13eaa1cc1e6539fdb3275994c98f75d83549334534dc1db7ccc2ef7c2fb94f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nGET handler for resolving DoH queries\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get(\n State(state): State,\n DnsRequestQuery(request, accept_type): DnsRequestQuery,\n) -> AppResult {\n let message_bytes = state.dns_handler.answer_request(request).await?;\n let message = proto::op::Message::from_bytes(&message_bytes).e()?;\n\n let min_ttl = message.answers().iter().map(|rec| rec.ttl()).min();\n\n let mut response = match accept_type {\n DnsMimeType::Message => (StatusCode::OK, message_bytes).into_response(),\n DnsMimeType::Json => {\n let response = self::response::DnsResponse::from_message(message)?;\n (StatusCode::OK, Json(response)).into_response()\n }\n };\n\n response\n .headers_mut()\n .insert(CONTENT_TYPE, accept_type.to_header_value());\n\n if let Some(min_ttl) = min_ttl {\n let maxage = HeaderValue::from_str(&format!(\"s-maxage={min_ttl}\")).e()?;\n response.headers_mut().insert(CACHE_CONTROL, maxage);\n }\n\n Ok(response)\n}\n```"}], "func_name": "get", "docstring": "GET handler for resolving DoH queries", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/http/doh.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/http/doh.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4a19d7f96aaff88f83e9f844e9e134ae52432eeafd7a384cd694cd3db3a5f51e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: post\n\nDocumentation:\nPOST handler for resolvng DoH queries\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn post(\n State(state): State,\n DnsRequestBody(request): DnsRequestBody,\n) -> Response {\n let response = match state.dns_handler.answer_request(request).await {\n Ok(response) => response,\n Err(err) => return (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()).into_response(),\n };\n\n (\n StatusCode::OK,\n [(CONTENT_TYPE, DnsMimeType::Message.to_string())],\n response,\n )\n .into_response()\n}\n```"}], "func_name": "post", "docstring": "POST handler for resolvng DoH queries", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/http/doh.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/http/doh.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2923d1543a92f8f968b6bea18ea5ee6e75a98317a593538f84e86afbff10d509"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build\n\nDocumentation:\nBuild the [`TlsAcceptor`] for this mode.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) async fn build(\n &self,\n domains: Vec,\n cert_cache: PathBuf,\n letsencrypt_contact: Option,\n letsencrypt_prod: bool,\n ) -> Result {\n Ok(match self {\n CertMode::Manual => TlsAcceptor::manual(domains, cert_cache).await?,\n CertMode::SelfSigned => TlsAcceptor::self_signed(domains).await?,\n CertMode::LetsEncrypt => {\n let contact =\n letsencrypt_contact.context(\"contact is required for letsencrypt cert mode\")?;\n TlsAcceptor::letsencrypt(domains, &contact, letsencrypt_prod, cert_cache)?\n }\n })\n }\n```"}], "func_name": "build", "docstring": "Build the [`TlsAcceptor`] for this mode.", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/http/tls.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/http/tls.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "750cb8de9240d67c09423c28540c5e5aab21f675ca6aa98910e3b03fd2705eff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_header_value\n\nDocumentation:\nTurn this mime type to an `Accept` HTTP header value\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_header_value(&self) -> HeaderValue {\n HeaderValue::from_static(match self {\n Self::Message => \"application/dns-message\",\n Self::Json => \"application/dns-json\",\n })\n }\n```"}], "func_name": "to_header_value", "docstring": "Turn this mime type to an `Accept` HTTP header value", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/http/doh/extract.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/http/doh/extract.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6567a89cf9afa67fa74ff45b6cfcec31731abc5d626add35d4b6a7c72239f24d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode_query_as_request\n\nDocumentation:\nExposed to make it usable internally...\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn encode_query_as_request(\n question: DnsQuery,\n src_addr: SocketAddr,\n) -> Result {\n let query_type = if let Some(record_type) = question.record_type {\n record_type\n .parse::()\n .map(proto::rr::RecordType::from)\n .or_else(|_| FromStr::from_str(&record_type.to_uppercase()))\n .map_err(|err| AppError::new(StatusCode::BAD_REQUEST, Some(err)))?\n } else {\n proto::rr::RecordType::A\n };\n\n let name = proto::rr::Name::from_utf8(question.name)\n .map_err(|err| AppError::new(StatusCode::BAD_REQUEST, Some(err)))?;\n\n let query = proto::op::Query::query(name, query_type);\n\n let mut message = proto::op::Message::new();\n\n message\n .add_query(query)\n .set_message_type(proto::op::MessageType::Query)\n .set_op_code(proto::op::OpCode::Query)\n .set_checking_disabled(question.cd.unwrap_or(false))\n .set_recursion_desired(question.recursion_desired.unwrap_or(true))\n .set_recursion_available(true)\n .set_authentic_data(question.dnssec_ok.unwrap_or(false));\n\n // This is kind of a hack, but the only way I can find to\n // create a MessageRequest is by decoding a buffer of bytes,\n // so we encode the message into a buffer and then decode it\n let mut buf = Vec::with_capacity(4096);\n let mut encoder = BinEncoder::new(&mut buf);\n\n message\n .emit(&mut encoder)\n .map_err(|err| AppError::new(StatusCode::BAD_REQUEST, Some(err)))?;\n\n let request = decode_request(&buf, src_addr)?;\n\n Ok(request)\n}\n```"}], "func_name": "encode_query_as_request", "docstring": "Exposed to make it usable internally...", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/http/doh/extract.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/http/doh/extract.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1dea704ae41479ccdf8aaa22348a6914cc2ba8021a7f9e489ffaecd3d62fabb2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_message\n\nDocumentation:\nCreate a new JSON response from a DNS message\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_message(message: proto::op::Message) -> Result {\n ensure_whatever!(\n message.message_type() == proto::op::MessageType::Response,\n \"Expected message type to be response\"\n );\n\n ensure_whatever!(\n message.query_count() == message.queries().len() as u16,\n \"Query count mismatch\"\n );\n\n ensure_whatever!(\n message.answer_count() == message.answers().len() as u16,\n \"Answer count mismatch\"\n );\n\n let status: u32 =\n >::from(message.response_code()) as u32;\n\n let question: Vec<_> = message\n .queries()\n .iter()\n .map(DohQuestionJson::from_query)\n .collect();\n\n let answer: Vec<_> = message\n .answers()\n .iter()\n .map(DohRecordJson::from_record)\n .collect::>()?;\n\n Ok(DnsResponse {\n status,\n tc: message.truncated(),\n rd: message.recursion_desired(),\n ra: message.recursion_available(),\n ad: message.authentic_data(),\n cd: message.checking_disabled(),\n question,\n answer,\n comment: None,\n edns_client_subnet: None,\n })\n }\n```"}], "func_name": "from_message", "docstring": "Create a new JSON response from a DNS message", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/http/doh/response.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/http/doh/response.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a20a359003e9e882a7a00e555830bcd15cce1a8f13e1eb224afa318cf2e97964"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_query\n\nDocumentation:\nCreate a new JSON question from a DNS query\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_query(query: &proto::op::Query) -> Self {\n Self {\n name: query.name().to_string(),\n question_type: query.query_type().into(),\n }\n }\n```"}], "func_name": "from_query", "docstring": "Create a new JSON question from a DNS query", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/http/doh/response.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/http/doh/response.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c056e775420f5383872ddd423b07ed10d5863d7fcfe724f533c1e7bda5d1dce7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_record\n\nDocumentation:\nCreate a new JSON record from a DNS record\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_record(record: &proto::rr::Record) -> Result {\n Ok(Self {\n name: record.name().to_string(),\n record_type: record.record_type().into(),\n ttl: record.ttl(),\n data: record.data().to_string(),\n })\n }\n```"}], "func_name": "from_record", "docstring": "Create a new JSON record from a DNS record", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/http/doh/response.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/http/doh/response.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aa46bf20667ac9c66ac80e7110ac9de7ca6455cdf7e47f02586427eae4a25164"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: evict_task_inner\n\nDocumentation:\nPeriodically check for expired packets and remove them.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn evict_task_inner(send: mpsc::Sender, options: Options) -> Result<()> {\n let expiry_us = options.eviction.as_micros() as u64;\n loop {\n let (tx, rx) = oneshot::channel();\n let _ = send.send(Message::Snapshot { res: tx }).await.ok();\n // if we can't get the snapshot we exit the loop, main actor dead\n let snapshot = rx.await.context(\"failed to get snapshot\")?;\n\n let expired = Timestamp::now() - expiry_us;\n trace!(\"evicting packets older than {}\", fmt_time(expired));\n // if getting the range fails we exit the loop and shut down\n // if individual reads fail we log the error and limp on\n for item in snapshot.update_time.range(..expired.to_bytes()).e()? {\n let (time, keys) = match item {\n Ok(v) => v,\n Err(e) => {\n error!(\"failed to read update_time row {:?}\", e);\n continue;\n }\n };\n let time = Timestamp::from(time.value());\n trace!(\"evicting expired packets at {}\", fmt_time(time));\n for item in keys {\n let key = match item {\n Ok(v) => v,\n Err(e) => {\n error!(\n \"failed to read update_time item at {}: {:?}\",\n fmt_time(time),\n e\n );\n continue;\n }\n };\n let key = PublicKeyBytes::new(key.value());\n\n debug!(\"evicting expired packet {} {}\", fmt_time(time), key);\n send.send(Message::CheckExpired { time, key }).await.e()?;\n }\n }\n // sleep for the eviction interval so we don't constantly check\n tokio::time::sleep(options.eviction_interval).await;\n }\n}\n```"}], "func_name": "evict_task_inner", "docstring": "Periodically check for expired packets and remove them.", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/store/signed_packets.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/store/signed_packets.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "47f4be20ad38e3f8e6141e2d705b11abea99cd9c36cb17506b60683acff9e3f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nSpawn a new io thread.\n\nCalling this function requires that the current thread is running in a\ntokio runtime. It is up to the caller to make sure the future exits,\ne.g. by using a cancellation token. Otherwise, drop will block.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(name: &str, f: F) -> Result\n where\n F: FnOnce() -> Fut + Send + 'static,\n Fut: Future,\n {\n let rt = tokio::runtime::Handle::try_current().context(\"get tokio handle\")?;\n let handle = std::thread::Builder::new()\n .name(name.into())\n .spawn(move || rt.block_on(f()))\n .context(\"failed to spawn thread\")?;\n Ok(Self {\n handle: Some(handle),\n })\n }\n```"}], "func_name": "new", "docstring": "Spawn a new io thread.\n\nCalling this function requires that the current thread is running in a\ntokio runtime. It is up to the caller to make sure the future exits,\ne.g. by using a cancellation token. Otherwise, drop will block.", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/store/signed_packets.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/store/signed_packets.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d53fda1c3f0014a36a4e075fbab707bdaa3498b04b85e3da87dfa5a936dd3b39"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: recv\n\nDocumentation:\nReceive the next message.\n\nWill block if there are no messages.\nReturns None only if there are no more messages (sender is dropped).\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn recv(&mut self) -> Option {\n if let Some(msg) = self.msg.take() {\n return Some(msg);\n }\n self.recv.recv().await\n }\n```"}], "func_name": "recv", "docstring": "Receive the next message.\n\nWill block if there are no messages.\nReturns None only if there are no more messages (sender is dropped).", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/store/signed_packets.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/store/signed_packets.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd287376092947078bf857edcff53032412b9b613d5147e4ca12d8aa3256f5c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_back\n\nDocumentation:\nPush back a message. This will only work if there is room for it.\nOtherwise, it will fail and return the message.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn push_back(&mut self, msg: T) -> std::result::Result<(), T> {\n if self.msg.is_none() {\n self.msg = Some(msg);\n Ok(())\n } else {\n Err(msg)\n }\n }\n```"}], "func_name": "push_back", "docstring": "Push back a message. This will only work if there is room for it.\nOtherwise, it will fail and return the message.", "repo": "n0-computer/iroh", "path": "iroh-dns-server/src/store/signed_packets.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-dns-server/src/store/signed_packets.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e3cce719514070575c21030357e24da1dd35d7cb0b2eb35d4ee4281b0d02dfa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: protocol\n\nDocumentation:\nSets whether to connect to the relay via websockets or not.\nSet to use non-websocket, normal relaying by default.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn protocol(mut self, protocol: Protocol) -> Self {\n self.protocol = protocol;\n self\n }\n```"}], "func_name": "protocol", "docstring": "Sets whether to connect to the relay via websockets or not.\nSet to use non-websocket, normal relaying by default.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/client.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e23e0687cf024cc883b459fbc0d4e8113c19cc4355f93e0444931358f18e00d2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: address_family_selector\n\nDocumentation:\nReturns if we should prefer ipv6\nit replaces the relayhttp.AddressFamilySelector we pass\nIt provides the hint as to whether in an IPv4-vs-IPv6 race that\nIPv4 should be held back a bit to give IPv6 a better-than-50/50\nchance of winning. We only return true when we believe IPv6 will\nwork anyway, so we don't artificially delay the connection speed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn address_family_selector(mut self, selector: S) -> Self\n where\n S: Fn() -> bool + Send + Sync + 'static,\n {\n self.address_family_selector = Some(Arc::new(selector));\n self\n }\n```"}], "func_name": "address_family_selector", "docstring": "Returns if we should prefer ipv6\nit replaces the relayhttp.AddressFamilySelector we pass\nIt provides the hint as to whether in an IPv4-vs-IPv6 race that\nIPv4 should be held back a bit to give IPv6 a better-than-50/50\nchance of winning. We only return true when we believe IPv6 will\nwork anyway, so we don't artificially delay the connection speed.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/client.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48954c106578fcc57d65ff620190bcba45cd76e37bb3dc792c635c016e75c664"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: key_cache_capacity\n\nDocumentation:\nSet the capacity of the cache for public keys.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn key_cache_capacity(mut self, capacity: usize) -> Self {\n self.key_cache = KeyCache::new(capacity);\n self\n }\n```"}], "func_name": "key_cache_capacity", "docstring": "Set the capacity of the cache for public keys.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/client.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "647e6945413f282948ce678deef744a1c87568329c38c521ca7dcda7e1263f92"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nEstablishes a new connection to the relay server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn connect(&self) -> Result {\n let (conn, local_addr) = match self.protocol {\n #[cfg(wasm_browser)]\n Protocol::Websocket => {\n let conn = self.connect_ws().await?;\n let local_addr = None;\n (conn, local_addr)\n }\n #[cfg(not(wasm_browser))]\n Protocol::Websocket => {\n let (conn, local_addr) = self.connect_ws().await?;\n (conn, Some(local_addr))\n }\n #[cfg(not(wasm_browser))]\n Protocol::Relay => {\n let (conn, local_addr) = self.connect_relay().await?;\n (conn, Some(local_addr))\n }\n #[cfg(wasm_browser)]\n Protocol::Relay => return Err(RelayProtoNotAvailableSnafu.build()),\n };\n\n event!(\n target: \"events.net.relay.connected\",\n Level::DEBUG,\n url = %self.url,\n protocol = ?self.protocol,\n );\n\n trace!(\"connect done\");\n Ok(Client { conn, local_addr })\n }\n```"}], "func_name": "connect", "docstring": "Establishes a new connection to the relay server.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/client.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "419d5bdfc244bdfe05e5dbb1edbec560ab295b702e17a78a8f948542e68b2991"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: split\n\nDocumentation:\nSplits the client into a sink and a stream.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn split(self) -> (ClientStream, ClientSink) {\n let (sink, stream) = split(self.conn);\n (\n ClientStream {\n stream,\n local_addr: self.local_addr,\n },\n ClientSink { sink },\n )\n }\n```"}], "func_name": "split", "docstring": "Splits the client into a sink and a stream.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/client.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "55551b8c19071da0acb8738308e7a5392e6cfcff87861ba1024a4298f1b7dea1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_dangerous_client_config\n\nDocumentation:\nCreates a client config that trusts any servers without verifying their TLS certificate.\n\nShould be used for testing local relay setups only.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn make_dangerous_client_config() -> rustls::ClientConfig {\n warn!(\n \"Insecure config: SSL certificates from relay servers will be trusted without verification\"\n );\n rustls::client::ClientConfig::builder_with_provider(Arc::new(\n rustls::crypto::ring::default_provider(),\n ))\n .with_protocol_versions(&[&rustls::version::TLS13])\n .expect(\"protocols supported by ring\")\n .dangerous()\n .with_custom_certificate_verifier(Arc::new(NoCertVerifier))\n .with_no_client_auth()\n}\n```"}], "func_name": "make_dangerous_client_config", "docstring": "Creates a client config that trusts any servers without verifying their TLS certificate.\n\nShould be used for testing local relay setups only.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/client.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "586f990c7d01e176242a97de80e66b09d7fbc202237f7e449a909be977a1d3e5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new DNS resolver with sensible cross-platform defaults.\n\nWe first try to read the system's resolver from `/etc/resolv.conf`.\nThis does not work at least on some Androids, therefore we fallback\nto the default `ResolverConfig` which uses eg. to google's `8.8.8.8` or `8.8.4.4`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new() -> Self {\n let (system_config, mut options) =\n hickory_resolver::system_conf::read_system_conf().unwrap_or_default();\n\n // Copy all of the system config, but strip the bad windows nameservers. Unfortunately\n // there is no easy way to do this.\n let mut config = hickory_resolver::config::ResolverConfig::new();\n if let Some(name) = system_config.domain() {\n config.set_domain(name.clone());\n }\n for name in system_config.search() {\n config.add_search(name.clone());\n }\n for nameserver_cfg in system_config.name_servers() {\n if !WINDOWS_BAD_SITE_LOCAL_DNS_SERVERS.contains(&nameserver_cfg.socket_addr.ip()) {\n config.add_name_server(nameserver_cfg.clone());\n }\n }\n\n // see [`DnsResolver::lookup_ipv4_ipv6`] for info on why we avoid `LookupIpStrategy::Ipv4AndIpv6`\n options.ip_strategy = hickory_resolver::config::LookupIpStrategy::Ipv4thenIpv6;\n\n let mut builder =\n TokioResolver::builder_with_config(config, TokioConnectionProvider::default());\n *builder.options_mut() = options;\n DnsResolver(builder.build())\n }\n```"}], "func_name": "new", "docstring": "Create a new DNS resolver with sensible cross-platform defaults.\n\nWe first try to read the system's resolver from `/etc/resolv.conf`.\nThis does not work at least on some Androids, therefore we fallback\nto the default `ResolverConfig` which uses eg. to google's `8.8.8.8` or `8.8.4.4`.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cfb9b5f8bb048d5f043e7978c1932b53f2e80ae5201a2f7f3d8d32184fd128cb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_nameserver\n\nDocumentation:\nCreate a new DNS resolver configured with a single UDP DNS nameserver.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_nameserver(nameserver: SocketAddr) -> Self {\n let mut config = hickory_resolver::config::ResolverConfig::new();\n let nameserver_config = hickory_resolver::config::NameServerConfig::new(\n nameserver,\n hickory_resolver::proto::xfer::Protocol::Udp,\n );\n config.add_name_server(nameserver_config);\n\n let builder =\n TokioResolver::builder_with_config(config, TokioConnectionProvider::default());\n DnsResolver(builder.build())\n }\n```"}], "func_name": "with_nameserver", "docstring": "Create a new DNS resolver configured with a single UDP DNS nameserver.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f5d0cafa9ed4abe07e8d6f24e002a9495cb0e1fd7326985750626de5ed93385"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lookup_ipv4_ipv6\n\nDocumentation:\nResolve IPv4 and IPv6 in parallel with a timeout.\n\n`LookupIpStrategy::Ipv4AndIpv6` will wait for ipv6 resolution timeout, even if it is\nnot usable on the stack, so we manually query both lookups concurrently and time them out\nindividually.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn lookup_ipv4_ipv6(\n &self,\n host: impl ToString,\n timeout: Duration,\n ) -> Result, DnsError> {\n let host = host.to_string();\n let res = tokio::join!(\n self.lookup_ipv4(host.clone(), timeout),\n self.lookup_ipv6(host, timeout)\n );\n\n match res {\n (Ok(ipv4), Ok(ipv6)) => Ok(LookupIter::Both(ipv4.chain(ipv6))),\n (Ok(ipv4), Err(_)) => Ok(LookupIter::Ipv4(ipv4)),\n (Err(_), Ok(ipv6)) => Ok(LookupIter::Ipv6(ipv6)),\n (Err(ipv4_err), Err(ipv6_err)) => Err(ResolveBothSnafu {\n ipv4: Box::new(ipv4_err),\n ipv6: Box::new(ipv6_err),\n }\n .build()),\n }\n }\n```"}], "func_name": "lookup_ipv4_ipv6", "docstring": "Resolve IPv4 and IPv6 in parallel with a timeout.\n\n`LookupIpStrategy::Ipv4AndIpv6` will wait for ipv6 resolution timeout, even if it is\nnot usable on the stack, so we manually query both lookups concurrently and time them out\nindividually.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93ce738fec9ccf9edf80e330592dd9a7f89e22b2ac2b06bdf8faa56f80d8fa4e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve_host\n\nDocumentation:\nResolve a hostname from a URL to an IP address.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn resolve_host(\n &self,\n url: &Url,\n prefer_ipv6: bool,\n timeout: Duration,\n ) -> Result {\n let host = url.host().context(MissingHostSnafu)?;\n match host {\n url::Host::Domain(domain) => {\n // Need to do a DNS lookup\n let lookup = tokio::join!(\n self.lookup_ipv4(domain, timeout),\n self.lookup_ipv6(domain, timeout)\n );\n let (v4, v6) = match lookup {\n (Err(ipv4_err), Err(ipv6_err)) => {\n return Err(ResolveBothSnafu {\n ipv4: Box::new(ipv4_err),\n ipv6: Box::new(ipv6_err),\n }\n .build());\n }\n (Err(_), Ok(mut v6)) => (None, v6.next()),\n (Ok(mut v4), Err(_)) => (v4.next(), None),\n (Ok(mut v4), Ok(mut v6)) => (v4.next(), v6.next()),\n };\n if prefer_ipv6 {\n v6.or(v4).context(NoResponseSnafu)\n } else {\n v4.or(v6).context(NoResponseSnafu)\n }\n }\n url::Host::Ipv4(ip) => Ok(IpAddr::V4(ip)),\n url::Host::Ipv6(ip) => Ok(IpAddr::V6(ip)),\n }\n }\n```"}], "func_name": "resolve_host", "docstring": "Resolve a hostname from a URL to an IP address.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "27c0514ba7370419b034e8f3c9f3bd2558dadc92910935c65c022bcb532d680a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lookup_ipv4_staggered\n\nDocumentation:\nPerform an ipv4 lookup with a timeout in a staggered fashion.\n\nFrom the moment this function is called, each lookup is scheduled after the delays in\n`delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls\nat T+0ms, T+200ms and T+300ms. The `timeout` is applied to each call individually. The\nresult of the first successful call is returned, or a summary of all errors otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn lookup_ipv4_staggered(\n &self,\n host: impl ToString,\n timeout: Duration,\n delays_ms: &[u64],\n ) -> Result, StaggeredError> {\n let host = host.to_string();\n let f = || self.lookup_ipv4(host.clone(), timeout);\n stagger_call(f, delays_ms).await\n }\n```"}], "func_name": "lookup_ipv4_staggered", "docstring": "Perform an ipv4 lookup with a timeout in a staggered fashion.\n\nFrom the moment this function is called, each lookup is scheduled after the delays in\n`delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls\nat T+0ms, T+200ms and T+300ms. The `timeout` is applied to each call individually. The\nresult of the first successful call is returned, or a summary of all errors otherwise.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca0759c5123d3e95579803ef0a9f3d451bf050ee9994851bfcd3c3710ae84012"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lookup_ipv6_staggered\n\nDocumentation:\nPerform an ipv6 lookup with a timeout in a staggered fashion.\n\nFrom the moment this function is called, each lookup is scheduled after the delays in\n`delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls\nat T+0ms, T+200ms and T+300ms. The `timeout` is applied to each call individually. The\nresult of the first successful call is returned, or a summary of all errors otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn lookup_ipv6_staggered(\n &self,\n host: impl ToString,\n timeout: Duration,\n delays_ms: &[u64],\n ) -> Result, StaggeredError> {\n let host = host.to_string();\n let f = || self.lookup_ipv6(host.clone(), timeout);\n stagger_call(f, delays_ms).await\n }\n```"}], "func_name": "lookup_ipv6_staggered", "docstring": "Perform an ipv6 lookup with a timeout in a staggered fashion.\n\nFrom the moment this function is called, each lookup is scheduled after the delays in\n`delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls\nat T+0ms, T+200ms and T+300ms. The `timeout` is applied to each call individually. The\nresult of the first successful call is returned, or a summary of all errors otherwise.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c5f888d3ffe1254746976628790e46f3e2e3c3fc4e289965c350f42fa0d6ba5f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lookup_ipv4_ipv6_staggered\n\nDocumentation:\nRace an ipv4 and ipv6 lookup with a timeout in a staggered fashion.\n\nFrom the moment this function is called, each lookup is scheduled after the delays in\n`delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls\nat T+0ms, T+200ms and T+300ms. The `timeout` is applied as stated in\n[`Self::lookup_ipv4_ipv6`]. The result of the first successful call is returned, or a\nsummary of all errors otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn lookup_ipv4_ipv6_staggered(\n &self,\n host: impl ToString,\n timeout: Duration,\n delays_ms: &[u64],\n ) -> Result, StaggeredError> {\n let host = host.to_string();\n let f = || self.lookup_ipv4_ipv6(host.clone(), timeout);\n stagger_call(f, delays_ms).await\n }\n```"}], "func_name": "lookup_ipv4_ipv6_staggered", "docstring": "Race an ipv4 and ipv6 lookup with a timeout in a staggered fashion.\n\nFrom the moment this function is called, each lookup is scheduled after the delays in\n`delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls\nat T+0ms, T+200ms and T+300ms. The `timeout` is applied as stated in\n[`Self::lookup_ipv4_ipv6`]. The result of the first successful call is returned, or a\nsummary of all errors otherwise.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a2a1743fabf705fef7f6276e524bda69460023cc1c2081250e8a3446c93de58"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lookup_node_by_id\n\nDocumentation:\nLooks up node info by [`NodeId`] and origin domain name.\n\nTo lookup nodes that published their node info to the DNS servers run by n0,\npass [`N0_DNS_NODE_ORIGIN_PROD`] as `origin`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn lookup_node_by_id(\n &self,\n node_id: &NodeId,\n origin: &str,\n ) -> Result {\n let attrs = crate::node_info::TxtAttrs::::lookup_by_id(\n self, node_id, origin,\n )\n .await?;\n let info = attrs.into();\n Ok(info)\n }\n```"}], "func_name": "lookup_node_by_id", "docstring": "Looks up node info by [`NodeId`] and origin domain name.\n\nTo lookup nodes that published their node info to the DNS servers run by n0,\npass [`N0_DNS_NODE_ORIGIN_PROD`] as `origin`.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ecc1aa40f842f6b231e10b8a50dd7d63d90f3ebece65cecc403bcb016c171a46"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lookup_node_by_domain_name\n\nDocumentation:\nLooks up node info by DNS name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn lookup_node_by_domain_name(&self, name: &str) -> Result {\n let attrs =\n crate::node_info::TxtAttrs::::lookup_by_name(self, name)\n .await?;\n let info = attrs.into();\n Ok(info)\n }\n```"}], "func_name": "lookup_node_by_domain_name", "docstring": "Looks up node info by DNS name.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94b320782e7e04ea51b87b4c6243bde215950ab36c689d115bc3825a26a1cbd5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lookup_node_by_domain_name_staggered\n\nDocumentation:\nLooks up node info by DNS name in a staggered fashion.\n\nFrom the moment this function is called, each lookup is scheduled after the delays in\n`delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls\nat T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a\nsummary of all errors otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn lookup_node_by_domain_name_staggered(\n &self,\n name: &str,\n delays_ms: &[u64],\n ) -> Result> {\n let f = || self.lookup_node_by_domain_name(name);\n stagger_call(f, delays_ms).await\n }\n```"}], "func_name": "lookup_node_by_domain_name_staggered", "docstring": "Looks up node info by DNS name in a staggered fashion.\n\nFrom the moment this function is called, each lookup is scheduled after the delays in\n`delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls\nat T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a\nsummary of all errors otherwise.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5a23595fe1dc7f117f8ff0efdd58cb187262b3628e780b3dd38a957485e802f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: lookup_node_by_id_staggered\n\nDocumentation:\nLooks up node info by [`NodeId`] and origin domain name.\n\nFrom the moment this function is called, each lookup is scheduled after the delays in\n`delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls\nat T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a\nsummary of all errors otherwise.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn lookup_node_by_id_staggered(\n &self,\n node_id: &NodeId,\n origin: &str,\n delays_ms: &[u64],\n ) -> Result> {\n let f = || self.lookup_node_by_id(node_id, origin);\n stagger_call(f, delays_ms).await\n }\n```"}], "func_name": "lookup_node_by_id_staggered", "docstring": "Looks up node info by [`NodeId`] and origin domain name.\n\nFrom the moment this function is called, each lookup is scheduled after the delays in\n`delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls\nat T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a\nsummary of all errors otherwise.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e9d61630937607a1a998801ffa788f776157c1482b511d2016b61127d6c096d3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stagger_call\n\nDocumentation:\nStaggers calls to the future F with the given delays.\n\nThe first call is performed immediately. The first call to succeed generates an Ok result\nignoring any previous error. If all calls fail, an error summarizing all errors is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn stagger_call<\n T,\n E: std::fmt::Debug + std::fmt::Display,\n F: Fn() -> Fut,\n Fut: Future>,\n>(\n f: F,\n delays_ms: &[u64],\n) -> Result> {\n let mut calls = n0_future::FuturesUnorderedBounded::new(delays_ms.len() + 1);\n // NOTE: we add the 0 delay here to have a uniform set of futures. This is more performant than\n // using alternatives that allow futures of different types.\n for delay in std::iter::once(&0u64).chain(delays_ms) {\n let delay = Duration::from_millis(*delay);\n let fut = f();\n let staggered_fut = async move {\n time::sleep(delay).await;\n fut.await\n };\n calls.push(staggered_fut)\n }\n\n let mut errors = vec![];\n while let Some(call_result) = calls.next().await {\n match call_result {\n Ok(t) => return Ok(t),\n Err(e) => errors.push(e),\n }\n }\n\n Err(StaggeredError::new(errors))\n}\n```"}], "func_name": "stagger_call", "docstring": "Staggers calls to the future F with the given delays.\n\nThe first call is performed immediately. The first call to succeed generates an Ok result\nignoring any previous error. If all calls fail, an error summarizing all errors is returned.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/dns.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/dns.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "102865636a4c8d8db4daaadde4c9d6b28fbc66e6df88de04c5bb84cba72eb4e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: upgrade_header\n\nDocumentation:\nThe HTTP upgrade header used or expected.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub const fn upgrade_header(&self) -> &'static str {\n match self {\n Protocol::Relay => HTTP_UPGRADE_PROTOCOL,\n Protocol::Websocket => WEBSOCKET_UPGRADE_PROTOCOL,\n }\n }\n```"}], "func_name": "upgrade_header", "docstring": "The HTTP upgrade header used or expected.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/http.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/http.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8413dc5512beea5e1efd74745ca91aa1220b37dfe426eb32ddf620d3ea9ff2ad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_header\n\nDocumentation:\nTries to match the value of an HTTP upgrade header to figure out which protocol should be initiated.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_header(header: &http::HeaderValue) -> Option {\n let header_bytes = header.as_bytes();\n if header_bytes == Protocol::Relay.upgrade_header().as_bytes() {\n Some(Protocol::Relay)\n } else if header_bytes == Protocol::Websocket.upgrade_header().as_bytes() {\n Some(Protocol::Websocket)\n } else {\n None\n }\n }\n```"}], "func_name": "parse_header", "docstring": "Tries to match the value of an HTTP upgrade header to figure out which protocol should be initiated.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/http.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/http.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9f193805adc90f0d6075f8f37e8a5a7af8c7e99a8334e931578a5796170e79f2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new key cache with the given capacity.\n\nIf the capacity is zero, the cache is disabled and has zero overhead.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(capacity: usize) -> Self {\n let Some(capacity) = NonZeroUsize::new(capacity) else {\n return Self::Disabled;\n };\n let cache = lru::LruCache::new(capacity);\n Self::Shared(Arc::new(Mutex::new(cache)))\n }\n```"}], "func_name": "new", "docstring": "Create a new key cache with the given capacity.\n\nIf the capacity is zero, the cache is disabled and has zero overhead.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/key_cache.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/key_cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "810a73ed359e51110be5a6031c4fd8dddab897a6a80adf036a81d501ad4b0821"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: key_from_slice\n\nDocumentation:\nGet a key from a slice of bytes.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn key_from_slice(&self, slice: &[u8]) -> Result {\n let Self::Shared(cache) = self else {\n return PublicKey::try_from(slice);\n };\n let Ok(bytes) = PublicKeyBytes::try_from(slice) else {\n // if the size is wrong, use PublicKey::try_from to fail with a\n // SignatureError.\n return Err(PublicKey::try_from(slice).expect_err(\"invalid length\"));\n };\n let mut cache = cache.lock().expect(\"not poisoned\");\n if let Some((key, _)) = cache.get_key_value(&bytes) {\n return Ok(*key);\n }\n let key = PublicKey::from_bytes(&bytes)?;\n cache.put(key, ());\n Ok(key)\n }\n```"}], "func_name": "key_from_slice", "docstring": "Get a key from a slice of bytes.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/key_cache.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/key_cache.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3ec4ba4b304ee41b353ad453d46b2c5476b1db13a82b927367633020217e1687"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: build_relay_config\n\nDocumentation:\nConvert the TOML-loaded config to the [`relay::RelayConfig`] format.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn build_relay_config(cfg: Config) -> Result> {\n // Don't bind to https, even if tls configuration is available.\n // Is really only relevant if we are in `--dev` mode & we also have TLS configuration\n // enabled to use QUIC address discovery locally.\n let dangerous_http_only = cfg.tls.as_ref().is_some_and(|tls| tls.dangerous_http_only);\n let relay_tls = maybe_load_tls(&cfg).await?;\n\n let mut quic_config = None;\n if cfg.enable_quic_addr_discovery {\n if let Some(ref tls) = relay_tls {\n quic_config = Some(QuicConfig {\n server_config: tls.server_config.clone(),\n bind_addr: tls.quic_bind_addr,\n });\n } else {\n whatever!(\"Must have a valid TLS configuration to enable a QUIC server for QUIC address discovery\")\n }\n };\n let limits = match cfg.limits {\n Some(ref limits) => {\n let client_rx = match &limits.client {\n Some(PerClientRateLimitConfig { rx: Some(rx) }) => {\n if rx.bytes_per_second.is_none() && rx.max_burst_bytes.is_some() {\n whatever!(\"bytes_per_seconds must be specified to enable the rate-limiter\");\n }\n match rx.bytes_per_second {\n Some(bps) => Some(ClientRateLimit {\n bytes_per_second: TryInto::::try_into(bps)\n .context(\"bytes_per_second must be non-zero u32\")?,\n max_burst_bytes: rx\n .max_burst_bytes\n .map(|v| {\n TryInto::::try_into(v)\n .context(\"max_burst_bytes must be non-zero u32\")\n })\n .transpose()?,\n }),\n None => None,\n }\n }\n Some(PerClientRateLimitConfig { rx: None }) | None => None,\n };\n relay::Limits {\n accept_conn_limit: limits.accept_conn_limit,\n accept_conn_burst: limits.accept_conn_burst,\n client_rx,\n }\n }\n None => Default::default(),\n };\n\n let relay_config = relay::RelayConfig {\n http_bind_addr: cfg.http_bind_addr(),\n // if `dangerous_http_only` is set, do not pass in any tls configuration\n tls: relay_tls.and_then(|tls| if dangerous_http_only { None } else { Some(tls) }),\n limits,\n key_cache_capacity: cfg.key_cache_capacity,\n access: cfg.access.clone().into(),\n };\n\n let stun_config = relay::StunConfig {\n bind_addr: cfg.stun_bind_addr(),\n };\n Ok(relay::ServerConfig {\n relay: Some(relay_config),\n stun: Some(stun_config).filter(|_| cfg.enable_stun),\n quic: quic_config,\n #[cfg(feature = \"metrics\")]\n metrics_addr: Some(cfg.metrics_bind_addr()).filter(|_| cfg.enable_metrics),\n })\n}\n```"}], "func_name": "build_relay_config", "docstring": "Convert the TOML-loaded config to the [`relay::RelayConfig`] format.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/main.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/main.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1254d771289030462f4e5f04ec1288290498673a6545bbef1df981c801d5c15d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new [`NodeData`] with a relay URL and a set of direct addresses.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(relay_url: Option, direct_addresses: BTreeSet) -> Self {\n Self {\n relay_url,\n direct_addresses,\n user_data: None,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new [`NodeData`] with a relay URL and a set of direct addresses.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f90193cbdcda71618c6a49cd729eedefc054599da7eacd2986fbde83f4703bc1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_relay_url\n\nDocumentation:\nSets the relay URL and returns the updated node data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_relay_url(mut self, relay_url: Option) -> Self {\n self.relay_url = relay_url;\n self\n }\n```"}], "func_name": "with_relay_url", "docstring": "Sets the relay URL and returns the updated node data.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2010878f6e5aaf4667dff4ed2222de96844b7f98367f274a067b61f557468b8c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_direct_addresses\n\nDocumentation:\nSets the direct addresses and returns the updated node data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_direct_addresses(mut self, direct_addresses: BTreeSet) -> Self {\n self.direct_addresses = direct_addresses;\n self\n }\n```"}], "func_name": "with_direct_addresses", "docstring": "Sets the direct addresses and returns the updated node data.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "303b0a222cd2c0da70e4200900cf10ea39c7f81ed2fbcc04dce691d3d36331d6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_user_data\n\nDocumentation:\nSets the user-defined data and returns the updated node data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_user_data(mut self, user_data: Option) -> Self {\n self.user_data = user_data;\n self\n }\n```"}], "func_name": "with_user_data", "docstring": "Sets the user-defined data and returns the updated node data.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e43822cc3fe6638010567b24df624c672b2ca3a1473e21a2a16cce51d9ed4846"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clear_direct_addresses\n\nDocumentation:\nRemoves all direct addresses from the node data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clear_direct_addresses(&mut self) {\n self.direct_addresses = Default::default();\n }\n```"}], "func_name": "clear_direct_addresses", "docstring": "Removes all direct addresses from the node data.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "78699be7802fa5107a2e55f98bca3bee3f86f7a1342dd82c403770d342490eaf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_relay_url\n\nDocumentation:\nSets the relay URL of the node data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_relay_url(&mut self, relay_url: Option) {\n self.relay_url = relay_url\n }\n```"}], "func_name": "set_relay_url", "docstring": "Sets the relay URL of the node data.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "010a4310585e1f99a1479788b00eb0119da05e004e879f7df08661256d36c24a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_user_data\n\nDocumentation:\nSets the user-defined data of the node data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_user_data(&mut self, user_data: Option) {\n self.user_data = user_data;\n }\n```"}], "func_name": "set_user_data", "docstring": "Sets the user-defined data of the node data.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf0aced4f1d1bbc07935e49e5ad8c1983973997dd9d911149ff7db35facf4108"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new [`NodeInfo`] with an empty [`NodeData`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(node_id: NodeId) -> Self {\n Self::from_parts(node_id, Default::default())\n }\n```"}], "func_name": "new", "docstring": "Creates a new [`NodeInfo`] with an empty [`NodeData`].", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "29596c3b4844848585e9dc1300eff4d4c3b593c5c74b7ab532a1eefe0a0968df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_parts\n\nDocumentation:\nCreates a new [`NodeInfo`] from its parts.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_parts(node_id: NodeId, data: NodeData) -> Self {\n Self { node_id, data }\n }\n```"}], "func_name": "from_parts", "docstring": "Creates a new [`NodeInfo`] from its parts.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "413a68fc288714dca336412190c65281fc9b78bd12320f8ce50bd04fdfb715eb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_relay_url\n\nDocumentation:\nSets the relay URL and returns the updated node info.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_relay_url(mut self, relay_url: Option) -> Self {\n self.data = self.data.with_relay_url(relay_url);\n self\n }\n```"}], "func_name": "with_relay_url", "docstring": "Sets the relay URL and returns the updated node info.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a6ac8f41e78314a17a60c352c715c04ce65f4f8d03333ffa2465c7cf611e9e2a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_direct_addresses\n\nDocumentation:\nSets the direct addresses and returns the updated node info.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_direct_addresses(mut self, direct_addresses: BTreeSet) -> Self {\n self.data = self.data.with_direct_addresses(direct_addresses);\n self\n }\n```"}], "func_name": "with_direct_addresses", "docstring": "Sets the direct addresses and returns the updated node info.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f54c5649c6bc4ca26f8812bdaac83b88e031eaf0a530f0ff6a3b27e57ea85cef"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_user_data\n\nDocumentation:\nSets the user-defined data and returns the updated node info.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_user_data(mut self, user_data: Option) -> Self {\n self.data = self.data.with_user_data(user_data);\n self\n }\n```"}], "func_name": "with_user_data", "docstring": "Sets the user-defined data and returns the updated node info.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "646e5b87113cd1b555289efb84fa85dc09283882e0264bd4e64a2deccd994558"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_node_addr\n\nDocumentation:\nConverts into a [`NodeAddr`] by cloning the needed fields.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_node_addr(&self) -> NodeAddr {\n NodeAddr {\n node_id: self.node_id,\n relay_url: self.data.relay_url.clone(),\n direct_addresses: self.data.direct_addresses.clone(),\n }\n }\n```"}], "func_name": "to_node_addr", "docstring": "Converts into a [`NodeAddr`] by cloning the needed fields.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3dd39ce68bbed6648a35a6b2b7c318cec76b0214348dc4c6c942a224514d4615"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_txt_lookup\n\nDocumentation:\nParses a [`NodeInfo`] from a TXT records lookup.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn from_txt_lookup(lookup: crate::dns::TxtLookup) -> Result {\n let attrs = TxtAttrs::from_txt_lookup(lookup)?;\n Ok(attrs.into())\n }\n```"}], "func_name": "from_txt_lookup", "docstring": "Parses a [`NodeInfo`] from a TXT records lookup.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a380ae9ade8952b53698dcfc2c8364dbef82d2c8b05b3af561968d18315e614"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_pkarr_signed_packet\n\nDocumentation:\nCreates a [`pkarr::SignedPacket`].\n\nThis constructs a DNS packet and signs it with a [`SecretKey`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_pkarr_signed_packet(\n &self,\n secret_key: &SecretKey,\n ttl: u32,\n ) -> Result {\n self.to_attrs().to_pkarr_signed_packet(secret_key, ttl)\n }\n```"}], "func_name": "to_pkarr_signed_packet", "docstring": "Creates a [`pkarr::SignedPacket`].\n\nThis constructs a DNS packet and signs it with a [`SecretKey`].", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8f220550cb4e6b7e8d30cab99866d89492ed30723f44483422eed99608ed4baa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_parts\n\nDocumentation:\nCreates [`TxtAttrs`] from a node id and an iterator of key-value pairs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn from_parts(node_id: NodeId, pairs: impl Iterator) -> Self {\n let mut attrs: BTreeMap> = BTreeMap::new();\n for (k, v) in pairs {\n attrs.entry(k).or_default().push(v);\n }\n Self { attrs, node_id }\n }\n```"}], "func_name": "from_parts", "docstring": "Creates [`TxtAttrs`] from a node id and an iterator of key-value pairs.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "600459ecb8cf8a3d0f5afd05cc3172c14705d41b5a7b2b4378596a280a2ef023"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_strings\n\nDocumentation:\nCreates [`TxtAttrs`] from a node id and an iterator of \"{key}={value}\" strings.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn from_strings(\n node_id: NodeId,\n strings: impl Iterator,\n ) -> Result {\n let mut attrs: BTreeMap> = BTreeMap::new();\n for s in strings {\n let mut parts = s.split('=');\n let (Some(key), Some(value)) = (parts.next(), parts.next()) else {\n return Err(UnexpectedFormatSnafu { s }.build());\n };\n let attr = T::from_str(key).map_err(|_| AttrFromStringSnafu { key }.build())?;\n attrs.entry(attr).or_default().push(value.to_string());\n }\n Ok(Self { attrs, node_id })\n }\n```"}], "func_name": "from_strings", "docstring": "Creates [`TxtAttrs`] from a node id and an iterator of \"{key}={value}\" strings.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "81573917d77c3897a6e623d02e678200b6dec1124b295cbe7f7285ed286037f2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_pkarr_signed_packet\n\nDocumentation:\nCreates a [`pkarr::SignedPacket`]\n\nThis constructs a DNS packet and signs it with a [`SecretKey`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn to_pkarr_signed_packet(\n &self,\n secret_key: &SecretKey,\n ttl: u32,\n ) -> Result {\n use pkarr::dns::{self, rdata};\n let keypair = pkarr::Keypair::from_secret_key(&secret_key.to_bytes());\n let name = dns::Name::new(IROH_TXT_NAME).expect(\"constant\");\n\n let mut builder = pkarr::SignedPacket::builder();\n for s in self.to_txt_strings() {\n let mut txt = rdata::TXT::new();\n txt.add_string(&s).context(InvalidTxtEntrySnafu)?;\n builder = builder.txt(name.clone(), txt.into_owned(), ttl);\n }\n let signed_packet = builder.build(&keypair)?;\n Ok(signed_packet)\n }\n```"}], "func_name": "to_pkarr_signed_packet", "docstring": "Creates a [`pkarr::SignedPacket`]\n\nThis constructs a DNS packet and signs it with a [`SecretKey`].", "repo": "n0-computer/iroh", "path": "iroh-relay/src/node_info.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/node_info.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4bef6aa389b1e74d99de0843b0155ce256d94dd0abf843f6c9b11350e51327f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new ping tracker, setting the ping timeout for pings.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(default_timeout: Duration) -> Self {\n Self {\n inner: None,\n default_timeout,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new ping tracker, setting the ping timeout for pings.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/ping_tracker.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/ping_tracker.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7b9066489ce265e3cf46d9a23b65fa9e90ae3cdd7b84b26c39eb5515fd6de2cb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pong_received\n\nDocumentation:\nUpdates the ping tracker with a received pong.\n\nOnly the pong of the most recent ping will do anything. There is no harm feeding\nany pong however.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pong_received(&mut self, data: [u8; 8]) {\n if self.inner.as_ref().map(|inner| inner.data) == Some(data) {\n debug!(?data, \"Pong received from relay server\");\n self.inner = None;\n }\n }\n```"}], "func_name": "pong_received", "docstring": "Updates the ping tracker with a received pong.\n\nOnly the pong of the most recent ping will do anything. There is no harm feeding\nany pong however.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/ping_tracker.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/ping_tracker.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ab0cab5adcba4d581eb1c77e8818e3632a497d49d5475c9048548f57a059d79d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: timeout\n\nDocumentation:\nCancel-safe waiting for a ping timeout.\n\nUnless the most recent sent ping times out, this will never return.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn timeout(&mut self) {\n match self.inner {\n Some(PingInner { deadline, data }) => {\n time::sleep_until(deadline).await;\n debug!(?data, \"Ping timeout.\");\n self.inner = None;\n }\n None => std::future::pending().await,\n }\n }\n```"}], "func_name": "timeout", "docstring": "Cancel-safe waiting for a ping timeout.\n\nUnless the most recent sent ping times out, this will never return.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/ping_tracker.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/ping_tracker.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4c56cc075ce9127a0b20223ac3302cf3d074a3b5d52295b23a5e043f9e91c89b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle\n\nDocumentation:\nReturns a handle for this server.\n\nThe server runs in the background as several async tasks. This allows controlling\nthe server, in particular it allows gracefully shutting down the server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn handle(&self) -> ServerHandle {\n ServerHandle {\n cancel_token: self.cancel.clone(),\n }\n }\n```"}], "func_name": "handle", "docstring": "Returns a handle for this server.\n\nThe server runs in the background as several async tasks. This allows controlling\nthe server, in particular it allows gracefully shutting down the server.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/quic.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/quic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "697d0c96683af0ebbbf1ace4e97a3b13e589a8066f5f04484f84bff0b044bede"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: task_handle\n\nDocumentation:\nReturns the [`AbortOnDropHandle`] for the supervisor task managing the endpoint.\n\nThis is the root of all the tasks for the QUIC address discovery service. Aborting it will abort all the\nother tasks for the service. Awaiting it will complete when all the service tasks are\ncompleted.[]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn task_handle(&mut self) -> &mut AbortOnDropHandle<()> {\n &mut self.handle\n }\n```"}], "func_name": "task_handle", "docstring": "Returns the [`AbortOnDropHandle`] for the supervisor task managing the endpoint.\n\nThis is the root of all the tasks for the QUIC address discovery service. Aborting it will abort all the\nother tasks for the service. Awaiting it will complete when all the service tasks are\ncompleted.[]", "repo": "n0-computer/iroh", "path": "iroh-relay/src/quic.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/quic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8b3f15d40cd81d5b9b24c8533fc3571948195e9acef0a239dfeec7b0696b771b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn\n\nDocumentation:\nSpawns a QUIC server that creates and QUIC endpoint and listens\nfor QUIC connections for address discovery\n\n# Errors\nIf the given `quic_config` contains a [`rustls::ServerConfig`] that cannot\nbe converted to a [`QuicServerConfig`], usually because it does not support\nTLS 1.3, a [`NoInitialCipherSuite`] will occur.\n\n# Panics\nIf there is a panic during a connection, it will be propagated\nup here. Any other errors in a connection will be logged as a\nwarning.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn spawn(mut quic_config: QuicConfig) -> Result {\n quic_config.server_config.alpn_protocols =\n vec![crate::quic::ALPN_QUIC_ADDR_DISC.to_vec()];\n let server_config = QuicServerConfig::try_from(quic_config.server_config)?;\n let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(server_config));\n let transport_config =\n Arc::get_mut(&mut server_config.transport).expect(\"not used yet\");\n transport_config\n .max_concurrent_uni_streams(0_u8.into())\n .max_concurrent_bidi_streams(0_u8.into())\n // enable sending quic address discovery frames\n .send_observed_address_reports(true);\n\n let endpoint = quinn::Endpoint::server(server_config, quic_config.bind_addr)\n .context(EndpointServerSnafu)?;\n let bind_addr = endpoint.local_addr().context(LocalAddrSnafu)?;\n\n info!(?bind_addr, \"QUIC server listening on\");\n\n let cancel = CancellationToken::new();\n let cancel_accept_loop = cancel.clone();\n\n let task = tokio::task::spawn(\n async move {\n let mut set = JoinSet::new();\n debug!(\"waiting for connections...\");\n loop {\n tokio::select! {\n biased;\n _ = cancel_accept_loop.cancelled() => {\n break;\n }\n Some(res) = set.join_next() => {\n if let Err(err) = res {\n if err.is_panic() {\n panic!(\"task panicked: {err:#?}\");\n } else {\n debug!(\"error accepting incoming connection: {err:#?}\");\n }\n }\n }\n res = endpoint.accept() => match res {\n Some(conn) => {\n debug!(\"accepting connection\");\n let remote_addr = conn.remote_address();\n set.spawn(\n handle_connection(conn).instrument(info_span!(\"qad-conn\", %remote_addr))\n ); }\n None => {\n debug!(\"endpoint closed\");\n break;\n }\n }\n }\n }\n // close all connections and wait until they have all grace\n // fully closed.\n endpoint.close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON);\n endpoint.wait_idle().await;\n\n // all tasks should be closed, since the endpoint has shutdown\n // all connections, but await to ensure they are finished.\n set.abort_all();\n while !set.is_empty() {\n _ = set.join_next().await;\n }\n\n debug!(\"quic endpoint has been shutdown.\");\n }\n .instrument(info_span!(\"quic-endpoint\")),\n );\n Ok(Self {\n bind_addr,\n cancel,\n handle: AbortOnDropHandle::new(task),\n })\n }\n```"}], "func_name": "spawn", "docstring": "Spawns a QUIC server that creates and QUIC endpoint and listens\nfor QUIC connections for address discovery\n\n# Errors\nIf the given `quic_config` contains a [`rustls::ServerConfig`] that cannot\nbe converted to a [`QuicServerConfig`], usually because it does not support\nTLS 1.3, a [`NoInitialCipherSuite`] will occur.\n\n# Panics\nIf there is a panic during a connection, it will be propagated\nup here. Any other errors in a connection will be logged as a\nwarning.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/quic.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/quic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea629d3b51f49c02199a4bd12bc97b0b051c4d9ce689616e64841a7bd43be604"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shutdown\n\nDocumentation:\nCloses the underlying QUIC endpoint and the tasks running the\nQUIC connections.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn shutdown(mut self) {\n self.cancel.cancel();\n if !self.task_handle().is_finished() {\n // only possible error is a `JoinError`, no errors about what might\n // have happened during a connection are propagated.\n _ = self.task_handle().await;\n }\n }\n```"}], "func_name": "shutdown", "docstring": "Closes the underlying QUIC endpoint and the tasks running the\nQUIC connections.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/quic.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/quic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5e4a5446d998b8aa0e7f7a0e252b61caaeca226686cd192628daed5d54723102"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_connection\n\nDocumentation:\nHandle the connection from the client.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_connection(incoming: quinn::Incoming) -> Result<(), ConnectionError> {\n let connection = match incoming.await {\n Ok(conn) => conn,\n Err(e) => {\n return Err(e);\n }\n };\n debug!(\"established\");\n // wait for the client to close the connection\n let connection_err = connection.closed().await;\n match connection_err {\n quinn::ConnectionError::ApplicationClosed(ApplicationClose { error_code, .. })\n if error_code == QUIC_ADDR_DISC_CLOSE_CODE =>\n {\n Ok(())\n }\n _ => Err(connection_err),\n }\n }\n```"}], "func_name": "handle_connection", "docstring": "Handle the connection from the client.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/quic.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/quic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a0d1aa8c95a782eeb5313e2a22b4f12e4b14e7aa4004828d3dc93a8cb31d889f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new QuicClient to handle the client side of QUIC\naddress discovery.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(\n ep: quinn::Endpoint,\n mut client_config: rustls::ClientConfig,\n ) -> Result {\n // add QAD alpn\n client_config.alpn_protocols = vec![ALPN_QUIC_ADDR_DISC.into()];\n // go from rustls client config to rustls QUIC specific client config to\n // a quinn client config\n let mut client_config =\n quinn::ClientConfig::new(Arc::new(QuicClientConfig::try_from(client_config)?));\n\n // enable the receive side of address discovery\n let mut transport = quinn_proto::TransportConfig::default();\n // Setting the initial RTT estimate to a low value means\n // we're sacrificing initial throughput, which is fine for\n // QAD, which doesn't require us to have good initial throughput.\n // It also implies a 999ms probe timeout, which means that\n // if the packet gets lost (e.g. because we're probing ipv6, but\n // ipv6 packets always get lost in our network configuration) we\n // time out *closing the connection* after only 999ms.\n // Even if the round trip time is bigger than 999ms, this doesn't\n // prevent us from connecting, since that's dependent on the idle\n // timeout (set to 30s by default).\n transport.initial_rtt(Duration::from_millis(111));\n transport.receive_observed_address_reports(true);\n client_config.transport_config(Arc::new(transport));\n\n Ok(Self { ep, client_config })\n }\n```"}], "func_name": "new", "docstring": "Create a new QuicClient to handle the client side of QUIC\naddress discovery.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/quic.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/quic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8eb353d8803e0af075ce2e221e5f804c742885960802bdeca05f1d57255a4bf0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_addr_and_latency\n\nDocumentation:\nClient side of QUIC address discovery.\n\nCreates a connection and returns the observed address\nand estimated latency of the connection.\n\nConsumes and gracefully closes the connection.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn get_addr_and_latency(\n &self,\n server_addr: SocketAddr,\n host: &str,\n ) -> Result<(SocketAddr, std::time::Duration), Error> {\n let connecting = self\n .ep\n .connect_with(self.client_config.clone(), server_addr, host);\n let conn = connecting?.await?;\n let mut external_addresses = conn.observed_external_addr();\n // TODO(ramfox): I'd like to be able to cancel this so we can close cleanly\n // if there the task that runs this function gets aborted.\n // tokio::select! {\n // _ = cancel.cancelled() => {\n // conn.close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON);\n // bail!(\"QUIC address discovery canceled early\");\n // },\n // res = external_addresses.wait_for(|addr| addr.is_some()) => {\n // let addr = res?.expect(\"checked\");\n // let latency = conn.rtt() / 2;\n // // gracefully close the connections\n // conn.close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON);\n // Ok((addr, latency))\n // }\n\n let res = match external_addresses.wait_for(|addr| addr.is_some()).await {\n Ok(res) => res,\n Err(err) => {\n // attempt to gracefully close the connections\n conn.close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON);\n return Err(err.into());\n }\n };\n let mut observed_addr = res.expect(\"checked\");\n // if we've sent to an ipv4 address, but received an observed address\n // that is ivp6 then the address is an [IPv4-Mapped IPv6 Addresses](https://doc.rust-lang.org/beta/std/net/struct.Ipv6Addr.html#ipv4-mapped-ipv6-addresses)\n observed_addr = SocketAddr::new(observed_addr.ip().to_canonical(), observed_addr.port());\n let latency = conn.rtt();\n // gracefully close the connections\n conn.close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON);\n Ok((observed_addr, latency))\n }\n```"}], "func_name": "get_addr_and_latency", "docstring": "Client side of QUIC address discovery.\n\nCreates a connection and returns the observed address\nand estimated latency of the connection.\n\nConsumes and gracefully closes the connection.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/quic.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/quic.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "835b1093541804098b158a9d0c966c01003257c3b14539e9dcce24ce0393ee13"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from\n\nDocumentation:\nCreates a [`RelayMap`] from a [`RelayUrl`].\n\nThe [`RelayNode`]s in the [`RelayMap`] will have the default STUN and QUIC address\ndiscovery ports.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from(value: RelayUrl) -> Self {\n Self {\n nodes: Arc::new([(value.clone(), Arc::new(value.into()))].into()),\n }\n }\n```"}], "func_name": "from", "docstring": "Creates a [`RelayMap`] from a [`RelayUrl`].\n\nThe [`RelayNode`]s in the [`RelayMap`] will have the default STUN and QUIC address\ndiscovery ports.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/relay_map.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/relay_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6237c9c803655a0106fd69faac5197302a35e01d88c42c876604680c8db38f1e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: from_iter\n\nDocumentation:\nCreates a [`RelayMap`] from an iterator of [`RelayUrl`].\n\nThe [`RelayNode`]s in the [`RelayMap`] will have the default STUN and QUIC address\ndiscovery ports.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn from_iter>(iter: T) -> Self {\n Self {\n nodes: Arc::new(\n iter.into_iter()\n .map(|url| (url.clone(), Arc::new(url.into())))\n .collect(),\n ),\n }\n }\n```"}], "func_name": "from_iter", "docstring": "Creates a [`RelayMap`] from an iterator of [`RelayUrl`].\n\nThe [`RelayNode`]s in the [`RelayMap`] will have the default STUN and QUIC address\ndiscovery ports.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/relay_map.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/relay_map.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d429949221a60370cf2d75c63834f6412f3e130a667331f45dd0f277a15fbe28"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shutdown\n\nDocumentation:\nRequests graceful shutdown.\n\nReturns once all server tasks have stopped.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn shutdown(self) -> Result<(), SupervisorError> {\n // Only the Relay server and QUIC server need shutting down, the supervisor will abort the tasks in\n // the JoinSet when the server terminates.\n if let Some(handle) = self.relay_handle {\n handle.shutdown();\n }\n if let Some(handle) = self.quic_handle {\n handle.shutdown();\n }\n self.supervisor.await?\n }\n```"}], "func_name": "shutdown", "docstring": "Requests graceful shutdown.\n\nReturns once all server tasks have stopped.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "38e8be26f39746f3d9e04fb54cf21a93f85d8a7a49eef8aaae7e26837d0ae72d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: task_handle\n\nDocumentation:\nReturns the handle for the task.\n\nThis allows waiting for the server's supervisor task to finish. Can be useful in\ncase there is an error in the server before it is shut down.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn task_handle(&mut self) -> &mut AbortOnDropHandle> {\n &mut self.supervisor\n }\n```"}], "func_name": "task_handle", "docstring": "Returns the handle for the task.\n\nThis allows waiting for the server's supervisor task to finish. Can be useful in\ncase there is an error in the server before it is shut down.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c73f38f8b2eccf3dbbe3c7156d42b21ed7c90534a504d13248434bb019b6af8f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: server_stun_listener\n\nDocumentation:\nRuns a STUN server.\n\nWhen the future is dropped, the server stops.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn server_stun_listener(sock: UdpSocket, metrics: Arc) {\n info!(addr = ?sock.local_addr().ok(), \"running STUN server\");\n let sock = Arc::new(sock);\n let mut buffer = vec![0u8; 64 << 10];\n let mut tasks = JoinSet::new();\n loop {\n tokio::select! {\n biased;\n\n Some(res) = tasks.join_next() => {\n if let Err(err) = res {\n if err.is_panic() {\n panic!(\"task panicked: {:#?}\", err);\n }\n }\n }\n res = sock.recv_from(&mut buffer) => {\n match res {\n Ok((n, src_addr)) => {\n metrics.requests.inc();\n let pkt = &buffer[..n];\n if !protos::stun::is(pkt) {\n debug!(%src_addr, \"STUN: ignoring non stun packet\");\n metrics.bad_requests.inc();\n continue;\n }\n let pkt = pkt.to_vec();\n tasks.spawn(handle_stun_request(src_addr, pkt, sock.clone(), metrics.clone()));\n }\n Err(err) => {\n metrics.failures.inc();\n warn!(\"failed to recv: {err:#}\");\n }\n }\n }\n }\n }\n}\n```"}], "func_name": "server_stun_listener", "docstring": "Runs a STUN server.\n\nWhen the future is dropped, the server stops.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dcf845d1ca214a38642e59bee37df5be4f2d00389071a0f8a45ee3658e86e4d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_stun_request\n\nDocumentation:\nHandles a single STUN request, doing all logging required.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_stun_request(\n src_addr: SocketAddr,\n pkt: Vec,\n sock: Arc,\n metrics: Arc,\n) {\n let (txid, response) = match protos::stun::parse_binding_request(&pkt) {\n Ok(txid) => {\n debug!(%src_addr, %txid, \"STUN: received binding request\");\n (txid, protos::stun::response(txid, src_addr))\n }\n Err(err) => {\n metrics.bad_requests.inc();\n warn!(%src_addr, \"STUN: invalid binding request: {:?}\", err);\n return;\n }\n };\n\n match sock.send_to(&response, src_addr).await {\n Ok(len) => {\n if len != response.len() {\n warn!(\n %src_addr,\n %txid,\n \"failed to write response, {len}/{} bytes sent\",\n response.len()\n );\n } else {\n match src_addr {\n SocketAddr::V4(_) => metrics.ipv4_success.inc(),\n SocketAddr::V6(_) => metrics.ipv6_success.inc(),\n };\n }\n trace!(%src_addr, %txid, \"sent {len} bytes\");\n }\n Err(err) => {\n metrics.failures.inc();\n warn!(%src_addr, %txid, \"failed to write response: {err:#}\");\n }\n }\n}\n```"}], "func_name": "handle_stun_request", "docstring": "Handles a single STUN request, doing all logging required.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0a16f4f22a732c76b2cb89a5b4f0136ade8c18cdadbd139143efa9c7c7a2e372"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_captive_portal_service\n\nDocumentation:\nThis is a future that never returns, drop it to cancel/abort.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn run_captive_portal_service(http_listener: TcpListener) {\n info!(\"serving\");\n\n // If this future is cancelled, this is dropped and all tasks are aborted.\n let mut tasks = JoinSet::new();\n\n loop {\n tokio::select! {\n biased;\n\n Some(res) = tasks.join_next() => {\n if let Err(err) = res {\n if err.is_panic() {\n panic!(\"task panicked: {:#?}\", err);\n }\n }\n }\n\n res = http_listener.accept() => {\n match res {\n Ok((stream, peer_addr)) => {\n debug!(%peer_addr, \"Connection opened\",);\n let handler = CaptivePortalService;\n\n tasks.spawn(async move {\n let stream = crate::server::streams::MaybeTlsStream::Plain(stream);\n let stream = hyper_util::rt::TokioIo::new(stream);\n if let Err(err) = hyper::server::conn::http1::Builder::new()\n .serve_connection(stream, handler)\n .with_upgrades()\n .await\n {\n error!(\"Failed to serve connection: {err:?}\");\n }\n });\n }\n Err(err) => {\n error!(\n \"[CaptivePortalService] failed to accept connection: {:#?}\",\n err\n );\n }\n }\n }\n }\n }\n}\n```"}], "func_name": "run_captive_portal_service", "docstring": "This is a future that never returns, drop it to cancel/abort.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "195499b35df2340dbea7557dfb74a4b9357eaf77819eb4943d816368c767c4e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect_relay\n\nDocumentation:\nConnects to configured relay using HTTP(S) with an upgrade header\nset to [`HTTP_UPGRADE_PROTOCOL`].\n\n[`HTTP_UPGRADE_PROTOCOL`]: crate::http::HTTP_UPGRADE_PROTOCOL\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn connect_relay(&self) -> Result<(Conn, SocketAddr), ConnectError> {\n #[allow(unused_mut)]\n let mut builder =\n MaybeTlsStreamBuilder::new(self.url.clone().into(), self.dns_resolver.clone())\n .prefer_ipv6(self.prefer_ipv6())\n .proxy_url(self.proxy_url.clone());\n\n #[cfg(any(test, feature = \"test-utils\"))]\n if self.insecure_skip_cert_verify {\n builder = builder.insecure_skip_cert_verify(self.insecure_skip_cert_verify);\n }\n\n let stream = builder.connect().await?;\n let local_addr = stream\n .as_ref()\n .local_addr()\n .map_err(|_| NoLocalAddrSnafu.build())?;\n let response = self.http_upgrade_relay(stream).await?;\n\n if response.status() != hyper::StatusCode::SWITCHING_PROTOCOLS {\n UnexpectedUpgradeStatusSnafu {\n code: response.status(),\n }\n .fail()?;\n }\n\n debug!(\"starting upgrade\");\n let upgraded = hyper::upgrade::on(response).await.context(UpgradeSnafu)?;\n\n debug!(\"connection upgraded\");\n let conn = downcast_upgrade(upgraded).expect(\"must use TcpStream or client::TlsStream\");\n\n let conn = Conn::new_relay(conn, self.key_cache.clone(), &self.secret_key).await?;\n\n Ok((conn, local_addr))\n }\n```"}], "func_name": "connect_relay", "docstring": "Connects to configured relay using HTTP(S) with an upgrade header\nset to [`HTTP_UPGRADE_PROTOCOL`].\n\n[`HTTP_UPGRADE_PROTOCOL`]: crate::http::HTTP_UPGRADE_PROTOCOL", "repo": "n0-computer/iroh", "path": "iroh-relay/src/client/tls.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/client/tls.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "367deb5f3cff02a37345f11338461f1bee8ce7b80d9e72118992e64bdde7da50"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: http_upgrade_relay\n\nDocumentation:\nSends the HTTP upgrade request to the relay server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn http_upgrade_relay(&self, io: T) -> Result, ConnectError>\n where\n T: AsyncRead + AsyncWrite + Send + Unpin + 'static,\n {\n use hyper_util::rt::TokioIo;\n let host_header_value =\n host_header_value(self.url.clone()).context(InvalidRelayUrlSnafu {\n url: Url::from(self.url.clone()),\n })?;\n\n let io = TokioIo::new(io);\n let (mut request_sender, connection) = hyper::client::conn::http1::Builder::new()\n .handshake(io)\n .await\n .context(UpgradeSnafu)?;\n task::spawn(\n // This task drives the HTTP exchange, completes once connection is upgraded.\n async move {\n debug!(\"HTTP upgrade driver started\");\n if let Err(err) = connection.with_upgrades().await {\n error!(\"HTTP upgrade error: {err:#}\");\n }\n debug!(\"HTTP upgrade driver finished\");\n }\n .instrument(info_span!(\"http-driver\")),\n );\n debug!(\"Sending upgrade request\");\n let req = Request::builder()\n .uri(RELAY_PATH)\n .header(UPGRADE, Protocol::Relay.upgrade_header())\n // https://datatracker.ietf.org/doc/html/rfc2616#section-14.23\n // > A client MUST include a Host header field in all HTTP/1.1 request messages.\n // This header value helps reverse proxies identify how to forward requests.\n .header(HOST, host_header_value)\n .body(http_body_util::Empty::::new())\n .expect(\"fixed config\");\n request_sender.send_request(req).await.context(UpgradeSnafu)\n }\n```"}], "func_name": "http_upgrade_relay", "docstring": "Sends the HTTP upgrade request to the relay server.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/client/tls.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/client/tls.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9a2bdb09af3d39935413d6e581bd6237b69a60eb8edb842146e1a0fa9022e04a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: prefer_ipv6\n\nDocumentation:\nReports whether IPv4 dials should be slightly\ndelayed to give IPv6 a better chance of winning dial races.\nImplementations should only return true if IPv6 is expected\nto succeed. (otherwise delaying IPv4 will delay the connection\noverall)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn prefer_ipv6(&self) -> bool {\n match self.address_family_selector {\n Some(ref selector) => selector(),\n None => false,\n }\n }\n```"}], "func_name": "prefer_ipv6", "docstring": "Reports whether IPv4 dials should be slightly\ndelayed to give IPv6 a better chance of winning dial races.\nImplementations should only return true if IPv6 is expected\nto succeed. (otherwise delaying IPv4 will delay the connection\noverall)", "repo": "n0-computer/iroh", "path": "iroh-relay/src/client/tls.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/client/tls.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ece8ad71ce82c67fc8261f37acb65f96b0a27091a552af5d4821e9c4e7890b19"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: host_header_value\n\nDocumentation:\nReturns none if no valid url host was found.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn host_header_value(relay_url: RelayUrl) -> Option {\n // grab the host, turns e.g. https://example.com:8080/xyz -> example.com.\n let relay_url_host = relay_url.host_str()?;\n\n // strip the trailing dot, if present: example.com. -> example.com\n let relay_url_host = relay_url_host.strip_suffix('.').unwrap_or(relay_url_host);\n // build the host header value (reserve up to 6 chars for the \":\" and port digits):\n let mut host_header_value = String::with_capacity(relay_url_host.len() + 6);\n host_header_value += relay_url_host;\n if let Some(port) = relay_url.port() {\n host_header_value += \":\";\n host_header_value += &port.to_string();\n }\n Some(host_header_value)\n}\n```"}], "func_name": "host_header_value", "docstring": "Returns none if no valid url host was found.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/client/tls.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/client/tls.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f3d596d397f4efcf16a0ddcd6d6eb58b9203eca632d5bf3d57c1dd6217dfa8d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_ref\n\nDocumentation:\nGets references to the underlying readers in this `Chain`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn get_ref(&self) -> (&T, &U) {\n (&self.first, &self.second)\n }\n```"}], "func_name": "get_ref", "docstring": "Gets references to the underlying readers in this `Chain`.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/client/util.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/client/util.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c81fc977b3b66c0e9547bfbb6921ca22aa42b5555e91d4384b2edf5e64ada0e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_mut\n\nDocumentation:\nGets mutable references to the underlying readers in this `Chain`.\n\nCare should be taken to avoid modifying the internal I/O state of the\nunderlying readers as doing so may corrupt the internal state of this\n`Chain`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(crate) fn get_mut(&mut self) -> (&mut T, &mut U) {\n (&mut self.first, &mut self.second)\n }\n```"}], "func_name": "get_mut", "docstring": "Gets mutable references to the underlying readers in this `Chain`.\n\nCare should be taken to avoid modifying the internal I/O state of the\nunderlying readers as doing so may corrupt the internal state of this\n`Chain`.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/client/util.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/client/util.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "df36ff64788691f3e58cbfe892b6c18cf69ba3cc7b26e07dca5a6acc27695a1d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_response\n\nDocumentation:\nParses a successful binding response STUN packet.\nThe IP address is extracted from the XOR-MAPPED-ADDRESS attribute.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_response(b: &[u8]) -> Result<(TransactionId, SocketAddr), StunError> {\n let decoder = MessageDecoder::default();\n let (msg, _) = decoder.decode(b).map_err(|_| InvalidMessageSnafu.build())?;\n\n let tx = *msg.transaction_id();\n if msg.class() != MessageClass::SuccessResponse {\n return Err(NotSuccessResponseSnafu.build());\n }\n\n // Read through the attributes.\n // The the addr+port reported by XOR-MAPPED-ADDRESS\n // as the canonical value. If the attribute is not\n // present but the STUN server responds with\n // MAPPED-ADDRESS we fall back to it.\n\n let mut addr = None;\n let mut fallback_addr = None;\n for attr in msg.attributes() {\n match attr {\n StunAttribute::XorMappedAddress(a) => {\n let mut a = *a.socket_address();\n a.set_ip(a.ip().to_canonical());\n addr = Some(a);\n }\n StunAttribute::MappedAddress(a) => {\n let mut a = *a.socket_address();\n a.set_ip(a.ip().to_canonical());\n fallback_addr = Some(a);\n }\n _ => {}\n }\n }\n\n if let Some(addr) = addr {\n return Ok((tx, addr));\n }\n\n if let Some(addr) = fallback_addr {\n return Ok((tx, addr));\n }\n\n Err(MalformedAttrsSnafu.build())\n}\n```"}], "func_name": "parse_response", "docstring": "Parses a successful binding response STUN packet.\nThe IP address is extracted from the XOR-MAPPED-ADDRESS attribute.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/protos/stun.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/protos/stun.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d0b2c3e4f0982011ece46c50624a522b4b9016f50238b3f2589ad4ebd95f4a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a client from a connection & starts a read and write loop to handle io to and from\nthe client\nCall [`Client::shutdown`] to close the read and write loops before dropping the [`Client`]\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn new(\n config: Config,\n connection_id: u64,\n clients: &Clients,\n metrics: Arc,\n ) -> Client {\n let Config {\n node_id,\n stream: io,\n write_timeout,\n channel_capacity,\n rate_limit,\n } = config;\n\n let stream = match rate_limit {\n Some(cfg) => {\n let mut quota = governor::Quota::per_second(cfg.bytes_per_second);\n if let Some(max_burst) = cfg.max_burst_bytes {\n quota = quota.allow_burst(max_burst);\n }\n let limiter = governor::RateLimiter::direct(quota);\n RateLimitedRelayedStream::new(io, limiter, metrics.clone())\n }\n None => RateLimitedRelayedStream::unlimited(io, metrics.clone()),\n };\n\n let done = CancellationToken::new();\n let (send_queue_s, send_queue_r) = mpsc::channel(channel_capacity);\n\n let (disco_send_queue_s, disco_send_queue_r) = mpsc::channel(channel_capacity);\n let (peer_gone_s, peer_gone_r) = mpsc::channel(channel_capacity);\n\n let actor = Actor {\n stream,\n timeout: write_timeout,\n send_queue: send_queue_r,\n disco_send_queue: disco_send_queue_r,\n node_gone: peer_gone_r,\n node_id,\n connection_id,\n clients: clients.clone(),\n client_counter: ClientCounter::default(),\n ping_tracker: PingTracker::default(),\n metrics,\n };\n\n // start io loop\n let io_done = done.clone();\n let handle = tokio::task::spawn(actor.run(io_done).instrument(tracing::info_span!(\n \"client connection actor\",\n remote_node = %node_id.fmt_short(),\n connection_id = connection_id\n )));\n\n Client {\n node_id,\n connection_id,\n handle: AbortOnDropHandle::new(handle),\n done,\n send_queue: send_queue_s,\n disco_send_queue: disco_send_queue_s,\n peer_gone: peer_gone_s,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a client from a connection & starts a read and write loop to handle io to and from\nthe client\nCall [`Client::shutdown`] to close the read and write loops before dropping the [`Client`]", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/client.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cd51d9eb686fcf7a4a93f7d755cdbc20154493ee0f20499ca3a0777919dee177"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: shutdown\n\nDocumentation:\nShutdown the reader and writer loops and closes the connection.\n\nAny shutdown errors will be logged as warnings.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn shutdown(self) {\n self.start_shutdown();\n if let Err(e) = self.handle.await {\n warn!(\n remote_node = %self.node_id.fmt_short(),\n \"error closing actor loop: {e:#?}\",\n );\n };\n }\n```"}], "func_name": "shutdown", "docstring": "Shutdown the reader and writer loops and closes the connection.\n\nAny shutdown errors will be logged as warnings.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/client.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fff2c24fbe1f5a97015daaa3f077fb9b7adf8348604d1a9e2d3aa4116855f8bb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_frame\n\nDocumentation:\nWrites the given frame to the connection.\n\nErrors if the send does not happen within the `timeout` duration\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn write_frame(&mut self, frame: Frame) -> Result<(), SendRelayError> {\n write_frame(&mut self.stream, frame, Some(self.timeout)).await\n }\n```"}], "func_name": "write_frame", "docstring": "Writes the given frame to the connection.\n\nErrors if the send does not happen within the `timeout` duration", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/client.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f96d9e1c7e44707e5ab85840ab5d136a378a1c47803570bef69c94c99e20aa66"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_raw\n\nDocumentation:\nWrites contents to the client in a `RECV_PACKET` frame.\n\nErrors if the send does not happen within the `timeout` duration\nDoes not flush.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn send_raw(&mut self, packet: Packet) -> Result<(), SendRelayError> {\n let src_key = packet.src;\n let content = packet.data;\n\n if let Ok(len) = content.len().try_into() {\n self.metrics.bytes_sent.inc_by(len);\n }\n self.write_frame(Frame::RecvPacket { src_key, content })\n .await\n }\n```"}], "func_name": "send_raw", "docstring": "Writes contents to the client in a `RECV_PACKET` frame.\n\nErrors if the send does not happen within the `timeout` duration\nDoes not flush.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/client.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ac96b144f59201645d245434b996f1de6ca58dbe1a56a4e93606ce1e0f88f924"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: update\n\nDocumentation:\nMarks this node as seen, returns whether it is new today or not.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn update(&mut self, client: NodeId) -> bool {\n self.check_and_clear();\n self.clients.insert(client)\n }\n```"}], "func_name": "update", "docstring": "Marks this node as seen, returns whether it is new today or not.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/client.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/client.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "89e2c8b38273e55bbd8429c6fe9e22ba400c6c1b64e8665fe7cb9be3b1ab78bb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: register\n\nDocumentation:\nBuilds the client handler and starts the read & write loops for the connection.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn register(&self, client_config: Config, metrics: Arc) {\n let node_id = client_config.node_id;\n let connection_id = self.get_connection_id();\n trace!(remote_node = node_id.fmt_short(), \"registering client\");\n\n let client = Client::new(client_config, connection_id, self, metrics);\n if let Some(old_client) = self.0.clients.insert(node_id, client) {\n debug!(\n remote_node = node_id.fmt_short(),\n \"multiple connections found, pruning old connection\",\n );\n old_client.shutdown().await;\n }\n }\n```"}], "func_name": "register", "docstring": "Builds the client handler and starts the read & write loops for the connection.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/clients.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/clients.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "14872341599e0d623f2c8d8f21d9235f513a8c573845d30ad040983221d6184d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unregister\n\nDocumentation:\nRemoves the client from the map of clients, & sends a notification\nto each client that peers has sent data to, to let them know that\npeer is gone from the network.\n\nMust be passed a matching connection_id.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn unregister(&self, connection_id: u64, node_id: NodeId) {\n trace!(\n node_id = node_id.fmt_short(),\n connection_id,\n \"unregistering client\"\n );\n\n if let Some((_, client)) = self\n .0\n .clients\n .remove_if(&node_id, |_, c| c.connection_id() == connection_id)\n {\n if let Some((_, sent_to)) = self.0.sent_to.remove(&node_id) {\n for key in sent_to {\n match client.try_send_peer_gone(key) {\n Ok(_) => {}\n Err(TrySendError::Full(_)) => {\n debug!(\n dst = key.fmt_short(),\n \"client too busy to receive packet, dropping packet\"\n );\n }\n Err(TrySendError::Closed(_)) => {\n debug!(\n dst = key.fmt_short(),\n \"can no longer write to client, dropping packet\"\n );\n }\n }\n }\n }\n }\n }\n```"}], "func_name": "unregister", "docstring": "Removes the client from the map of clients, & sends a notification\nto each client that peers has sent data to, to let them know that\npeer is gone from the network.\n\nMust be passed a matching connection_id.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/clients.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/clients.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "551376b307f042a89544afdef16008f3e032ed1afcb66d98d982db419c905fa1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_packet\n\nDocumentation:\nAttempt to send a packet to client with [`NodeId`] `dst`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn send_packet(\n &self,\n dst: NodeId,\n data: Bytes,\n src: NodeId,\n metrics: &Metrics,\n ) -> Result<(), ForwardPacketError> {\n let Some(client) = self.0.clients.get(&dst) else {\n debug!(dst = dst.fmt_short(), \"no connected client, dropped packet\");\n metrics.send_packets_dropped.inc();\n return Ok(());\n };\n match client.try_send_packet(src, data) {\n Ok(_) => {\n // Record sent_to relationship\n self.0.sent_to.entry(src).or_default().insert(dst);\n Ok(())\n }\n Err(TrySendError::Full(_)) => {\n debug!(\n dst = dst.fmt_short(),\n \"client too busy to receive packet, dropping packet\"\n );\n Err(ForwardPacketError::new(PacketScope::Data, SendError::Full))\n }\n Err(TrySendError::Closed(_)) => {\n debug!(\n dst = dst.fmt_short(),\n \"can no longer write to client, dropping message and pruning connection\"\n );\n client.start_shutdown();\n Err(ForwardPacketError::new(\n PacketScope::Data,\n SendError::Closed,\n ))\n }\n }\n }\n```"}], "func_name": "send_packet", "docstring": "Attempt to send a packet to client with [`NodeId`] `dst`.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/clients.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/clients.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "695b4fd5b9859ea7dd0db2b0fc54750b213b1688bb045d74b2bf1c9a2b012924"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: send_disco_packet\n\nDocumentation:\nAttempt to send a disco packet to client with [`NodeId`] `dst`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn send_disco_packet(\n &self,\n dst: NodeId,\n data: Bytes,\n src: NodeId,\n metrics: &Metrics,\n ) -> Result<(), ForwardPacketError> {\n let Some(client) = self.0.clients.get(&dst) else {\n debug!(\n dst = dst.fmt_short(),\n \"no connected client, dropped disco packet\"\n );\n metrics.disco_packets_dropped.inc();\n return Ok(());\n };\n match client.try_send_disco_packet(src, data) {\n Ok(_) => {\n // Record sent_to relationship\n self.0.sent_to.entry(src).or_default().insert(dst);\n Ok(())\n }\n Err(TrySendError::Full(_)) => {\n debug!(\n dst = dst.fmt_short(),\n \"client too busy to receive disco packet, dropping packet\"\n );\n Err(ForwardPacketError::new(PacketScope::Disco, SendError::Full))\n }\n Err(TrySendError::Closed(_)) => {\n debug!(\n dst = dst.fmt_short(),\n \"can no longer write to client, dropping disco message and pruning connection\"\n );\n client.start_shutdown();\n Err(ForwardPacketError::new(\n PacketScope::Disco,\n SendError::Closed,\n ))\n }\n }\n }\n```"}], "func_name": "send_disco_packet", "docstring": "Attempt to send a disco packet to client with [`NodeId`] `dst`.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/clients.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/clients.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9dc6b8979a456c92cc7836fa548a9265ea014e787c8d1b361dee8be8d9fed2b3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: derive_accept_key\n\nDocumentation:\nDerives the accept key for WebSocket handshake according to RFC 6455.\nTakes the client's Sec-WebSocket-Key value and returns the calculated accept key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn derive_accept_key(client_key: &HeaderValue) -> String {\n use sha1::Digest;\n\n let mut sha1 = sha1::Sha1::new();\n sha1.update(client_key.as_bytes());\n sha1.update(SEC_WEBSOCKET_ACCEPT_GUID);\n data_encoding::BASE64.encode(&sha1.finalize())\n}\n```"}], "func_name": "derive_accept_key", "docstring": "Derives the accept key for WebSocket handshake according to RFC 6455.\nTakes the client's Sec-WebSocket-Key value and returns the calculated accept key.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/http_server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/http_server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c2be6be487804aa980c1e99334d462182603748946b2b1ea03dd7d5b926ca618"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: task_handle\n\nDocumentation:\nReturns the [`AbortOnDropHandle`] for the supervisor task managing the server.\n\nThis is the root of all the tasks for the server. Aborting it will abort all the\nother tasks for the server. Awaiting it will complete when all the server tasks are\ncompleted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn task_handle(&mut self) -> &mut AbortOnDropHandle<()> {\n &mut self.http_server_task\n }\n```"}], "func_name": "task_handle", "docstring": "Returns the [`AbortOnDropHandle`] for the supervisor task managing the server.\n\nThis is the root of all the tasks for the server. Aborting it will abort all the\nother tasks for the server. Awaiting it will complete when all the server tasks are\ncompleted.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/http_server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/http_server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ff4f41cfd77a95169b0dc57960e082bcde9159d213dc0ec155975b9f2ad75714"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tls_config\n\nDocumentation:\nServes all requests content using TLS.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn tls_config(mut self, config: Option) -> Self {\n self.tls_config = config;\n self\n }\n```"}], "func_name": "tls_config", "docstring": "Serves all requests content using TLS.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/http_server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/http_server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b686820ada06eae1e1257d560078bd6955255a83d54a311b78cf31df6e58595"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: request_handler\n\nDocumentation:\nAdds a custom handler for a specific Method & URI.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) fn request_handler(\n mut self,\n method: Method,\n uri_path: &'static str,\n handler: HyperHandler,\n ) -> Self {\n self.handlers.insert((method, uri_path), handler);\n self\n }\n```"}], "func_name": "request_handler", "docstring": "Adds a custom handler for a specific Method & URI.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/http_server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/http_server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3572c6c00d22dad28c4db61f7ce3875944e4bc2161bd8a9287d212cff9e2812f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn\n\nDocumentation:\nBuilds and spawns an HTTP(S) Relay Server.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub(super) async fn spawn(self) -> Result {\n use snafu::ResultExt;\n\n let cancel_token = CancellationToken::new();\n\n let service = RelayService::new(\n self.handlers,\n self.headers,\n self.client_rx_ratelimit,\n KeyCache::new(self.key_cache_capacity),\n self.access,\n self.metrics.unwrap_or_default(),\n );\n\n let addr = self.addr;\n let tls_config = self.tls_config;\n\n // Bind a TCP listener on `addr` and handles content using HTTPS.\n\n let listener = TcpListener::bind(&addr)\n .await\n .map_err(|_| BindTcpListenerSnafu { addr }.build())?;\n\n let addr = listener.local_addr().context(NoLocalAddrSnafu)?;\n let http_str = tls_config.as_ref().map_or(\"HTTP/WS\", |_| \"HTTPS/WSS\");\n info!(\"[{http_str}] relay: serving on {addr}\");\n\n let cancel = cancel_token.clone();\n let task = tokio::task::spawn(\n async move {\n // create a join set to track all our connection tasks\n let mut set = tokio::task::JoinSet::new();\n loop {\n tokio::select! {\n biased;\n _ = cancel.cancelled() => {\n break;\n }\n Some(res) = set.join_next() => {\n if let Err(err) = res {\n if err.is_panic() {\n panic!(\"task panicked: {:#?}\", err);\n }\n }\n }\n res = listener.accept() => match res {\n Ok((stream, peer_addr)) => {\n debug!(\"connection opened from {peer_addr}\");\n let tls_config = tls_config.clone();\n let service = service.clone();\n // spawn a task to handle the connection\n set.spawn(async move {\n service\n .handle_connection(stream, tls_config)\n .await\n }.instrument(info_span!(\"conn\", peer = %peer_addr)));\n }\n Err(err) => {\n error!(\"failed to accept connection: {err}\");\n }\n }\n }\n }\n service.shutdown().await;\n set.shutdown().await;\n debug!(\"server has been shutdown.\");\n }\n .instrument(info_span!(\"relay-http-serve\")),\n );\n\n Ok(Server {\n addr,\n http_server_task: AbortOnDropHandle::new(task),\n cancel_server_loop: cancel_token,\n })\n }\n```"}], "func_name": "spawn", "docstring": "Builds and spawns an HTTP(S) Relay Server.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/http_server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/http_server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "018eb54560213a204bceb546871ba93928e5588c4c4b56a0b7cff4dbe3d6fec2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: call_client_conn\n\nDocumentation:\nUpgrades the HTTP connection to the relay protocol, runs relay client.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn call_client_conn(\n &self,\n mut req: Request,\n ) -> Pin, hyper::Error>> + Send>> {\n // TODO: soooo much cloning. See if there is an alternative\n let this = self.clone();\n let mut builder = Response::builder();\n for (key, value) in self.0.headers.iter() {\n builder = builder.header(key, value);\n }\n\n async move {\n {\n // Send a 400 to any request that doesn't have an `Upgrade` header.\n let Some(protocol) = req.headers().get(UPGRADE).and_then(Protocol::parse_header)\n else {\n return Ok(builder\n .status(StatusCode::BAD_REQUEST)\n .body(body_empty())\n .expect(\"valid body\"));\n };\n\n let websocket_headers = if protocol == Protocol::Websocket {\n let Some(key) = req.headers().get(\"Sec-WebSocket-Key\").cloned() else {\n warn!(\"missing header Sec-WebSocket-Key for websocket relay protocol\");\n return Ok(builder\n .status(StatusCode::BAD_REQUEST)\n .body(body_empty())\n .expect(\"valid body\"));\n };\n\n let Some(version) = req.headers().get(\"Sec-WebSocket-Version\").cloned() else {\n warn!(\"missing header Sec-WebSocket-Version for websocket relay protocol\");\n return Ok(builder\n .status(StatusCode::BAD_REQUEST)\n .body(body_empty())\n .expect(\"valid body\"));\n };\n\n if version.as_bytes() != SUPPORTED_WEBSOCKET_VERSION.as_bytes() {\n warn!(\"invalid header Sec-WebSocket-Version: {:?}\", version);\n return Ok(builder\n .status(StatusCode::BAD_REQUEST)\n // It's convention to send back the version(s) we *do* support\n .header(\"Sec-WebSocket-Version\", SUPPORTED_WEBSOCKET_VERSION)\n .body(body_empty())\n .expect(\"valid body\"));\n }\n\n Some((key, version))\n } else {\n None\n };\n\n debug!(?protocol, \"upgrading connection\");\n\n // Setup a future that will eventually receive the upgraded\n // connection and talk a new protocol, and spawn the future\n // into the runtime.\n //\n // Note: This can't possibly be fulfilled until the 101 response\n // is returned below, so it's better to spawn this future instead\n // waiting for it to complete to then return a response.\n tokio::task::spawn(\n async move {\n match hyper::upgrade::on(&mut req).await {\n Ok(upgraded) => {\n if let Err(err) =\n this.0.relay_connection_handler(protocol, upgraded).await\n {\n warn!(\n ?protocol,\n \"error accepting upgraded connection: {err:#}\",\n );\n } else {\n debug!(?protocol, \"upgraded connection completed\");\n };\n }\n Err(err) => warn!(\"upgrade error: {err:#}\"),\n }\n }\n .instrument(debug_span!(\"handler\")),\n );\n\n // Now return a 101 Response saying we agree to the upgrade to the\n // HTTP_UPGRADE_PROTOCOL\n builder = builder\n .status(StatusCode::SWITCHING_PROTOCOLS)\n .header(UPGRADE, HeaderValue::from_static(protocol.upgrade_header()));\n\n if let Some((key, _version)) = websocket_headers {\n Ok(builder\n .header(SEC_WEBSOCKET_ACCEPT, derive_accept_key(&key))\n .header(CONNECTION, \"upgrade\")\n .body(body_full(\"switching to websocket protocol\"))\n .expect(\"valid body\"))\n } else {\n Ok(builder.body(body_empty()).expect(\"valid body\"))\n }\n }\n }\n .boxed()\n }\n```"}], "func_name": "call_client_conn", "docstring": "Upgrades the HTTP connection to the relay protocol, runs relay client.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/http_server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/http_server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1177f79b813d829b6642f6cfd0f8cbf039a8bf41039b25765ca85d8d5d44a790"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: relay_connection_handler\n\nDocumentation:\nThe server HTTP handler to do HTTP upgrades.\n\nThis handler runs while doing the connection upgrade handshake. Once the connection\nis upgraded it sends the stream to the relay server which takes it over. After\nhaving sent off the connection this handler returns.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn relay_connection_handler(\n &self,\n protocol: Protocol,\n upgraded: Upgraded,\n ) -> Result<(), ConnectionHandlerError> {\n debug!(?protocol, \"relay_connection upgraded\");\n let (io, read_buf) = downcast_upgrade(upgraded)?;\n if !read_buf.is_empty() {\n return Err(BufferNotEmptySnafu { buf: read_buf }.build());\n }\n\n self.accept(protocol, io).await?;\n Ok(())\n }\n```"}], "func_name": "relay_connection_handler", "docstring": "The server HTTP handler to do HTTP upgrades.\n\nThis handler runs while doing the connection upgrade handshake. Once the connection\nis upgraded it sends the stream to the relay server which takes it over. After\nhaving sent off the connection this handler returns.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/http_server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/http_server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "06cdb0c557396f19d21f0ae079543b18d36cbee4d2ef09d75869fab67b09037d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accept\n\nDocumentation:\nAdds a new connection to the server and serves it.\n\nWill error if it takes too long (10 sec) to write or read to the connection, if there is\nsome read or write error to the connection, if the server is meant to verify clients,\nand is unable to verify this one, or if there is some issue communicating with the server.\n\nThe provided [`AsyncRead`] and [`AsyncWrite`] must be already connected to the connection.\n\n[`AsyncRead`]: tokio::io::AsyncRead\n[`AsyncWrite`]: tokio::io::AsyncWrite\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn accept(&self, protocol: Protocol, io: MaybeTlsStream) -> Result<(), AcceptError> {\n use snafu::ResultExt;\n\n trace!(?protocol, \"accept: start\");\n let mut io = match protocol {\n Protocol::Relay => {\n self.metrics.relay_accepts.inc();\n RelayedStream::Relay(Framed::new(io, RelayCodec::new(self.key_cache.clone())))\n }\n Protocol::Websocket => {\n self.metrics.websocket_accepts.inc();\n // Since we already did the HTTP upgrade in the previous step,\n // we use tokio-websockets to handle this connection\n // Create a server builder with default config\n let builder = tokio_websockets::ServerBuilder::new();\n // Serve will create a WebSocketStream on an already upgraded connection\n let websocket = builder.serve(io);\n RelayedStream::Ws(websocket, self.key_cache.clone())\n }\n };\n trace!(\"accept: recv client key\");\n let (client_key, info) = recv_client_key(&mut io).await.context(RecvClientKeySnafu)?;\n\n trace!(\"accept: checking access: {:?}\", self.access);\n if !self.access.is_allowed(client_key).await {\n io.send(Frame::Health {\n problem: Bytes::from_static(b\"not authenticated\"),\n })\n .await?;\n io.flush().await?;\n\n return Err(ClientNotAuthenticatedSnafu { key: client_key }.build());\n }\n\n if info.version != PROTOCOL_VERSION {\n return Err(UnexpectedClientVersionSnafu {\n version: info.version,\n expected_version: PROTOCOL_VERSION,\n }\n .build());\n }\n\n trace!(\"accept: build client conn\");\n let client_conn_builder = Config {\n node_id: client_key,\n stream: io,\n write_timeout: self.write_timeout,\n channel_capacity: PER_CLIENT_SEND_QUEUE_DEPTH,\n rate_limit: self.rate_limit,\n };\n trace!(\"accept: create client\");\n let node_id = client_conn_builder.node_id;\n trace!(node_id = node_id.fmt_short(), \"create client\");\n\n // build and register client, starting up read & write loops for the client\n // connection\n self.clients\n .register(client_conn_builder, self.metrics.clone())\n .await;\n Ok(())\n }\n```"}], "func_name": "accept", "docstring": "Adds a new connection to the server and serves it.\n\nWill error if it takes too long (10 sec) to write or read to the connection, if there is\nsome read or write error to the connection, if the server is meant to verify clients,\nand is unable to verify this one, or if there is some issue communicating with the server.\n\nThe provided [`AsyncRead`] and [`AsyncWrite`] must be already connected to the connection.\n\n[`AsyncRead`]: tokio::io::AsyncRead\n[`AsyncWrite`]: tokio::io::AsyncWrite", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/http_server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/http_server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5cb2478cc7052a8a49893429081f7890e8728ee51539e4a14453108c82d8cf3c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_connection\n\nDocumentation:\nHandle the incoming connection.\n\nIf a `tls_config` is given, will serve the connection using HTTPS.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn handle_connection(self, stream: TcpStream, tls_config: Option) {\n let res = match tls_config {\n Some(tls_config) => {\n debug!(\"HTTPS: serve connection\");\n self.tls_serve_connection(stream, tls_config).await\n }\n None => {\n debug!(\"HTTP: serve connection\");\n self.serve_connection(MaybeTlsStream::Plain(stream))\n .await\n .context(HttpSnafu)\n }\n };\n match res {\n Ok(()) => {}\n Err(error) => match error {\n ServeConnectionError::ManualAccept { source, .. }\n | ServeConnectionError::LetsEncryptAccept { source, .. }\n if source.kind() == std::io::ErrorKind::UnexpectedEof =>\n {\n debug!(reason=?source, \"peer disconnected\");\n }\n // From hyper: \n // `hyper::Error::IncompleteMessage` is hyper's equivalent of UnexpectedEof\n ServeConnectionError::Https { source, .. }\n | ServeConnectionError::Http { source, .. }\n if source.is_incomplete_message() =>\n {\n debug!(reason=?source, \"peer disconnected\");\n }\n _ => {\n error!(?error, \"failed to handle connection\");\n }\n },\n }\n }\n```"}], "func_name": "handle_connection", "docstring": "Handle the incoming connection.\n\nIf a `tls_config` is given, will serve the connection using HTTPS.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/http_server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/http_server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "636ba6d908f6c1d235436f3a376af918e0316012776228cc9494a583019b9706"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: serve_connection\n\nDocumentation:\nWrapper for the actual http connection (with upgrades)\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nasync fn serve_connection(self, io: I) -> Result<(), hyper::Error>\n where\n I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + Sync + 'static,\n {\n hyper::server::conn::http1::Builder::new()\n .serve_connection(hyper_util::rt::TokioIo::new(io), self)\n .with_upgrades()\n .await\n }\n```"}], "func_name": "serve_connection", "docstring": "Wrapper for the actual http connection (with upgrades)", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/http_server.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/http_server.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fcb5b1a3b947ba171732caceaa9b70fe3ce910f39cffcea4bc65c918dd48e6b7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init\n\nDocumentation:\nPerform the initial load and construct the [`ReloadingResolver`].\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub async fn init(loader: Loader, interval: Duration) -> Result {\n let (reloadable, _) = Reloadable::init_load(loader).await?;\n let reloadable = Arc::new(reloadable);\n\n let cancel_token = CancellationToken::new();\n\n // Spawn a task to reload the certificate every interval.\n let _reloadable = reloadable.clone();\n let _cancel_token = cancel_token.clone();\n let _handle = task::spawn(async move {\n let mut interval = time::interval(interval);\n loop {\n tokio::select! {\n _ = interval.tick() => {\n let _ = _reloadable.reload().await;\n tracing::info!(\"Reloaded the certificate\");\n },\n _ = _cancel_token.cancelled() => {\n tracing::trace!(\"shutting down\");\n break;\n }\n }\n }\n });\n let _handle = AbortOnDropHandle::new(_handle);\n\n Ok(Self {\n reloadable,\n _handle,\n cancel_token,\n })\n }\n```"}], "func_name": "init", "docstring": "Perform the initial load and construct the [`ReloadingResolver`].", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/resolver.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/resolver.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fcaa8ced1b970e81657855679eb02566c097791cb54c8bc02dcda17a6d488bc1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stun_config\n\nDocumentation:\nCreates a [`StunConfig`] suitable for testing.\n\nTo ensure port availability for testing, the port is configured to be assigned by the OS.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stun_config() -> StunConfig {\n StunConfig {\n bind_addr: (Ipv4Addr::LOCALHOST, 0).into(),\n }\n}\n```"}], "func_name": "stun_config", "docstring": "Creates a [`StunConfig`] suitable for testing.\n\nTo ensure port availability for testing, the port is configured to be assigned by the OS.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/testing.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/testing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "98e147ef6c5022bc5a62c87a5c19cb5d720bfc3fe1465667390f8e13933b826b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: self_signed_tls_certs_and_config\n\nDocumentation:\nCreates a [`rustls::ServerConfig`] and certificates suitable for testing.\n\n- Uses a self signed certificate valid for the `\"localhost\"` and `\"127.0.0.1\"` domains.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn self_signed_tls_certs_and_config() -> (\n Vec>,\n rustls::ServerConfig,\n) {\n let cert = rcgen::generate_simple_self_signed(vec![\n \"localhost\".to_string(),\n \"127.0.0.1\".to_string(),\n \"::1\".to_string(),\n ])\n .expect(\"valid\");\n let rustls_cert = cert.cert.der();\n let private_key = rustls::pki_types::PrivatePkcs8KeyDer::from(cert.key_pair.serialize_der());\n let private_key = rustls::pki_types::PrivateKeyDer::from(private_key);\n let certs = vec![rustls_cert.clone()];\n let server_config = rustls::ServerConfig::builder_with_provider(std::sync::Arc::new(\n rustls::crypto::ring::default_provider(),\n ))\n .with_safe_default_protocol_versions()\n .expect(\"protocols supported by ring\")\n .with_no_client_auth();\n\n let server_config = server_config\n .with_single_cert(certs.clone(), private_key)\n .expect(\"valid\");\n (certs, server_config)\n}\n```"}], "func_name": "self_signed_tls_certs_and_config", "docstring": "Creates a [`rustls::ServerConfig`] and certificates suitable for testing.\n\n- Uses a self signed certificate valid for the `\"localhost\"` and `\"127.0.0.1\"` domains.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/testing.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/testing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f9d23a0711a45b8e67861bda76c86e2df4e1923cc85699de9981abc10419874d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tls_config\n\nDocumentation:\nCreates a [`TlsConfig`] suitable for testing.\n\n- Uses a self signed certificate valid for the `\"localhost\"` and `\"127.0.0.1\"` domains.\n- Configures https to be served on an OS assigned port on ipv4.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn tls_config() -> TlsConfig<()> {\n let (certs, server_config) = self_signed_tls_certs_and_config();\n TlsConfig {\n server_config,\n cert: CertConfig::<(), ()>::Manual { certs },\n https_bind_addr: (Ipv4Addr::LOCALHOST, 0).into(),\n quic_bind_addr: (Ipv4Addr::UNSPECIFIED, 0).into(),\n }\n}\n```"}], "func_name": "tls_config", "docstring": "Creates a [`TlsConfig`] suitable for testing.\n\n- Uses a self signed certificate valid for the `\"localhost\"` and `\"127.0.0.1\"` domains.\n- Configures https to be served on an OS assigned port on ipv4.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/testing.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/testing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "21e8e3bbd28c4ab9ddd53c875ff463099e124b8d4429c81f35d3271d1097fb4e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: quic_config\n\nDocumentation:\nCreates a [`QuicConfig`] suitable for testing.\n\n- Binds to an OS assigned port on ipv4\n- Uses [`self_signed_tls_certs_and_config`] to create tls certificates\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn quic_config() -> QuicConfig {\n let (_, server_config) = self_signed_tls_certs_and_config();\n QuicConfig {\n bind_addr: (Ipv4Addr::UNSPECIFIED, 0).into(),\n server_config,\n }\n}\n```"}], "func_name": "quic_config", "docstring": "Creates a [`QuicConfig`] suitable for testing.\n\n- Binds to an OS assigned port on ipv4\n- Uses [`self_signed_tls_certs_and_config`] to create tls certificates", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/testing.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/testing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "46baaa7366cc38168ca3ef8a2f4d00365febc048f2dae425994e253f27a28469"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: server_config\n\nDocumentation:\nCreates a [`ServerConfig`] suitable for testing.\n\n- Relaying is enabled using [`relay_config`]\n- Stun is enabled using [`stun_config`]\n- QUIC addr discovery is disabled.\n- Metrics are not enabled.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn server_config() -> ServerConfig<()> {\n ServerConfig {\n relay: Some(relay_config()),\n stun: Some(stun_config()),\n quic: Some(quic_config()),\n #[cfg(feature = \"metrics\")]\n metrics_addr: None,\n }\n}\n```"}], "func_name": "server_config", "docstring": "Creates a [`ServerConfig`] suitable for testing.\n\n- Relaying is enabled using [`relay_config`]\n- Stun is enabled using [`stun_config`]\n- QUIC addr discovery is disabled.\n- Metrics are not enabled.", "repo": "n0-computer/iroh", "path": "iroh-relay/src/server/testing.rs", "url": "https://github.com/n0-computer/iroh/blob/master/iroh-relay/src/server/testing.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c0007677a70b3aa7fd9cb4ad70eb62b8874321361abea8085c69a75380b14f38"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `Hello` to say \"Hello\" to `who`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(who: String) -> Hello {\n Hello{who: who}\n }\n```"}], "func_name": "new", "docstring": "Creates a new `Hello` to say \"Hello\" to `who`.", "repo": "murarth/ketos", "path": "examples/interop.rs", "url": "https://github.com/murarth/ketos/blob/master/examples/interop.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c19d5b06240cb15aae6c3217d74c5dea001598561f830499c9779e4067b7acb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: say_hello\n\nDocumentation:\nReturns a string saying \"Hello\" to someone.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn say_hello(&self) -> String {\n format!(\"Hello, {}!\", self.who)\n }\n```"}], "func_name": "say_hello", "docstring": "Returns a string saying \"Hello\" to someone.", "repo": "murarth/ketos", "path": "examples/interop.rs", "url": "https://github.com/murarth/ketos/blob/master/examples/interop.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "59385969c83af408119b7f19466fe3bf7402a5eba4ea575236edf3fb9b3b2419"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `Counter` with counter value `0`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new() -> Counter {\n Counter{count: Cell::new(0)}\n }\n```"}], "func_name": "new", "docstring": "Creates a new `Counter` with counter value `0`.", "repo": "murarth/ketos", "path": "examples/interop.rs", "url": "https://github.com/murarth/ketos/blob/master/examples/interop.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3c2bb9c55c4f9aa25291dc000ec39628374e786576d37e2f01c5ff771979ee7a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: count\n\nDocumentation:\nIncrements the internal counter and returns the previous value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn count(&self) -> u32 {\n let old = self.count.get();\n self.count.set(old + 1);\n old\n }\n```"}], "func_name": "count", "docstring": "Increments the internal counter and returns the previous value.", "repo": "murarth/ketos", "path": "examples/interop.rs", "url": "https://github.com/murarth/ketos/blob/master/examples/interop.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d0897aa06356fdd1dc0c7ed1c6febb1f62ae9fc7a68312fb1d020f0644f5c49a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_trivial\n\nDocumentation:\nReturns whether the `Instruction` is trivial;\nthat is, in valid top-level code, it does not produce any side effects.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_trivial(&self) -> bool {\n use self::Instruction::*;\n\n match *self {\n Unit | True | False | Const(_) | Return => true,\n _ => false\n }\n }\n```"}], "func_name": "is_trivial", "docstring": "Returns whether the `Instruction` is trivial;\nthat is, in valid top-level code, it does not produce any side effects.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "42481b22c54865cce7f05de664d5926e985a593fbb709bbd8f80385c2244225f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: jump_label\n\nDocumentation:\nIf the instruction is a jump instruction, returns the jump offset.\nOtherwise, returns `None`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn jump_label(&self) -> Option {\n use self::Instruction::*;\n\n match *self {\n Jump(label) |\n JumpIf(label) |\n JumpIfBound(label, _) |\n JumpIfNot(label) |\n JumpIfNull(label) |\n JumpIfNotNull(label) |\n JumpIfEq(label) |\n JumpIfNotEq(label) |\n JumpIfEqConst(label, _) |\n JumpIfNotEqConst(label, _) => Some(label),\n _ => None\n }\n }\n```"}], "func_name": "jump_label", "docstring": "If the instruction is a jump instruction, returns the jump offset.\nOtherwise, returns `None`.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a311621f324c40a4c9412c25507dcdb86519b9286f746ececd9d08e212b30ad8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_label\n\nDocumentation:\nReturns an `Instruction` by inserting the given label value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_label(self, label: u32) -> Instruction {\n use self::JumpInstruction::*;\n\n match self {\n Jump => Instruction::Jump(label),\n JumpIf => Instruction::JumpIf(label),\n JumpIfBound(n) => Instruction::JumpIfBound(label, n),\n JumpIfNot => Instruction::JumpIfNot(label),\n JumpIfNull => Instruction::JumpIfNull(label),\n JumpIfNotNull => Instruction::JumpIfNotNull(label),\n JumpIfEq => Instruction::JumpIfEq(label),\n JumpIfNotEq => Instruction::JumpIfNotEq(label),\n JumpIfEqConst(n) => Instruction::JumpIfEqConst(label, n),\n JumpIfNotEqConst(n) => Instruction::JumpIfNotEqConst(label, n),\n }\n }\n```"}], "func_name": "set_label", "docstring": "Returns an `Instruction` by inserting the given label value.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ed0e344ce90afb13660ed01f0aa27b11fcffa39e5eef08bc3ae3c6a187c852e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: len\n\nDocumentation:\nLength, in bytes, of this jump instruction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn len(self, short: bool) -> usize {\n use self::JumpInstruction::*;\n let len = if short { 1 } else { 2 };\n\n match self {\n Jump |\n JumpIf |\n JumpIfNot |\n JumpIfNull |\n JumpIfNotNull |\n JumpIfEq |\n JumpIfNotEq => 1 + len,\n JumpIfBound(n) |\n JumpIfEqConst(n) |\n JumpIfNotEqConst(n) => {\n let op_len = if is_short_operand(n) { 1 } else { 2 };\n 1 + len + op_len\n }\n }\n }\n```"}], "func_name": "len", "docstring": "Length, in bytes, of this jump instruction.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d69e1e9c8d3710d91b880af856d91618ae660f82ca5d0c9d8fb6f1d0b0bb4dad"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: arity\n\nDocumentation:\nReturns the computed arity of the compiled function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn arity(&self) -> Arity {\n if self.has_rest_params() {\n Arity::Min(self.req_params)\n } else {\n let kw = self.kw_params.len() as u32;\n let max = self.n_params + kw;\n if self.req_params == max {\n Arity::Exact(max)\n } else {\n Arity::Range(self.req_params, max)\n }\n }\n }\n```"}], "func_name": "arity", "docstring": "Returns the computed arity of the compiled function.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c1c7bb123be1b58283799c0b7d4351ad1df281780d444400aa6fefd12a6faaa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_rest_params\n\nDocumentation:\nReturns whether the function accepts a rest parameter.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn has_rest_params(&self) -> bool {\n self.flags & code_flags::PARAM_FLAGS_MASK == code_flags::HAS_REST_PARAMS\n }\n```"}], "func_name": "has_rest_params", "docstring": "Returns whether the function accepts a rest parameter.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3eef95c801f2530f06b1c7dd2df9591f02dfee7a7dcbc64f0217b9f659b8747d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_kw_params\n\nDocumentation:\nReturns whether the function accepts one or more keyword parameters.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn has_kw_params(&self) -> bool {\n self.flags & code_flags::PARAM_FLAGS_MASK == code_flags::HAS_KW_PARAMS\n }\n```"}], "func_name": "has_kw_params", "docstring": "Returns whether the function accepts one or more keyword parameters.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ac6ad6a393e5c4acc0dfb5f8900a2ea86c80574c0f6a360d7f44b386d12065a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_trivial\n\nDocumentation:\nReturns whether all bytecode instructions can be executed without\nside effects.\n\nSuch a code object typically results from compilation of compile-time\noperators.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_trivial(&self) -> bool {\n let mut r = CodeReader::new(&self.code, 0);\n let end = self.code.len();\n\n while r.offset() != end {\n match r.read_instruction() {\n Ok(instr) if instr.is_trivial() => (),\n _ => return false\n }\n }\n\n true\n }\n```"}], "func_name": "is_trivial", "docstring": "Returns whether all bytecode instructions can be executed without\nside effects.\n\nSuch a code object typically results from compilation of compile-time\noperators.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e765dffe819ab45d30a65b917d55b2e4cefe243c257cd5fe5c571222c38bfcc6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `CodeReader` wrapping a series of bytes.\nThe first instruction will be read from `offset`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(bytes: &[u8], offset: usize) -> CodeReader {\n CodeReader { bytes, offset }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `CodeReader` wrapping a series of bytes.\nThe first instruction will be read from `offset`.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "38c021cabcb6531c2eed1238b6ecca433c3ee2d787b534ced4b5e7b00c2083ae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates an empty `CodeBlock` with a small reserved buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new() -> CodeBlock {\n CodeBlock{\n bytes: Vec::with_capacity(16),\n instr_part: None,\n jump: None,\n next: None,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates an empty `CodeBlock` with a small reserved buffer.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "560e729222481057b541ff8691680d71f53566b90677cf47026487d6ee24da44"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: empty\n\nDocumentation:\nCreates an empty `CodeBlock` without reserving data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn empty() -> CodeBlock {\n CodeBlock{\n bytes: Vec::new(),\n instr_part: None,\n jump: None,\n next: None,\n }\n }\n```"}], "func_name": "empty", "docstring": "Creates an empty `CodeBlock` without reserving data.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f3464b037f6d2356dc0c09e1c54ba96ab557b7b60eeb3983c2cb702d2984066b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: calculate_size\n\nDocumentation:\nReturns the final size of the block, including all encoded instructions\nand final jump instruction.\n`short` indicates whether jump instruction offsets are encoded in\nshort format.\n\nIf there is an unencoded instruction, its size is estimated.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn calculate_size(&self, short: bool) -> usize {\n let jump_len = self.jump.map_or(0, |(j, _)| j.len(short));\n let part_len = self.instr_part.map_or(0, |_| Instruction::max_len());\n\n self.bytes.len() + jump_len + part_len\n }\n```"}], "func_name": "calculate_size", "docstring": "Returns the final size of the block, including all encoded instructions\nand final jump instruction.\n`short` indicates whether jump instruction offsets are encoded in\nshort format.\n\nIf there is an unencoded instruction, its size is estimated.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "70d1550ffe7e91d59eec56b23b303023ceef50a42b4151d4e1be46f13814df19"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_next\n\nDocumentation:\nSets the block which will immediately follow this block.\n\nMay only be called once.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_next(&mut self, block: u32) {\n assert!(self.next.is_none());\n self.next = Some(block);\n }\n```"}], "func_name": "set_next", "docstring": "Sets the block which will immediately follow this block.\n\nMay only be called once.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c01f78841839608e10e476b643f72702220a952a43c9f0f6d29fb03e1fd49f4c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: jump_to\n\nDocumentation:\nSets the jump instruction at the end of the block.\n\nMay only be called once.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn jump_to(&mut self, instr: JumpInstruction, block: u32) {\n assert!(self.jump.is_none());\n\n match self.instr_part.and_then(|i| merge_jump_instruction(i, instr)) {\n Some(j) => {\n self.instr_part = None;\n self.jump = Some((j, block));\n }\n None => self.jump = Some((instr, block))\n }\n }\n```"}], "func_name": "jump_to", "docstring": "Sets the jump instruction at the end of the block.\n\nMay only be called once.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0da53f28e521536ff84dd68525f8994b4b32cedc8adbecb2454d6c82e2494807"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_jump\n\nDocumentation:\nWrite stored jump instruction to buffer, if present.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn write_jump(&mut self, label: u32, short: bool) -> Result<(), CompileError> {\n if let Some((instr, _)) = self.jump.take() {\n instr.set_label(label).encode(self, short)?;\n }\n Ok(())\n }\n```"}], "func_name": "write_jump", "docstring": "Write stored jump instruction to buffer, if present.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "522fdfb387c1beeba3c23032b0c30d8299d1939d849f9ce4cbaa83b89c2f7225"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: flush\n\nDocumentation:\nForcibly encodes a pending instruction.\nDoes not encode a jump instruction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn flush(&mut self) -> Result<(), CompileError> {\n if let Some(instr) = self.instr_part.take() {\n self.write_instruction(instr)\n } else {\n Ok(())\n }\n }\n```"}], "func_name": "flush", "docstring": "Forcibly encodes a pending instruction.\nDoes not encode a jump instruction.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f71031595d4ded337b9c109dbf0e7bb432b7d14b099461b5964ca87dc8534840"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_instruction\n\nDocumentation:\nAdds an instruction the block. The instruction may be stored until later\nto be merged into a combination instruction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn push_instruction(&mut self, instr: Instruction) -> Result<(), CompileError> {\n if let Some(part) = self.instr_part {\n match merge_instructions(part, instr) {\n Some(new) => self.instr_part = Some(new),\n None => {\n self.write_instruction(part)?;\n self.instr_part = Some(instr);\n }\n }\n } else {\n self.instr_part = Some(instr);\n }\n Ok(())\n }\n```"}], "func_name": "push_instruction", "docstring": "Adds an instruction the block. The instruction may be stored until later\nto be merged into a combination instruction.", "repo": "murarth/ketos", "path": "src/ketos/bytecode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/bytecode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a5dff7e233f891f0e8c6256204a8a30a1559f29abaf7e9447ce1cdefc534bae4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile\n\nDocumentation:\nCompiles an expression into a code object.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compile(ctx: &Context, value: &Value) -> Result {\n let mut compiler = Compiler::new(ctx);\n\n compiler.compile(value)\n .map_err(|e| { set_traceback(compiler.take_trace()); e })\n}\n```"}], "func_name": "compile", "docstring": "Compiles an expression into a code object.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4268fe0a397142c80af75c1fbb87e0a278b2e9483210c7b94cee791da066503a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_jumps\n\nDocumentation:\nWrites jump instructions with real offsets to each code blocks.\nReturns the total size, in bytes, of code blocks.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_jumps(&mut self) -> Result {\n // If all possible offsets can be shortened, shorten them.\n let short = estimate_size(&self.blocks) <= MAX_SHORT_OPERAND as usize;\n\n let n_blocks = self.blocks.len();\n\n let mut new_blocks = Vec::with_capacity(n_blocks);\n let mut offsets = vec![!0; n_blocks];\n // Blocks which are a target of a conditional jump must be written out\n // even if they contain only a Return instruction.\n let mut must_live = vec![false; n_blocks];\n let mut off = 0;\n let mut i = 0;\n\n loop {\n let mut b = replace(&mut self.blocks[i], CodeBlock::empty());\n let next = b.next;\n let mut skip_block = false;\n\n match b.jump {\n Some((JumpInstruction::Jump, _)) => (),\n Some((_, n)) => must_live[n as usize] = true,\n _ => ()\n }\n\n if block_returns(&b, &self.blocks) {\n // If the block is empty and no other blocks will conditionally\n // jump to it, then the block may be pruned altogether.\n // Any blocks which would *unconditionally* jump will\n // instead themselves return.\n skip_block = !must_live[i] && b.is_mostly_empty();\n\n if !skip_block {\n // If the block returns, its jump could not possibly have\n // pointed anywhere but an empty, returning block.\n b.jump = None;\n b.push_instruction(Instruction::Return)?;\n }\n }\n\n if !skip_block {\n b.flush()?;\n\n // Jump block numbers refer to initial ordering\n offsets[i] = off as u32;\n off += b.calculate_size(short);\n new_blocks.push(b);\n }\n\n match next {\n Some(n) => i = n as usize,\n None => break\n }\n }\n\n replace(&mut self.blocks, new_blocks);\n\n for block in &mut self.blocks {\n if let Some((_, dest)) = block.jump {\n let dest_off = offsets[dest as usize];\n assert!(dest_off != !0, \"jump to dead block {}\", dest);\n block.write_jump(dest_off, short)?;\n }\n }\n\n Ok(off)\n }\n```"}], "func_name": "write_jumps", "docstring": "Writes jump instructions with real offsets to each code blocks.\nReturns the total size, in bytes, of code blocks.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8bf5bf109bb91a2e4a33bf166852c565810540673f29158e2d1a59af94fe74fc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: eval_constant_quasi_value\n\nDocumentation:\nEvaluates a quasiquote value into a constant expression.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn eval_constant_quasi_value(&mut self, value: &Value, depth: u32)\n -> Result {\n match *value {\n Value::List(ref li) =>\n self.eval_constant_quasiquote_list(li, depth),\n Value::Comma(_, n) if n > depth => {\n self.set_trace_expr(value);\n Err(From::from(CompileError::UnbalancedComma))\n }\n Value::Comma(ref v, n) if n == depth => {\n match self.eval_constant(v)? {\n ConstResult::IsConstant => Ok(ConstResult::Constant((&**v).clone())),\n res => Ok(res)\n }\n }\n Value::Comma(ref v, n) => {\n match self.eval_constant_quasi_value(v, depth - n)? {\n ConstResult::Constant(v) =>\n Ok(ConstResult::Constant(v.comma(n))),\n res => Ok(res)\n }\n }\n Value::CommaAt(_, _) => {\n self.set_trace_expr(value);\n Err(From::from(CompileError::InvalidCommaAt))\n }\n Value::Quote(ref v, n) => {\n match self.eval_constant_quasi_value(v, depth)? {\n ConstResult::Constant(v) =>\n Ok(ConstResult::Constant(v.quote(n))),\n res => Ok(res)\n }\n }\n Value::Quasiquote(ref v, n) => {\n match self.eval_constant_quasi_value(v, depth + n)? {\n ConstResult::Constant(v) =>\n Ok(ConstResult::Constant(v.quasiquote(n))),\n res => Ok(res)\n }\n }\n _ => Ok(ConstResult::IsConstant)\n }\n }\n```"}], "func_name": "eval_constant_quasi_value", "docstring": "Evaluates a quasiquote value into a constant expression.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bcc45e3c927c27215a3ae979a98f7683ada30c9e8af4eafa3f180ef23b620650"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_quasiquote\n\nDocumentation:\nCompiles the expression `Quasiquote(value, depth)`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_quasiquote(&mut self, value: &Value, depth: u32) -> Result<(), Error> {\n if self.check_quasi_const(value, depth)? {\n match depth {\n 1 => self.load_quoted_value(Borrowed(value))?,\n _ => self.load_quoted_value(Owned(\n value.clone().quasiquote(depth - 1)))?\n }\n } else {\n self.compile_quasi_value(value, depth)?;\n if depth != 1 {\n self.push_instruction(Instruction::Quasiquote(depth - 1))?;\n }\n }\n\n Ok(())\n }\n```"}], "func_name": "compile_quasiquote", "docstring": "Compiles the expression `Quasiquote(value, depth)`", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6b4b59f2b259c82209efd1af038e1f9ff43ea1b6b58b015aaec74f01d260f9a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_quasi_value\n\nDocumentation:\nCompiles a value found within a quasiquoted expression\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compile_quasi_value(&mut self, value: &Value, depth: u32) -> Result<(), Error> {\n if self.check_quasi_const(value, depth)? {\n self.load_quoted_value(Borrowed(value))?;\n return Ok(());\n }\n\n match *value {\n Value::Comma(ref v, n) if n == depth =>\n self.compile_value(v),\n Value::Comma(_, n) | Value::CommaAt(_, n) if n > depth => {\n self.set_trace_expr(value);\n Err(From::from(CompileError::UnbalancedComma))\n }\n Value::Comma(ref v, n) => {\n self.compile_quasi_value(v, depth - n)?;\n self.push_instruction(Instruction::Comma(n))?;\n Ok(())\n }\n Value::CommaAt(_, n) if n == depth => {\n self.set_trace_expr(value);\n Err(From::from(CompileError::InvalidCommaAt))\n }\n Value::List(ref li) =>\n self.compile_quasiquote_list(li, depth),\n Value::Quote(ref v, n) => {\n self.compile_quasi_value(v, depth)?;\n self.push_instruction(Instruction::Quote(n))?;\n Ok(())\n }\n Value::Quasiquote(ref v, n) => {\n if self.check_quasi_const(v, n)? {\n match n {\n 1 => self.load_const_value(v)?,\n _ => {\n let c = self.add_const(Owned(\n Value::Quasiquote(v.clone(), n - 1)));\n self.push_instruction(Instruction::Const(c))?;\n }\n }\n\n Ok(())\n } else {\n self.compile_quasi_value(v, depth + n)?;\n if depth == 0 {\n if n != 1 {\n self.push_instruction(Instruction::Quasiquote(n - 1))?;\n }\n } else {\n self.push_instruction(Instruction::Quasiquote(n))?;\n }\n Ok(())\n }\n }\n // Handled by `if check_quasi_const { ... }` above\n _ => unreachable!()\n }\n }\n```"}], "func_name": "compile_quasi_value", "docstring": "Compiles a value found within a quasiquoted expression", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "75656cc057770b41d51654f437d3ca0d3f46027fdc2195570021ca29b151c9fb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_quasi_const\n\nDocumentation:\nReturns true if a value found within a quasiquoted value does not\ncontain any expressions to be evaluated.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn check_quasi_const(&mut self, value: &Value, depth: u32) -> Result {\n match *value {\n Value::List(ref li) => {\n for v in li {\n if !self.check_quasi_const(v, depth)? {\n return Ok(false);\n }\n }\n\n Ok(true)\n }\n Value::Quasiquote(ref v, n) => self.check_quasi_const(v, depth + n),\n Value::Quote(ref v, _) => self.check_quasi_const(v, depth),\n Value::Comma(_, n)\n | Value::CommaAt(_, n) if n > depth => {\n self.set_trace_expr(value);\n Err(From::from(CompileError::UnbalancedComma))\n }\n Value::Comma(_, n)\n | Value::CommaAt(_, n) if n == depth => Ok(false),\n Value::Comma(ref v, n)\n | Value::CommaAt(ref v, n) =>\n self.check_quasi_const(v, depth - n),\n _ => Ok(true)\n }\n }\n```"}], "func_name": "check_quasi_const", "docstring": "Returns true if a value found within a quasiquoted value does not\ncontain any expressions to be evaluated.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c2dc84676563fbd597a6f793ee1e69114633d9cc6c45f447ebefa3cffca79fee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: specialize_call\n\nDocumentation:\nAttempt to compile a function call into a more efficient series of\ninstructions; e.g. `(= a b)` into the `Eq` instruction.\n\nIf specialized instructions cannot be generated, returns `Ok(false)`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn specialize_call(&mut self, name: Name, args: &[Value]) -> Result {\n let n_args = args.len();\n\n match name {\n standard_names::ADD if n_args == 2 => {\n let lhs = &args[0];\n let rhs = &args[1];\n\n return self.specialize_add(lhs, rhs);\n }\n standard_names::SUB if n_args == 2 => {\n let lhs = &args[0];\n let rhs = &args[1];\n\n return self.specialize_sub(lhs, rhs);\n }\n standard_names::NULL if n_args == 1 => {\n self.compile_value(&args[0])?;\n self.push_instruction(Instruction::Null)?;\n }\n standard_names::EQ if n_args == 2 => {\n let lhs = &args[0];\n let rhs = &args[1];\n\n self.specialize_eq(lhs, rhs)?;\n }\n standard_names::NOT_EQ if n_args == 2 => {\n let lhs = &args[0];\n let rhs = &args[1];\n\n self.specialize_ne(lhs, rhs)?;\n }\n standard_names::NOT if n_args == 1 => {\n self.compile_value(&args[0])?;\n self.push_instruction(Instruction::Not)?;\n }\n standard_names::APPEND if n_args == 2 => {\n self.compile_value(&args[0])?;\n self.push_instruction(Instruction::Push)?;\n self.compile_value(&args[1])?;\n self.push_instruction(Instruction::Append)?;\n }\n standard_names::FIRST if n_args == 1 => {\n self.compile_value(&args[0])?;\n self.push_instruction(Instruction::First)?;\n }\n standard_names::TAIL if n_args == 1 => {\n self.compile_value(&args[0])?;\n self.push_instruction(Instruction::Tail)?;\n }\n standard_names::INIT if n_args == 1 => {\n self.compile_value(&args[0])?;\n self.push_instruction(Instruction::Init)?;\n }\n standard_names::LAST if n_args == 1 => {\n self.compile_value(&args[0])?;\n self.push_instruction(Instruction::Last)?;\n }\n standard_names::LIST => {\n self.specialize_list(args)?;\n }\n standard_names::ID if n_args == 1 => {\n self.compile_value(&args[0])?;\n }\n _ => return Ok(false)\n }\n\n Ok(true)\n }\n```"}], "func_name": "specialize_call", "docstring": "Attempt to compile a function call into a more efficient series of\ninstructions; e.g. `(= a b)` into the `Eq` instruction.\n\nIf specialized instructions cannot be generated, returns `Ok(false)`.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2d21b512b09a6d7f646a120b5db515a5f27d0058d55093fe2a438db02eb4afdf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: closure_value\n\nDocumentation:\nSearches for a named value from enclosing scope.\nThe name will be added to the set of captures if not already present.\nIf the name is found, returns value index for use in `LoadC` instruction.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn closure_value(&mut self, name: Name) -> Option {\n match self.captures.iter().position(|&n| n == name) {\n Some(pos) => Some(pos as u32),\n None => {\n for o in self.outer {\n if o.stack.iter().any(|&(n, _)| n == name) {\n let n = self.captures.len() as u32;\n self.captures.push(name);\n return Some(n);\n }\n }\n\n None\n }\n }\n }\n```"}], "func_name": "closure_value", "docstring": "Searches for a named value from enclosing scope.\nThe name will be added to the set of captures if not already present.\nIf the name is found, returns value index for use in `LoadC` instruction.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef93256f6d2634eadd9acde724c35fa5d5383c8e38c48c78b779fdfc73bc87e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_const_value\n\nDocumentation:\nGenerates instructions to load a constant value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn load_const_value(&mut self, value: &Value) -> Result<(), CompileError> {\n match *value {\n Value::Unit => self.push_instruction(Instruction::Unit),\n Value::Bool(true) => self.push_instruction(Instruction::True),\n Value::Bool(false) => self.push_instruction(Instruction::False),\n Value::Quote(ref v, 1) => {\n self.load_quoted_value(Borrowed(v))\n }\n Value::Quote(ref v, n) => {\n let v = Value::Quote(v.clone(), n - 1);\n self.load_quoted_value(Owned(v))\n }\n ref v => {\n let c = self.add_const(Borrowed(v));\n self.push_instruction(Instruction::Const(c))\n }\n }\n }\n```"}], "func_name": "load_const_value", "docstring": "Generates instructions to load a constant value.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "271470a0af1ff66bc74c16dcb9bdfb64e559138471ae590606354bea589ab6aa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_var\n\nDocumentation:\nAdds a named value to the list of stack values.\nShould be followed by a `Push` instruction to adjust `stack_offset`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn push_var(&mut self, name: Name) {\n self.stack.push((name, self.stack_offset));\n }\n```"}], "func_name": "push_var", "docstring": "Adds a named value to the list of stack values.\nShould be followed by a `Push` instruction to adjust `stack_offset`.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "87f5df3aaca74ea1a924ce157db77fc27071540e8481e2d6847cf907fd714d71"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pop_vars\n\nDocumentation:\nRemove `n` named values from the list of stack values.\nShould be followed by a `Skip` instruction to adjust `stack_offset`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn pop_vars(&mut self, n: u32) {\n let n = self.stack.len() - n as usize;\n let _ = self.stack.drain(n..);\n }\n```"}], "func_name": "pop_vars", "docstring": "Remove `n` named values from the list of stack values.\nShould be followed by a `Skip` instruction to adjust `stack_offset`.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0c0c1e6fcc7ae94b1024c0b79ffe597d18939d26c08ffa76bc2d26523ed92db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fold_anticommutative\n\nDocumentation:\nFold constants for an anticommutative operation.\nThere are two strategies for partial constant evaluation, depending on\nwhether the first value is constant.\n\n`(- foo 1 2 3)` -> `(- foo 6)`\n\n`(- 1 foo 2 3)` -> `(- -4 foo)`\n\n`solo_name` is used in the case of `(foo value identity)`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fold_anticommutative(compiler: &mut Compiler,\n name: Name, solo_name: Name, args: &[Value])\n -> Result {\n let mut args = args.iter();\n let mut new_args = Vec::new();\n let mut value = None;\n\n let first = args.next().unwrap();\n\n let first_const = match compiler.eval_constant(first)? {\n ConstResult::IsRuntime => {\n new_args.push(first.clone());\n false\n }\n ConstResult::Partial(v) => {\n new_args.push(v);\n false\n }\n ConstResult::IsConstant => {\n F::type_check(first)?;\n value = Some(first.clone());\n true\n }\n ConstResult::Constant(v) => {\n F::type_check(&v)?;\n value = Some(v);\n true\n }\n };\n\n for v in args {\n let mut rhs = Borrowed(v);\n\n match compiler.eval_constant(v)? {\n ConstResult::IsRuntime => {\n new_args.push(v.clone());\n continue;\n }\n ConstResult::Partial(v) => {\n new_args.push(v);\n continue;\n }\n ConstResult::IsConstant => {\n F::type_check(v)?;\n }\n ConstResult::Constant(v) => {\n F::type_check(&v)?;\n rhs = Owned(v);\n }\n }\n\n match value {\n Some(lhs) => {\n value = if first_const {\n Some(F::fold(&compiler.ctx, lhs, &rhs)?)\n } else {\n Some(F::fold_inv(&compiler.ctx, lhs, &rhs)?)\n };\n }\n None => value = Some(rhs.into_owned())\n }\n }\n\n match value {\n None => Ok(ConstResult::IsRuntime),\n Some(v) => {\n if new_args.is_empty() {\n Ok(ConstResult::Constant(F::finish(v)?))\n } else {\n if F::is_identity(&v) {\n if first_const {\n new_args.insert(0, Value::Name(name));\n } else {\n new_args.insert(0, Value::Name(solo_name));\n }\n } else {\n new_args.insert(0, Value::Name(name));\n if first_const {\n new_args.insert(1, v);\n } else {\n new_args.push(v);\n }\n }\n Ok(ConstResult::Partial(new_args.into()))\n }\n }\n }\n}\n```"}], "func_name": "fold_anticommutative", "docstring": "Fold constants for an anticommutative operation.\nThere are two strategies for partial constant evaluation, depending on\nwhether the first value is constant.\n\n`(- foo 1 2 3)` -> `(- foo 6)`\n\n`(- 1 foo 2 3)` -> `(- -4 foo)`\n\n`solo_name` is used in the case of `(foo value identity)`.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "af96b91621d8163ce64a067b22d049f94dc731a71eb5867261961a0777ba26e2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fold_commutative\n\nDocumentation:\nFold constants for a commutative operation.\n\ne.g. `(+ 1 foo 2 3)` -> `(+ foo 6)`\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fold_commutative(compiler: &mut Compiler, name: Name, args: &[Value])\n -> Result {\n let mut new_args = Vec::new();\n let mut value = None;\n\n for v in args {\n let mut rhs = Borrowed(v);\n\n match compiler.eval_constant(v)? {\n ConstResult::IsRuntime => {\n new_args.push(v.clone());\n continue;\n }\n ConstResult::Partial(v) => {\n new_args.push(v);\n continue;\n }\n ConstResult::IsConstant => {\n F::type_check(v)?;\n }\n ConstResult::Constant(v) => {\n F::type_check(&v)?;\n rhs = Owned(v);\n }\n }\n\n match value {\n Some(lhs) => value = Some(F::fold(&compiler.ctx, lhs, &rhs)?),\n None => value = Some(rhs.into_owned())\n }\n }\n\n match value {\n None => Ok(ConstResult::IsRuntime),\n Some(v) => {\n if new_args.is_empty() {\n Ok(ConstResult::Constant(F::finish(v)?))\n } else {\n new_args.insert(0, Value::Name(name));\n if !F::is_identity(&v) {\n new_args.push(v);\n }\n Ok(ConstResult::Partial(new_args.into()))\n }\n }\n }\n}\n```"}], "func_name": "fold_commutative", "docstring": "Fold constants for a commutative operation.\n\ne.g. `(+ 1 foo 2 3)` -> `(+ foo 6)`", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "29011f23c309abff741e8a3a31030372adcfe0c55796d9ea76d344b8d070dc26"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: eval_system_fn\n\nDocumentation:\nEvaluates the named system function by calling it directly,\nif and only if all arguments are constant values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn eval_system_fn(compiler: &mut Compiler, name: Name, args: &[Value])\n -> Result {\n let sys_fn = get_system_fn(name)\n .expect(\"eval_system_fn got invalid name\");\n\n let n_args = args.len() as u32;\n\n if !sys_fn.arity.accepts(n_args) {\n return Err(From::from(CompileError::ArityError{\n name,\n expected: sys_fn.arity,\n found: n_args,\n }));\n }\n\n let mut values = Vec::new();\n\n for v in args {\n match compiler.eval_constant(v)? {\n ConstResult::IsRuntime |\n ConstResult::Partial(_) => return Ok(ConstResult::IsRuntime),\n ConstResult::IsConstant => {\n values.push(v.clone());\n }\n ConstResult::Constant(v) => {\n values.push(v);\n }\n }\n }\n\n let v = (sys_fn.callback)(&compiler.ctx, &mut values)?;\n\n Ok(ConstResult::Constant(v))\n}\n```"}], "func_name": "eval_system_fn", "docstring": "Evaluates the named system function by calling it directly,\nif and only if all arguments are constant values.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d8a011a4cb114c7d69d955fe270a37c01b12728d075237ca64646d5cab4c10ae"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_apply\n\nDocumentation:\n`apply` calls a function or lambda with a series of arguments.\nArguments to `apply` other than the last argument are passed directly\nto the function; the last argument to `apply` is a list whose elements\nwill be passed to the function.\n\n```lisp\n; Calls (foo 1 2 3 4 5)\n(apply foo 1 2 '(3 4 5))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_apply(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n let last = args.len() - 1;\n let n_args = last as u32 - 1;\n let mut iter = args[..last].iter();\n let mut apply_const = None;\n let mut apply_self = false;\n\n if let Value::Name(name) = args[0] {\n // Skip the first value when pushing args to the stack\n iter.next();\n\n if compiler.self_name() == Some(name) {\n apply_self = true;\n } else if compiler.load_local_name(name)? {\n compiler.push_instruction(Instruction::Push)?;\n } else {\n let c = compiler.add_const(Owned(Value::Name(name)));\n apply_const = Some(c);\n }\n }\n\n for arg in iter {\n compiler.compile_value(arg)?;\n compiler.push_instruction(Instruction::Push)?;\n }\n\n compiler.compile_value(&args[last])?;\n\n if let Some(c) = apply_const {\n compiler.push_instruction(Instruction::ApplyConst(c, n_args))?;\n } else if apply_self {\n compiler.push_instruction(Instruction::ApplySelf(n_args))?;\n } else {\n compiler.push_instruction(Instruction::Apply(n_args))?;\n }\n\n Ok(())\n}\n```"}], "func_name": "op_apply", "docstring": "`apply` calls a function or lambda with a series of arguments.\nArguments to `apply` other than the last argument are passed directly\nto the function; the last argument to `apply` is a list whose elements\nwill be passed to the function.\n\n```lisp\n; Calls (foo 1 2 3 4 5)\n(apply foo 1 2 '(3 4 5))\n```", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0b584d5873a878460c6ed4cb80eaa0b162b90d1c22d227335a3d0e896549db68"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_do\n\nDocumentation:\n`do` evaluates a series of expressions, yielding the value of the last\nexpression.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_do(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n for arg in args {\n compiler.compile_value(arg)?;\n }\n Ok(())\n}\n```"}], "func_name": "op_do", "docstring": "`do` evaluates a series of expressions, yielding the value of the last\nexpression.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1f9e5af63eb8195dd22f144b4be29c8fe9b413ba76c315175f73152f60f2bd6e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_let\n\nDocumentation:\n`let` defines a series of named value bindings.\n\n```lisp\n(let ((a (foo))\n(b (bar)))\n(baz a b))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_let(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n let mut n_vars = 0;\n\n match args[0] {\n Value::Unit => (),\n Value::List(ref li) => {\n n_vars = li.len() as u32;\n for v in li {\n match *v {\n Value::List(ref li) if li.len() == 2 => {\n let name = get_name(compiler, &li[0])?;\n\n compiler.compile_value(&li[1])?;\n compiler.push_var(name);\n compiler.push_instruction(Instruction::Push)?;\n }\n _ => {\n compiler.set_trace_expr(v);\n return Err(From::from(CompileError::SyntaxError(\n \"expected list of 2 elements\")))\n }\n }\n }\n }\n ref v => {\n compiler.set_trace_expr(v);\n return Err(From::from(CompileError::SyntaxError(\"expected list\")))\n }\n }\n\n compiler.compile_value(&args[1])?;\n\n // Create a new block containing the Skip.\n // This helps to optimize out unnecessary instructions in the assembly phase.\n let next_block = compiler.new_block();\n compiler.use_next(next_block);\n\n compiler.push_instruction(Instruction::Skip(n_vars))?;\n compiler.pop_vars(n_vars);\n\n Ok(())\n}\n```"}], "func_name": "op_let", "docstring": "`let` defines a series of named value bindings.\n\n```lisp\n(let ((a (foo))\n(b (bar)))\n(baz a b))\n```", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f8653fd499355768e560e507c21f3b44095f7e47afbb5bb5749df2948d73fabe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_define\n\nDocumentation:\n`define` declares a value binding or function binding in global scope.\n\n```lisp\n(define foo 123)\n\n(define (bar a) (+ a foo))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_define(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n match args[0] {\n Value::Name(name) => {\n // Replace operator item with more specific item\n compiler.trace.pop();\n compiler.trace.push(TraceItem::Define(compiler.ctx.scope().name(), name));\n\n let (doc, body) = extract_doc_string(args)?;\n test_define_name(compiler.scope(), name)?;\n compiler.compile_value(&body)?;\n\n if let Some(doc) = doc {\n compiler.scope().add_doc_string(name, doc.to_owned());\n }\n\n let c = compiler.add_const(Owned(Value::Name(name)));\n compiler.push_instruction(Instruction::SetDef(c))?;\n Ok(())\n }\n Value::List(ref li) => {\n let name = get_name(compiler, &li[0])?;\n\n // Replace operator item with more specific item\n compiler.trace.pop();\n compiler.trace.push(TraceItem::Define(compiler.ctx.scope().name(), name));\n\n test_define_name(compiler.scope(), name)?;\n let (doc, body) = extract_doc_string(args)?;\n\n let c = compiler.add_const(Owned(Value::Name(name)));\n\n let (lambda, captures) = make_lambda(\n compiler, Some(name), &li[1..], body, doc)?;\n\n if compiler.is_top_level() && captures.is_empty() {\n // Add top-level, non-capturing lambdas to global scope immediately.\n compiler.scope().add_value(name, Value::Lambda(lambda));\n let c = compiler.add_const(Owned(Value::Name(name)));\n compiler.push_instruction(Instruction::Const(c))?;\n } else {\n let code_c = compiler.add_const(Owned(Value::Lambda(lambda)));\n compiler.load_lambda(code_c, &captures)?;\n compiler.push_instruction(Instruction::SetDef(c))?;\n }\n\n Ok(())\n }\n ref v => {\n compiler.set_trace_expr(v);\n Err(From::from(CompileError::SyntaxError(\"expected name or list\")))\n }\n }\n}\n```"}], "func_name": "op_define", "docstring": "`define` declares a value binding or function binding in global scope.\n\n```lisp\n(define foo 123)\n\n(define (bar a) (+ a foo))\n```", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b1a007ed3b37762a00cb4c51bbdebf114dda1d2e115ff38201c3b1fc46b5173"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_macro\n\nDocumentation:\n`macro` defines a compile-time macro function in global scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_macro(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n let (name, params) = match args[0] {\n Value::List(ref li) => {\n let name = get_name(compiler, &li[0])?;\n (name, &li[1..])\n }\n ref v => {\n compiler.set_trace_expr(v);\n return Err(From::from(CompileError::SyntaxError(\"expected list\")));\n }\n };\n\n // Replace operator item with more specific item\n compiler.trace.pop();\n compiler.trace.push(TraceItem::DefineMacro(\n compiler.ctx.scope().name(), name));\n\n let (doc, body) = extract_doc_string(args)?;\n\n test_define_name(compiler.scope(), name)?;\n\n let (lambda, captures) = make_lambda(compiler,\n Some(name), params, &body, doc)?;\n\n if !captures.is_empty() {\n return Err(From::from(CompileError::SyntaxError(\n \"macro lambda cannot enclose values\")));\n }\n\n compiler.scope().add_macro(name, lambda);\n\n let c = compiler.add_const(Owned(Value::Name(name)));\n compiler.push_instruction(Instruction::Const(c))?;\n Ok(())\n}\n```"}], "func_name": "op_macro", "docstring": "`macro` defines a compile-time macro function in global scope.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b78889949fa9d25f00c634ef77e38e0c8cfe8ca4e440e94e01917cd73eda221d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_struct\n\nDocumentation:\n`struct` creates a struct definition and binds to global scope.\n\n```lisp\n(struct Foo ((name string)\n(num integer)))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_struct(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n let name = get_name(compiler, &args[0])?;\n\n // Replace operator item with more specific item\n compiler.trace.pop();\n compiler.trace.push(TraceItem::DefineStruct(\n compiler.ctx.scope().name(), name));\n\n let (doc, body) = extract_doc_string(args)?;\n\n test_define_name(compiler.scope(), name)?;\n let mut fields = NameMap::new();\n\n match *body {\n Value::Unit => (),\n Value::List(ref li) => {\n for v in li {\n match *v {\n Value::List(ref li) if li.len() == 2 => {\n let fname = get_name(compiler, &li[0])?;\n let fty = get_name(compiler, &li[1])?;\n\n fields.insert(fname, fty);\n }\n _ => {\n compiler.set_trace_expr(v);\n return Err(From::from(CompileError::SyntaxError(\n \"expected list of 2 elements\")))\n }\n }\n }\n }\n ref v => {\n compiler.set_trace_expr(v);\n return Err(From::from(CompileError::SyntaxError(\"expected list\")));\n }\n }\n\n let def = StructValueDef::new(fields.into_slice());\n let def = Value::StructDef(Rc::new(StructDef::new(name, Box::new(def))));\n\n if let Some(doc) = doc {\n compiler.scope().add_doc_string(name, doc.to_owned());\n }\n\n let name_c = compiler.add_const(Owned(Value::Name(name)));\n let c = compiler.add_const(Owned(def));\n compiler.push_instruction(Instruction::Const(c))?;\n compiler.push_instruction(Instruction::SetDef(name_c))?;\n Ok(())\n}\n```"}], "func_name": "op_struct", "docstring": "`struct` creates a struct definition and binds to global scope.\n\n```lisp\n(struct Foo ((name string)\n(num integer)))\n```", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f80530e63283c05ba756cdbd7a33d2d66ff949bc0b3b877708cb7632b228dac"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_if\n\nDocumentation:\n`if` evaluates a boolean condition expression and chooses a branch based\non the result.\n\n```lisp\n(if (foo)\n(bar)\n(baz))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_if(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n let then_block = compiler.new_block();\n let else_block = compiler.new_block();\n let final_block = compiler.new_block();\n\n compiler.compile_value(&args[0])?;\n compiler.current_block().jump_to(JumpInstruction::JumpIfNot, else_block);\n\n compiler.use_next(then_block);\n compiler.compile_value(&args[1])?;\n compiler.current_block().jump_to(JumpInstruction::Jump, final_block);\n\n compiler.use_next(else_block);\n match args.get(2) {\n Some(value) => compiler.compile_value(value)?,\n None => compiler.push_instruction(Instruction::Unit)?\n }\n\n compiler.use_next(final_block);\n Ok(())\n}\n```"}], "func_name": "op_if", "docstring": "`if` evaluates a boolean condition expression and chooses a branch based\non the result.\n\n```lisp\n(if (foo)\n(bar)\n(baz))\n```", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0f1c12d06662b6906045d48652e15ca03b3c0c934b0e951e6dd7b71ff77d05f4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_and\n\nDocumentation:\n`and` evaluates a series of boolean expressions, yielding the logical AND\nof all expressions. If a `false` value is evaluated, no further expressions\nwill be evaluated.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_and(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n let (last, init) = args.split_last().unwrap();\n let last_block = compiler.new_block();\n\n for arg in init {\n compiler.compile_value(arg)?;\n\n // The `and` operator expects a boolean value in the value register\n // after this jump instruction is run. Therefore, we must prevent\n // the compiler from merging it with a previous instruction,\n // which might result in a different value, e.g. () for JumpIfNotNull.\n compiler.flush_instructions()?;\n compiler.current_block().jump_to(JumpInstruction::JumpIfNot, last_block);\n\n let block = compiler.new_block();\n compiler.use_next(block);\n }\n\n compiler.compile_value(last)?;\n compiler.use_next(last_block);\n Ok(())\n}\n```"}], "func_name": "op_and", "docstring": "`and` evaluates a series of boolean expressions, yielding the logical AND\nof all expressions. If a `false` value is evaluated, no further expressions\nwill be evaluated.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "47539105924d7b365bca7ba643442f85fe45e9674ac50d4b71c80f644c6d5f24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_or\n\nDocumentation:\n`and` evaluates a series of boolean expressions, yielding the logical OR\nof all expressions. If a `true` value is evaluated, no further expressions\nwill be evaluated.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_or(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n let (last, init) = args.split_last().unwrap();\n let last_block = compiler.new_block();\n\n for arg in init {\n compiler.compile_value(arg)?;\n\n // The `or` operator expects a boolean value in the value register\n // after this jump instruction is run. Therefore, we must prevent\n // the compiler from merging it with a previous instruction,\n // which might result in a different value, e.g. () for JumpIfNull.\n compiler.flush_instructions()?;\n compiler.current_block().jump_to(JumpInstruction::JumpIf, last_block);\n\n let block = compiler.new_block();\n compiler.use_next(block);\n }\n\n compiler.compile_value(last)?;\n compiler.use_next(last_block);\n Ok(())\n}\n```"}], "func_name": "op_or", "docstring": "`and` evaluates a series of boolean expressions, yielding the logical OR\nof all expressions. If a `true` value is evaluated, no further expressions\nwill be evaluated.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8df9d0013b4a41e4cb984fd39c8797e49e7a7a7b66e08872676bd9b79eff22fe"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_case\n\nDocumentation:\n`case` evaluates an expression and selects a branch by comparing the value\nto a series of constant expressions.\n\nThe last branch may use `else` as its pattern to match all values.\nIf there is not a successful match, the value `()` is yielded.\n\n```lisp\n(case foo\n((0 2 4 6 8) 'even)\n((1 3 5 7 9) 'odd))\n\n(case bar\n((0 1 2 3) 'a)\n((4 5 6 7) 'b)\n(else 'c))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_case(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n let final_block = compiler.new_block();\n let mut code_blocks = Vec::with_capacity(args.len());\n let mut else_case = false;\n\n compiler.compile_value(&args[0])?;\n\n for case in &args[1..] {\n if else_case {\n compiler.set_trace_expr(case);\n return Err(From::from(CompileError::SyntaxError(\"unreachable case\")));\n }\n\n let li = match *case {\n Value::List(ref li) if li.len() == 2 => li,\n _ => {\n compiler.set_trace_expr(case);\n return Err(From::from(CompileError::SyntaxError(\n \"expected list of 2 elements\")));\n }\n };\n\n let pat = &li[0];\n let code = &li[1];\n\n let code_begin = compiler.new_block();\n\n match *pat {\n Value::List(ref li) => {\n for v in li {\n match *v {\n Value::Unit => compiler.current_block().jump_to(\n JumpInstruction::JumpIfNull, code_begin),\n Value::Bool(true) => compiler.current_block().jump_to(\n JumpInstruction::JumpIf, code_begin),\n Value::Bool(false) => compiler.current_block().jump_to(\n JumpInstruction::JumpIfNot, code_begin),\n ref v => {\n let c = compiler.add_const(Borrowed(v));\n compiler.current_block().jump_to(\n JumpInstruction::JumpIfEqConst(c), code_begin);\n }\n }\n let b = compiler.new_block();\n compiler.use_next(b);\n }\n }\n Value::Name(standard_names::ELSE) => {\n else_case = true;\n compiler.current_block().jump_to(JumpInstruction::Jump, code_begin);\n }\n ref v => {\n compiler.set_trace_expr(v);\n return Err(From::from(CompileError::SyntaxError(\n \"expected list or `else`\")));\n }\n }\n\n let prev_block = compiler.cur_block as u32;\n compiler.use_block(code_begin);\n compiler.compile_value(code)?;\n compiler.current_block().jump_to(JumpInstruction::Jump, final_block);\n let code_end = compiler.cur_block as u32;\n code_blocks.push((code_begin, code_end));\n\n let b = compiler.new_block();\n compiler.use_block(prev_block);\n compiler.use_next(b);\n }\n\n if !else_case {\n compiler.push_instruction(Instruction::Unit)?;\n compiler.current_block().jump_to(JumpInstruction::Jump, final_block);\n }\n\n for (begin, end) in code_blocks {\n compiler.current_block().set_next(begin);\n compiler.use_block(end);\n }\n\n compiler.use_next(final_block);\n Ok(())\n}\n```"}], "func_name": "op_case", "docstring": "`case` evaluates an expression and selects a branch by comparing the value\nto a series of constant expressions.\n\nThe last branch may use `else` as its pattern to match all values.\nIf there is not a successful match, the value `()` is yielded.\n\n```lisp\n(case foo\n((0 2 4 6 8) 'even)\n((1 3 5 7 9) 'odd))\n\n(case bar\n((0 1 2 3) 'a)\n((4 5 6 7) 'b)\n(else 'c))\n```", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ae18b45e245d5d395859ecde35043244522e1d1a9ad43f861dba2bdd7d70747"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_cond\n\nDocumentation:\n`cond` evaluates a series of boolean expressions and chooses the branch\nof the first expression evaluating to `true`.\n\n```lisp\n(cond\n((< a 50) 'low)\n((>= a 50) 'high))\n\n(cond\n((< a 10) 'low)\n((< a 90) 'mid)\n((< a 100) 'high)\n(else 'huge))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_cond(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n let final_block = compiler.new_block();\n let mut code_blocks = Vec::with_capacity(args.len());\n let mut else_case = false;\n\n for arg in args {\n if else_case {\n compiler.set_trace_expr(arg);\n return Err(From::from(CompileError::SyntaxError(\n \"unreachable condition\")));\n }\n\n let case = match *arg {\n Value::List(ref li) if li.len() == 2 => li,\n _ => {\n compiler.set_trace_expr(arg);\n return Err(From::from(CompileError::SyntaxError(\n \"expected list of 2 elements\")));\n }\n };\n\n let cond = &case[0];\n let code = &case[1];\n\n let code_begin = compiler.new_block();\n\n if let Value::Name(standard_names::ELSE) = *cond {\n else_case = true;\n compiler.current_block().jump_to(JumpInstruction::Jump, code_begin);\n } else {\n compiler.compile_value(cond)?;\n compiler.current_block().jump_to(JumpInstruction::JumpIf, code_begin);\n }\n\n let prev_block = compiler.cur_block as u32;\n compiler.use_block(code_begin);\n compiler.compile_value(code)?;\n compiler.current_block().jump_to(JumpInstruction::Jump, final_block);\n let code_end = compiler.cur_block as u32;\n code_blocks.push((code_begin, code_end));\n\n let b = compiler.new_block();\n compiler.use_block(prev_block);\n compiler.use_next(b);\n }\n\n if !else_case {\n compiler.push_instruction(Instruction::Unit)?;\n compiler.current_block().jump_to(JumpInstruction::Jump, final_block);\n }\n\n for (begin, end) in code_blocks {\n compiler.current_block().set_next(begin);\n compiler.use_block(end);\n }\n\n compiler.use_next(final_block);\n Ok(())\n}\n```"}], "func_name": "op_cond", "docstring": "`cond` evaluates a series of boolean expressions and chooses the branch\nof the first expression evaluating to `true`.\n\n```lisp\n(cond\n((< a 50) 'low)\n((>= a 50) 'high))\n\n(cond\n((< a 10) 'low)\n((< a 90) 'mid)\n((< a 100) 'high)\n(else 'huge))\n```", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a2e5e95fe4234922252181d4cca5a94f092966d7a7274d8838aee560ee0b7878"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_lambda\n\nDocumentation:\n`lambda` defines an anonymous lambda function which may enclose named values\nfrom the enclosing scope.\n\n```lisp\n(define (plus-n n)\n(lambda (v) (+ v n)))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_lambda(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n // Replace operator item with more specific item\n compiler.trace.pop();\n compiler.trace.push(TraceItem::DefineLambda(compiler.ctx.scope().name()));\n\n let (doc, body) = extract_doc_string(args)?;\n\n let li = match args[0] {\n Value::Unit => &[][..],\n Value::List(ref li) => &li[..],\n ref v => {\n compiler.set_trace_expr(v);\n return Err(From::from(CompileError::SyntaxError(\"expected list\")));\n }\n };\n\n let (lambda, captures) = make_lambda(\n compiler, None, li, body, doc)?;\n\n let c = compiler.add_const(Owned(Value::Lambda(lambda)));\n compiler.load_lambda(c, &captures)?;\n Ok(())\n}\n```"}], "func_name": "op_lambda", "docstring": "`lambda` defines an anonymous lambda function which may enclose named values\nfrom the enclosing scope.\n\n```lisp\n(define (plus-n n)\n(lambda (v) (+ v n)))\n```", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "05b075db6959c5f7ef605c6947759d093fb04349c40ffaa798287b203b2e2dd1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_export\n\nDocumentation:\n`export` declares the set of names exported from a code module.\n\n```lisp\n(export (foo bar baz))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_export(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n if compiler.scope().with_exports(|_| ()).is_some() {\n return Err(From::from(CompileError::DuplicateExports));\n }\n\n let li = match args[0] {\n Value::Unit => &[][..],\n Value::List(ref li) => &li[..],\n ref v => {\n compiler.set_trace_expr(v);\n return Err(From::from(CompileError::SyntaxError(\n \"expected list of names in `export`\")));\n }\n };\n\n let mut names = NameSet::new();\n\n for v in li {\n names.insert(get_name(compiler, v)?);\n }\n\n compiler.scope().set_exports(names.into_slice());\n\n compiler.push_instruction(Instruction::Unit)?;\n Ok(())\n}\n```"}], "func_name": "op_export", "docstring": "`export` declares the set of names exported from a code module.\n\n```lisp\n(export (foo bar baz))\n```", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bf1743826b374b134257fbdde9ff1f536eeb11956844500b4f51784efe096ab4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_use\n\nDocumentation:\n`use` imports a series of names from a module.\n\n```lisp\n(use foo (alpha beta gamma))\n\n(use foo :self)\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_use(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n let mod_name = get_name(compiler, &args[0])?;\n\n // Replace operator item with more specific item\n compiler.trace.pop();\n compiler.trace.push(TraceItem::UseModule(compiler.ctx.scope().name(), mod_name));\n\n let ctx = compiler.ctx.clone();\n let mods = ctx.scope().modules();\n let m = mods.load_module(mod_name, &ctx)\n .map_err(|e| { compiler.extend_global_trace(); e })?;\n\n let mut imp_set = ImportSet::new(mod_name);\n\n match args[1] {\n Value::Keyword(standard_names::ALL) => {\n let names = compiler.scope().import_all(&m.scope);\n imp_set.names.extend(names.iter().map(|&n| (n, n)));\n }\n Value::Keyword(standard_names::SELF) => {\n let names = compiler.scope().import_qualified(&m.scope);\n imp_set.names.extend(names);\n }\n Value::Unit => (),\n Value::List(ref li) => {\n import_names(mod_name, &mut imp_set,\n compiler.scope(), &m.scope, li)?;\n }\n ref v => {\n compiler.set_trace_expr(v);\n return Err(From::from(CompileError::SyntaxError(\n \"expected list of names or `:all`\")));\n }\n }\n\n compiler.scope().add_imports(imp_set);\n\n compiler.push_instruction(Instruction::Unit)?;\n Ok(())\n}\n```"}], "func_name": "op_use", "docstring": "`use` imports a series of names from a module.\n\n```lisp\n(use foo (alpha beta gamma))\n\n(use foo :self)\n```", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5120d492dccc87ada402cffaae202f57fb3ca3cecb36b2f33bc0612d057ca193"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_const\n\nDocumentation:\n`const` declares a named constant value in global scope.\nThe value must be a compile-time constant.\n\n```lisp\n(const foo 123)\n\n(const bar (+ foo 1))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_const(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n let name = get_name(compiler, &args[0])?;\n\n // Replace operator item with more specific item\n compiler.trace.pop();\n compiler.trace.push(TraceItem::DefineConst(\n compiler.ctx.scope().name(), name));\n\n let (doc, body) = extract_doc_string(args)?;\n\n test_define_name(compiler.scope(), name)?;\n\n if compiler.get_constant(name).is_some() {\n return Err(From::from(CompileError::ConstantExists(name)));\n }\n\n let mut value = Borrowed(body);\n\n match compiler.eval_constant(&value)? {\n ConstResult::IsConstant => (),\n ConstResult::IsRuntime |\n ConstResult::Partial(_) => {\n compiler.set_trace_expr(&value);\n return Err(From::from(CompileError::NotConstant(name)));\n }\n ConstResult::Constant(v) => value = Owned(v)\n }\n\n compiler.add_constant(name, value.into_owned());\n if let Some(doc) = doc {\n compiler.scope().add_doc_string(name, doc.to_owned());\n }\n\n compiler.load_quoted_value(Owned(Value::Name(name)))?;\n Ok(())\n}\n```"}], "func_name": "op_const", "docstring": "`const` declares a named constant value in global scope.\nThe value must be a compile-time constant.\n\n```lisp\n(const foo 123)\n\n(const bar (+ foo 1))\n```", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ea8fea45985469b582327fa9565b0a258a6eedb8e79f1ac02f35d377dd997db8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_set_module_doc\n\nDocumentation:\n`set-module-doc` initializes the docstring for the contained module.\nIt may only appear at most one time per module.\n\n```lisp\n(set-module-doc \"Module doc string\")\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_set_module_doc(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n let doc = <&str>::from_value_ref(&args[0])?;\n\n let scope = compiler.scope().clone();\n\n scope.with_module_doc_mut(|d| {\n if d.is_none() {\n *d = Some(doc.to_owned());\n compiler.push_instruction(Instruction::Unit)?;\n Ok(())\n } else {\n Err(From::from(CompileError::DuplicateModuleDoc))\n }\n })\n}\n```"}], "func_name": "op_set_module_doc", "docstring": "`set-module-doc` initializes the docstring for the contained module.\nIt may only appear at most one time per module.\n\n```lisp\n(set-module-doc \"Module doc string\")\n```", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "209cdf010248e3024c0a288b352697d4511420043ed1ad133425682db28c8a7c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: op_call_self\n\nDocumentation:\nCalls the function currently being executed.\n\nThis operator enables lambda functions to be recursive.\n\n```lisp\n(lambda (n) (call-self (+ n 1)))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn op_call_self(compiler: &mut Compiler, args: &[Value]) -> Result<(), Error> {\n if !compiler.is_inside_lambda() {\n return Err(CompileError::SyntaxError(\"`call-self` outside lambda\").into());\n }\n\n for arg in args {\n compiler.compile_value(arg)?;\n compiler.push_instruction(Instruction::Push)?;\n }\n\n compiler.push_instruction(Instruction::CallSelf(args.len() as u32))?;\n Ok(())\n}\n```"}], "func_name": "op_call_self", "docstring": "Calls the function currently being executed.\n\nThis operator enables lambda functions to be recursive.\n\n```lisp\n(lambda (n) (call-self (+ n 1)))\n```", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b005bb38cc0c9be069a6a6db729bf1a7e1c89e5508036681d3c34d159a047951"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_lambda\n\nDocumentation:\nCreates a `Lambda` object using scope and local values from the given compiler.\nReturns the `Lambda` object and the set of names captured by the lambda.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn make_lambda(compiler: &mut Compiler, name: Option,\n args: &[Value], body: &Value, doc: Option<&str>)\n -> Result<(Lambda, Vec), Error> {\n let mut params = Vec::new();\n let mut req_params = 0;\n let mut kw_params = Vec::new();\n // Whether we've encountered `:key`\n let mut key = false;\n // Whether we've encountered `:optional`\n let mut optional = false;\n // `:rest` argument, if encountered\n let mut rest = None;\n\n let mut iter = args.iter();\n\n while let Some(v) = iter.next() {\n let (name, default) = match *v {\n Value::Name(name) => (name, None),\n Value::Keyword(kw) => {\n match kw {\n standard_names::KEY => {\n if key {\n return Err(From::from(CompileError::SyntaxError(\n \"duplicate `:key`\")));\n } else if optional {\n return Err(From::from(CompileError::SyntaxError(\n \"`:key` and `:optional` are mutually exclusive\")));\n }\n key = true;\n req_params = params.len() as u32;\n }\n standard_names::OPTIONAL => {\n if optional {\n return Err(From::from(CompileError::SyntaxError(\n \"duplicate `:optional`\")));\n } else if key {\n return Err(From::from(CompileError::SyntaxError(\n \"`:key` and `:optional` are mutually exclusive\")));\n }\n optional = true;\n req_params = params.len() as u32;\n }\n standard_names::REST => {\n if key {\n return Err(From::from(CompileError::SyntaxError(\n \"`:key` and `:rest` are mutually exclusive\")));\n }\n\n let arg = match iter.next() {\n Some(arg) => arg,\n None => return Err(From::from(CompileError::SyntaxError(\n \"expected name after `:rest`\")))\n };\n\n rest = Some(get_name(compiler, arg)?);\n\n match iter.next() {\n Some(_) => return Err(From::from(CompileError::SyntaxError(\n \"extraneous token after `:rest` argument\"))),\n None => break\n }\n }\n _ => return Err(From::from(CompileError::SyntaxError(\n \"expected :key, :optional, or :rest\")))\n }\n continue;\n }\n Value::List(ref li) if li.len() == 2 => {\n let name = get_name(compiler, &li[0])?;\n (name, Some(li[1].clone()))\n }\n ref v => {\n compiler.set_trace_expr(v);\n return Err(From::from(CompileError::SyntaxError(\n \"expected name, keyword, or list of 2 elements\")));\n }\n };\n\n let exists = params.iter().any(|&(n, _)| n == name) ||\n kw_params.iter().any(|&(n, _)| n == name);\n\n if exists {\n compiler.set_trace_expr(v);\n return Err(From::from(CompileError::DuplicateParameter(name)));\n }\n\n if default.is_some() && !(key || optional) {\n compiler.set_trace_expr(v);\n return Err(From::from(CompileError::SyntaxError(\n \"default value before `:optional` or `:key`\")));\n }\n\n if key {\n kw_params.push((name, default));\n } else {\n params.push((name, default));\n }\n }\n\n if !optional {\n req_params = params.len() as u32;\n }\n\n if key && kw_params.is_empty() {\n return Err(From::from(CompileError::SyntaxError(\n \"expected arguments after `:key`\")));\n }\n\n if optional && req_params == params.len() as u32 {\n return Err(From::from(CompileError::SyntaxError(\n \"expected arguments after `:optional`\")));\n }\n\n let (mut code, captures) = compile_lambda(compiler,\n name, params, req_params, kw_params, rest, body)?;\n\n if let Some(doc) = doc {\n code.flags |= code_flags::HAS_DOC_STRING;\n code.doc = Some(doc.to_owned());\n }\n\n Ok((Lambda::new(Rc::new(code), compiler.scope()), captures))\n}\n```"}], "func_name": "make_lambda", "docstring": "Creates a `Lambda` object using scope and local values from the given compiler.\nReturns the `Lambda` object and the set of names captured by the lambda.", "repo": "murarth/ketos", "path": "src/ketos/compile.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/compile.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ac8101839f3a7be79ed3a34ee95d88d56d06eccc2d8b7d8c18924c29322e0bb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: complete_name\n\nDocumentation:\nReturns a sorted list of possible name completions for the given prefix.\n\nReturns `None` if no possible completions exist.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn complete_name(word: &str, scope: &GlobalScope)\n -> Option> {\n let mut results = Vec::new();\n\n for name in MasterScope::names() {\n scope.with_name(name, |name| {\n if name.starts_with(word) {\n results.push(name.to_owned());\n }\n });\n }\n\n scope.with_values(|values| {\n for &(name, _) in values {\n scope.with_name(name, |name| {\n if name.starts_with(word) {\n results.push(name.to_owned());\n }\n });\n }\n });\n\n scope.with_macros(|macros| {\n for &(name, _) in macros {\n scope.with_name(name, |name| {\n if name.starts_with(word) {\n results.push(name.to_owned());\n }\n });\n }\n });\n\n if results.is_empty() {\n None\n } else {\n results.sort();\n Some(results)\n }\n}\n```"}], "func_name": "complete_name", "docstring": "Returns a sorted list of possible name completions for the given prefix.\n\nReturns `None` if no possible completions exist.", "repo": "murarth/ketos", "path": "src/ketos/completion.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/completion.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dd194c21403e220e11fd4a513dd7bfb0fbd0ebb680b886c0ce4448503c48e930"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fold_inv\n\nDocumentation:\nInverse fold operation; used for anticommutative operators.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fold_inv(ctx: &Context, lhs: Value, rhs: &Value) -> Result {\n Self::fold(ctx, lhs, rhs)\n }\n```"}], "func_name": "fold_inv", "docstring": "Inverse fold operation; used for anticommutative operators.", "repo": "murarth/ketos", "path": "src/ketos/const_fold.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/const_fold.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25a15ee479f3a7855b5b50c1d53fb5fd879ab4d6a646df4d88ede9098b39080d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `ValueDecoder` reading from the given byte stream.\n`ctx` is the execution context whose module-level scope\nwill be passed to newly created `Lambda` objects.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(ctx: &'a Context, data: &'data [u8]) -> ValueDecoder<'a, 'data> {\n ValueDecoder{\n data: Cursor::new(data),\n ctx,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `ValueDecoder` reading from the given byte stream.\n`ctx` is the execution context whose module-level scope\nwill be passed to newly created `Lambda` objects.", "repo": "murarth/ketos", "path": "src/ketos/encode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/encode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b150dba085209eeefd3ca26ce66c945065b025a08f1481f05b477364856490dd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_empty\n\nDocumentation:\nReturns `true` if there is no data left to decode.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_empty(&self) -> bool {\n let buf = self.data.get_ref();\n self.data.position() as usize == buf.len()\n }\n```"}], "func_name": "is_empty", "docstring": "Returns `true` if there is no data left to decode.", "repo": "murarth/ketos", "path": "src/ketos/encode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/encode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d043d2a0a974353df3c6306a980b0e443b0db4b4b3afdeeee9831f6cb1534a7f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_value\n\nDocumentation:\nReads a `Value` from the byte stream.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_value(&mut self, names: &NameInputConversion) -> Result {\n use self::types::*;\n\n let ty = self.read_u8()?;\n\n match ty {\n UNIT => Ok(Value::Unit),\n BOOL_TRUE => Ok(Value::Bool(true)),\n BOOL_FALSE => Ok(Value::Bool(false)),\n FLOAT => Ok(Value::Float(self.read_f64()?)),\n INTEGER | INTEGER_NEG => {\n let sign = if ty == INTEGER {\n Sign::Plus\n } else {\n Sign::Minus\n };\n\n self.read_integer(sign).map(Value::Integer)\n }\n INTEGER_ZERO => Ok(Value::Integer(Integer::zero())),\n RATIO | RATIO_NEG => {\n let sign = if ty == RATIO {\n Sign::Plus\n } else {\n Sign::Minus\n };\n\n let numer = self.read_integer(sign)?;\n // Denominator is always positive\n let denom = self.read_integer(Sign::Plus)?;\n\n if denom.is_zero() {\n Err(DecodeError::DivisionByZero)\n } else {\n Ok(Ratio::new(numer, denom).into())\n }\n }\n RATIO_ZERO => Ok(Value::Ratio(Ratio::zero())),\n NAME => Ok(Value::Name(self.read_name(names)?)),\n KEYWORD => Ok(Value::Keyword(self.read_name(names)?)),\n CHAR => {\n let c = self.read_u32()?;\n from_u32(c)\n .map(Value::Char)\n .ok_or_else(|| DecodeError::InvalidChar(c))\n }\n STRING => self.read_string().map(|s| s.into()),\n BYTES => self.read_byte_string().map(|s| s.into()),\n PATH => self.read_string().map(|s| PathBuf::from(s).into()),\n // XXX: Decoding struct values is not implemented\n STRUCT => Err(DecodeError::InvalidType(STRUCT)),\n STRUCT_DEF => {\n let name = self.read_name(names)?;\n let n = self.read_uint()?;\n let mut fields = NameMap::new();\n\n for _ in 0..n {\n let field = self.read_name(names)?;\n let ty = self.read_name(names)?;\n\n fields.insert(field, ty);\n }\n\n let def = StructValueDef::new(fields.into_slice());\n\n Ok(Value::StructDef(Rc::new(StructDef::new(name, Box::new(def)))))\n }\n QUASI_QUOTE => {\n let n = u32::from(self.read_u8()?);\n self.read_value(names).map(|v| v.quasiquote(n))\n }\n QUASI_QUOTE_ONE => self.read_value(names).map(|v| v.quasiquote(1)),\n COMMA => {\n let n = u32::from(self.read_u8()?);\n self.read_value(names).map(|v| v.comma(n))\n }\n COMMA_ONE => self.read_value(names).map(|v| v.comma(1)),\n COMMA_AT => {\n let n = u32::from(self.read_u8()?);\n self.read_value(names).map(|v| v.comma_at(n))\n }\n COMMA_AT_ONE => self.read_value(names).map(|v| v.comma_at(1)),\n QUOTE => {\n let n = u32::from(self.read_u8()?);\n self.read_value(names).map(|v| v.quote(n))\n }\n QUOTE_ONE => self.read_value(names).map(|v| v.quote(1)),\n LIST => {\n let n = self.read_len()?;\n\n if n == 0 {\n return Err(DecodeError::EmptyList);\n }\n\n let mut v = Vec::with_capacity(n);\n\n for _ in 0..n {\n v.push(self.read_value(names)?);\n }\n\n Ok(v.into())\n }\n LAMBDA => {\n let code = self.read_code(names)?;\n Ok(Value::Lambda(Lambda::new(Rc::new(code), self.ctx.scope())))\n }\n _ => Err(DecodeError::InvalidType(ty))\n }\n }\n```"}], "func_name": "read_value", "docstring": "Reads a `Value` from the byte stream.", "repo": "murarth/ketos", "path": "src/ketos/encode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/encode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f3daefe15240504e0c376be42a766b44511ee7447f379e481400b007297263eb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_value\n\nDocumentation:\nWrites a `Value` to the byte stream.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_value(&mut self, value: &Value, names: &mut NameOutputConversion) -> Result<(), EncodeError> {\n use self::types::*;\n\n match *value {\n Value::Unit => self.write_u8(UNIT),\n Value::Bool(b) => if b {\n self.write_u8(BOOL_TRUE);\n } else {\n self.write_u8(BOOL_FALSE);\n },\n Value::Float(f) => {\n self.write_u8(FLOAT);\n self.write_f64(f);\n }\n Value::Integer(ref i) => {\n if i.is_zero() {\n self.write_u8(INTEGER_ZERO);\n } else {\n if i.is_negative() {\n self.write_u8(INTEGER_NEG);\n } else {\n self.write_u8(INTEGER);\n }\n\n self.write_integer(i)?;\n }\n }\n Value::Ratio(ref r) => {\n if r.is_zero() {\n self.write_u8(RATIO_ZERO);\n } else {\n if r.is_positive() {\n self.write_u8(RATIO);\n } else {\n self.write_u8(RATIO_NEG);\n }\n\n self.write_integer(r.numer())?;\n self.write_integer(r.denom())?;\n }\n }\n Value::Name(name) => {\n self.write_u8(NAME);\n self.write_name(name, names)?;\n }\n Value::Keyword(name) => {\n self.write_u8(KEYWORD);\n self.write_name(name, names)?;\n }\n Value::Char(c) => {\n self.write_u8(CHAR);\n self.write_u32(c as u32);\n }\n Value::String(ref s) => {\n self.write_u8(STRING);\n self.write_string(s)?;\n }\n Value::Bytes(ref s) => {\n self.write_u8(BYTES);\n self.write_byte_string(s)?;\n }\n Value::Path(ref p) => {\n self.write_u8(PATH);\n self.write_path(p)?;\n }\n // TODO: Encode/decode struct values.\n // Modules could begin with a listing of all defined StructDefs,\n // which could be referenced by index thereafter.\n // However, Struct encoding/decoding must also account for the\n // possibility that a Struct value exists in a module based on a\n // definition which is found in another module.\n Value::Struct(_) => return Err(EncodeError::UnencodableType(\"struct\")),\n Value::StructDef(ref def) => {\n if let Some(vdef) = def.def().downcast_ref::() {\n self.write_u8(STRUCT_DEF);\n\n let fields = vdef.fields();\n\n self.write_name(def.name(), names)?;\n self.write_len(fields.len())?;\n\n for &(name, ty) in fields {\n self.write_name(name, names)?;\n self.write_name(ty, names)?;\n }\n } else {\n return Err(EncodeError::UnencodableType(\"struct-def\"));\n }\n }\n Value::Quasiquote(ref v, 1) => {\n self.write_u8(QUASI_QUOTE_ONE);\n self.write_value(v, names)?;\n }\n Value::Quasiquote(ref v, n) if n <= 0xff => {\n self.write_u8(QUASI_QUOTE);\n self.write_u8(n as u8);\n self.write_value(v, names)?;\n }\n Value::Comma(ref v, 1) => {\n self.write_u8(COMMA_ONE);\n self.write_value(v, names)?;\n }\n Value::Comma(ref v, n) if n <= 0xff => {\n self.write_u8(COMMA);\n self.write_u8(n as u8);\n self.write_value(v, names)?;\n }\n Value::CommaAt(ref v, 1) => {\n self.write_u8(COMMA_AT_ONE);\n self.write_value(v, names)?;\n }\n Value::CommaAt(ref v, n) if n <= 0xff => {\n self.write_u8(COMMA_AT);\n self.write_u8(n as u8);\n self.write_value(v, names)?;\n }\n Value::Quote(ref v, 1) => {\n self.write_u8(QUOTE_ONE);\n self.write_value(v, names)?;\n }\n Value::Quote(ref v, n) if n <= 0xff => {\n self.write_u8(QUOTE);\n self.write_u8(n as u8);\n self.write_value(v, names)?;\n }\n Value::Comma(_, _)\n | Value::CommaAt(_, _)\n | Value::Quasiquote(_, _)\n | Value::Quote(_, _) => {\n return Err(EncodeError::Overflow);\n }\n Value::List(ref li) => {\n self.write_u8(LIST);\n self.write_len(li.len())?;\n\n for v in li {\n self.write_value(v, names)?;\n }\n }\n Value::Lambda(ref l) => {\n if l.values.is_some() {\n return Err(EncodeError::UnencodableValue(\n \"lambda with enclosed values\"));\n }\n self.write_u8(LAMBDA);\n self.write_code(&l.code, names)?;\n }\n Value::Foreign(_) =>\n return Err(EncodeError::UnencodableType(\"foreign value\")),\n ref v => return Err(EncodeError::UnencodableType(v.type_name()))\n }\n\n Ok(())\n }\n```"}], "func_name": "write_value", "docstring": "Writes a `Value` to the byte stream.", "repo": "murarth/ketos", "path": "src/ketos/encode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/encode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d5fd63da03b31b1b8436e865ce37c35edf8294ca01e0795e54559cdbfb385d50"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_cursor\n\nDocumentation:\nReads bytes from a cursor without copying data.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_cursor<'a>(cur: &mut Cursor<&'a [u8]>, n: usize) -> Option<&'a [u8]> {\n let pos = cur.position() as usize;\n let bytes = *cur.get_ref();\n\n if bytes.len() < pos + n {\n None\n } else {\n cur.set_position((pos + n) as u64);\n Some(&bytes[pos..pos + n])\n }\n}\n```"}], "func_name": "read_cursor", "docstring": "Reads bytes from a cursor without copying data.", "repo": "murarth/ketos", "path": "src/ketos/encode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/encode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17748df1761f66bbbca709eb759ac614b6a84e24430f34714d6a400384b48b7e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: description\n\nDocumentation:\nReturns a string describing the nature of the error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn description(&self) -> &'static str {\n match *self {\n Error::CompileError(_) => \"compile error\",\n Error::DecodeError(_) => \"decode error\",\n Error::EncodeError(_) => \"encode error\",\n Error::ExecError(_) => \"execution error\",\n Error::IoError(_) => \"I/O error\",\n Error::ParseError(_) => \"parse error\",\n Error::RestrictError(_) => \"restriction error\",\n Error::Custom(_) => \"error\",\n }\n }\n```"}], "func_name": "description", "docstring": "Returns a string describing the nature of the error.", "repo": "murarth/ketos", "path": "src/ketos/error.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/error.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c96eb9ad6dc8ac18f7a305a3e422582f9e0baa218d4f5ccc87fd93dd6cf4cce5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_scope\n\nDocumentation:\nCreates a new execution context with the given scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_scope(&self, scope: Scope) -> Context {\n Context::new(scope, self.restrict.clone())\n }\n```"}], "func_name": "with_scope", "docstring": "Creates a new execution context with the given scope.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "68f026c9bdafb508520e968ab4f5d600eb35ae735cda14dc43b3e02c7af5f8a0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: panic\n\nDocumentation:\nReturns a `Panic` error with the given value.\n\nThis is equivalent to `(panic value)`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn panic(value: T) -> E\n where T: Into, E: From {\n From::from(ExecError::Panic(Some(value.into())))\n}\n```"}], "func_name": "panic", "docstring": "Returns a `Panic` error with the given value.\n\nThis is equivalent to `(panic value)`.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d314781773562d1d84aea041e4e4097aaa345516ae281b1b761ae9264cc9fa5f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: panic_none\n\nDocumentation:\nReturns a `Panic` error with no value.\n\nThis is equivalent to `(panic)`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn panic_none() -> E\n where E: From {\n From::from(ExecError::Panic(None))\n}\n```"}], "func_name": "panic_none", "docstring": "Returns a `Panic` error with no value.\n\nThis is equivalent to `(panic)`.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "907a0125fe3f7c338eb2c492fa785923c033793c9c0f7528b1d8457e6e3eb9a2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expected\n\nDocumentation:\nConvenience function to return a `TypeError` value when `expected`\ntype is expected, but some other type of value is found.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expected(expected: &'static str, v: &Value) -> ExecError {\n ExecError::TypeError{\n expected,\n found: v.type_name(),\n value: Some(v.clone()),\n }\n }\n```"}], "func_name": "expected", "docstring": "Convenience function to return a `TypeError` value when `expected`\ntype is expected, but some other type of value is found.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0b77717a0cb60c9aa829c27bc4487469234e01bfc3fa144f3a5582d04fee9b18"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expected_field\n\nDocumentation:\nConvenience function to return a `FieldTypeError` value when a struct\nfield of the incorrect type is received.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn expected_field(struct_name: Name, field: Name,\n expected: Name, v: &Value) -> ExecError {\n ExecError::FieldTypeError{\n struct_name,\n field,\n expected,\n found: v.type_name(),\n value: Some(v.clone()),\n }\n }\n```"}], "func_name": "expected_field", "docstring": "Convenience function to return a `FieldTypeError` value when a struct\nfield of the incorrect type is received.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "890115e74ec31864a3fda777ba013296a5df56532d6160ae514973b2ba64f03f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: execute\n\nDocumentation:\nExecutes a code object and returns the value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn execute(ctx: &Context, code: Rc) -> Result {\n let mut mach = Machine::new(ctx);\n\n mach.execute(ctx.scope(), code)\n .map_err(|e| { set_traceback(mach.build_trace()); e })\n}\n```"}], "func_name": "execute", "docstring": "Executes a code object and returns the value.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "11fed19418d373f7cc589debed6cf4f2dfa75eafde424655462377870b40c99a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: call_function\n\nDocumentation:\nCalls a function or lambda in the given scope with the given arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn call_function(ctx: &Context, fun: Value, args: Vec) -> Result {\n match fun {\n Value::Function(fun) => execute_function(ctx, fun, args)\n .map_err(|e| { set_traceback(\n Trace::single(TraceItem::CallSys(fun.name), None)); e }),\n Value::Lambda(l) => execute_lambda(ctx, l, args),\n ref v => Err(From::from(ExecError::expected(\"function\", v)))\n }\n}\n```"}], "func_name": "call_function", "docstring": "Calls a function or lambda in the given scope with the given arguments.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e50494ae132a42d351f49abff13928905d3f3f574cbbf8229beb9b814c3e6384"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: execute_function\n\nDocumentation:\nExecutes a `Function` in the given scope and returns the value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn execute_function(ctx: &Context, fun: Function, mut args: Vec)\n -> Result {\n let n_args = args.len() as u32;\n\n if !fun.sys_fn.arity.accepts(n_args) {\n Err(From::from(ExecError::ArityError{\n name: Some(fun.name),\n expected: fun.sys_fn.arity,\n found: n_args,\n }))\n } else {\n (fun.sys_fn.callback)(ctx, &mut args)\n }\n}\n```"}], "func_name": "execute_function", "docstring": "Executes a `Function` in the given scope and returns the value.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "448b33f4b5b21cc0d62b855fa3189df96ec59612c195391bbf8baba086278a06"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: execute_lambda\n\nDocumentation:\nExecutes a `Lambda` in the given scope and returns the value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn execute_lambda(ctx: &Context, lambda: Lambda, args: Vec) -> Result {\n let mut mach = Machine::new(ctx);\n\n mach.execute_lambda(lambda, args)\n .map_err(|e| { set_traceback(mach.build_trace()); e })\n}\n```"}], "func_name": "execute_lambda", "docstring": "Executes a `Lambda` in the given scope and returns the value.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1c653911aaca25a412b415f7ace61782d08eee8daa0a577b6fb010f05e37929b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: call_function\n\nDocumentation:\nCalls a function on the stack with `n_args` arguments.\nThe callable value must be on the stack before the given arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn call_function(&mut self, frame: &mut StackFrame, n_args: u32)\n -> Result<(), Error> {\n let v = self.get_stack_top(n_args)?.clone();\n self.call_value(frame, v, n_args, true)\n }\n```"}], "func_name": "call_function", "docstring": "Calls a function on the stack with `n_args` arguments.\nThe callable value must be on the stack before the given arguments.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a004303841742fda8dff68f6e2211ace3128842bf9239414a0c2a98f7085d670"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: setup_call\n\nDocumentation:\nSets up a call to a `Code` object, ensuring that the incoming argument\ncount is valid for the given code object being called.\nKeyword and rest arguments are processed and `Unbound` values\nare pushed to the stack, if necessary.\n\nReturns the final count of stack argument values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn setup_call(&mut self, code: &Code, mut n_args: u32) -> Result {\n if n_args < code.req_params {\n return Err(From::from(ExecError::ArityError{\n name: code.name,\n expected: code.arity(),\n found: n_args,\n }));\n }\n\n if n_args < code.n_params {\n self.push_unbound(code.n_params - n_args)?;\n n_args = code.n_params;\n }\n\n if code.has_rest_params() {\n if n_args > code.n_params {\n self.build_list(n_args - code.n_params)?;\n self.push_value()?;\n n_args = code.n_params + 1;\n } else {\n self.push(Value::Unit)?;\n n_args += 1;\n };\n } else if code.has_kw_params() {\n let mut kw_values = vec![Value::Unbound; code.kw_params.len()];\n\n if n_args > code.n_params {\n let n_kw_args = n_args - code.n_params;\n let mut iter = self.drain_stack_top(n_kw_args)?;\n\n while let Some(kw) = iter.next() {\n let kw = get_keyword(&kw)?;\n let v = match iter.next() {\n Some(v) => v,\n None => return Err(From::from(ExecError::OddKeywordParams))\n };\n\n match code.kw_params.iter().position(|&n| n == kw) {\n Some(pos) => {\n if let Value::Unbound = kw_values[pos] {\n kw_values[pos] = v;\n } else {\n return Err(From::from(ExecError::DuplicateKeyword(kw)));\n }\n }\n None => return Err(From::from(ExecError::UnrecognizedKeyword(kw)))\n }\n }\n }\n\n n_args = code.n_params + kw_values.len() as u32;\n for v in kw_values {\n self.push(v)?;\n }\n } else if n_args != code.n_params {\n return Err(From::from(ExecError::ArityError{\n name: code.name,\n expected: code.arity(),\n found: n_args,\n }));\n }\n\n Ok(n_args)\n }\n```"}], "func_name": "setup_call", "docstring": "Sets up a call to a `Code` object, ensuring that the incoming argument\ncount is valid for the given code object being called.\nKeyword and rest arguments are processed and `Unbound` values\nare pushed to the stack, if necessary.\n\nReturns the final count of stack argument values.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3eaea0d6de5d2b022d605273c52ff0f62824a9cf348b9aecfa9aeeb46b2785ee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: expand_value\n\nDocumentation:\nConsumes value, which must be `Unit` or `List`,\nand pushes each contained value to the top of the stack,\nreturning the number of values pushed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn expand_value(&mut self) -> Result {\n let v = self.value.take();\n\n match v {\n Value::Unit => Ok(0),\n Value::List(li) => {\n let n = li.len();\n self.push_iter(li.to_vec())?;\n Ok(n)\n }\n ref v => Err(From::from(ExecError::expected(\"list\", v))),\n }\n }\n```"}], "func_name": "expand_value", "docstring": "Consumes value, which must be `Unit` or `List`,\nand pushes each contained value to the top of the stack,\nreturning the number of values pushed.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1fcd37c1c2388119ce81f6c42ed836b653676f56de69f1a1f1a4f04fb24f7b3d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clean_stack\n\nDocumentation:\nCleans the stack when returning from a function.\nAll values `stack[pos..]` are removed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn clean_stack(&mut self, pos: usize) {\n let n = self.stack[pos..].iter()\n .map(|v| v.size()).sum();\n self.context.set_memory(|m| m.saturating_sub(n));\n\n let _ = self.stack.drain(pos..);\n }\n```"}], "func_name": "clean_stack", "docstring": "Cleans the stack when returning from a function.\nAll values `stack[pos..]` are removed.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f00500ef79aa8e306341b28bdf3eac2521c87aa74a70de4783925ee762f54347"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: skip_stack\n\nDocumentation:\nRemoves the top `n` elements from the stack.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn skip_stack(&mut self, n: usize) -> Result<(), ExecError> {\n let len = self.stack.len();\n\n if n <= len {\n self.clean_stack(len - n);\n Ok(())\n } else {\n Err(ExecError::InvalidStack(len as u32))\n }\n }\n```"}], "func_name": "skip_stack", "docstring": "Removes the top `n` elements from the stack.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7e0a42b50316797178266bf80cda8e9dc53ddb340de82e85f5ebc8751eae72dc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: save_frame\n\nDocumentation:\nSaves the current call state to the call stack.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn save_frame(&mut self, frame: StackFrame) -> Result<(), Error> {\n if self.call_stack.len() == self.call_stack.capacity() {\n return Err(From::from(RestrictError::CallStackExceeded));\n }\n\n self.call_stack.push(frame);\n Ok(())\n }\n```"}], "func_name": "save_frame", "docstring": "Saves the current call state to the call stack.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "345b22f130df075a8c3097f2e79d9575c018a01bcec669d5c27d435f69b6a330"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: unbound_to_unit\n\nDocumentation:\nReplace an unbound value on the stack with `()`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn unbound_to_unit(&mut self, n: u32) -> Result<(), ExecError> {\n let v = self.get_stack_mut(n)?;\n if let Value::Unbound = *v {\n *v = Value::Unit;\n }\n Ok(())\n }\n```"}], "func_name": "unbound_to_unit", "docstring": "Replace an unbound value on the stack with `()`.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f96a83dd2c0740c709af186bc857cfb85dfa1a11831e1f1bcc2fe413301c0349"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_def\n\nDocumentation:\nLoad a value from the global scope named by a const value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_def(&mut self, frame: &StackFrame, n: u32) -> Result<(), ExecError> {\n let name = get_const_name(&frame.code, n)?;\n self.value = self.get_value(frame, name)?;\n\n Ok(())\n }\n```"}], "func_name": "get_def", "docstring": "Load a value from the global scope named by a const value.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54624b5e011fe66425f9e3e2f17de14299172df8ca26e34e687b7ffb9f2df28c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_value\n\nDocumentation:\nReturns a named value from global or master scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_value(&self, frame: &StackFrame, name: Name) -> Result {\n MasterScope::get(name)\n .or_else(|| frame.scope.get_value(name))\n .ok_or_else(|| ExecError::NameError(name))\n }\n```"}], "func_name": "get_value", "docstring": "Returns a named value from global or master scope.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "86f38051c6fcb292aa76fc844b167ddae4d18b7f39a7a76cc0e1ac43919a1256"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pop\n\nDocumentation:\nPop from the top of the stack and return the value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn pop(&mut self) -> Result {\n let v = self.stack.pop().ok_or(ExecError::InvalidStack(0))?;\n self.context.set_memory(|m| m.saturating_sub(v.size()));\n\n Ok(v)\n }\n```"}], "func_name": "pop", "docstring": "Pop from the top of the stack and return the value.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b6eec0b197d5f9bcc848b07d12e1fc06543dba34c89189b2b3d38537afc2ea8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_iter\n\nDocumentation:\nPush values onto the stack from an iterator.\n\n# Note\n\nIf `ExactSizeIterator::len` misrepresents the number of items in the\niterator, the stack's capacity may be exceeded without causing an error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn push_iter(&mut self, iter: I) -> Result<(), Error>\n where I: IntoIterator, I::IntoIter: ExactSizeIterator {\n let iter = iter.into_iter();\n\n if self.stack.len() + iter.len() > self.stack.capacity() {\n return Err(From::from(RestrictError::ValueStackExceeded));\n }\n\n let mut size = 0;\n\n self.stack.extend(iter\n .inspect(|v| size += v.size()));\n\n let total = self.context.set_memory(|m| m.saturating_add(size));\n\n self.check_memory(total)?;\n\n Ok(())\n }\n```"}], "func_name": "push_iter", "docstring": "Push values onto the stack from an iterator.\n\n# Note\n\nIf `ExactSizeIterator::len` misrepresents the number of items in the\niterator, the stack's capacity may be exceeded without causing an error.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ca5eae440b3de888c31cfd19915d216faaf498ed08d966576a8e45cb5ee96f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_closure_value\n\nDocumentation:\nReturns a reference to an enclosed value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_closure_value<'f>(&self, frame: &'f StackFrame, n: u32)\n -> Result<&'f Value, ExecError> {\n frame.values.as_ref().and_then(|v| v.get(n as usize))\n .ok_or_else(|| ExecError::InvalidClosureValue(n))\n }\n```"}], "func_name": "get_closure_value", "docstring": "Returns a reference to an enclosed value.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b4e2d072a9e531cfead0733608803c5f6617d54f0e19d75248a846658bc83df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_stack_top\n\nDocumentation:\nReturns a value from the stack `n` values from the top.\n`0` returns the top value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_stack_top(&self, n: u32) -> Result<&Value, ExecError> {\n let len = self.stack.len();\n\n if n as usize <= len {\n self.stack.get(len - 1 - n as usize)\n .ok_or_else(|| ExecError::InvalidStack(len as u32))\n } else {\n Err(ExecError::InvalidStack(n))\n }\n }\n```"}], "func_name": "get_stack_top", "docstring": "Returns a value from the stack `n` values from the top.\n`0` returns the top value.", "repo": "murarth/ketos", "path": "src/ketos/exec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/exec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1b20cbc4279a198dd7030c5668de7152850a440e5a0b15700f3e9dd07194c7c8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: accepts\n\nDocumentation:\nReturns whether this arity may accept `n` arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn accepts(&self, n: u32) -> bool {\n match *self {\n Arity::Exact(num) => n == num,\n Arity::Min(min) => n >= min,\n Arity::Range(min, max) => n >= min && n <= max,\n }\n }\n```"}], "func_name": "accepts", "docstring": "Returns whether this arity may accept `n` arguments.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "daadaad73cc172709a83c9ffd3b9e85c4fb40ef30eed5b26d12fb063e0aa26bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: plural\n\nDocumentation:\nReturns the suitable plural suffix `\"\"` or `\"s\"` for count `n`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn plural(n: u32) -> &'static str {\n if n == 1 { \"\" } else { \"s\" }\n}\n```"}], "func_name": "plural", "docstring": "Returns the suitable plural suffix `\"\"` or `\"s\"` for count `n`.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d799bd47d72c66cf69ccdc46e10584ae6339fca4f4cbc302f3242480156c8946"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_closure\n\nDocumentation:\nCreates a new `Lambda` enclosing a set of values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_closure(code: Rc, scope: WeakScope, values: Box<[Value]>) -> Lambda {\n Lambda{\n code,\n scope,\n values: Some(Rc::new(values)),\n }\n }\n```"}], "func_name": "new_closure", "docstring": "Creates a new `Lambda` enclosing a set of values.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "aa906c55ea7c6cab4f9c9d48722c903a436788d3f2e76c35264943d17a703894"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: value_is\n\nDocumentation:\nReturns whether a `Value` matches a given type.\n\nThe type name `number` will match `integer`, `float`, or `ratio` values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn value_is(scope: &Scope, a: &Value, ty: Name) -> bool {\n use crate::name::standard_names::*;\n\n match *a {\n Value::Float(_) | Value::Integer(_) | Value::Ratio(_)\n if ty == NUMBER => true,\n Value::Unit | Value::List(_) if ty == LIST => true,\n Value::Foreign(ref a) =>\n scope.with_name(ty, |name| a.is_type(name)),\n _ => type_of(scope, a) == ty\n }\n}\n```"}], "func_name": "value_is", "docstring": "Returns whether a `Value` matches a given type.\n\nThe type name `number` will match `integer`, `float`, or `ratio` values.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "866a07fe513b360708b4bce0e3297b367f7b42ddf2c212ac660054cf5623fe2f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_add\n\nDocumentation:\n`+` returns the sum of all arguments.\n\nGiven no arguments, returns the additive identity, `0`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_add(ctx: &Context, args: &mut [Value]) -> Result {\n if args.is_empty() {\n return Ok(Integer::zero().into());\n }\n\n let mut v = args[0].take();\n\n expect_number(&v)?;\n\n for arg in &args[1..] {\n expect_number(arg)?;\n v = add_number(ctx, v, arg)?;\n }\n\n Ok(v)\n}\n```"}], "func_name": "fn_add", "docstring": "`+` returns the sum of all arguments.\n\nGiven no arguments, returns the additive identity, `0`.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "abf35429e26e7a89b68c32e4d03c077c868f4eb1fb3b69639f8901a5d9c02fe1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_number\n\nDocumentation:\nReturns the result of adding two values together.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_number(ctx: &Context, lhs: Value, rhs: &Value) -> Result {\n let (lhs, rhs) = coerce_numbers(lhs, rhs)?;\n\n match (lhs, &*rhs) {\n (Value::Float(a), &Value::Float(b)) => Ok((a + b).into()),\n (Value::Integer(ref a), &Value::Integer(ref b)) => {\n check_bits(ctx, max(a.bits(), b.bits()) + 1)?;\n Ok((a + b).into())\n }\n (Value::Ratio(ref a), &Value::Ratio(ref b)) => {\n let nd = a.numer().bits() + b.denom().bits();\n let dn = a.denom().bits() + b.numer().bits();\n let dd = a.denom().bits() + b.denom().bits();\n\n check_bits(ctx, nd + dn)?;\n check_bits(ctx, dd)?;\n\n Ok((a + b).into())\n }\n (a, b) => Err(From::from(ExecError::TypeMismatch{\n lhs: a.type_name(),\n rhs: b.type_name(),\n })),\n }\n}\n```"}], "func_name": "add_number", "docstring": "Returns the result of adding two values together.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b7c83bcccc66f9a34677d165d14e1725aba996811f28b35cefb24ae2dd7eb3e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_sub\n\nDocumentation:\n`-` returns the cumulative difference between successive arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_sub(ctx: &Context, args: &mut [Value]) -> Result {\n let mut v = args[0].take();\n\n if args.len() == 1 {\n neg_number(v)\n } else {\n expect_number(&v)?;\n\n for arg in &args[1..] {\n expect_number(arg)?;\n v = sub_number(ctx, v, arg)?;\n }\n\n Ok(v)\n }\n}\n```"}], "func_name": "fn_sub", "docstring": "`-` returns the cumulative difference between successive arguments.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93a84ecf427a70ac9b86d0cc7f63bb2ce3aed9d51f97d03942216a8430c34f00"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: neg_number\n\nDocumentation:\nReturns the result of negating a value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn neg_number(v: Value) -> Result {\n match v {\n Value::Float(f) => Ok((-f).into()),\n Value::Integer(i) => Ok((-i).into()),\n Value::Ratio(r) => Ok((-r).into()),\n ref v => Err(From::from(ExecError::expected(\"number\", v)))\n }\n}\n```"}], "func_name": "neg_number", "docstring": "Returns the result of negating a value.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "153584760d1890a51f5d5ee6af2300d7568c0ac92594cfa5d8b3bbe94a38dbf9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: sub_number\n\nDocumentation:\nReturns the resulting of subtracting a value from another.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn sub_number(ctx: &Context, lhs: Value, rhs: &Value) -> Result {\n let (lhs, rhs) = coerce_numbers(lhs, rhs)?;\n\n match (lhs, &*rhs) {\n (Value::Float(a), &Value::Float(b)) => Ok((a - b).into()),\n (Value::Integer(ref a), &Value::Integer(ref b)) => {\n check_bits(ctx, max(a.bits(), b.bits()) + 1)?;\n Ok((a - b).into())\n }\n (Value::Ratio(ref a), &Value::Ratio(ref b)) => {\n let nd = a.numer().bits() + b.denom().bits();\n let dn = a.denom().bits() + b.numer().bits();\n let dd = a.denom().bits() + b.denom().bits();\n\n check_bits(ctx, nd + dn)?;\n check_bits(ctx, dd)?;\n\n Ok((a - b).into())\n }\n (a, b) => Err(From::from(ExecError::TypeMismatch{\n lhs: a.type_name(),\n rhs: b.type_name(),\n }))\n }\n}\n```"}], "func_name": "sub_number", "docstring": "Returns the resulting of subtracting a value from another.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "40dc49179cedcc938c7f0688454fe35158fd85b23bb9ae09522610cfc256f439"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_mul\n\nDocumentation:\n`*` returns the product of all arguments.\n\nGiven no arguments, returns the multiplicative identity, `1`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_mul(ctx: &Context, args: &mut [Value]) -> Result {\n if args.is_empty() {\n return Ok(Integer::one().into());\n }\n\n let mut v = args[0].take();\n\n expect_number(&v)?;\n\n for arg in &args[1..] {\n expect_number(arg)?;\n v = mul_number(ctx, v, arg)?;\n }\n\n Ok(v)\n}\n```"}], "func_name": "fn_mul", "docstring": "`*` returns the product of all arguments.\n\nGiven no arguments, returns the multiplicative identity, `1`.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "67d395f55f596944dff903866dc225d2c93367785016f2eecd9fdd70864e667b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: mul_number\n\nDocumentation:\nReturns the result of multiplying two values together.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn mul_number(ctx: &Context, lhs: Value, rhs: &Value) -> Result {\n let (lhs, rhs) = coerce_numbers(lhs, rhs)?;\n\n match (lhs, &*rhs) {\n (Value::Float(a), &Value::Float(b)) => Ok((a * b).into()),\n (Value::Integer(ref a), &Value::Integer(ref b)) => {\n check_bits(ctx, a.bits() + b.bits())?;\n Ok((a * b).into())\n }\n (Value::Ratio(ref a), &Value::Ratio(ref b)) => {\n let nn = a.numer().bits() + b.numer().bits();\n let dd = a.denom().bits() + b.denom().bits();\n\n check_bits(ctx, nn)?;\n check_bits(ctx, dd)?;\n\n Ok((a * b).into())\n }\n (a, b) => Err(From::from(ExecError::TypeMismatch{\n lhs: a.type_name(),\n rhs: b.type_name(),\n }))\n }\n}\n```"}], "func_name": "mul_number", "docstring": "Returns the result of multiplying two values together.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7d3f32cb0627ab12c997db02bb590b54ca3283dcf0e32fe274600212f7bfca40"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_pow\n\nDocumentation:\n`^` returns a base value raised to an exponent.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_pow(ctx: &Context, args: &mut [Value]) -> Result {\n let a = args[0].take();\n let b = args[1].take();\n\n expect_number(&a)?;\n expect_number(&b)?;\n\n pow_number(ctx, a, b)\n}\n```"}], "func_name": "fn_pow", "docstring": "`^` returns a base value raised to an exponent.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0b37bde9ef92d9507f631208e492730a299843943be32ea3199440445ad3ef5c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_div\n\nDocumentation:\n`/` returns the cumulative quotient of successive arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_div(ctx: &Context, args: &mut [Value]) -> Result {\n let mut v = args[0].take();\n\n expect_number(&v)?;\n\n if args.len() == 1 {\n // Call div instead of recip so that (/ 1) = 1\n div_number(ctx, 1.into(), &v)\n } else {\n for arg in &args[1..] {\n expect_number(arg)?;\n v = div_number(ctx, v, arg)?;\n }\n\n Ok(v)\n }\n}\n```"}], "func_name": "fn_div", "docstring": "`/` returns the cumulative quotient of successive arguments.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ae2ead7651158ed692b83db4d676ff1de4d17f8188e127ae091ab76610a9828"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_floor_div\n\nDocumentation:\n`//` returns the cumulative quotient of successive arguments,\nrounded toward negative infinity.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_floor_div(ctx: &Context, args: &mut [Value]) -> Result {\n let mut v = args[0].take();\n\n expect_number(&v)?;\n\n if args.len() == 1 {\n floor_recip_number(v)\n } else {\n for arg in &args[1..] {\n expect_number(arg)?;\n v = floor_div_number_step(ctx, v, arg)?;\n }\n\n floor_number(v)\n }\n}\n```"}], "func_name": "fn_floor_div", "docstring": "`//` returns the cumulative quotient of successive arguments,\nrounded toward negative infinity.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2916966cf88a7de6dc92918e0b748928bb2d1b5594c611967de5be517ee02389"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: div_number\n\nDocumentation:\nReturns the result of dividing two values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn div_number(ctx: &Context, lhs: Value, rhs: &Value) -> Result {\n let (lhs, rhs) = coerce_numbers(lhs, rhs)?;\n\n match (lhs, &*rhs) {\n (Value::Float(a), &Value::Float(b)) => {\n Ok((a / b).into())\n }\n (Value::Integer(ref a), &Value::Integer(ref b)) => {\n test_zero(b)?;\n if a.is_multiple_of(b) {\n Ok((a / b).into())\n } else {\n Ok(Ratio::new(a.clone(), b.clone()).into())\n }\n }\n (Value::Ratio(ref a), &Value::Ratio(ref b)) => {\n test_zero(b)?;\n\n let nd = a.numer().bits() + b.denom().bits();\n let dn = a.denom().bits() + b.numer().bits();\n\n check_bits(ctx, nd)?;\n check_bits(ctx, dn)?;\n\n Ok((a / b).into())\n }\n (a, b) => Err(From::from(ExecError::TypeMismatch{\n lhs: a.type_name(),\n rhs: b.type_name(),\n }))\n }\n}\n```"}], "func_name": "div_number", "docstring": "Returns the result of dividing two values.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2acd89b3a38375a1edff13f93019e8123fe859bf04fe0848f1f8ae9999371429"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: floor_div_number_step\n\nDocumentation:\nReturns the result of floor-dividing two values,\nwithout calling `floor` on the result.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn floor_div_number_step(ctx: &Context, lhs: Value, rhs: &Value) -> Result {\n let (lhs, rhs) = coerce_numbers(lhs, rhs)?;\n\n match (lhs, &*rhs) {\n (Value::Integer(ref a), &Value::Integer(ref b)) => {\n test_zero(b)?;\n Ok((a / b).into())\n }\n (lhs, rhs) => div_number(ctx, lhs, rhs)\n }\n}\n```"}], "func_name": "floor_div_number_step", "docstring": "Returns the result of floor-dividing two values,\nwithout calling `floor` on the result.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a596f6b04e043cf5ff495273db8e082b56239e660365a21dbaf3d2f9b3fc785"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_rem\n\nDocumentation:\n`rem` returns the remainder of two arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_rem(_ctx: &Context, args: &mut [Value]) -> Result {\n let a = args[0].take();\n expect_number(&a)?;\n\n let b = &args[1];\n expect_number(b)?;\n\n rem_number(a, b)\n}\n```"}], "func_name": "fn_rem", "docstring": "`rem` returns the remainder of two arguments.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9d143df5aec7a9860e1a7f0494bc2c2dc5c84ba7babf216c1c32c07ca1b3c2d2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_shl\n\nDocumentation:\n`<<` returns an integer, bit shifted left by a given number.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_shl(ctx: &Context, args: &mut [Value]) -> Result {\n let a = &args[0];\n let b = &args[1];\n\n shl_integer(ctx, a, b)\n}\n```"}], "func_name": "fn_shl", "docstring": "`<<` returns an integer, bit shifted left by a given number.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e6f753fdcd7df1c53943a5120e2e0591f26d1d896d7900fafc3020fd4f1f7c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_shr\n\nDocumentation:\n`>>` returns an integer, bit shifted right by a given number.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_shr(_ctx: &Context, args: &mut [Value]) -> Result {\n let a = &args[0];\n let b = &args[1];\n\n shr_integer(a, b)\n}\n```"}], "func_name": "fn_shr", "docstring": "`>>` returns an integer, bit shifted right by a given number.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e4f96b8f070be9515b5af7e8ce6e40c58db18832eead1c246e6e595ec32e0907"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_bit_and\n\nDocumentation:\n`bit-and` The bitwise AND operator.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_bit_and(_ctx: &Context, args: &mut [Value]) -> Result {\n if args.is_empty() {\n return Ok((-Integer::one()).into());\n }\n\n let mut v = expect_integer_owned(args[0].take())?;\n\n for arg in &args[1..] {\n v &= expect_integer(arg)?;\n }\n\n Ok(v.into())\n}\n```"}], "func_name": "fn_bit_and", "docstring": "`bit-and` The bitwise AND operator.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c8f3f702250aa1b9ad81cd438294309303db570c0714dc428814f8e14d90ee15"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bit_and_integer\n\nDocumentation:\nReturns the bitwise AND of two integer values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bit_and_integer(lhs: Value, rhs: &Value) -> Result {\n let lhs = expect_integer_owned(lhs)?;\n let rhs = expect_integer(rhs)?;\n\n Ok((lhs & rhs).into())\n}\n```"}], "func_name": "bit_and_integer", "docstring": "Returns the bitwise AND of two integer values.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "045ae49871e9a8c1e0993b913de54a11e278ea67bd77dbe2797130774f53fc5f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_bit_or\n\nDocumentation:\n`bit-or` The bitwise OR operator.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_bit_or(_ctx: &Context, args: &mut [Value]) -> Result {\n if args.is_empty() {\n return Ok(Integer::zero().into());\n }\n\n let mut v = expect_integer_owned(args[0].take())?;\n\n for arg in &args[1..] {\n v |= expect_integer(arg)?;\n }\n\n Ok(v.into())\n}\n```"}], "func_name": "fn_bit_or", "docstring": "`bit-or` The bitwise OR operator.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4fa079daed9c42c0f2e0cd90361d44e85bc8a691c4975925bf96e7cd08fe1bf0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bit_or_integer\n\nDocumentation:\nReturns the bitwise OR of two integers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bit_or_integer(lhs: Value, rhs: &Value) -> Result {\n let lhs = expect_integer_owned(lhs)?;\n let rhs = expect_integer(rhs)?;\n\n Ok((lhs | rhs).into())\n}\n```"}], "func_name": "bit_or_integer", "docstring": "Returns the bitwise OR of two integers.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5ed23304869c5fca556ce7cca99189d0549292259ae5bcfff121480fef2f5d67"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_bit_xor\n\nDocumentation:\n`bit-xor` The bitwise XOR operator.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_bit_xor(_ctx: &Context, args: &mut [Value]) -> Result {\n if args.is_empty() {\n return Ok(Integer::zero().into());\n }\n\n let mut v = expect_integer_owned(args[0].take())?;\n\n for arg in &args[1..] {\n v ^= expect_integer(arg)?;\n }\n\n Ok(v.into())\n}\n```"}], "func_name": "fn_bit_xor", "docstring": "`bit-xor` The bitwise XOR operator.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "08d86f65f36e6d8ce5db6334b31eea73ff1f1cd31110eb502d01e393fc5d793e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bit_xor_integer\n\nDocumentation:\nReturns the bitwise XOR of two integers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bit_xor_integer(lhs: Value, rhs: &Value) -> Result {\n let lhs = expect_integer_owned(lhs)?;\n let rhs = expect_integer(rhs)?;\n\n Ok((lhs ^ rhs).into())\n}\n```"}], "func_name": "bit_xor_integer", "docstring": "Returns the bitwise XOR of two integers.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "06b40d23e062cebb809eda382f64c9d904f6bc779b22a5db75670ce4fdfa924a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_eq\n\nDocumentation:\n`=` returns whether the given arguments compare equal to one another.\n\nValues of different types may not be compared. Attempts to do so will\nresult in a `TypeMismatch` error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_eq(_ctx: &Context, args: &mut [Value]) -> Result {\n let mut r = true;\n let v = &args[0];\n\n for arg in &args[1..] {\n let eq = v.is_equal(arg)?;\n\n if !eq {\n r = false;\n break;\n }\n }\n\n Ok(r.into())\n}\n```"}], "func_name": "fn_eq", "docstring": "`=` returns whether the given arguments compare equal to one another.\n\nValues of different types may not be compared. Attempts to do so will\nresult in a `TypeMismatch` error.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9b0ce7fb0860bc2746350db91e360420e88cc8e9050e696269ff38ad5ef31097"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_ne\n\nDocumentation:\n`/=` returns whether each given argument differs in value from each other argument.\n\nValues of different types may not be compared. Attempts to do so will\nresult in a `TypeMismatch` error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_ne(_ctx: &Context, args: &mut [Value]) -> Result {\n let mut r = true;\n\n 'outer: for (i, lhs) in args.iter().enumerate() {\n for rhs in &args[i + 1..] {\n let eq = lhs.is_equal(rhs)?;\n\n if eq {\n r = false;\n break 'outer;\n }\n }\n }\n\n Ok(r.into())\n}\n```"}], "func_name": "fn_ne", "docstring": "`/=` returns whether each given argument differs in value from each other argument.\n\nValues of different types may not be compared. Attempts to do so will\nresult in a `TypeMismatch` error.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6245acc01115dc14030acf249cff7ba848a24931c1ff1d936f7320ed901961e8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_weak_eq\n\nDocumentation:\n`eq` performs \"weak\" equality comparison of arguments.\n\nAny case in which `=` would cause an error, `eq` instead returns `false`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_weak_eq(ctx: &Context, args: &mut [Value]) -> Result {\n match fn_eq(ctx, args) {\n Ok(v) => Ok(v),\n Err(_) => Ok(false.into())\n }\n}\n```"}], "func_name": "fn_weak_eq", "docstring": "`eq` performs \"weak\" equality comparison of arguments.\n\nAny case in which `=` would cause an error, `eq` instead returns `false`.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "803d2011a46e69967e9978cb848943ec0ffbff4c4ce955fd87c70131cc99dee7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_weak_ne\n\nDocumentation:\n`ne` performs \"weak\" inequality comparison of arguments.\n\nAny case in which `/=` would cause an error, `ne` instead returns `true`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_weak_ne(ctx: &Context, args: &mut [Value]) -> Result {\n match fn_ne(ctx, args) {\n Ok(v) => Ok(v),\n Err(_) => Ok(true.into())\n }\n}\n```"}], "func_name": "fn_weak_ne", "docstring": "`ne` performs \"weak\" inequality comparison of arguments.\n\nAny case in which `/=` would cause an error, `ne` instead returns `true`.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7d38feefc67144b37b9edbceefc61668f430e2c145b5bf8d4cf39329db8ef348"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_lt\n\nDocumentation:\n`<` returns whether each argument compares less than each successive argument.\n\nValues of different types may not be compared. Attempts to do so will\nresult in a `TypeMismatch` error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_lt(_ctx: &Context, args: &mut [Value]) -> Result {\n let mut r = true;\n let mut v = &args[0];\n\n for arg in &args[1..] {\n let ord = v.compare(arg)?;\n\n if ord != Ordering::Less {\n r = false;\n break;\n }\n v = arg;\n }\n\n Ok(r.into())\n}\n```"}], "func_name": "fn_lt", "docstring": "`<` returns whether each argument compares less than each successive argument.\n\nValues of different types may not be compared. Attempts to do so will\nresult in a `TypeMismatch` error.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a4c730bc62bab29ff0548e39e393de8ad6f3338b9f66721a52dfd6325d7c24df"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_gt\n\nDocumentation:\n`>` returns whether each argument compares greater than each successive argument.\n\nValues of different types may not be compared. Attempts to do so will\nresult in a `TypeMismatch` error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_gt(_ctx: &Context, args: &mut [Value]) -> Result {\n let mut r = true;\n let mut v = &args[0];\n\n for arg in &args[1..] {\n let ord = v.compare(arg)?;\n\n if ord != Ordering::Greater {\n r = false;\n break;\n }\n v = arg;\n }\n\n Ok(r.into())\n}\n```"}], "func_name": "fn_gt", "docstring": "`>` returns whether each argument compares greater than each successive argument.\n\nValues of different types may not be compared. Attempts to do so will\nresult in a `TypeMismatch` error.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bc6d563ecf964f6d7bb98a2ad2b27c789ea775406a0c02777769737ab1da68ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_le\n\nDocumentation:\n`<=` returns whether each argument compares less than or equal to each\nsuccessive argument.\n\nValues of different types may not be compared. Attempts to do so will\nresult in a `TypeMismatch` error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_le(_ctx: &Context, args: &mut [Value]) -> Result {\n let mut r = true;\n let mut v = &args[0];\n\n for arg in &args[1..] {\n let ord = v.compare(arg)?;\n\n if ord == Ordering::Greater {\n r = false;\n break;\n }\n v = arg;\n }\n\n Ok(r.into())\n}\n```"}], "func_name": "fn_le", "docstring": "`<=` returns whether each argument compares less than or equal to each\nsuccessive argument.\n\nValues of different types may not be compared. Attempts to do so will\nresult in a `TypeMismatch` error.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cfcb66d098cf895e44367417375a539aecd029d9be1e98df46dfc6d831e733c9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_ge\n\nDocumentation:\n`>=` returns whether each argument compares greater than or equal to each\nsuccessive argument.\n\nValues of different types may not be compared. Attempts to do so will\nresult in a `TypeMismatch` error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_ge(_ctx: &Context, args: &mut [Value]) -> Result {\n let mut r = true;\n let mut v = &args[0];\n\n for arg in &args[1..] {\n let ord = v.compare(arg)?;\n\n if ord == Ordering::Less {\n r = false;\n break;\n }\n v = arg;\n }\n\n Ok(r.into())\n}\n```"}], "func_name": "fn_ge", "docstring": "`>=` returns whether each argument compares greater than or equal to each\nsuccessive argument.\n\nValues of different types may not be compared. Attempts to do so will\nresult in a `TypeMismatch` error.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "77c968e0debd7b79fdbb591ec4ba6fe0566f43b69d15ddadd97311c6af0ba690"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_zero\n\nDocumentation:\n`zero` returns whether all given values are equal to zero.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_zero(_ctx: &Context, args: &mut [Value]) -> Result {\n let mut r = true;\n\n for arg in args {\n let is_zero = match *arg {\n Value::Float(a) => a == 0.0,\n Value::Integer(ref a) => a.is_zero(),\n Value::Ratio(ref a) => a.is_zero(),\n ref v => return Err(From::from(ExecError::expected(\"number\", v)))\n };\n\n if !is_zero {\n r = false;\n break;\n }\n }\n\n Ok(r.into())\n}\n```"}], "func_name": "fn_zero", "docstring": "`zero` returns whether all given values are equal to zero.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e3004ee67ee4fea7e025d52801d5003e9eb1f4313880fbd567e0106d7aaa8cda"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_xor\n\nDocumentation:\n`xor` returns the exclusive-or of the given boolean values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_xor(_ctx: &Context, args: &mut [Value]) -> Result {\n let a = &args[0];\n let b = &args[1];\n\n match (a, b) {\n (&Value::Bool(a), &Value::Bool(b)) => Ok((a ^ b).into()),\n (&Value::Bool(_), b) => Err(From::from(ExecError::expected(\"bool\", b))),\n (a, _) => Err(From::from(ExecError::expected(\"bool\", a)))\n }\n}\n```"}], "func_name": "fn_xor", "docstring": "`xor` returns the exclusive-or of the given boolean values.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "35fc02fca94ca1c3ccd9e50af428ebfe671fb6196170384dab22b4b5c4c70f21"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_not\n\nDocumentation:\n`not` returns the inverse of the given boolean value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_not(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0] {\n Value::Bool(a) => Ok((!a).into()),\n ref v => Err(From::from(ExecError::expected(\"bool\", v)))\n }\n}\n```"}], "func_name": "fn_not", "docstring": "`not` returns the inverse of the given boolean value.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "72d2864efe1ccac8a187313c8e2ee3b5f2e12c3474c8019a959edcd96a8197cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_is\n\nDocumentation:\n`is` returns whether a given expression matches the named type.\n\n```lisp\n(is 'integer 1)\n(is 'list '(1 2 3))\n```\n\n`is` also accepts `'number` as a type name, which matches `integer`, `float`,\nand `ratio` type values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_is(ctx: &Context, args: &mut [Value]) -> Result {\n let name = get_name(&args[0])?;\n Ok(Value::Bool(value_is(ctx.scope(), &args[1], name)))\n}\n```"}], "func_name": "fn_is", "docstring": "`is` returns whether a given expression matches the named type.\n\n```lisp\n(is 'integer 1)\n(is 'list '(1 2 3))\n```\n\n`is` also accepts `'number` as a type name, which matches `integer`, `float`,\nand `ratio` type values.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ccb118c46da3217ce6be014505a2b1ce65b154e7b0f8094b52c7e77585b2d448"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_is_instance\n\nDocumentation:\n`is-instance` returns whether a given struct value is an instance of\nthe named struct definition.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_is_instance(_ctx: &Context, args: &mut [Value]) -> Result {\n let def = get_struct_def(&args[0])?;\n\n let sv = &args[1];\n\n Ok(def.def().is_instance(sv, def).into())\n}\n```"}], "func_name": "fn_is_instance", "docstring": "`is-instance` returns whether a given struct value is an instance of\nthe named struct definition.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "85421f6848e9bd64f11b88757b33c88dd03bcb652a22679545de799dc0876cdc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_null\n\nDocumentation:\n`null` returns whether the given value is unit, `()`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_null(_ctx: &Context, args: &mut [Value]) -> Result {\n let is_null = match args[0] {\n Value::Unit => true,\n _ => false\n };\n\n Ok(is_null.into())\n}\n```"}], "func_name": "fn_null", "docstring": "`null` returns whether the given value is unit, `()`.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9f12e2f4188df8fe82e1d85bfe36f346e399d5c974a0c6204e07da281bc574ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_type_of\n\nDocumentation:\n`type-of` returns a name representing the type of the given value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_type_of(ctx: &Context, args: &mut [Value]) -> Result {\n Ok(Value::Name(type_of(ctx.scope(), &args[0])))\n}\n```"}], "func_name": "fn_type_of", "docstring": "`type-of` returns a name representing the type of the given value.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7bef4300fe27d3b62c6e0da704ae00a3e1877e12de0e3cec2164fa833fbd04ba"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_dot\n\nDocumentation:\n`.` accesses a field from a struct value.\n\n```lisp\n(. foo :bar)\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_dot(ctx: &Context, args: &mut [Value]) -> Result {\n let def = get_struct_def_for(ctx.scope(), &args[0])?;\n let field = get_keyword(&args[1])?;\n\n def.def().get_field(ctx.scope(), &def, &args[0], field)\n}\n```"}], "func_name": "fn_dot", "docstring": "`.` accesses a field from a struct value.\n\n```lisp\n(. foo :bar)\n```", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fc1164d2a812f52d7b477d01e66b2f0f7a7dffdeffe0adce670723e7c710245b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_dot_eq\n\nDocumentation:\n`.=` assigns a value to one or more fields of a struct value.\n\n```lisp\n(.= foo :bar 1)\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_dot_eq(ctx: &Context, args: &mut [Value]) -> Result {\n let value = args[0].take();\n\n let def = get_struct_def_for(ctx.scope(), &value)?;\n\n let mut fields = Vec::with_capacity(args.len() / 2);\n\n let mut iter = args[1..].iter_mut();\n\n while let Some(name) = iter.next() {\n let name = get_keyword(name)?;\n\n let value = match iter.next() {\n Some(v) => v.take(),\n None => return Err(From::from(ExecError::OddKeywordParams))\n };\n\n if fields.iter().any(|&(n, _)| n == name) {\n return Err(ExecError::DuplicateField(name).into());\n }\n\n fields.push((name, value));\n }\n\n def.def().replace_fields(ctx.scope(), &def, value, &mut fields)\n}\n```"}], "func_name": "fn_dot_eq", "docstring": "`.=` assigns a value to one or more fields of a struct value.\n\n```lisp\n(.= foo :bar 1)\n```", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9d07b56986c11e76a16ce471d1dcd5758db926aa377eec67e020af085753cd66"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_new\n\nDocumentation:\n`new` creates a struct value.\n\n```lisp\n(new 'foo :a 1 :b 2)\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_new(ctx: &Context, args: &mut [Value]) -> Result {\n let def = get_struct_def(&args[0])?.clone();\n\n let mut fields = Vec::with_capacity(args.len() / 2);\n let mut iter = args[1..].iter_mut();\n\n while let Some(name) = iter.next() {\n let name = get_keyword(name)?;\n\n let value = match iter.next() {\n Some(value) => value.take(),\n None => return Err(From::from(ExecError::OddKeywordParams))\n };\n\n if fields.iter().any(|&(n, _)| n == name) {\n return Err(ExecError::DuplicateField(name).into());\n }\n\n fields.push((name, value));\n }\n\n def.def().from_fields(ctx.scope(), &def, &mut fields)\n}\n```"}], "func_name": "fn_new", "docstring": "`new` creates a struct value.\n\n```lisp\n(new 'foo :a 1 :b 2)\n```", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b62922bac4ebb5bc85817d89f242eea6028c2003325cdbf806d702ec4c46c2b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_print\n\nDocumentation:\n`print` prints a formatted string to `stdout`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_print(ctx: &Context, args: &mut [Value]) -> Result {\n let fmt = get_string(&args[0])?;\n let scope = ctx.scope();\n\n let s = format_string(&scope.borrow_names(), fmt, &args[1..])?;\n\n scope.io().stdout.write_all(s.as_bytes())?;\n scope.io().stdout.flush()?;\n\n Ok(Value::Unit)\n}\n```"}], "func_name": "fn_print", "docstring": "`print` prints a formatted string to `stdout`.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6501ed948460eaca8e52c8e228423830ea7f25d2a2518b4e43577c00a342ce89"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_println\n\nDocumentation:\n`println` prints a formatted string to `stdout`, followed by a newline.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_println(ctx: &Context, args: &mut [Value]) -> Result {\n let fmt = get_string(&args[0])?;\n let scope = ctx.scope();\n\n let mut s = format_string(&scope.borrow_names(), fmt, &args[1..])?;\n if !s.ends_with('\\n') {\n s.push('\\n');\n }\n\n scope.io().stdout.write_all(s.as_bytes())?;\n scope.io().stdout.flush()?;\n\n Ok(Value::Unit)\n}\n```"}], "func_name": "fn_println", "docstring": "`println` prints a formatted string to `stdout`, followed by a newline.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "18d6d03cd88f98e498de44c78795582e4d474e0b69d29d142f0479797b6a625a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_eprint\n\nDocumentation:\n`eprint` prints a formatted string to `stderr`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_eprint(ctx: &Context, args: &mut [Value]) -> Result {\n let fmt = get_string(&args[0])?;\n let scope = ctx.scope();\n\n let s = format_string(&scope.borrow_names(), fmt, &args[1..])?;\n\n scope.io().stderr.write_all(s.as_bytes())?;\n scope.io().stderr.flush()?;\n\n Ok(Value::Unit)\n}\n```"}], "func_name": "fn_eprint", "docstring": "`eprint` prints a formatted string to `stderr`.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1dc42d6a3556cf78576420e6c383fef25391b1cb85f465216d6fc78f41d0d289"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_append\n\nDocumentation:\n`append` append a series of elements to a given list.\n\n```lisp\n(append '(1 2 3) 4 5 6)\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_append(_ctx: &Context, args: &mut [Value]) -> Result {\n let mut v = match args[0].take() {\n Value::Unit => Vec::new(),\n Value::List(li) => li.into_vec(),\n ref v => return Err(From::from(ExecError::expected(\"list\", v)))\n };\n\n v.extend(args[1..].iter_mut().map(|v| v.take()));\n\n Ok(v.into())\n}\n```"}], "func_name": "fn_append", "docstring": "`append` append a series of elements to a given list.\n\n```lisp\n(append '(1 2 3) 4 5 6)\n```", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4e7f8893d09239635cdcfec04ccc79e7a5b538db8abcba8dc228b36946ac3953"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_elt\n\nDocumentation:\n`elt` returns an element from a list, starting at zero index.\n\n```lisp\n(elt '(1 2 3) 0)\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_elt(_ctx: &Context, args: &mut [Value]) -> Result {\n let li = &args[0];\n let idx = &args[1];\n\n let idx = usize::from_value_ref(idx)?;\n\n match *li {\n Value::List(ref li) => li.get(idx).cloned()\n .ok_or_else(|| From::from(ExecError::OutOfBounds(idx))),\n Value::Bytes(ref b) => b.get(idx).cloned()\n .map(|b| b.into())\n .ok_or_else(|| From::from(ExecError::OutOfBounds(idx))),\n ref v => Err(From::from(ExecError::expected(\"indexable sequence\", v)))\n }\n}\n```"}], "func_name": "fn_elt", "docstring": "`elt` returns an element from a list, starting at zero index.\n\n```lisp\n(elt '(1 2 3) 0)\n```", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "96e17e0b69c703f12bc2ee17b3ca05b2de0488136e6989aa0479336152fb1a5c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_concat\n\nDocumentation:\n`concat` concatenates a series of lists or strings and chars.\n\n```lisp\n(concat '(1 2 3) () '(4 5 6))\n(concat \"foo\" \"bar\")\n(concat \"foo\" #'/' \"bar\")\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_concat(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0] {\n Value::Unit | Value::List(_) => concat_list(args),\n Value::Char(_) | Value::String(_) => concat_string(args),\n Value::Bytes(_) => concat_bytes(args),\n Value::Path(_) => concat_path(args),\n ref v => Err(From::from(ExecError::expected(\"list or string\", v)))\n }\n}\n```"}], "func_name": "fn_concat", "docstring": "`concat` concatenates a series of lists or strings and chars.\n\n```lisp\n(concat '(1 2 3) () '(4 5 6))\n(concat \"foo\" \"bar\")\n(concat \"foo\" #'/' \"bar\")\n```", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5e8128061db3062dea1ecac1123315ad96c27c784cbbfbdd2fc764a1c51c105c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_join\n\nDocumentation:\n`join` joins a series of lists or strings and chars using a separator value.\n\n```lisp\n(join '(0) '(1 2 3) '(4 5 6))\n(join \":\" \"foo\" \"bar\")\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_join(_ctx: &Context, args: &mut [Value]) -> Result {\n let (first, rest) = args.split_first_mut().unwrap();\n\n match *first {\n Value::Unit => concat_list(rest),\n Value::List(ref li) => join_list(li, rest),\n Value::Char(ch) => {\n let mut s = String::new();\n s.push(ch);\n join_string(&s, rest)\n }\n Value::String(ref s) if s.is_empty() => concat_string(rest),\n Value::String(ref s) => join_string(s, rest),\n Value::Bytes(ref s) => join_bytes(s, rest),\n ref v => Err(From::from(ExecError::expected(\"list or string\", v)))\n }\n}\n```"}], "func_name": "fn_join", "docstring": "`join` joins a series of lists or strings and chars using a separator value.\n\n```lisp\n(join '(0) '(1 2 3) '(4 5 6))\n(join \":\" \"foo\" \"bar\")\n```", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d6fa0276b4c963b78db6aeff42556b4329b370e221ff1bf682edcdbd717b1d31"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_len\n\nDocumentation:\n`len` returns the length of the given list or string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_len(_ctx: &Context, args: &mut [Value]) -> Result {\n let n = match args[0] {\n Value::Unit => 0,\n Value::List(ref li) => li.len(),\n Value::String(ref s) => s.len(),\n Value::Bytes(ref b) => b.len(),\n ref v => return Err(From::from(ExecError::expected(\"sequence\", v)))\n };\n\n Ok(n.into())\n}\n```"}], "func_name": "fn_len", "docstring": "`len` returns the length of the given list or string.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48d6805f3c38a8a4376a430b82943d83431ba13a435b1432cbbf66c16a394767"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_slice\n\nDocumentation:\n`slice` returns a subsequence of a list or string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_slice(_ctx: &Context, args: &mut [Value]) -> Result {\n let begin = usize::from_value_ref(&args[1])?;\n\n if args.len() == 2 {\n match args[0] {\n Value::Unit => {\n if begin > 0 {\n Err(From::from(ExecError::OutOfBounds(begin)))\n } else {\n Ok(Value::Unit)\n }\n }\n Value::List(ref li) => {\n let n = li.len();\n if begin > n {\n Err(From::from(ExecError::OutOfBounds(begin)))\n } else {\n Ok(li.slice(begin..).into())\n }\n }\n Value::String(ref s) => {\n let n = s.len();\n if begin > n {\n Err(From::from(ExecError::OutOfBounds(begin)))\n } else if !s.is_char_boundary(begin) {\n Err(From::from(ExecError::NotCharBoundary(begin)))\n } else {\n Ok(s.slice(begin..).into())\n }\n }\n Value::Bytes(ref b) => {\n let n = b.len();\n if begin > n {\n Err(From::from(ExecError::OutOfBounds(begin)))\n } else {\n Ok(b.slice(begin..).into())\n }\n }\n ref v => Err(From::from(ExecError::expected(\"list or string\", v)))\n }\n } else {\n let end = usize::from_value_ref(&args[2])?;\n\n if end < begin {\n return Err(From::from(ExecError::InvalidSlice(begin, end)));\n }\n\n match args[0] {\n Value::Unit => {\n if begin > 0 {\n Err(From::from(ExecError::OutOfBounds(begin)))\n } else if end > 0 {\n Err(From::from(ExecError::OutOfBounds(end)))\n } else {\n Ok(Value::Unit)\n }\n }\n Value::List(ref li) => {\n let n = li.len();\n if begin > n {\n Err(From::from(ExecError::OutOfBounds(begin)))\n } else if end > n {\n Err(From::from(ExecError::OutOfBounds(end)))\n } else {\n Ok(li.slice(begin..end).into())\n }\n }\n Value::String(ref s) => {\n let n = s.len();\n if begin > n {\n Err(From::from(ExecError::OutOfBounds(begin)))\n } else if end > n {\n Err(From::from(ExecError::OutOfBounds(end)))\n } else if !s.is_char_boundary(begin) {\n Err(From::from(ExecError::NotCharBoundary(begin)))\n } else if !s.is_char_boundary(end) {\n Err(From::from(ExecError::NotCharBoundary(end)))\n } else {\n Ok(s.slice(begin..end).into())\n }\n }\n Value::Bytes(ref b) => {\n let n = b.len();\n if begin > n {\n Err(From::from(ExecError::OutOfBounds(begin)))\n } else if end > n {\n Err(From::from(ExecError::OutOfBounds(end)))\n } else {\n Ok(b.slice(begin..end).into())\n }\n }\n ref v => Err(From::from(ExecError::expected(\"list or string\", v)))\n }\n }\n}\n```"}], "func_name": "fn_slice", "docstring": "`slice` returns a subsequence of a list or string.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "763fb237fdafe8e86559e0a5360e98213dc817b358670b32665433ea4a2dab21"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_second\n\nDocumentation:\n`second` returns the second element of the given list.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_second(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0] {\n Value::List(ref mut li) => li.get(1).cloned()\n .ok_or_else(|| From::from(ExecError::OutOfBounds(1))),\n ref v => Err(From::from(ExecError::expected(\"list\", v)))\n }\n}\n```"}], "func_name": "fn_second", "docstring": "`second` returns the second element of the given list.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fecb78f027a2f2ddca6e81354e74881e31513db472932d637f1572814fc40334"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: first\n\nDocumentation:\nReturns the first element of a list or string.\n\nReturns an error in case of an empty list or string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn first(v: &Value) -> Result {\n match *v {\n // There can't be an empty list, so this should never panic.\n Value::List(ref li) => Ok(li[0].clone()),\n Value::String(ref s) => match s.chars().next() {\n Some(ch) => Ok(ch.into()),\n None => Err(From::from(ExecError::OutOfBounds(0)))\n },\n Value::Bytes(ref b) => match b.iter().next() {\n Some(&b) => Ok(b.into()),\n None => Err(From::from(ExecError::OutOfBounds(0)))\n },\n ref v => Err(From::from(ExecError::expected(\"sequence\", v)))\n }\n}\n```"}], "func_name": "first", "docstring": "Returns the first element of a list or string.\n\nReturns an error in case of an empty list or string.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d578bad1bf8f5c051a2a737fc4a5d0876696accfbd13cb06d7345e19f78f49a7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: last\n\nDocumentation:\nReturns the last element of a list or string.\n\nReturns an error in case of an empty list or string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn last(v: &Value) -> Result {\n match *v {\n Value::List(ref li) => Ok(li.last().cloned().unwrap()),\n Value::String(ref s) => match s.chars().next_back() {\n Some(ch) => Ok(ch.into()),\n None => Err(From::from(ExecError::OutOfBounds(0)))\n },\n Value::Bytes(ref b) => match b.iter().next_back() {\n Some(&b) => Ok(b.into()),\n None => Err(From::from(ExecError::OutOfBounds(0)))\n },\n ref v => Err(From::from(ExecError::expected(\"sequence\", v)))\n }\n}\n```"}], "func_name": "last", "docstring": "Returns the last element of a list or string.\n\nReturns an error in case of an empty list or string.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bafa488988fb3d99726c15be393901b70ea44adc0c43897e742e2dcb32cd1610"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: init\n\nDocumentation:\nReturns all but the last element of a list or string.\n\nReturns an error in case of an empty list or string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn init(v: &Value) -> Result {\n match *v {\n Value::List(ref li) => {\n let len = li.len();\n Ok(li.slice(..len - 1).into())\n }\n Value::String(ref s) => {\n let mut chars = s.char_indices();\n\n match chars.next_back() {\n Some((idx, _)) => Ok(s.slice(..idx).into()),\n None => Err(From::from(ExecError::OutOfBounds(0)))\n }\n }\n Value::Bytes(ref b) => {\n if b.is_empty() {\n Err(From::from(ExecError::OutOfBounds(0)))\n } else {\n let len = b.len();\n Ok(b.slice(..len - 1).into())\n }\n }\n ref v => Err(From::from(ExecError::expected(\"sequence\", v)))\n }\n}\n```"}], "func_name": "init", "docstring": "Returns all but the last element of a list or string.\n\nReturns an error in case of an empty list or string.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ab77b934d5034ffb813c9352b8af7e17b868d65a9edd947814b2a316aac3a69"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: tail\n\nDocumentation:\nReturns all but the first element of a list or string.\n\nReturns an error in case of an empty list or string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn tail(v: &Value) -> Result {\n match *v {\n Value::List(ref li) => {\n Ok(li.slice(1..).into())\n }\n Value::String(ref s) => {\n let mut chars = s.chars();\n\n match chars.next() {\n Some(ch) => Ok(s.slice(ch.len_utf8()..).into()),\n None => Err(From::from(ExecError::OutOfBounds(0)))\n }\n }\n Value::Bytes(ref b) => {\n if b.is_empty() {\n Err(From::from(ExecError::OutOfBounds(0)))\n } else {\n Ok(b.slice(1..).into())\n }\n }\n ref v => Err(From::from(ExecError::expected(\"sequence\", v)))\n }\n}\n```"}], "func_name": "tail", "docstring": "Returns all but the first element of a list or string.\n\nReturns an error in case of an empty list or string.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5bce6da67034c4d32cbb5897c670862df7c971508216863af674994c60d52c12"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_list\n\nDocumentation:\n`list` returns a list of values. In contrast with the `'(a b c ...)` list\nconstruction syntax, this function will evaluate each of its arguments.\n\n```lisp\n(list 1 2 3)\n(list (foo) (+ 1 2 3))\n```\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_list(_ctx: &Context, args: &mut [Value]) -> Result {\n Ok(args.iter_mut().map(|v| v.take())\n .collect::>().into())\n}\n```"}], "func_name": "fn_list", "docstring": "`list` returns a list of values. In contrast with the `'(a b c ...)` list\nconstruction syntax, this function will evaluate each of its arguments.\n\n```lisp\n(list 1 2 3)\n(list (foo) (+ 1 2 3))\n```", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "481b139b870fe1b6c64e9c0165d164e6c3a9f76999cac6f7ef228e5ebd2bb19d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_reverse\n\nDocumentation:\n`reverse` returns a list in reverse order.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_reverse(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0].take() {\n Value::Unit => Ok(Value::Unit),\n Value::List(li) => {\n let mut li = li.into_vec();\n li.reverse();\n Ok(li.into())\n }\n ref v => Err(From::from(ExecError::expected(\"list\", v)))\n }\n}\n```"}], "func_name": "fn_reverse", "docstring": "`reverse` returns a list in reverse order.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5bd879fb25a25b3d8a24d4440adf08fdd1c3be00ece04ee211c4813e3b556608"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_abs\n\nDocumentation:\n`abs` returns the absolute value of the given numerical value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_abs(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0] {\n Value::Float(f) => Ok(f.abs().into()),\n Value::Integer(ref i) => Ok(i.abs().into()),\n Value::Ratio(ref r) => Ok(r.abs().into()),\n ref v => Err(From::from(ExecError::expected(\"number\", v)))\n }\n}\n```"}], "func_name": "fn_abs", "docstring": "`abs` returns the absolute value of the given numerical value.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "47e8a371d733bffdb544304172e036d8a99a14e8bf8aa004c23cd38e839b57af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_ceil\n\nDocumentation:\n`ceil` returns a number value rounded toward positive infinity.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_ceil(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0].take() {\n Value::Float(f) => Ok(f.ceil().into()),\n Value::Integer(i) => Ok(i.into()),\n Value::Ratio(ref r) => Ok(r.ceil().into()),\n ref v => Err(From::from(ExecError::expected(\"number\", v)))\n }\n}\n```"}], "func_name": "fn_ceil", "docstring": "`ceil` returns a number value rounded toward positive infinity.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9aa4ef0cb6019d7d87fede2e377442c102e878689ed0081445f0b33b0a2bedbb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: floor_number\n\nDocumentation:\nReturns a value rounded toward negative infinity.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn floor_number(v: Value) -> Result {\n match v {\n Value::Float(f) => Ok(f.floor().into()),\n Value::Integer(i) => Ok(i.into()),\n Value::Ratio(ref r) => Ok(r.floor().into()),\n ref v => Err(From::from(ExecError::expected(\"number\", v)))\n }\n}\n```"}], "func_name": "floor_number", "docstring": "Returns a value rounded toward negative infinity.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4eb92cd61af3f0343eafc6df46fc0f00a60a8504357f2f601b5502bbddf6e887"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_round\n\nDocumentation:\n`round` returns a number rounded to the nearest integer.\nRounds half-way cases away from zero.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_round(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0].take() {\n Value::Float(f) => Ok(f.round().into()),\n Value::Integer(i) => Ok(i.into()),\n Value::Ratio(ref r) => Ok(r.round().into()),\n ref v => Err(From::from(ExecError::expected(\"number\", v)))\n }\n}\n```"}], "func_name": "fn_round", "docstring": "`round` returns a number rounded to the nearest integer.\nRounds half-way cases away from zero.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4bfd65451528c0a96820499fbc2db2641233192e6083c1eb9b18fbe9eb9fd4f9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_trunc\n\nDocumentation:\n`trunc` returns a number rounded toward zero.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_trunc(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0].take() {\n Value::Float(f) => Ok(f.trunc().into()),\n Value::Integer(i) => Ok(i.into()),\n Value::Ratio(ref r) => Ok(r.trunc().into()),\n ref v => Err(From::from(ExecError::expected(\"number\", v)))\n }\n}\n```"}], "func_name": "fn_trunc", "docstring": "`trunc` returns a number rounded toward zero.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0f5e30aa3f8cf405de41d76288c3c991dc5745b5a920fda79e7931ccf0eb31ca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_int\n\nDocumentation:\n`int` truncates a float or ratio value and returns its whole portion as an integer.\n\nIf the given value is infinite or `NaN`, an error will result.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_int(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0].take() {\n Value::Float(f) => match f {\n f if f.is_infinite() || f.is_nan() => Err(From::from(ExecError::Overflow)),\n f => Integer::from_f64(f)\n .map(Value::Integer).ok_or_else(|| From::from(ExecError::Overflow)),\n },\n Value::Integer(i) => Ok(i.into()),\n Value::Ratio(ref r) => Ok(r.to_integer().into()),\n ref v => Err(From::from(ExecError::expected(\"number\", v)))\n }\n}\n```"}], "func_name": "fn_int", "docstring": "`int` truncates a float or ratio value and returns its whole portion as an integer.\n\nIf the given value is infinite or `NaN`, an error will result.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "064329e260e41e58ea1c10d50a874babbd4022e84f8851fb1283ad9008cb1d28"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_float\n\nDocumentation:\n`float` returns the given value as a floating point value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_float(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0] {\n Value::Float(f) => Ok(f.into()),\n Value::Integer(ref i) => Ok(i.to_f64().ok_or(ExecError::Overflow)?.into()),\n Value::Ratio(ref r) => Ok(r.to_f64().ok_or(ExecError::Overflow)?.into()),\n ref v => Err(From::from(ExecError::expected(\"number\", v)))\n }\n}\n```"}], "func_name": "fn_float", "docstring": "`float` returns the given value as a floating point value.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0eee12b6e8a4a301e1053fe3ff448abc4f2ea8f319ac943815427694f5eec39"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_inf\n\nDocumentation:\n`inf` returns whether all given arguments are equal to positive or negative infinity.\nGiven no arguments, returns the value of positive infinity.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_inf(_ctx: &Context, args: &mut [Value]) -> Result {\n if args.is_empty() {\n Ok(f64::INFINITY.into())\n } else {\n let mut r = true;\n\n for arg in args {\n if get_float(arg)?.is_finite() {\n r = false;\n break;\n }\n }\n\n Ok(r.into())\n }\n}\n```"}], "func_name": "fn_inf", "docstring": "`inf` returns whether all given arguments are equal to positive or negative infinity.\nGiven no arguments, returns the value of positive infinity.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "784dea700fa0c730588caeab784e2766f0ea2224ea8de99e73017ad6f6403ee8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_nan\n\nDocumentation:\n`nan` returns whether all given arguments are equal to `NaN`.\nGiven no arguments, returns the value of `NaN`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_nan(_ctx: &Context, args: &mut [Value]) -> Result {\n if args.is_empty() {\n Ok(f64::nan().into())\n } else {\n let mut r = true;\n\n for arg in args {\n if !get_float(arg)?.is_nan() {\n r = false;\n break;\n }\n }\n\n Ok(r.into())\n }\n}\n```"}], "func_name": "fn_nan", "docstring": "`nan` returns whether all given arguments are equal to `NaN`.\nGiven no arguments, returns the value of `NaN`.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2026a0187faa771a3c059c4f01c5dcdd2f1f4f52c7b94df55790d1e843f8fbaa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_denom\n\nDocumentation:\n`denom` returns the denominator of a ratio.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_denom(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0] {\n Value::Integer(_) => Ok(Integer::one().into()),\n Value::Ratio(ref r) => Ok(r.denom().clone().into()),\n ref v => Err(From::from(ExecError::expected(\"integer or ratio\", v)))\n }\n}\n```"}], "func_name": "fn_denom", "docstring": "`denom` returns the denominator of a ratio.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c35486e9973f01c31edcba5b17efbab52ef0e57b20740fb8dd4fc8cd4643610f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_fract\n\nDocumentation:\n`fract` returns the fractional portion of a float or ratio.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_fract(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0] {\n Value::Float(f) => Ok(f.fract().into()),\n Value::Ratio(ref r) => Ok(r.fract().into()),\n ref v => Err(From::from(ExecError::expected(\"float or ratio\", v)))\n }\n}\n```"}], "func_name": "fn_fract", "docstring": "`fract` returns the fractional portion of a float or ratio.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "977fb235d77a8f6f319ce8072a8f21b64052f6d6ad2e0fdb5821715f3658a696"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_numer\n\nDocumentation:\n`numer` returns the numerator of a ratio.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_numer(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0].take() {\n i @ Value::Integer(_) => Ok(i),\n Value::Ratio(r) => Ok(r.numer().clone().into()),\n ref v => Err(From::from(ExecError::expected(\"integer or ratio\", v)))\n }\n}\n```"}], "func_name": "fn_numer", "docstring": "`numer` returns the numerator of a ratio.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0d3686f7667c2689c5a7809504c5345a8a05d35ec9ad70659287d11f3ce86ec1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_rat\n\nDocumentation:\n`rat` returns the given numerical value as a ratio.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_rat(_ctx: &Context, args: &mut [Value]) -> Result {\n if args.len() == 1 {\n match args[0].take() {\n Value::Float(f) => Ratio::from_f64(f)\n .map(Value::Ratio).ok_or_else(|| From::from(ExecError::Overflow)),\n Value::Integer(a) =>\n Ok(Ratio::from_integer(a).into()),\n Value::Ratio(r) => Ok(r.into()),\n ref v => Err(From::from(ExecError::expected(\"number\", v)))\n }\n } else { // args.len() == 2\n let a = args[0].take();\n let b = args[1].take();\n\n match (a, b) {\n (Value::Integer(a), Value::Integer(b)) => {\n test_zero(&b)?;\n Ok(Ratio::new(a, b).into())\n }\n (Value::Integer(_), ref b) => Err(From::from(ExecError::expected(\"integer\", b))),\n (ref a, _) => Err(From::from(ExecError::expected(\"integer\", a)))\n }\n }\n}\n```"}], "func_name": "fn_rat", "docstring": "`rat` returns the given numerical value as a ratio.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f28fbd3afb6994964b571bb837edaa253d678d61aa8fe48d176e2143d4938416"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_chars\n\nDocumentation:\n`chars` returns a string transformed into a list of characters.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_chars(_ctx: &Context, args: &mut [Value]) -> Result {\n let s = get_string(&args[0])?;\n Ok(s.chars().collect::>().into())\n}\n```"}], "func_name": "fn_chars", "docstring": "`chars` returns a string transformed into a list of characters.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "871e47096c68bc6b559fb3a8d657a8cc599bccde233c1af5ade28f951d204919"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_string\n\nDocumentation:\n`string` returns an argument converted into a string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_string(ctx: &Context, args: &mut [Value]) -> Result {\n match args[0].take() {\n Value::Char(ch) => {\n let mut s = String::new();\n s.push(ch);\n Ok(s.into())\n }\n Value::Name(name) => Ok(ctx.scope().with_name(name, |s| s.into())),\n v @ Value::String(_) => Ok(v),\n ref v => Err(From::from(ExecError::expected(\"char or string or name\", v)))\n }\n}\n```"}], "func_name": "fn_string", "docstring": "`string` returns an argument converted into a string.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "066f02f8079ab6139b7f01384830077552e061730671149f790eeaf310b1b58f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_path\n\nDocumentation:\n`path` returns an argument converted into a path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_path(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0].take() {\n Value::String(s) => Ok(PathBuf::from(s.into_string()).into()),\n v @ Value::Path(_) => Ok(v),\n ref v => Err(From::from(ExecError::expected(\"string or path\", v)))\n }\n}\n```"}], "func_name": "fn_path", "docstring": "`path` returns an argument converted into a path.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f428b59831d2f50d169a52f4a04a2a0039a134e0d114e6a82a3b0b3a70630e63"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_bytes\n\nDocumentation:\n`bytes` returns an argument converted into a byte string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_bytes(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0].take() {\n Value::Unit => Ok(Bytes::from(Vec::new()).into()),\n li @ Value::List(_) => >::from_value_ref(&li)\n .map(|b| Bytes::from(b).into()).map_err(From::from),\n Value::String(s) => Ok(Bytes::from(s.into_string()).into()),\n v @ Value::Bytes(_) => Ok(v),\n ref v => Err(From::from(ExecError::expected(\"bytes or string\", v)))\n }\n}\n```"}], "func_name": "fn_bytes", "docstring": "`bytes` returns an argument converted into a byte string.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "95aecab9dae7d9f2c394f79ad8ca44258121f7b19275e9b95c2132d0dc070d76"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_max\n\nDocumentation:\n`max` returns the greatest value of given arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_max(_ctx: &Context, args: &mut [Value]) -> Result {\n let mut v = args[0].take();\n\n for arg in &mut args[1..] {\n if v.compare(arg)? == Ordering::Less {\n v = arg.take();\n }\n }\n\n Ok(v)\n}\n```"}], "func_name": "fn_max", "docstring": "`max` returns the greatest value of given arguments.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "646fbdfb61004b770b19bd67ad63aee8d3e1632c78306ddaa82a73632e80d068"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_min\n\nDocumentation:\n`min` returns the least value of given arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_min(_ctx: &Context, args: &mut [Value]) -> Result {\n let mut v = args[0].take();\n\n for arg in &mut args[1..] {\n if v.compare(arg)? == Ordering::Greater {\n v = arg.take();\n }\n }\n\n Ok(v)\n}\n```"}], "func_name": "fn_min", "docstring": "`min` returns the least value of given arguments.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09c57df0af5b5e5fee9b7edbe00c875646a5ae472447c7deed566b7499ab4707"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_panic\n\nDocumentation:\n`panic` immediately interrupts execution upon evaluation.\nIt accepts an optional parameter describing the reason for the panic.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_panic(_ctx: &Context, args: &mut [Value]) -> Result {\n Err(From::from(ExecError::Panic(args.get_mut(0).map(|v| v.take()))))\n}\n```"}], "func_name": "fn_panic", "docstring": "`panic` immediately interrupts execution upon evaluation.\nIt accepts an optional parameter describing the reason for the panic.", "repo": "murarth/ketos", "path": "src/ketos/function.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/function.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a745e5366637abce93dcdee0483316a74fcce4fb8892b2a91ae90dc3f929d757"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: name\n\nDocumentation:\nSets the name of the new scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn name(mut self, name: &'static str) -> Self {\n exclude!(self.context, \"name\", \"context\");\n exclude!(self.scope, \"name\", \"scope\");\n\n self.name = Some(name);\n self\n }\n```"}], "func_name": "name", "docstring": "Sets the name of the new scope.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "87a59122e4937fa9a6df0c4cb7d97a18bca6924aa302a9607e88453523524bec"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: context\n\nDocumentation:\nSets the context of the new interpreter.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn context(mut self, ctx: Context) -> Self {\n exclude!(self.name, \"context\", \"name\");\n exclude!(self.scope, \"context\", \"scope\");\n exclude!(self.restrict, \"context\", \"restrict\");\n exclude!(self.io, \"context\", \"io\");\n exclude!(self.module_loader, \"context\", \"module_loader\");\n exclude!(self.search_paths, \"context\", \"search_paths\");\n\n self.context = Some(ctx);\n self\n }\n```"}], "func_name": "context", "docstring": "Sets the context of the new interpreter.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "96a9b17f2dd79de9c026c2d07b4e37c864f8154ee1a7e9178b5d9558eed15584"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: restrict\n\nDocumentation:\nSets the restriction configuration in the new context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn restrict(mut self, restrict: RestrictConfig) -> Self {\n exclude!(self.context, \"restrict\", \"context\");\n\n self.restrict = Some(restrict);\n self\n }\n```"}], "func_name": "restrict", "docstring": "Sets the restriction configuration in the new context.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09a9b7edd30277da7f9ec0a969b1e98a764752cb97d98d787253ee699cf2af09"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: scope\n\nDocumentation:\nSets the scope in the new context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn scope(mut self, scope: Scope) -> Self {\n exclude!(self.name, \"scope\", \"name\");\n exclude!(self.context, \"scope\", \"context\");\n exclude!(self.io, \"scope\", \"io\");\n exclude!(self.module_loader, \"scope\", \"module_loader\");\n exclude!(self.search_paths, \"scope\", \"search_paths\");\n\n self.scope = Some(scope);\n self\n }\n```"}], "func_name": "scope", "docstring": "Sets the scope in the new context.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "281fc780ee96eb5b414250f344a94080873dbe525389b2e504db0f7471a38d27"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: struct_defs\n\nDocumentation:\nSets the struct definitions in the new context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn struct_defs(mut self, defs: Rc>) -> Self {\n exclude!(self.context, \"struct_defs\", \"context\");\n exclude!(self.scope, \"struct_defs\", \"scope\");\n\n self.struct_defs = Some(defs);\n self\n }\n```"}], "func_name": "struct_defs", "docstring": "Sets the struct definitions in the new context.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1de9c6c116b7b601b119f39b9ba735758ff61c83a9f89ca6358c85b4b662ab65"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: io\n\nDocumentation:\nSets the I/O handles in the new scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn io(mut self, io: Rc) -> Self {\n exclude!(self.context, \"io\", \"context\");\n exclude!(self.scope, \"io\", \"scope\");\n\n self.io = Some(io);\n self\n }\n```"}], "func_name": "io", "docstring": "Sets the I/O handles in the new scope.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e81af66d01135d0d7d6ca8b66e571924e0cfdf95b2acfa30b82121a82921702a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: module_loader\n\nDocumentation:\nSets the module loader in the new scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn module_loader(mut self, loader: Box) -> Self {\n exclude!(self.context, \"module_loader\", \"context\");\n exclude!(self.scope, \"module_loader\", \"scope\");\n exclude!(self.search_paths, \"module_loader\", \"search_paths\");\n\n self.module_loader = Some(loader);\n self\n }\n```"}], "func_name": "module_loader", "docstring": "Sets the module loader in the new scope.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "672dac2799e9baea462a48add1ff2fc161d89f32a9bd676fa7d9b54e287913f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: search_paths\n\nDocumentation:\nSets the search paths for a new `FileModuleLoader`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn search_paths(mut self, paths: Vec) -> Self {\n exclude!(self.context, \"search_paths\", \"context\");\n exclude!(self.scope, \"search_paths\", \"scope\");\n exclude!(self.module_loader, \"search_paths\", \"module_loader\");\n\n self.search_paths = Some(paths);\n self\n }\n```"}], "func_name": "search_paths", "docstring": "Sets the search paths for a new `FileModuleLoader`.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7a000e277a9c7f7e8a5efe81883c0f221954845a092c4f6ce60fd76aa0b01778"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_loader\n\nDocumentation:\nCreates a new `Interpreter` using the given `ModuleLoader` instance.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_loader(loader: Box) -> Interpreter {\n let mut names = NameStore::new();\n let name = names.add(\"main\");\n\n let names = Rc::new(RefCell::new(names));\n let codemap = Rc::new(RefCell::new(CodeMap::new()));\n let modules = Rc::new(ModuleRegistry::new(loader));\n let io = Rc::new(GlobalIo::default());\n let defs = Rc::new(RefCell::new(StructDefMap::new()));\n\n Interpreter::with_scope(\n Rc::new(GlobalScope::new(\n name,\n names.clone(),\n codemap.clone(),\n modules,\n io,\n defs)))\n }\n```"}], "func_name": "with_loader", "docstring": "Creates a new `Interpreter` using the given `ModuleLoader` instance.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6aaa7c4e6e1bd682b8997c715de88e64993dce515f54c94d3f4fc80686e36a7b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_context\n\nDocumentation:\nCreates a new `Interpreter` using the given `Context` instance.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_context(context: Context) -> Interpreter {\n Interpreter{ context }\n }\n```"}], "func_name": "with_context", "docstring": "Creates a new `Interpreter` using the given `Context` instance.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8c305f8f14d1f98eed0c4913a165e393dfd731a10d346a373f2e9abeabd5245f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_scope\n\nDocumentation:\nCreates a new `Interpreter` using the given `Scope` instance.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_scope(scope: Scope) -> Interpreter {\n Interpreter::with_context(Context::new(\n scope, RestrictConfig::permissive()))\n }\n```"}], "func_name": "with_scope", "docstring": "Creates a new `Interpreter` using the given `Scope` instance.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54d3286c6cac7b5bd76d53d133249c20dbc01603f632d31263bde4dffaa476fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_search_paths\n\nDocumentation:\nCreates a new `Interpreter` that searches for module files in a given\nseries of directories.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_search_paths(paths: Vec) -> Interpreter {\n Interpreter::with_loader(Box::new(\n BuiltinModuleLoader.chain(FileModuleLoader::with_search_paths(paths))))\n }\n```"}], "func_name": "with_search_paths", "docstring": "Creates a new `Interpreter` that searches for module files in a given\nseries of directories.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "395002687ff14b4cb6090eddb7f9c5081fd6052cfddb461ea3d0c5c544a3c11d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: display_value\n\nDocumentation:\nPrints a string representation of a value to `stdout`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn display_value(&self, value: &Value) {\n println!(\"{}\", debug_names(&self.scope().borrow_names(), value));\n }\n```"}], "func_name": "display_value", "docstring": "Prints a string representation of a value to `stdout`.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "22549ec0caa9b74c62a7a19c9422782beb204ac83f2692436038565fb22f4d15"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: format_trace\n\nDocumentation:\nFormats a `Trace` into a `String`.\n\nThe result does *not* include the `\"Traceback:\"` preamble.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn format_trace(&self, trace: &Trace) -> String {\n display_names(&self.scope().borrow_names(), trace).to_string()\n }\n```"}], "func_name": "format_trace", "docstring": "Formats a `Trace` into a `String`.\n\nThe result does *not* include the `\"Traceback:\"` preamble.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fa8a1978ca28492cea59a63358df06c78b8f3254bb3a9c7121a4caaab22b37a3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: execute_code\n\nDocumentation:\nExecutes a `Rc` object taking no parameters.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn execute_code(&self, code: Rc) -> Result {\n let v = execute(&self.context, code)?;\n Ok(v)\n }\n```"}], "func_name": "execute_code", "docstring": "Executes a `Rc` object taking no parameters.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b100a821ddac6ac89482420acf2841559d18e86c5ca46643725813192362e42"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: execute_program\n\nDocumentation:\nExecutes a series of code objects sequentially and returns the value\nof the final expression. If `code` is empty, the value `()` is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn execute_program(&self, code: Vec) -> Result {\n let mut last_v = Value::Unit;\n\n for c in code {\n last_v = self.execute(c)?;\n }\n\n Ok(last_v)\n }\n```"}], "func_name": "execute_program", "docstring": "Executes a series of code objects sequentially and returns the value\nof the final expression. If `code` is empty, the value `()` is returned.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f440f4c0510f836f8d786580a3493739140e483daa2ad7afad4f5e2cb26390a0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: call\n\nDocumentation:\nCalls a named function with the given arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn call(&self, name: &str, args: Vec) -> Result {\n let name = self.scope().borrow_names_mut().add(name);\n\n let v = self.scope().get_value(name).ok_or_else(|| ExecError::NameError(name))?;\n self.call_value(v, args)\n }\n```"}], "func_name": "call", "docstring": "Calls a named function with the given arguments.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e4d2ed4c4f80f99dee76904c3da1713781c706922b5bf299bda9cab7070fa85f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: call_value\n\nDocumentation:\nCalls a function with the given arguments.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn call_value(&self, value: Value, args: Vec) -> Result {\n let v = call_function(&self.context, value, args)?;\n Ok(v)\n }\n```"}], "func_name": "call_value", "docstring": "Calls a function with the given arguments.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e6d37a3902855bdfa457010780fec004967cf51e754ef38a35fbb3bb35fb2d32"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_args\n\nDocumentation:\nSets the value of `argv` within the execution scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_args>(&self, args: &[T]) {\n let args = args.iter()\n .map(|s| s.as_ref().into())\n .collect::>();\n\n self.scope().add_named_value(\"argv\", args.into());\n }\n```"}], "func_name": "set_args", "docstring": "Sets the value of `argv` within the execution scope.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25c1c70f3442963a08e7d161d274d3b13c7273064f187e23485788ae327c90cd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_file\n\nDocumentation:\nCompiles and executes the contents of a file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn run_file(&self, path: &Path) -> Result<(), Error> {\n let mut f = File::open(path)\n .map_err(|e| IoError::new(IoMode::Open, path, e))?;\n\n let mut buf = String::new();\n\n f.read_to_string(&mut buf)\n .map_err(|e| IoError::new(IoMode::Read, path, e))?;\n\n self.run_main(&buf, path.to_string_lossy().into_owned())\n }\n```"}], "func_name": "run_file", "docstring": "Compiles and executes the contents of a file.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bfb9543d668369dc84e28d7b7a3ccf1a16689cedbd189bfa11882dc9f274170a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_single_expr\n\nDocumentation:\nCompiles and executes an input expression.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn run_single_expr(&self, input: &str, path: Option) -> Result {\n let c = self.compile_single_expr(input, path)?;\n self.execute(c)\n }\n```"}], "func_name": "run_single_expr", "docstring": "Compiles and executes an input expression.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cfe2ce26dd3ae79efe3f03cfd1f3fe7f1c86792cdc0f47a19fdbbe1b1b5c0d8a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_code\n\nDocumentation:\nParses and executes a series of expressions and return the last value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn run_code(&self, input: &str, path: Option) -> Result {\n let code = self.compile_code(input, path)?;\n self.execute_program(code)\n }\n```"}], "func_name": "run_code", "docstring": "Parses and executes a series of expressions and return the last value.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fd2397ca610b48518a5fb52715afc896d6369f2123f5216e77c197d93be5465e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_single_expr\n\nDocumentation:\nCompiles and compiles a single expression and returns a code object.\nIf the input string contains more than one expression, an error is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compile_single_expr(&self, input: &str, path: Option) -> Result {\n let v = self.parse_single_expr(input, path)?;\n\n let code = compile(&self.context, &v)?;\n Ok(code)\n }\n```"}], "func_name": "compile_single_expr", "docstring": "Compiles and compiles a single expression and returns a code object.\nIf the input string contains more than one expression, an error is returned.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ac6d08c3970888a65c3f73bb5957dc04c0089486ae22cdd8f62abcdde1d0932"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compile_exprs\n\nDocumentation:\nCompiles and compiles a series of expressions.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compile_exprs(&self, input: &str) -> Result, Error> {\n self.compile_code(input, None)\n }\n```"}], "func_name": "compile_exprs", "docstring": "Compiles and compiles a series of expressions.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "085febcfb7467c3f866116cf7a8338cdb9600a5b6a418960e936cd5b485599c1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_single_expr\n\nDocumentation:\nParses a single expression and returns it as a `Value`.\nIf `input` contains more than one expression, an error is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_single_expr(&self, input: &str, path: Option) -> Result {\n let offset = self.scope().borrow_codemap_mut().add_source(input, path);\n\n let mut p = Parser::new(&self.context, Lexer::new(input, offset));\n let v = p.parse_single_expr()?;\n\n Ok(v)\n }\n```"}], "func_name": "parse_single_expr", "docstring": "Parses a single expression and returns it as a `Value`.\nIf `input` contains more than one expression, an error is returned.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "804926c64c4ea9643e93a299684f53bdbed8507d4c586f16cacde1a7f486438e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_exprs\n\nDocumentation:\nParses a series of expressions and returns them as `Value`s.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_exprs(&self, input: &str, path: Option) -> Result, Error> {\n let offset = self.scope().borrow_codemap_mut().add_source(input, path);\n\n let mut p = Parser::new(&self.context, Lexer::new(input, offset));\n\n let v = p.parse_exprs()?;\n\n Ok(v)\n }\n```"}], "func_name": "parse_exprs", "docstring": "Parses a series of expressions and returns them as `Value`s.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e2f90d9d066aba690337fa0a84dcadd55ee6d6d9c930f4f90a388cb79a3e166b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_file\n\nDocumentation:\nParses a series of expressions from the contents of a file and\nreturns them as `Value`s.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_file(&self, input: &str, path: Option) -> Result, Error> {\n let offset = self.scope().borrow_codemap_mut().add_source(input, path);\n\n let mut p = Parser::new(&self.context, Lexer::new(input, offset));\n p.skip_shebang();\n\n let v = p.parse_exprs()?;\n\n Ok(v)\n }\n```"}], "func_name": "parse_file", "docstring": "Parses a series of expressions from the contents of a file and\nreturns them as `Value`s.", "repo": "murarth/ketos", "path": "src/ketos/interpreter.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/interpreter.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "66f7a650ae2352655921d0c632f8661e96ab27fef9f99ca3bb39a5fec26fb66e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a `GlobalIo` instance using the given `stdout` and `stderr`\nwriters.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(stdout: Rc, stderr: Rc) -> GlobalIo {\n GlobalIo{ stdout, stderr }\n }\n```"}], "func_name": "new", "docstring": "Creates a `GlobalIo` instance using the given `stdout` and `stderr`\nwriters.", "repo": "murarth/ketos", "path": "src/ketos/io.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/io.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7a5a7e4e2cb4e7fcf5152244acd28496510ecd007e251f873eb72b4966385b5d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: null\n\nDocumentation:\nCreates a `GlobalIo` instance that ignores all output.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn null() -> GlobalIo {\n GlobalIo::new(Rc::new(Sink), Rc::new(Sink))\n }\n```"}], "func_name": "null", "docstring": "Creates a `GlobalIo` instance that ignores all output.", "repo": "murarth/ketos", "path": "src/ketos/io.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/io.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b9405cb8a4e50553a8a21ac463d6ae68bb0846540a0724a9861092a91d9704e8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default\n\nDocumentation:\nCreates a `GlobalIo` instance using `stdout`/`stderr` writers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn default() -> GlobalIo {\n GlobalIo::new(Rc::new(io::stdout()), Rc::new(io::stderr()))\n }\n```"}], "func_name": "default", "docstring": "Creates a `GlobalIo` instance using `stdout`/`stderr` writers.", "repo": "murarth/ketos", "path": "src/ketos/io.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/io.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2fdb71861c3eba8b950e023eefab3d7654a275f79a2534a1648fe414666db551"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `File` from an open filehandle and path.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(file: fs::File, path: PathBuf) -> File {\n File{ file, path }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `File` from an open filehandle and path.", "repo": "murarth/ketos", "path": "src/ketos/io.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/io.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0ddbe8dd2c25cc4a36bc902fe942a1e4ce69fb25b5c1dac6cc4832219b5f4745"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: name\n\nDocumentation:\nReturns a human-readable name of a token.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn name(&self) -> &'static str {\n match *self {\n Token::LeftParen => \"(\",\n Token::RightParen => \")\",\n Token::DocComment(_) => \"doc-comment\",\n Token::Float(_) => \"float\",\n Token::Integer(_, _) => \"integer\",\n Token::Ratio(_) => \"ratio\",\n Token::Name(_) => \"name\",\n Token::Char(_) => \"char\",\n Token::String(_) => \"string\",\n Token::Byte(_) => \"byte\",\n Token::Bytes(_) => \"bytes\",\n Token::Path(_) => \"path\",\n Token::Keyword(_) => \"keyword\",\n Token::BackQuote => \"`\",\n Token::Comma => \",\",\n Token::CommaAt => \",@\",\n Token::Quote => \"'\",\n Token::End => \"end-of-file\",\n }\n }\n```"}], "func_name": "name", "docstring": "Returns a human-readable name of a token.", "repo": "murarth/ketos", "path": "src/ketos/lexer.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2d00553af698e00a980a648f6936a01bf251682720f536c1ca62143970f69937"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: highlight_span\n\nDocumentation:\nReturns a structure which helps in highlighting a span within a body of text.\n\n# Panics\n\nPanics if `span` is not valid.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn highlight_span(text: &str, span: Span) -> SpanDisplay {\n let line_start = match text[..span.lo as usize].rfind('\\n') {\n Some(pos) => pos + 1,\n None => 0\n };\n\n let line_end = match text[line_start..].find('\\n') {\n Some(pos) => line_start + pos,\n None => text.len()\n };\n\n let pre_chars = text[line_start..span.lo as usize].chars().count();\n let span_str = &text[span.lo as usize..span.hi as usize];\n\n // If the span spans multiple lines, just highlight to the end of the line.\n let span_chars = match span_str.find('\\n') {\n Some(pos) => span_str[..pos].chars().count(),\n None => span_str.chars().count()\n };\n\n let line_no = text[..line_start].chars()\n .filter(|&ch| ch == '\\n').count() + 1;\n\n SpanDisplay{\n filename: None,\n line: line_no,\n col: pre_chars,\n source: &text[line_start..line_end],\n highlight: repeat(' ').take(pre_chars)\n .chain(once('^'))\n .chain(repeat('~').take(span_chars.saturating_sub(1))).collect(),\n }\n}\n```"}], "func_name": "highlight_span", "docstring": "Returns a structure which helps in highlighting a span within a body of text.\n\n# Panics\n\nPanics if `span` is not valid.", "repo": "murarth/ketos", "path": "src/ketos/lexer.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4b6fb2523fc54775f425f42c22aeeface94c4c2dd6f903633c804dc445b4769a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_source\n\nDocumentation:\nAdds a source to the codemap, returning its offset in the internal buffer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_source(&mut self, text: &str, path: Option) -> BytePos {\n let begin = self.text.len() as BytePos;\n\n self.text.push_str(text);\n self.files.push(File{ path, begin });\n\n begin\n }\n```"}], "func_name": "add_source", "docstring": "Adds a source to the codemap, returning its offset in the internal buffer.", "repo": "murarth/ketos", "path": "src/ketos/lexer.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a71594332cc67591576c0c002ea927e9f353d16f724d814491228a3a59e02be"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clear\n\nDocumentation:\nClears all source from the codemap.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clear(&mut self) {\n self.text.clear();\n self.files.clear();\n }\n```"}], "func_name": "clear", "docstring": "Clears all source from the codemap.", "repo": "murarth/ketos", "path": "src/ketos/lexer.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f192b723ae1155f42094f6d9397781575347c376449220c221b6491b20a3daa9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: highlight_span\n\nDocumentation:\nHighlights a span within the codemap.\n\n# Panics\n\nPanics if `span` is not valid.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn highlight_span(&self, span: Span) -> SpanDisplay {\n let n = match self.files.binary_search_by(|f| f.begin.cmp(&span.lo)) {\n Ok(n) => n,\n Err(n) => n - 1\n };\n\n let end = match self.files.get(n as usize + 1) {\n Some(f) => f.begin,\n None => self.text.len() as BytePos\n };\n\n if span.hi > end {\n panic!(\"span {:?} spans multiple files\", span);\n }\n\n let f = &self.files[n as usize];\n\n let Span{lo, hi} = span;\n let adj_span = Span{lo: lo - f.begin, hi: hi - f.begin};\n\n SpanDisplay{\n filename: f.path.as_ref().map(|s| &s[..]),\n ..highlight_span(&self.text[f.begin as usize..end as usize], adj_span)\n }\n }\n```"}], "func_name": "highlight_span", "docstring": "Highlights a span within the codemap.\n\n# Panics\n\nPanics if `span` is not valid.", "repo": "murarth/ketos", "path": "src/ketos/lexer.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "883bf1a44d805d37355bec24d6030099a65df28f79f18e14b2e40dea807d02d6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: empty\n\nDocumentation:\nReturns an empty `Span` at the given offset.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn empty(pos: BytePos) -> Span {\n Span{lo: pos, hi: pos}\n }\n```"}], "func_name": "empty", "docstring": "Returns an empty `Span` at the given offset.", "repo": "murarth/ketos", "path": "src/ketos/lexer.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e60851190e0a62cd848268fb71228348a0af7cc9295f7f2de85edb3ee1618ca7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `Lexer` to read tokens from the input string.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(input: &str, offset: BytePos) -> Lexer {\n Lexer{\n input,\n cur_pos: 0,\n code_offset: offset,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `Lexer` to read tokens from the input string.", "repo": "murarth/ketos", "path": "src/ketos/lexer.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0b8f8ace6f2b31181baaf631c31cd3ecc76526fa4ac8bc661ff7e181015cb776"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: next_token\n\nDocumentation:\nScans the input stream for the next token, returning the token and\nthe span of input text from which it was scanned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn next_token(&mut self) -> Result<(Span, Token<'lex>), ParseError> {\n let mut chars = self.input.char_indices();\n\n while let Some((ind, ch)) = chars.next() {\n let lo = self.cur_pos;\n\n let res = match ch {\n '(' => Ok((Token::LeftParen, 1)),\n ')' => Ok((Token::RightParen, 1)),\n '\\'' => Ok((Token::Quote, 1)),\n '`' => Ok((Token::BackQuote, 1)),\n ',' => match chars.next() {\n Some((_, '@')) => Ok((Token::CommaAt, 2)),\n _ => Ok((Token::Comma, 1)),\n },\n '-' | '0' ..= '9' => parse_number(&self.input[ind..]),\n '\"' => Ok(parse_string(&self.input[ind..], self.code_offset + lo)?),\n '#' => match chars.next() {\n Some((_, 'b')) => {\n match chars.next() {\n Some((_, 'r')) => Ok(parse_raw_bytes(&self.input[ind..],\n self.code_offset + lo)?),\n Some((_, '\"')) => Ok(parse_bytes(&self.input[ind..],\n self.code_offset + lo)?),\n Some((_, '\\'')) => Ok(parse_byte(&self.input[ind..],\n self.code_offset + lo)?),\n _ => Err(ParseErrorKind::InvalidToken)\n }\n }\n Some((_, 'p')) => {\n match chars.next() {\n Some((_, 'r')) => Ok(parse_raw_path(&self.input[ind..],\n self.code_offset + lo)?),\n Some((_, '\"')) => Ok(parse_path(&self.input[ind..],\n self.code_offset + lo)?),\n _ => Err(ParseErrorKind::InvalidToken)\n }\n }\n Some((_, '\\'')) => Ok(parse_char(&self.input[ind..],\n self.code_offset + lo)?),\n Some((_, '|')) => match consume_block_comment(ind, &mut chars) {\n Ok(n) => {\n self.cur_pos += n as BytePos;\n continue;\n }\n Err(k) => Err(k)\n },\n Some(_) => Err(ParseErrorKind::InvalidToken),\n None => Err(ParseErrorKind::UnexpectedEof)\n },\n 'r' => match chars.next() {\n Some((_, '\"')) | Some((_, '#')) =>\n Ok(parse_raw_string(&self.input[ind..],\n self.code_offset + lo)?),\n _ => parse_name(&self.input[ind..])\n },\n ':' => parse_keyword(&self.input[ind..]),\n ';' => {\n match chars.clone().next() {\n Some((_, ';')) => Ok(parse_doc_comment(&self.input[ind..])),\n _ => {\n self.cur_pos += consume_line_comment(ind, &mut chars) as BytePos;\n continue;\n }\n }\n }\n '\\r' => match chars.next() {\n Some((_, '\\n')) => {\n self.cur_pos += 2;\n continue;\n }\n _ => Err(ParseErrorKind::InvalidChar('\\r'))\n },\n ch if ch.is_whitespace() => {\n self.cur_pos += ch.len_utf8() as BytePos;\n continue;\n }\n _ if is_identifier(ch) => parse_name(&self.input[ind..]),\n ch => Err(ParseErrorKind::InvalidChar(ch))\n };\n\n let (tok, size) = match res {\n Ok(v) => v,\n Err(kind) => return Err(ParseError::new(\n self.span(Span::one(lo, ch)), kind))\n };\n\n self.cur_pos += size as BytePos;\n self.input = &self.input[ind + size..];\n\n let sp = Span{lo, hi: lo + size as BytePos};\n\n return Ok((self.span(sp), tok));\n }\n\n self.input = &self.input[..0];\n Ok((self.span(Span::empty(self.cur_pos)), Token::End))\n }\n```"}], "func_name": "next_token", "docstring": "Scans the input stream for the next token, returning the token and\nthe span of input text from which it was scanned.", "repo": "murarth/ketos", "path": "src/ketos/lexer.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d7b7bcc68eb47870e0feddb8a0f8f43cbb150bc8fcd7ccf65f72c5c7b0c4091b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: skip_shebang\n\nDocumentation:\nSkips over a shebang line at the start of input. This is used when\nparsing files which, on Unix systems, may use a line consisting of `#!`\nfollowed by a path to the interpreter.\n\n# Panics\n\nPanics if any tokens have already been scanned from the input stream.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn skip_shebang(&mut self) {\n if self.cur_pos != 0 {\n panic!(\"skip_shebang called after next_token\");\n }\n\n if self.input.starts_with(\"#!\") {\n let pos = match self.input.find('\\n') {\n Some(pos) => pos,\n None => self.input.len()\n };\n self.input = &self.input[pos..];\n self.cur_pos = pos as BytePos;\n }\n }\n```"}], "func_name": "skip_shebang", "docstring": "Skips over a shebang line at the start of input. This is used when\nparsing files which, on Unix systems, may use a line consisting of `#!`\nfollowed by a path to the interpreter.\n\n# Panics\n\nPanics if any tokens have already been scanned from the input stream.", "repo": "murarth/ketos", "path": "src/ketos/lexer.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/lexer.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a71395e16941e6627423c77bb63ebcb46b8b9085e77f13930d86ec7951079fd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new module using the given scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(name: &str, scope: Scope) -> Module {\n let name = scope.add_name(name);\n Module{ name, scope }\n }\n```"}], "func_name": "new", "docstring": "Creates a new module using the given scope.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2df0ec3319647d2bd1ae31b4ee8b95671d30678203d18c750eaf95ed1ef80e4d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `ModuleBuilder` for the given scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(name: &str, scope: Scope) -> ModuleBuilder {\n let mod_name = scope.borrow_names_mut().add(name);\n\n ModuleBuilder{\n name: mod_name,\n scope: scope.clone(),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `ModuleBuilder` for the given scope.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f9489d6a38a8096b796a055f0ff84a0ab400349f08395871f820b225f557d82"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_constant\n\nDocumentation:\nAdds a constant value to the module.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_constant>(self, name: &str, value: T) -> Self {\n let name = self.scope.add_name(name);\n self.scope.add_constant(name, value.into());\n self\n }\n```"}], "func_name": "add_constant", "docstring": "Adds a constant value to the module.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d8db3868e8ff46ccf10c7cac20239250cc4d808d5c78b7b6cc5570a6e79644c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_doc\n\nDocumentation:\nAdds a documentation string for the given name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_doc(self, name: &str, doc: &str) -> Self {\n let name = self.scope.add_name(name);\n self.scope.add_doc_string(name, doc.to_owned());\n self\n }\n```"}], "func_name": "add_doc", "docstring": "Adds a documentation string for the given name.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "84148f4a5ccb250232ba16b79c27d55abd8a645e7e7bee65f1143f3f34c5abd3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_value_with_name\n\nDocumentation:\nAdds a value to the module using the generated name value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_value_with_name(self, name: &str, f: F) -> Self\n where F: FnOnce(Name) -> Value {\n self.scope.add_value_with_name(name, f);\n self\n }\n```"}], "func_name": "add_value_with_name", "docstring": "Adds a value to the module using the generated name value.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "667dbb50293fd6e815e9a083bb003cd0224f2fb801b8096b78d1494b816f60bc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: finish\n\nDocumentation:\nConsumes the builder and returns the new `Module`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn finish(self) -> Module {\n let mut exports = Vec::new();\n\n self.scope.with_constants(\n |v| exports.extend(v.iter().map(|&(name, _)| name)));\n self.scope.with_macros(\n |v| exports.extend(v.iter().map(|&(name, _)| name)));\n self.scope.with_values(\n |v| exports.extend(v.iter().map(|&(name, _)| name)));\n\n self.scope.set_exports(exports.into_iter().collect());\n\n Module{\n name: self.name,\n scope: self.scope,\n }\n }\n```"}], "func_name": "finish", "docstring": "Consumes the builder and returns the new `Module`.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b6ef0e4106ddd58e117674de2a5867b8628f06bf14023426d08d81a4e817fcc9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a `ModuleCode` from a series of code objects and a `Scope`.\n\nTrivial code objects will be removed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(mut code: Vec>, scope: &Scope) -> ModuleCode {\n fn is_lambda(v: &Value) -> bool {\n match *v {\n Value::Lambda(_) => true,\n _ => false\n }\n }\n\n code.retain(|code| !code.is_trivial());\n\n ModuleCode{\n code,\n constants: scope.with_constants(\n |consts| consts.iter().cloned().collect()),\n macros: scope.with_macros(\n |macros| macros.iter()\n .map(|&(name, ref l)| (name, l.code.clone())).collect()),\n values: scope.with_values(\n |values| values.iter()\n .filter(|&&(_, ref v)| is_lambda(v))\n .filter(|&&(name, _)| !scope.is_imported(name))\n .cloned().collect()),\n exports: scope.with_exports(|e| e.clone())\n .unwrap_or_else(NameSetSlice::default),\n imports: scope.with_imports(|i| i.to_vec()),\n module_doc: scope.with_module_doc(|d| d.to_owned()),\n docs: scope.with_docs(\n |d| d.iter().filter(|&&(name, _)| !scope.is_imported(name))\n .cloned().collect()),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a `ModuleCode` from a series of code objects and a `Scope`.\n\nTrivial code objects will be removed.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a62497faf189e37458f171cb723a0a460287aaeb604b8642efbecbfc799dfe6e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_in_context\n\nDocumentation:\nLoads contained values into the given scope, which should be empty,\nand sequentially executes all contained code objects within the scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load_in_context(self, ctx: &Context) -> Result<(), Error> {\n for (name, value) in self.constants {\n ctx.scope().add_constant(name, value);\n }\n\n for (name, code) in self.macros {\n let mac = Lambda::new(code, ctx.scope());\n ctx.scope().add_macro(name, mac);\n }\n\n for (name, value) in self.values {\n ctx.scope().add_value(name, value);\n }\n\n process_imports(ctx, &self.imports)?;\n\n ctx.scope().set_exports(self.exports);\n\n let mdoc = self.module_doc;\n ctx.scope().with_module_doc_mut(|d| *d = mdoc);\n let docs = self.docs;\n ctx.scope().with_docs_mut(|d| *d = docs.into_iter().collect());\n\n for code in self.code {\n execute(ctx, code)?;\n }\n\n Ok(())\n }\n```"}], "func_name": "load_in_context", "docstring": "Loads contained values into the given scope, which should be empty,\nand sequentially executes all contained code objects within the scope.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dbda28f6d781660b4fd56c7e9935b7f3aa0888a946d04221e8d9de485b4b445e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `ModuleRegistry` using the given `ModuleLoader`\nto load new modules.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(loader: Box) -> ModuleRegistry {\n ModuleRegistry{\n loader,\n modules: RefCell::new(NameMap::new()),\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `ModuleRegistry` using the given `ModuleLoader`\nto load new modules.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "009be812ac1e9b3711c163ebe12a31c52b204fac786ed40e3debec3557af2d71"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_module\n\nDocumentation:\nInserts a named module into the registry.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_module(&self, name: Name, module: Module) -> Option {\n self.modules.borrow_mut().insert(name, module)\n }\n```"}], "func_name": "add_module", "docstring": "Inserts a named module into the registry.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "da0c8bb8124359928c6e58fdf05f65a2cd7aaae3b2967292e62a7f8c004aa8b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load_module\n\nDocumentation:\nReturns a loaded module. If the module has not been loaded in this\nregistry; the contained `ModuleLoader` instance will be used to load it.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load_module(&self, name: Name, ctx: &Context) -> Result {\n // It's not necessary to borrow_mut here, but it means that this\n // function has consistent behavior with respect to existing borrows.\n if let Some(m) = self.modules.borrow_mut().get(name).cloned() {\n return Ok(m);\n }\n\n // ... And the borrow_mut must be dropped before load_module is called.\n\n let new_scope = GlobalScope::new_using(name, ctx.scope());\n let new_ctx = ctx.with_scope(new_scope);\n\n let m = self.loader.load_module(name, new_ctx)?;\n self.modules.borrow_mut().insert(name, m.clone());\n\n Ok(m)\n }\n```"}], "func_name": "load_module", "docstring": "Returns a loaded module. If the module has not been loaded in this\nregistry; the contained `ModuleLoader` instance will be used to load it.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d4b8b79476dcdd272ac86cdb5653db8e42387fb335cea1ca1727f1d003a7003e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: chain\n\nDocumentation:\nCreates a `ChainModuleLoader` using this loader and another.\n\nThe `ChainModuleLoader` will attempt to load a module first from `self`,\nfalling back on the supplied `ModuleLoader` if it unable to find a\nmodule.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn chain(self, second: T) -> ChainModuleLoader\n where Self: Sized {\n ChainModuleLoader{\n first: self,\n second,\n }\n }\n```"}], "func_name": "chain", "docstring": "Creates a `ChainModuleLoader` using this loader and another.\n\nThe `ChainModuleLoader` will attempt to load a module first from `self`,\nfalling back on the supplied `ModuleLoader` if it unable to find a\nmodule.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "926e61963cbb3f46107847edb03320ccd6f44cc5d6eee301e2a454502430f01a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_search_paths\n\nDocumentation:\nCreates a new `FileModuleLoader` that will search the given series\nof directories to load modules.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_search_paths(paths: Vec) -> FileModuleLoader {\n FileModuleLoader{\n chain: RefCell::new(Vec::new()),\n paths,\n read_bytecode: true,\n write_bytecode: true,\n }\n }\n```"}], "func_name": "with_search_paths", "docstring": "Creates a new `FileModuleLoader` that will search the given series\nof directories to load modules.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb6502647f90906f7d4c11e1dba52f0e82da822a38afa83a3174b48cb5aac28e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_read_bytecode\n\nDocumentation:\nSets whether the `FileModuleLoader` will search for compiled bytecode\nfiles when loading modules. The default is `true`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_read_bytecode(&mut self, set: bool) {\n self.read_bytecode = set;\n }\n```"}], "func_name": "set_read_bytecode", "docstring": "Sets whether the `FileModuleLoader` will search for compiled bytecode\nfiles when loading modules. The default is `true`.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8816be77b32eb64c326cf2541dee67e99d97fcc1ebffc1d133600c5ae8bc966e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_write_bytecode\n\nDocumentation:\nSets whether the `FileModuleLoader` will write compiled bytecode\nfiles after loading a module from source. The default is `true`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_write_bytecode(&mut self, set: bool) {\n self.write_bytecode = set;\n }\n```"}], "func_name": "set_write_bytecode", "docstring": "Sets whether the `FileModuleLoader` will write compiled bytecode\nfiles after loading a module from source. The default is `true`.", "repo": "murarth/ketos", "path": "src/ketos/module.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/module.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "410fc3bc88d6fffc6096dcb3dd930499e0741343576c25ee93e3008089197e51"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load\n\nDocumentation:\nLoads the `code` module into the given scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load(scope: Scope) -> Module {\n ModuleBuilder::new(\"code\", scope)\n .add_function(\"compile\", fn_compile, Exact(1),\n Some(\"Compiles an expression into a lambda.\"))\n .add_function(\"disassemble\", fn_disassemble, Exact(1),\n Some(\"Prints bytecode for the given lambda.\"))\n .add_function(\"documentation\", fn_documentation, Exact(1), Some(\n\"Returns the documentation string for a lambda value or a name.\nReturns `()` if the item has no documentation.\"))\n .add_function(\"get-const\", fn_get_const, Exact(2), Some(\n\" (get-const lambda n)\n\nReturns the nth const value of a lambda.\"))\n .add_function(\"get-value\", fn_get_value, Exact(2), Some(\n\" (get-value lambda n)\n\nReturns the nth captured value of a lambda.\"))\n .add_function(\"module-documentation\",\n fn_module_documentation, Range(0, 1), Some(\n\" (module-documentation)\n (module-documentation name)\n\nReturns the documentation string for the named module.\nGiven no arguments, returns the documentation string for the current module.\"))\n .finish()\n}\n```"}], "func_name": "load", "docstring": "Loads the `code` module into the given scope.", "repo": "murarth/ketos", "path": "src/ketos/mod_code.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c9f43b84a7c9dc1d1311797ff04b263ec060d3404a07b8972566d5e4ed5cf24"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_compile\n\nDocumentation:\n`compile` compiles an expression into a code object.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_compile(ctx: &Context, args: &mut [Value]) -> Result {\n let code = compile(ctx, &args[0])?;\n Ok(Value::Lambda(Lambda::new(Rc::new(code), ctx.scope())))\n}\n```"}], "func_name": "fn_compile", "docstring": "`compile` compiles an expression into a code object.", "repo": "murarth/ketos", "path": "src/ketos/mod_code.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2f7125958075e67fcfdeabc20b1e79555d2994c477251c11e3df6711f087e762"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_disassemble\n\nDocumentation:\n`disassemble` prints information about a `Lambda` code object.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_disassemble(ctx: &Context, args: &mut [Value]) -> Result {\n let l = match args[0] {\n Value::Lambda (ref l) => l,\n ref v => return Err(From::from(ExecError::expected(\"lambda\", v)))\n };\n\n let scope = ctx.scope();\n let code = &l.code;\n let out = &scope.io().stdout;\n\n writeln!(out, \"{} positional argument{} total\",\n code.n_params, plural(code.n_params))?;\n writeln!(out, \"{} positional argument{} required\",\n code.req_params, plural(code.req_params))?;\n\n if code.kw_params.is_empty() {\n writeln!(out, \"0 keyword arguments\")?;\n } else {\n let names = scope.borrow_names();\n\n writeln!(out, \"{} keyword argument{}: {}\",\n code.kw_params.len(), plural(code.kw_params.len() as u32),\n code.kw_params.iter().map(|&n| names.get(n))\n .collect::>().join(\" \"))?;\n }\n\n if code.has_rest_params() {\n writeln!(out, \"Has rest parameter\")?;\n } else {\n writeln!(out, \"No rest parameter\")?;\n }\n\n if code.consts.is_empty() {\n writeln!(out, \"0 const values\")?;\n } else {\n writeln!(out, \"{} const value{}:\",\n code.consts.len(), plural(code.consts.len() as u32))?;\n\n let names = scope.borrow_names();\n\n for (i, v) in code.consts.iter().enumerate() {\n writeln!(out, \" {} = {}\", i, debug_names(&names, v))?;\n }\n }\n\n if let Some(ref v) = l.values {\n writeln!(out, \"{} enclosed value{}:\", v.len(), plural(v.len() as u32))?;\n\n let names = scope.borrow_names();\n\n for (i, v) in v.iter().enumerate() {\n writeln!(out, \" {} = {}\", i, debug_names(&names, v))?;\n }\n } else {\n writeln!(out, \"0 enclosed values\")?;\n }\n\n let instrs = get_instructions(&code.code)?;\n let mut jumps = Vec::with_capacity(16);\n\n // Collect all jump labels\n for &(_, ref instr) in &instrs {\n if let Some(off) = instr.jump_label() {\n match jumps.binary_search(&off) {\n Ok(_) => (),\n Err(pos) => jumps.insert(pos, off)\n }\n }\n }\n\n writeln!(out, \"{} bytecode instruction{}:\", instrs.len(), plural(instrs.len() as u32))?;\n\n for (off, instr) in instrs {\n let is_label = jumps.binary_search(&off).is_ok();\n print_instruction(ctx, l, off, instr, is_label)?;\n }\n\n out.flush()?;\n Ok(().into())\n}\n```"}], "func_name": "fn_disassemble", "docstring": "`disassemble` prints information about a `Lambda` code object.", "repo": "murarth/ketos", "path": "src/ketos/mod_code.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2246998ba7d2c240a6ba44fa14cecf9096abfa6eead54288d691710f87dac9af"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_documentation\n\nDocumentation:\n`documentation` returns the docstring for a value.\n\nIf the named value does not exist or does not have a docstring,\n`()` is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_documentation(ctx: &Context, args: &mut [Value]) -> Result {\n match args[0] {\n Value::Function(ref f) => {\n Ok(f.sys_fn.doc\n .map(Value::from)\n .unwrap_or(Value::Unit))\n }\n Value::Lambda(ref l) => {\n Ok(l.code.doc.clone()\n .map(Value::from)\n .unwrap_or(Value::Unit))\n }\n Value::Name(name) => {\n let scope = ctx.scope();\n Ok(scope\n .with_doc(name, |d| d.into())\n .or_else(|| scope.get_value(name)\n .and_then(|v| value_doc(&v))\n .map(Value::from))\n .or_else(|| scope.get_macro(name)\n .and_then(|l| l.code.doc.clone())\n .map(Value::from))\n .unwrap_or(Value::Unit))\n }\n ref v => Err(From::from(ExecError::expected(\"name or function\", v)))\n }\n}\n```"}], "func_name": "fn_documentation", "docstring": "`documentation` returns the docstring for a value.\n\nIf the named value does not exist or does not have a docstring,\n`()` is returned.", "repo": "murarth/ketos", "path": "src/ketos/mod_code.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "69d5b2dc15c7c4e61cd3fd10daa6ce782e6165a6220b2c60a58ec582f8c8b7c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_get_const\n\nDocumentation:\n`get-const` returns the specified const value from a `Lambda` object.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_get_const(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0] {\n Value::Lambda(ref l) => {\n let n = usize::from_value_ref(&args[1])?;\n\n let v = l.code.consts.get(n)\n .ok_or_else(|| ExecError::OutOfBounds(n))?;\n\n Ok(v.clone())\n }\n ref v => Err(From::from(ExecError::expected(\"lambda\", v)))\n }\n}\n```"}], "func_name": "fn_get_const", "docstring": "`get-const` returns the specified const value from a `Lambda` object.", "repo": "murarth/ketos", "path": "src/ketos/mod_code.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f9887a811d028e35ed27ecfc50345e0b7924f2aa16920d37d56f5a5b72c27ecc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_get_value\n\nDocumentation:\n`get-value` returns the specified enclosed value from a `Lambda` object.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_get_value(_ctx: &Context, args: &mut [Value]) -> Result {\n match args[0] {\n Value::Lambda(ref l) => {\n let n = usize::from_value_ref(&args[1])?;\n\n let v = l.values.as_ref().and_then(|v| v.get(n))\n .ok_or_else(|| ExecError::OutOfBounds(n))?;\n\n Ok(v.clone())\n }\n ref v => Err(From::from(ExecError::expected(\"lambda\", v)))\n }\n}\n```"}], "func_name": "fn_get_value", "docstring": "`get-value` returns the specified enclosed value from a `Lambda` object.", "repo": "murarth/ketos", "path": "src/ketos/mod_code.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "605224bfa88eccc09fa9428a9dc2604f1d5b4b5c4f1ea1bc5278635476231cc3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_module_documentation\n\nDocumentation:\n`module-documentation` returns the docstring for the named module.\n\nIf the named module is not currently loaded or it does not have a docstring,\n`()` is returned.\n\nWhen given no parameters, the documentation for the current scope is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_module_documentation(ctx: &Context, args: &mut [Value]) -> Result {\n if args.is_empty() {\n return Ok(ctx.scope().with_module_doc(|d| d.into())\n .unwrap_or(Value::Unit));\n }\n\n let name = match args[0] {\n Value::Name(name) => name,\n ref v => return Err(From::from(ExecError::expected(\"name\", v)))\n };\n\n let m = ctx.scope().modules();\n\n Ok(m.get_module(name)\n .and_then(|m| m.scope.with_module_doc(|d| d.into()))\n .unwrap_or(Value::Unit))\n}\n```"}], "func_name": "fn_module_documentation", "docstring": "`module-documentation` returns the docstring for the named module.\n\nIf the named module is not currently loaded or it does not have a docstring,\n`()` is returned.\n\nWhen given no parameters, the documentation for the current scope is returned.", "repo": "murarth/ketos", "path": "src/ketos/mod_code.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_code.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f74850b159f8309302eec3a814203f845d10fb2930c7681786d4c541af9b1b7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load\n\nDocumentation:\nLoads the `math` module into the given scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load(scope: Scope) -> Module {\n ModuleBuilder::new(\"math\", scope)\n .add_constant(\"e\", consts::E)\n .add_doc (\"e\", \"Euler's number\")\n .add_constant(\"pi\", consts::PI)\n .add_doc (\"pi\", \"The ratio of a circle's circumference to its diameter\")\n .add_function(\"acos\", fn_acos, Exact(1), Some(\"\\\nComputes the arctangent of a number.\nReturn value is in radians in the range `[-pi/2, pi/2]`.\"))\n .add_function(\"acosh\", fn_acosh, Exact(1),\n Some(\"Inverse hyperbolic cosine function.\"))\n .add_function(\"asin\", fn_asin, Exact(1), Some(\"\\\nComputes the arcsine of a number.\nReturn value is in radians in the range `[-pi/2, pi/2]` or `NaN`\nif the number is outside the range `[-1, 1]`.\"))\n .add_function(\"asinh\", fn_asinh, Exact(1),\n Some(\"Inverse hyperbolic sine function\"))\n .add_function(\"atan\", fn_atan, Exact(1), Some(\"\\\nComputes the arctangent of a number.\nReturn value is in radians in the range `[-pi/2, pi/2]`.\"))\n .add_function(\"atanh\", fn_atanh, Exact(1),\n Some(\"Inverse hyperbolic tangent function.\"))\n .add_function(\"atan2\", fn_atan2, Exact(2), Some(\"\\\n (atan2 y x)\n\nComputes the four quadrant arctangent of `y` and `x`.\n\n* `x = 0`, `y = 0`: `0`\n* `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]`\n* `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]`\n* `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`\"))\n .add_function(\"cos\", fn_cos, Exact(1),\n Some(\"Computes the cosine of a number, in radians.\"))\n .add_function(\"cosh\", fn_cosh, Exact(1),\n Some(\"Hyperbolic cosine function.\"))\n .add_function(\"degrees\", fn_degrees, Exact(1),\n Some(\"Converts a value in radians to degrees.\"))\n .add_function(\"ln\", fn_ln, Exact(1),\n Some(\"Returns the natural logarithm of a number.\"))\n .add_function(\"log\", fn_log, Exact(2), Some(\"\\\n (log n base)\n\nReturns the logarithm of a number with respect to an arbitrary base.\"))\n .add_function(\"log2\", fn_log2, Exact(1), Some(\"\\\nReturns the base 2 logarithm of a number.\"))\n .add_function(\"log10\", fn_log10, Exact(1), Some(\"\\\nReturns the base 10 logarithm of a number.\"))\n .add_function(\"radians\", fn_radians, Exact(1),\n Some(\"Converts a value in degrees to radians.\"))\n .add_function(\"sin\", fn_sin, Exact(1),\n Some(\"Computes the sine of a number, in radians.\"))\n .add_function(\"sinh\", fn_sinh, Exact(1),\n Some(\"Hyperbolic sine function.\"))\n .add_function(\"sqrt\", fn_sqrt, Exact(1), Some(\"\\\nReturns the square root of a number.\nReturns `NaN` if the number is negative.\"))\n .add_function(\"tan\", fn_tan, Exact(1),\n Some(\"Computes the tangent of a number, in radians.\"))\n .add_function(\"tanh\", fn_tanh, Exact(1),\n Some(\"Hyperbolic tangent function\"))\n .finish()\n}\n```"}], "func_name": "load", "docstring": "Loads the `math` module into the given scope.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "11067ce0416b456d494c5e7dc2de078b4f920ada0199b1843a23e05d7b391218"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_acos\n\nDocumentation:\n`acos` returns the arccosine of a number. Return value is in radians\nin the range `[0, pi]` or `NaN` if the number is outside the range `[-1, 1]`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_acos(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.acos().into())\n}\n```"}], "func_name": "fn_acos", "docstring": "`acos` returns the arccosine of a number. Return value is in radians\nin the range `[0, pi]` or `NaN` if the number is outside the range `[-1, 1]`.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "73c41e83f54fd2e1b20e4b4b2132315533e205d8454c01f2caca2232a5bd1596"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_acosh\n\nDocumentation:\n`acosh` is the inverse hyperbolic cosine.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_acosh(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.acosh().into())\n}\n```"}], "func_name": "fn_acosh", "docstring": "`acosh` is the inverse hyperbolic cosine.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7950c61ef545d69dec96285a00aa8077656952bd4c2cd5d09074e5a96e9bd5ed"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_asin\n\nDocumentation:\n`asin` returns the arcsine of a number. Return value is in radians\nin the range `[-pi/2, pi/2]` or `NaN` if the number is outside the range\n`[-1, 1]`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_asin(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.asin().into())\n}\n```"}], "func_name": "fn_asin", "docstring": "`asin` returns the arcsine of a number. Return value is in radians\nin the range `[-pi/2, pi/2]` or `NaN` if the number is outside the range\n`[-1, 1]`.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "01a778cc4ac3ef03bc2d74c0c404f20a1909b4d85fc4d25c0c2bb628ce942757"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_asinh\n\nDocumentation:\n`asinh` is the inverse hyperbolic sine function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_asinh(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.asinh().into())\n}\n```"}], "func_name": "fn_asinh", "docstring": "`asinh` is the inverse hyperbolic sine function.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4cf816cc75bc97dfe91d6c2b724da5222e647e251ae8b8dc4c9ce2d301ef63ca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_atan\n\nDocumentation:\n`atan` returns the arctangent of a number. Return value is in the range\n`[-pi/2, pi/2]`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_atan(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.atan().into())\n}\n```"}], "func_name": "fn_atan", "docstring": "`atan` returns the arctangent of a number. Return value is in the range\n`[-pi/2, pi/2]`.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9c4e924435a1ae6e3bc54ab19d063b7ca60394a26840f401d25707ef0ac4c0cf"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_atanh\n\nDocumentation:\n`atanh` is the inverse hyperbolic tangent function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_atanh(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.atanh().into())\n}\n```"}], "func_name": "fn_atanh", "docstring": "`atanh` is the inverse hyperbolic tangent function.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "008204a3d6885febe29b74ad6e4f620dec143e56c4155907384628a37c12a761"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_atan2\n\nDocumentation:\n`atan2` computes the four quadrant arctangent of `y` and `x`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_atan2(_ctx: &Context, args: &mut [Value]) -> Result {\n let fa = get_float(&args[0])?;\n let fb = get_float(&args[1])?;\n Ok(fa.atan2(fb).into())\n}\n```"}], "func_name": "fn_atan2", "docstring": "`atan2` computes the four quadrant arctangent of `y` and `x`.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "efc647aa01ddffe873a6b2c3527fb7632774ffebc980c8100cbe028a7f98d877"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_cos\n\nDocumentation:\n`cos` computes the cosine of a number, in radians.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_cos(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.cos().into())\n}\n```"}], "func_name": "fn_cos", "docstring": "`cos` computes the cosine of a number, in radians.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "91bec10a5dfafef26f13233a9859871825b3309c6cf5e1cb20b4fb611fe62db3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_cosh\n\nDocumentation:\n`cosh` is the hyperbolic cosine function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_cosh(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.cosh().into())\n}\n```"}], "func_name": "fn_cosh", "docstring": "`cosh` is the hyperbolic cosine function.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ef6860142e6e7a99801ad2a69cf1b05e89cf91ae6f52a736cb730571d277a77"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_degrees\n\nDocumentation:\n`degrees` converts a value in radians to the equivalent value in degrees.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_degrees(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.to_degrees().into())\n}\n```"}], "func_name": "fn_degrees", "docstring": "`degrees` converts a value in radians to the equivalent value in degrees.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "39cf94c20e1e53b58545778f3629b1a96a6f9602eae72bd6447a0ecc9509ee06"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_ln\n\nDocumentation:\n`ln` returns the natural logarithm of a number.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_ln(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.ln().into())\n}\n```"}], "func_name": "fn_ln", "docstring": "`ln` returns the natural logarithm of a number.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f53c13b115279d4281292bc4a92f824ad54e5babf98f3c55d655e3b019bb36c4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_log\n\nDocumentation:\n`log` returns the logarithm of a number with respect to an arbitrary base.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_log(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n let base = get_float(&args[1])?;\n Ok(f.log(base).into())\n}\n```"}], "func_name": "fn_log", "docstring": "`log` returns the logarithm of a number with respect to an arbitrary base.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8a73f94a92a460dcaa82cfc22c8e6b41abcee079ec455dc0cd66425293a1b7a6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_log2\n\nDocumentation:\n`log2` returns the base 2 logarithm of a number.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_log2(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.log2().into())\n}\n```"}], "func_name": "fn_log2", "docstring": "`log2` returns the base 2 logarithm of a number.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "31c64cd7cfecb5c1201a9bc711f8385a700ecff06d2ca8fbf746a67580004699"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_log10\n\nDocumentation:\n`log10` returns the base 10 logarithm of a number.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_log10(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.log10().into())\n}\n```"}], "func_name": "fn_log10", "docstring": "`log10` returns the base 10 logarithm of a number.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6a1d08c7c8e4b8b09b3ef92e5cca85ca286a5af565282616e51b35a14e19dbb9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_radians\n\nDocumentation:\n`radians` converts a value in degrees to the equivalent value in radians.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_radians(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.to_radians().into())\n}\n```"}], "func_name": "fn_radians", "docstring": "`radians` converts a value in degrees to the equivalent value in radians.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2946fdeb7208d69de5262baac82193d3eb72f22962496489fa3a2535f580ddc8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_sin\n\nDocumentation:\n`sin` computes the sine of a number, in radians.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_sin(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.sin().into())\n}\n```"}], "func_name": "fn_sin", "docstring": "`sin` computes the sine of a number, in radians.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2484a3ad849c68952a1cd16d57c6cb7610b43e3e9a9e0db3858e16ad88049a3f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_sinh\n\nDocumentation:\n`sinh` is the hyperbolic sine function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_sinh(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.sinh().into())\n}\n```"}], "func_name": "fn_sinh", "docstring": "`sinh` is the hyperbolic sine function.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c4349e691406bf61cca07099307490977803eb37356e435439458b648642c719"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_sqrt\n\nDocumentation:\n`sqrt` returns the square root of the given value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_sqrt(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.sqrt().into())\n}\n```"}], "func_name": "fn_sqrt", "docstring": "`sqrt` returns the square root of the given value.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "21df7efc58b45162e73522157ac1807ca577e69c5acf0b97ecc54edfd5bb9f32"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_tan\n\nDocumentation:\n`tan` computes the tangent of a number, in radians.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_tan(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.tan().into())\n}\n```"}], "func_name": "fn_tan", "docstring": "`tan` computes the tangent of a number, in radians.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4b43cb7abc34b9abfea5cd769818f0bf63ebc425b74112441916f8052d42ef6b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_tanh\n\nDocumentation:\n`tanh` is the hyperbolic tangent function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_tanh(_ctx: &Context, args: &mut [Value]) -> Result {\n let f = get_float(&args[0])?;\n Ok(f.tanh().into())\n}\n```"}], "func_name": "fn_tanh", "docstring": "`tanh` is the hyperbolic tangent function.", "repo": "murarth/ketos", "path": "src/ketos/mod_math.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_math.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "33f7a4834f3f411453d8c6c4510e367e27e897dd96eed72275f723db04b1a796"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: load\n\nDocumentation:\nLoads the `random` module into the given scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn load(scope: Scope) -> Module {\n ModuleBuilder::new(\"random\", scope)\n .add_function(\"random\", fn_random, Exact(0),\n Some(\"Returns a random float value in the range `[0.0, 1.0)`.\"))\n .add_function(\"shuffle\", fn_shuffle, Exact(1),\n Some(\"Given a list, returns a new list with the elements shuffled.\"))\n .finish()\n}\n```"}], "func_name": "load", "docstring": "Loads the `random` module into the given scope.", "repo": "murarth/ketos", "path": "src/ketos/mod_random.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_random.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dd08650a9a57b8a43dd31e8ea761ee9d9a6f250ca517d7dfef243dcd6f149f2f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_random\n\nDocumentation:\n`random` returns a random float value in the range `[0.0, 1.0)`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_random(_ctx: &Context, _args: &mut [Value]) -> Result {\n let value: f64 = thread_rng().gen();\n Ok(value.into())\n}\n```"}], "func_name": "fn_random", "docstring": "`random` returns a random float value in the range `[0.0, 1.0)`.", "repo": "murarth/ketos", "path": "src/ketos/mod_random.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_random.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8159c799dc533348a4fa776281e164ed2278c4b14d268cc7835813c78fa6aa56"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fn_shuffle\n\nDocumentation:\n`shuffle` shuffles the values of a list.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fn_shuffle(_ctx: &Context, args: &mut [Value]) -> Result {\n let mut v = args[0].take();\n\n match v {\n Value::Unit => (),\n Value::List(ref mut li) => li.shuffle(&mut thread_rng()),\n ref v => return Err(From::from(ExecError::expected(\"list\", v)))\n }\n\n Ok(v)\n}\n```"}], "func_name": "fn_shuffle", "docstring": "`shuffle` shuffles the values of a list.", "repo": "murarth/ketos", "path": "src/ketos/mod_random.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/mod_random.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "56d9ad3afe18d68a7df3b28987c37bf0e72b56bbe63ad8856c4f7ddcac8d10f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_standard_name\n\nDocumentation:\nReturns the standard name for the given integer value, if it exists.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_standard_name(name: u32) -> Option {\n if name < NUM_STANDARD_NAMES {\n Some(Name(name))\n } else {\n None\n }\n}\n```"}], "func_name": "get_standard_name", "docstring": "Returns the standard name for the given integer value, if it exists.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "36ea4433f73cbafb8260bf429d869af5556c83d88553c7e6a2ff90a85dcd21d6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_standard_name\n\nDocumentation:\nReturns whether the given name is a standard name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_standard_name(name: Name) -> bool {\n name.0 < NUM_STANDARD_NAMES\n}\n```"}], "func_name": "is_standard_name", "docstring": "Returns whether the given name is a standard name.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0c1b51af78ae36d32a5e7b131c905c46b8e976a376848c9dd0e8326a6558929d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_standard_value\n\nDocumentation:\nReturns whether a standard value corresponds to the given name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_standard_value(name: Name) -> bool {\n name.0 < NUM_STANDARD_VALUES\n}\n```"}], "func_name": "is_standard_value", "docstring": "Returns whether a standard value corresponds to the given name.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48a8c06976e3604c6fdf2aa8b9e997ff38c3af08734d53ae23a6fd6ae6459cf9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_system_fn\n\nDocumentation:\nReturns the system function for the given name, if one exists.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_system_fn(name: Name) -> Option<&'static SystemFn> {\n SYSTEM_FNS.get(name.0 as usize)\n}\n```"}], "func_name": "get_system_fn", "docstring": "Returns the system function for the given name, if one exists.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9fefd003175cad533227b5f52ad50f0d2f8f5fc87c8d1213707689baccb9e54e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_system_fn\n\nDocumentation:\nReturns whether the given name corresponds to a system function.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_system_fn(name: Name) -> bool {\n name.0 < NUM_SYSTEM_FNS as u32\n}\n```"}], "func_name": "is_system_fn", "docstring": "Returns whether the given name corresponds to a system function.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b788efdaa2f709609367e3b4a7c08f6be549b1ab61606874853afb9683b225db"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_system_operator\n\nDocumentation:\nReturns whether the given name corresponds to a system operator.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_system_operator(name: Name) -> bool {\n name.0 >= SYSTEM_OPERATORS_BEGIN && name.0 < SYSTEM_OPERATORS_END\n}\n```"}], "func_name": "is_system_operator", "docstring": "Returns whether the given name corresponds to a system operator.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e1f960ed056a7a17bbce7f58ee022b42b02d1ad019f9f34133a1a42d99a772f2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `NameInputConversion` from a local-to-global mapping.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new() -> NameInputConversion {\n NameInputConversion{\n map: HashMap::new(),\n next_value: NUM_STANDARD_NAMES,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `NameInputConversion` from a local-to-global mapping.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c20a57e88cf17212a974c1c26919968ac662d2257e1b4ef9444874c701207736"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturns the global name value for the given module-local value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(&self, name: u32) -> Option {\n get_standard_name(name).or_else(|| self.map.get(&name).cloned())\n }\n```"}], "func_name": "get", "docstring": "Returns the global name value for the given module-local value.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "639265291825517967e78500c00b9929bb36d43b6969ca5f0949a393fb50eb14"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nInsert a global name value into the map.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert(&mut self, name: Name) {\n self.map.insert(self.next_value, name);\n self.next_value += 1;\n }\n```"}], "func_name": "insert", "docstring": "Insert a global name value into the map.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f4bb2fb06f26ffc0929bf96fb896a7983a96e960c8f150329eb1ef3fef1359d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `NameOutputConversion`, using the given `NameStore`\nto lookup global name values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(store: &NameStore) -> NameOutputConversion {\n NameOutputConversion{\n names: Vec::new(),\n map: HashMap::new(),\n store,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `NameOutputConversion`, using the given `NameStore`\nto lookup global name values.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5c9f92013ec943503816c99f82c9d8abb606752d725cc1dbfdfcaf6901708b30"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add\n\nDocumentation:\nAdds a name to the collection and returns a module-local value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add(&mut self, name: Name) -> u32 {\n if is_standard_name(name) {\n name.0\n } else {\n let names = &mut self.names;\n let store = self.store;\n *self.map.entry(name).or_insert_with(|| {\n let name = store.get(name);\n let n = names.len();\n names.push(name);\n n as u32 + NUM_STANDARD_NAMES\n })\n }\n }\n```"}], "func_name": "add", "docstring": "Adds a name to the collection and returns a module-local value.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eda2756cff0b03a98fc8bc954444546d78381012ac9f775f02939ddfb432d855"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add\n\nDocumentation:\nAdds a name to the `NameStore` if it is not present.\nReturns a `Name` value to refer to the new or existing name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add(&mut self, name: &str) -> Name {\n if let Some(name) = get_standard_name_for(name) {\n name\n } else if let Some(pos) = self.iter().position(|n| n == name) {\n Name(pos as u32 + NUM_STANDARD_NAMES)\n } else {\n let n = self.names.len();\n self.names.push(name.to_owned().into_boxed_str());\n Name(n as u32 + NUM_STANDARD_NAMES)\n }\n }\n```"}], "func_name": "add", "docstring": "Adds a name to the `NameStore` if it is not present.\nReturns a `Name` value to refer to the new or existing name.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ca0d1bdbc1d36a6215f9407ca88bed9d6ae918cac75802a86f325d22299424a0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_name\n\nDocumentation:\nReturns the `Name` value of a given string, if it exists.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_name(&self, name: &str) -> Option {\n if let Some(pos) = self.iter().position(|n| n == name) {\n Some(Name(pos as u32 + NUM_STANDARD_NAMES))\n } else {\n None\n }\n }\n```"}], "func_name": "get_name", "docstring": "Returns the `Name` value of a given string, if it exists.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d30f27e4966ebb71cc069fa7351d3555f95ca4e79e1b3890553bde4cd6de5d8d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturns the string representation of an interned name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(&self, name: Name) -> &str {\n if name == Name::dummy() {\n \"\"\n } else {\n standard_name(name)\n .or_else(|| self.names.get((name.0 - NUM_STANDARD_NAMES) as usize)\n .map(|s| &s[..]))\n .unwrap_or(\"\")\n }\n }\n```"}], "func_name": "get", "docstring": "Returns the string representation of an interned name.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6409b72ca4ac97ac9cdc57818c1fe47c6a73d8dee72e8c87f3281237d885b4b0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: contains_key\n\nDocumentation:\nReturns whether the map contains a value for the given name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn contains_key(&self, name: Name) -> bool {\n self.values.binary_search_by(|&(ref n, _)| n.cmp(&name)).is_ok()\n }\n```"}], "func_name": "contains_key", "docstring": "Returns whether the map contains a value for the given name.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "58c3cd39c70d343370a8cb756df297829222aafa05df2f92e15c67da583d29dd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturns the value corresponding to the given name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(&self, name: Name) -> Option<&T> {\n self.values.binary_search_by(|&(ref n, _)| n.cmp(&name))\n .ok().map(|pos| &self.values[pos].1)\n }\n```"}], "func_name": "get", "docstring": "Returns the value corresponding to the given name.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "48a1431a0f064e4f604b38fa6aa16c121399afc809ca4ebc18e4883623f91507"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nInsert a name-value pair into the map.\nIf a value was already present for the name, it is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert(&mut self, name: Name, value: T) -> Option {\n match self.values.binary_search_by(|&(ref n, _)| n.cmp(&name)) {\n Ok(pos) => {\n let old = replace(&mut self.values[pos].1, value);\n Some(old)\n }\n Err(pos) => {\n self.values.insert(pos, (name, value));\n None\n }\n }\n }\n```"}], "func_name": "insert", "docstring": "Insert a name-value pair into the map.\nIf a value was already present for the name, it is returned.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c8bcc121885725c0a9b4a39c8298641d44a26d5008b7d31e40bcb1e2d7757da7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a `NameMapSlice` wrapping the given boxed slice,\nwhich must already be sorted by name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(values: Box<[(Name, T)]>) -> NameMapSlice {\n NameMapSlice{ values }\n }\n```"}], "func_name": "new", "docstring": "Creates a `NameMapSlice` wrapping the given boxed slice,\nwhich must already be sorted by name.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "41ddaa7d3569ce674708b3f53dbb879d459e883d77c67d1d905ea3f2b57882bd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: index\n\nDocumentation:\nReturns the index within the internal `Vec` of the given key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn index(&self, name: Name) -> Option {\n self.values.binary_search_by(|&(n, _)| n.cmp(&name)).ok()\n }\n```"}], "func_name": "index", "docstring": "Returns the index within the internal `Vec` of the given key.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4be304ba2cbce99d500a4c076bd725c112446280d5990cf9178a5849c7228a23"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set\n\nDocumentation:\nOverwrites the value for the given name.\n\nReturns `None` if the name does not exist in the mapping.\nWhen `None` is returned, no value will have been stored in the mapping.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set(&mut self, name: Name, value: T) -> Option {\n match self.values.binary_search_by(|&(n, _)| n.cmp(&name)) {\n Ok(n) => Some(replace(&mut self.values[n].1, value)),\n Err(_) => None\n }\n }\n```"}], "func_name": "set", "docstring": "Overwrites the value for the given name.\n\nReturns `None` if the name does not exist in the mapping.\nWhen `None` is returned, no value will have been stored in the mapping.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e9c4908412fef38e61c5d380134fbeebe0c9b4e5d5b7d10c5457edb3b8024456"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_name_map\n\nDocumentation:\nElevates the map into `NameMap`, which may receive new key-value pairs.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_name_map(self) -> NameMap {\n NameMap{values: self.values.into_vec()}\n }\n```"}], "func_name": "into_name_map", "docstring": "Elevates the map into `NameMap`, which may receive new key-value pairs.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b79d3d539d4f64b465ccc299aa68839254088f0ce0ef05526475dfa5c13aa418"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: insert\n\nDocumentation:\nInserts the given name into the set.\nReturns `true` if the name was not already contained.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn insert(&mut self, name: Name) -> bool {\n self.map.insert(name, ()).is_none()\n }\n```"}], "func_name": "insert", "docstring": "Inserts the given name into the set.\nReturns `true` if the name was not already contained.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f27008bc48810a144de385c47da3395b694e7afd590fc66beb4434fe6363108"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a `NameSetSlice` wrapping the given boxed slice,\nwhich must already be sorted.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn new(map: NameMapSlice<()>) -> NameSetSlice {\n NameSetSlice{ map }\n }\n```"}], "func_name": "new", "docstring": "Creates a `NameSetSlice` wrapping the given boxed slice,\nwhich must already be sorted.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1ac07b7da9e52e66485aa1bda8a9c232a873c56cac524c4c55d7ae3448437f8c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_name_set\n\nDocumentation:\nElevates the set into a `NameSet`, which may receive new name values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_name_set(self) -> NameSet {\n NameSet{map: self.map.into_name_map()}\n }\n```"}], "func_name": "into_name_set", "docstring": "Elevates the set into a `NameSet`, which may receive new name values.", "repo": "murarth/ketos", "path": "src/ketos/name.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/name.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54f28454a6ada3eb6c608ee6ff784969028ab7bda64297a92a666358224a8cd4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `Parser` using the given `Lexer`.\nIdentifiers received from the lexer will be inserted into the given context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(ctx: &'a Context, lexer: Lexer<'lex>) -> Parser<'a, 'lex> {\n Parser{\n lexer,\n ctx,\n name_cache: HashMap::new(),\n cur_token: None,\n }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `Parser` using the given `Lexer`.\nIdentifiers received from the lexer will be inserted into the given context.", "repo": "murarth/ketos", "path": "src/ketos/parser.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "94f03cb1c19bf5a410ec18d77c0628c624b0ef769268bf01a65661212cf65b46"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_expr\n\nDocumentation:\nParses an expression from the input stream.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_expr(&mut self) -> Result {\n let mut stack = Vec::new();\n let mut total_backticks = 0;\n\n loop {\n if stack.len() >= self.ctx.restrict().max_syntax_nesting {\n return Err(From::from(RestrictError::MaxSyntaxNestingExceeded));\n }\n\n let mut doc = self.read_doc_comment()?;\n\n let (sp, tok) = self.next()?;\n\n let r = match tok {\n Token::DocComment(_) =>\n return Err(From::from(ParseError::new(\n doc.unwrap().0, ParseErrorKind::CannotDocumentItem))),\n Token::LeftParen => {\n if let Some((doc_sp, _)) = doc {\n match self.peek()? {\n (_, Token::Name(\"const\")) |\n (_, Token::Name(\"define\")) |\n (_, Token::Name(\"lambda\")) |\n (_, Token::Name(\"macro\")) |\n (_, Token::Name(\"struct\"))\n => (),\n _ => return Err(From::from(ParseError::new(\n doc_sp, ParseErrorKind::CannotDocumentItem)))\n }\n }\n\n stack.push(Group::Parens(Vec::new(), doc.take()));\n continue;\n }\n Token::RightParen => {\n let group = stack.pop().ok_or_else(\n || ParseError::new(sp, ParseErrorKind::UnmatchedParen))?;\n\n match group {\n Group::Parens(values, doc) =>\n insert_doc_comment(values, doc)\n .map_err(From::from),\n _ => Err(From::from(ParseError::new(sp,\n ParseErrorKind::UnexpectedToken{\n expected: \"expression\",\n found: \")\",\n })))\n }\n }\n Token::Float(f) => parse_float(f)\n .map(Value::Float)\n .map_err(|kind| From::from(ParseError::new(sp, kind))),\n Token::Integer(i, base) => parse_integer(self.ctx, i, base, sp)\n .map(Value::Integer),\n Token::Ratio(r) => parse_ratio(self.ctx, r, sp)\n .map(Value::Ratio),\n Token::Char(ch) => parse_char(ch)\n .map(Value::Char).map_err(From::from),\n Token::String(s) => parse_string(s)\n .map(|s| s.into()).map_err(From::from),\n Token::Byte(b) => parse_byte(b)\n .map(|v| v.into()).map_err(From::from),\n Token::Bytes(b) => parse_bytes(b)\n .map(Value::Bytes).map_err(From::from),\n Token::Path(p) => parse_path(p)\n .map(|p| p.into()).map_err(From::from),\n Token::Name(name) => Ok(self.name_value(name)),\n Token::Keyword(name) => Ok(Value::Keyword(self.add_name(name))),\n Token::BackQuote => {\n total_backticks += 1;\n if let Some(&mut Group::Backticks(ref mut n)) = stack.last_mut() {\n *n += 1;\n continue;\n }\n stack.push(Group::Backticks(1));\n continue;\n }\n Token::Comma => {\n if total_backticks <= 0 {\n return Err(From::from(ParseError::new(sp, ParseErrorKind::UnbalancedComma)));\n }\n total_backticks -= 1;\n if let Some(&mut Group::Backticks(ref mut n)) = stack.last_mut() {\n *n -= 1;\n continue;\n }\n stack.push(Group::Backticks(-1));\n continue;\n }\n Token::CommaAt => {\n if total_backticks <= 0 {\n return Err(From::from(ParseError::new(sp, ParseErrorKind::UnbalancedComma)));\n }\n total_backticks -= 1;\n stack.push(Group::CommaAt);\n continue;\n }\n Token::Quote => {\n if let Some(&mut Group::Quotes(ref mut n)) = stack.last_mut() {\n *n += 1;\n continue;\n }\n stack.push(Group::Quotes(1));\n continue;\n }\n Token::End => {\n if let Some((doc_sp, _)) = doc {\n return Err(From::from(ParseError::new(doc_sp,\n ParseErrorKind::DocCommentEof)));\n }\n\n let any_paren = stack.iter().any(|group| {\n match *group {\n Group::Parens(_, _) => true,\n _ => false\n }\n });\n\n if any_paren {\n Err(From::from(ParseError::new(sp,\n ParseErrorKind::MissingCloseParen)))\n } else {\n Err(From::from(ParseError::new(sp,\n ParseErrorKind::UnexpectedEof)))\n }\n }\n };\n\n if let Some((doc_sp, _)) = doc {\n return Err(From::from(ParseError::new(doc_sp,\n ParseErrorKind::CannotDocumentItem)));\n }\n\n let mut v = r?;\n\n loop {\n match stack.last_mut() {\n None => return Ok(v),\n Some(&mut Group::Parens(ref mut values, _)) => {\n values.push(v);\n break;\n }\n _ => ()\n }\n\n let group = stack.pop().unwrap();\n\n match group {\n // 0 backticks is ignored, but must still be considered\n // a group because an expression must follow.\n Group::Backticks(n) if n > 0 => {\n total_backticks -= n;\n v = v.quasiquote(n as u32);\n }\n Group::Backticks(n) if n < 0 => {\n total_backticks -= n; // Subtracting a negative\n v = v.comma((-n) as u32);\n }\n Group::CommaAt => {\n total_backticks += 1;\n v = v.comma_at(1);\n }\n Group::Quotes(n) => v = v.quote(n),\n _ => ()\n }\n }\n }\n }\n```"}], "func_name": "parse_expr", "docstring": "Parses an expression from the input stream.", "repo": "murarth/ketos", "path": "src/ketos/parser.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8772b465750f8cb79e0fa130d9e4c1fd644a84533e8a0dd73a5c964ee9844b53"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_single_expr\n\nDocumentation:\nParses a single expression from the input stream.\nIf any tokens remain after the expression, an error is returned.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_single_expr(&mut self) -> Result {\n let expr = self.parse_expr()?;\n\n match self.next()? {\n (_, Token::End) => Ok(expr),\n (sp, tok) => Err(From::from(ParseError::new(sp, ParseErrorKind::UnexpectedToken{\n expected: \"eof\",\n found: tok.name(),\n })))\n }\n }\n```"}], "func_name": "parse_single_expr", "docstring": "Parses a single expression from the input stream.\nIf any tokens remain after the expression, an error is returned.", "repo": "murarth/ketos", "path": "src/ketos/parser.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "443291c4a617d0e3d55789154a46d06b356ed44ce8f3491798c1babdee158a47"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: parse_exprs\n\nDocumentation:\nParse a series of expressions from the input stream.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn parse_exprs(&mut self) -> Result, Error> {\n let mut res = Vec::new();\n\n if let Some((_, doc)) = self.read_module_doc_comment()? {\n res.push(vec![\n Value::Name(standard_names::SET_MODULE_DOC),\n format_doc_comment(doc).into(),\n ].into());\n }\n\n loop {\n match self.peek()? {\n (_sp, Token::End) => break,\n _ => res.push(self.parse_expr()?)\n }\n }\n\n Ok(res)\n }\n```"}], "func_name": "parse_exprs", "docstring": "Parse a series of expressions from the input stream.", "repo": "murarth/ketos", "path": "src/ketos/parser.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "44dc4ef0669aa78a8ebdce1a3fe048b6fdf8cceb70864bf55659015a23c004f0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_doc_comment\n\nDocumentation:\nReturns the the next token if it is a doc comment.\nOtherwise, `None` is returned and no token is consumed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_doc_comment(&mut self)\n -> Result, ParseError> {\n match self.peek()? {\n (sp, Token::DocComment(doc)) => {\n self.cur_token.take();\n Ok(Some((sp, doc)))\n }\n _ => Ok(None)\n }\n }\n```"}], "func_name": "read_doc_comment", "docstring": "Returns the the next token if it is a doc comment.\nOtherwise, `None` is returned and no token is consumed.", "repo": "murarth/ketos", "path": "src/ketos/parser.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "77543079f35504ef0adc3ee6ae34fdbc9689219d5cbc5ba979db7cb3a54d5baa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_module_doc_comment\n\nDocumentation:\nReturns the content of the next token if it is a module-level doc\ncomment, one beginning with at least three semicolon characters.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn read_module_doc_comment(&mut self)\n -> Result, ParseError> {\n match self.peek()? {\n (sp, Token::DocComment(doc)) if doc.starts_with(MODULE_DOC_COMMENT) => {\n self.cur_token.take();\n Ok(Some((sp, doc)))\n }\n _ => Ok(None)\n }\n }\n```"}], "func_name": "read_module_doc_comment", "docstring": "Returns the content of the next token if it is a module-level doc\ncomment, one beginning with at least three semicolon characters.", "repo": "murarth/ketos", "path": "src/ketos/parser.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "50bde7e77f0a678bc82b32064e5f061b9004d995d3ed81b33bcd7b2e52bff580"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: peek\n\nDocumentation:\nReturns the next token without consuming it\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn peek(&mut self) -> Result<(Span, Token<'lex>), ParseError> {\n if let Some(tok) = self.cur_token {\n Ok(tok)\n } else {\n let tok = self.lexer.next_token()?;\n self.cur_token = Some(tok);\n Ok(tok)\n }\n }\n```"}], "func_name": "peek", "docstring": "Returns the next token without consuming it", "repo": "murarth/ketos", "path": "src/ketos/parser.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/parser.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "84621228dce643f756a6b785845516aaa46497718e1b12bc554dc1b4a5784afc"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: pretty_print\n\nDocumentation:\nWrites a human-readable representation of a `Value` to the given `fmt::Write`.\n\n`indent` specifies the base indentation for items contained within lists.\nIndentation is not applied to the top level value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn pretty_print(w: &mut W, names: &NameStore, v: &Value, indent: u32) -> fmt::Result {\n match *v {\n Value::List(ref li) => {\n let mut iter = li.iter();\n\n let first = iter.next().expect(\"empty list value\");\n\n let sub_indent = match *first {\n Value::Name(_) => indent + 2,\n _ => indent + 1\n };\n\n w.write_char('(')?;\n pretty_print(w, names, first, indent)?;\n\n if is_short_args(&li[1..]) {\n for v in iter {\n w.write_char(' ')?;\n pretty_print(w, names, v, sub_indent)?;\n }\n } else {\n while let Some(v) = iter.next() {\n w.write_char('\\n')?;\n write_indent(w, sub_indent)?;\n pretty_print(w, names, v, sub_indent)?;\n\n // Pair keywords with their arguments\n if let Value::Keyword(_) = *v {\n if let Some(v) = iter.next() {\n w.write_char(' ')?;\n pretty_print(w, names, v, sub_indent)?;\n }\n }\n }\n }\n\n w.write_char(')')\n }\n _ => write!(w, \"{}\", debug_names(names, v))\n }\n}\n```"}], "func_name": "pretty_print", "docstring": "Writes a human-readable representation of a `Value` to the given `fmt::Write`.\n\n`indent` specifies the base indentation for items contained within lists.\nIndentation is not applied to the top level value.", "repo": "murarth/ketos", "path": "src/ketos/pretty.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/pretty.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e4c2c835d02311ea7d5b20a1c982a6db456fea11fd0d6ddf4e42e6f00242f6f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_string\n\nDocumentation:\nConsumes the `RcString` and returns a `String`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_string(self) -> String {\n match Rc::try_unwrap(self.data) {\n Ok(mut s) => {\n let _ = s.drain(self.end..);\n let _ = s.drain(..self.start);\n s\n }\n Err(data) => data[self.start..self.end].to_owned()\n }\n }\n```"}], "func_name": "into_string", "docstring": "Consumes the `RcString` and returns a `String`.", "repo": "murarth/ketos", "path": "src/ketos/rc_vec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/rc_vec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6265c8be226b0e4f1918612e1af25fafbcac6aa4619b0afc92dcdd52d6a5a2c6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push\n\nDocumentation:\nPushes a `char` to the end of the contained `String`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn push(&mut self, ch: char) {\n self.make_mut().push(ch);\n self.end += ch.len_utf8();\n }\n```"}], "func_name": "push", "docstring": "Pushes a `char` to the end of the contained `String`.", "repo": "murarth/ketos", "path": "src/ketos/rc_vec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/rc_vec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f467d80a47d281ad1bd80c9e59176b290654b0734896e7d7d1f771ca37205ae5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push_str\n\nDocumentation:\nPushes a `&str` to the end of the contained `String`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn push_str(&mut self, s: &str) {\n self.make_mut().push_str(s);\n self.end += s.len();\n }\n```"}], "func_name": "push_str", "docstring": "Pushes a `&str` to the end of the contained `String`.", "repo": "murarth/ketos", "path": "src/ketos/rc_vec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/rc_vec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0f84c987b784e625d0776e7a11de02bbb1e3b225ea22e38325cb607ee48bbfd7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: slice\n\nDocumentation:\nReturns a subslice of the `RcVec`, with the range being relative\nto this slice's boundaries.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn slice>(&self, range: R) -> RcVec {\n let start = range.start().map_or(0, |v| *v);\n let end = range.end().map_or(self.len(), |v| *v);\n\n let a = self.start + start;\n let b = self.start + end;\n\n if a > self.end {\n panic!(\"RcVec slice out of bounds; start is {} but length is {}\",\n start, self.len());\n }\n\n if b > self.end {\n panic!(\"RcVec slice out of bounds; end is {} but length is {}\",\n end, self.len());\n }\n\n RcVec{\n data: self.data.clone(),\n start: a,\n end: b,\n }\n }\n```"}], "func_name": "slice", "docstring": "Returns a subslice of the `RcVec`, with the range being relative\nto this slice's boundaries.", "repo": "murarth/ketos", "path": "src/ketos/rc_vec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/rc_vec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "25875887d9b213b10beb184d6f4991a566a174ef295b21d7167d4fe8cb8c0d7f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: into_vec\n\nDocumentation:\nConsumes the `RcVec` and returns the contained `Vec`.\nThis will clone the contained values unless the data was uniquely held.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn into_vec(self) -> Vec {\n match Rc::try_unwrap(self.data) {\n Ok(mut v) => {\n let _ = v.drain(self.end..);\n let _ = v.drain(..self.start);\n v\n }\n Err(data) => data[self.start..self.end].to_vec()\n }\n }\n```"}], "func_name": "into_vec", "docstring": "Consumes the `RcVec` and returns the contained `Vec`.\nThis will clone the contained values unless the data was uniquely held.", "repo": "murarth/ketos", "path": "src/ketos/rc_vec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/rc_vec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b9071eae8b85771216c574bf6098cac765f93117e9bcf8bc056098c03b11d29b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_mut\n\nDocumentation:\nMakes wrapped data unique and returns a mutable reference,\nafter adjusting `start` and `end` fields.\n\n# Note\n\nIf the length of the `Vec` is modified, the `end` field of `RcVec`\nmust be adjusted manually. That's why this method is private.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn make_mut(&mut self) -> &mut Vec {\n let v = Rc::make_mut(&mut self.data);\n\n let _ = v.drain(self.end..);\n let _ = v.drain(..self.start);\n let n = v.len();\n\n self.start = 0;\n self.end = n;\n\n v\n }\n```"}], "func_name": "make_mut", "docstring": "Makes wrapped data unique and returns a mutable reference,\nafter adjusting `start` and `end` fields.\n\n# Note\n\nIf the length of the `Vec` is modified, the `end` field of `RcVec`\nmust be adjusted manually. That's why this method is private.", "repo": "murarth/ketos", "path": "src/ketos/rc_vec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/rc_vec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a03f294b8cbffe07bff3c543393995adbdecb09ee415cddb32834b5134b5caf2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: push\n\nDocumentation:\nPushes a value into the contained `Vec`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn push(&mut self, t: T) {\n self.make_mut().push(t);\n self.end += 1;\n }\n```"}], "func_name": "push", "docstring": "Pushes a value into the contained `Vec`.", "repo": "murarth/ketos", "path": "src/ketos/rc_vec.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/rc_vec.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8cd0f471add83679723a43ce09f6597e81acc48b54d832fa91471787beef7723"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: description\n\nDocumentation:\nReturns a string describing the error that occurred.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn description(self) -> &'static str {\n use self::RestrictError::*;\n\n match self {\n ExecutionTimeExceeded => \"execution time exceeded\",\n CallStackExceeded => \"max call stack exceeded\",\n ValueStackExceeded => \"max value stack exceeded\",\n NamespaceSizeExceeded => \"max namespace size exceeded\",\n MemoryLimitExceeded => \"max memory limit exceeded\",\n IntegerLimitExceeded => \"integer size limit exceeded\",\n MaxSyntaxNestingExceeded => \"max syntax nesting exceeded\",\n }\n }\n```"}], "func_name": "description", "docstring": "Returns a string describing the error that occurred.", "repo": "murarth/ketos", "path": "src/ketos/restrict.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/restrict.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c1f30f1ecaa00756d35ffc45f63d14f44984b444f7bfac22bf8672af5c4d5276"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: permissive\n\nDocumentation:\nReturns a `RestrictConfig` that is most permissive.\n\nNo restrictions are placed on executing code.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn permissive() -> RestrictConfig {\n RestrictConfig{\n execution_time: None,\n call_stack_size: PERMISSIVE_CALL_STACK_SIZE,\n value_stack_size: PERMISSIVE_VALUE_STACK_SIZE,\n namespace_size: usize::max_value(),\n memory_limit: usize::max_value(),\n max_integer_size: usize::max_value(),\n max_syntax_nesting: usize::max_value(),\n }\n }\n```"}], "func_name": "permissive", "docstring": "Returns a `RestrictConfig` that is most permissive.\n\nNo restrictions are placed on executing code.", "repo": "murarth/ketos", "path": "src/ketos/restrict.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/restrict.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "41a5ec992878a0b57d3c09ca4240d655f12b75c5a45dcb892705ed80b3a70fe4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: strict\n\nDocumentation:\nReturns a `RestrictConfig` that is most strict.\n\nSmall programs with short runtimes should not have a problem operating\nwithin these restrictions.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn strict() -> RestrictConfig {\n RestrictConfig{\n execution_time: Some(Duration::from_millis(100)),\n call_stack_size: STRICT_CALL_STACK_SIZE,\n value_stack_size: STRICT_VALUE_STACK_SIZE,\n namespace_size: 32,\n memory_limit: STRICT_VALUE_STACK_SIZE,\n max_integer_size: 100,\n max_syntax_nesting: 32,\n }\n }\n```"}], "func_name": "strict", "docstring": "Returns a `RestrictConfig` that is most strict.\n\nSmall programs with short runtimes should not have a problem operating\nwithin these restrictions.", "repo": "murarth/ketos", "path": "src/ketos/restrict.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/restrict.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "72e67efe845be3a70b29b8e7e15fc3cca8105a33a67faa777d30ca3ad1d060d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: run_code\n\nDocumentation:\nParses, compiles, and executes the given code within a context.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn run_code(ctx: &Context, input: &str) -> Result {\n let offset = ctx.scope().borrow_codemap_mut().add_source(input, None);\n\n let exprs = {\n let mut p = Parser::new(ctx, Lexer::new(input, offset));\n\n p.parse_exprs()?\n };\n\n let code = exprs.iter()\n .map(|v| compile(ctx, v))\n .collect::, _>>()?;\n\n let mut r = Value::Unit;\n\n for c in code {\n r = execute(ctx, Rc::new(c))?;\n }\n\n Ok(r)\n}\n```"}], "func_name": "run_code", "docstring": "Parses, compiles, and executes the given code within a context.", "repo": "murarth/ketos", "path": "src/ketos/run.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/run.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7070a5fad1eec0a51749f70d4a4362ad0bbdeda900e85192bee7d4ecaf4c0153"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConvenience method to create an empty `ImportSet` for the named module.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(module_name: Name) -> ImportSet {\n ImportSet{\n module_name,\n names: Vec::new(),\n }\n }\n```"}], "func_name": "new", "docstring": "Convenience method to create an empty `ImportSet` for the named module.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7862f4286cbcfd7ffdb6cc2b47ce0be63c754eeb3901dc25d33cc7fbf65257ee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: default\n\nDocumentation:\nCreates a new global scope with the given name and default environment.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn default(name: &str) -> GlobalScope {\n let mut names = NameStore::new();\n let name = names.add(name);\n\n let names = Rc::new(RefCell::new(names));\n let codemap = Rc::new(RefCell::new(CodeMap::new()));\n let modules = Rc::new(ModuleRegistry::new(Box::new(BuiltinModuleLoader)));\n let io = Rc::new(GlobalIo::default());\n let struct_defs = Rc::new(RefCell::new(StructDefMap::new()));\n\n GlobalScope::new(name, names, codemap, modules, io, struct_defs)\n }\n```"}], "func_name": "default", "docstring": "Creates a new global scope with the given name and default environment.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "090daed76c674045dd750e4d7dec0806366f5d49e8f4e5765c9b9b2073b46a34"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new_using\n\nDocumentation:\nCreates a new global scope using the shared data from the given scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new_using(name: Name, scope: &Scope) -> Scope {\n Rc::new(GlobalScope::new(\n name,\n scope.name_store.clone(),\n scope.codemap.clone(),\n scope.modules.clone(),\n scope.io.clone(),\n scope.struct_defs.clone()))\n }\n```"}], "func_name": "new_using", "docstring": "Creates a new global scope using the shared data from the given scope.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8d602a3b101076e8293c8e18993c527bbe0ba17c306ad73f2c71190f1a3f09ca"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clone_scope\n\nDocumentation:\nCreates a semi-\"deep\" clone of the `GlobalScope` object.\n\nAll constants, macros, and values will be cloned into the new scope.\n\nOther data will be shared between this scope and the new scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clone_scope(&self) -> Scope {\n Rc::new(GlobalScope{\n name: self.name,\n namespace: self.namespace.clone(),\n name_store: self.name_store.clone(),\n codemap: self.codemap.clone(),\n modules: self.modules.clone(),\n io: self.io.clone(),\n struct_defs: self.struct_defs.clone(),\n })\n }\n```"}], "func_name": "clone_scope", "docstring": "Creates a semi-\"deep\" clone of the `GlobalScope` object.\n\nAll constants, macros, and values will be cloned into the new scope.\n\nOther data will be shared between this scope and the new scope.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9df775a7883012e7c13201ec47b326e36d7235714c4a147b1e9a6053ce3c8702"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_constant\n\nDocumentation:\nAdds a named constant value to the scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_constant(&self, name: Name, value: Value) {\n self.namespace.borrow_mut().constants.insert(name, value);\n }\n```"}], "func_name": "add_constant", "docstring": "Adds a named constant value to the scope.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c62cb390c3dcff12634fff5a58121af41458bbbf82e7bc095f112cb85dbeb518"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_doc_string\n\nDocumentation:\nAdds a docstring for the named constant or value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_doc_string(&self, name: Name, doc: String) {\n self.namespace.borrow_mut().docs.insert(name, doc);\n }\n```"}], "func_name": "add_doc_string", "docstring": "Adds a docstring for the named constant or value.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b9ed757dce22e76e2310eabda25b2104b482638644408afb34e1dd7cc2411876"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_macro\n\nDocumentation:\nAdds a macro function to the global scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_macro(&self, name: Name, lambda: Lambda) {\n self.namespace.borrow_mut().macros.insert(name, lambda);\n }\n```"}], "func_name": "add_macro", "docstring": "Adds a macro function to the global scope.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "83c3b8d46f9725f67c5036ffef64155fe450b870ca35385fd7198f0f371d9043"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_value\n\nDocumentation:\nAdds a value to the global scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_value(&self, name: Name, value: Value) {\n self.namespace.borrow_mut().values.insert(name, value);\n }\n```"}], "func_name": "add_value", "docstring": "Adds a value to the global scope.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5f2039cac5da5eae9b241b4095d5a98d8db9c8a8ccb2537e8b8737b5097ef957"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_named_value\n\nDocumentation:\nAdds a value with the given name to the global scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_named_value(&self, name: &str, value: Value) {\n let name = self.name_store.borrow_mut().add(name);\n self.add_value(name, value);\n }\n```"}], "func_name": "add_named_value", "docstring": "Adds a value with the given name to the global scope.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "17f5c1cccdaaa0baf3cabb3f9843c0ce120b318ba6e6821ec5b2011a909f51c8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_value_with_name\n\nDocumentation:\nAdds a value to the global scope. The `Name` value for the given\nstring representation is passed to the given closure to create the value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_value_with_name(&self, name: &str, f: F)\n where F: FnOnce(Name) -> Value {\n let name = self.name_store.borrow_mut().add(name);\n self.add_value(name, f(name));\n }\n```"}], "func_name": "add_value_with_name", "docstring": "Adds a value to the global scope. The `Name` value for the given\nstring representation is passed to the given closure to create the value.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c779cae448d2b8b47098d1e70adc29972a345c35113d23b5e6ab7a3dddb78fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_named_constant\n\nDocumentation:\nReturns a named constant value, if present.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_named_constant(&self, name: &str) -> Option {\n let name = self.borrow_names().get_name(name);\n name.and_then(|name| self.get_constant(name))\n }\n```"}], "func_name": "get_named_constant", "docstring": "Returns a named constant value, if present.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "32ab83b35727df01c253d8c67340188d4e3ba0462c07fb997de3a82562238cee"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: register_struct_value\n\nDocumentation:\nCreates a `StructDef` for the given type, inserting the definition\ninto the global namespace.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn register_struct_value(&self) {\n let name = self.add_name(T::struct_name());\n\n let def = Rc::new(StructDef::new(name,\n Box::new(ForeignStructDef::::new(&mut self.name_store.borrow_mut()))));\n\n self.insert_struct_def(TypeId::of::(), def.clone());\n self.add_value(name, Value::StructDef(def));\n }\n```"}], "func_name": "register_struct_value", "docstring": "Creates a `StructDef` for the given type, inserting the definition\ninto the global namespace.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7b3bf7486b0bbe9a4f654ce74da1d0a0a788449192efd22d28f3c3e904b0c841"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: contains_name\n\nDocumentation:\nReturns whether the scope contains a given exportable name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn contains_name(&self, name: Name) -> bool {\n let ns = self.namespace.borrow();\n\n ns.constants.contains_key(name) ||\n ns.macros.contains_key(name) ||\n ns.values.contains_key(name)\n }\n```"}], "func_name": "contains_name", "docstring": "Returns whether the scope contains a given exportable name.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "311bdf225253ada10aaa8a4e67989f39f720ee27c7fe7ebfc5ad1e044b62e621"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_named_macro\n\nDocumentation:\nReturns a macro function for the given name, if present.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_named_macro(&self, name: &str) -> Option {\n let name = self.borrow_names().get_name(name);\n name.and_then(|name| self.get_macro(name))\n }\n```"}], "func_name": "get_named_macro", "docstring": "Returns a macro function for the given name, if present.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bcb4246b4e93c718789d2e74ac6fb0fe43d1d0d75d797fd15b042e5a7d76eb21"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_named_value\n\nDocumentation:\nReturns a `Value` for the given name, if present.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_named_value(&self, name: &str) -> Option {\n let name = self.borrow_names().get_name(name);\n name.and_then(|name| self.get_value(name))\n }\n```"}], "func_name": "get_named_value", "docstring": "Returns a `Value` for the given name, if present.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fd9816c8678313dfe2de90ef994ab6c1bfa456170a4810c84454095dba32faa3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: import_all\n\nDocumentation:\nClones all exported values from a scope into this scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn import_all(&self, other: &GlobalScope) -> Vec {\n self.namespace.borrow_mut()\n .import_all(&other.namespace.borrow())\n }\n```"}], "func_name": "import_all", "docstring": "Clones all exported values from a scope into this scope.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8dd4895784c0092fb43abae0189db9fe84dc792af7abaf985321fa5ef84547a5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: import_qualified\n\nDocumentation:\nImports all exported values from a scope into this scope,\nprefixing the name of the scope to the name of each imported value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn import_qualified(&self, other: &GlobalScope) -> Vec<(Name, Name)> {\n let mut names = self.name_store.borrow_mut();\n let prefix = names.get(other.name).to_owned();\n\n self.namespace.borrow_mut().import_qualified(\n &prefix, &mut *names, &other.namespace.borrow())\n }\n```"}], "func_name": "import_qualified", "docstring": "Imports all exported values from a scope into this scope,\nprefixing the name of the scope to the name of each imported value.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a7e1bff291d2564457d801fbb521f8957e40dfe8286a2b484ca83cbcae976d58"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_exported\n\nDocumentation:\nReturns whether the given name has been exported in this scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_exported(&self, name: Name) -> bool {\n self.namespace.borrow().exports.as_ref()\n .map_or(false, |e| e.contains(name))\n }\n```"}], "func_name": "is_exported", "docstring": "Returns whether the given name has been exported in this scope.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d60f28a0c244d6d82e0546668d9a9fdbb70785e947051b9e56dc61a9acd0ad97"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_exports\n\nDocumentation:\nAssigns a set of exported names for this scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_exports(&self, names: NameSetSlice) {\n self.namespace.borrow_mut().exports = Some(names);\n }\n```"}], "func_name": "set_exports", "docstring": "Assigns a set of exported names for this scope.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bffc6df9f023e527a86f881040c7aa644ec13f713a9ee1789de4bbf25e37a3c2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_doc\n\nDocumentation:\nCalls a closure with a borrowed reference to the named documentation,\nif present.\n\n# Note\n\nWhen a function is declared with a docstring, that docstring is stored\nin the compiled `Code` object rather than the `GlobalScope`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_doc(&self, name: Name, f: F) -> Option\n where F: FnOnce(&str) -> R {\n let ns = self.namespace.borrow();\n ns.docs.get(name).map(|s| f(s))\n }\n```"}], "func_name": "with_doc", "docstring": "Calls a closure with a borrowed reference to the named documentation,\nif present.\n\n# Note\n\nWhen a function is declared with a docstring, that docstring is stored\nin the compiled `Code` object rather than the `GlobalScope`.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e1f7c3de61027deac9f0fc318e4833580093cac87505310f3664526c117f5d92"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_docs\n\nDocumentation:\nCalls a closure with a borrowed reference to the contained docstrings.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_docs(&self, f: F) -> R\n where F: FnOnce(&NameMap) -> R {\n let ns = self.namespace.borrow();\n f(&ns.docs)\n }\n```"}], "func_name": "with_docs", "docstring": "Calls a closure with a borrowed reference to the contained docstrings.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "051c904a15044cfe761e5e5898018ab8c642177e99ce9165a8d151d93f661633"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_docs_mut\n\nDocumentation:\nCalls a closure with a mutable reference to the contained docstrings.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_docs_mut(&self, f: F) -> R\n where F: FnOnce(&mut NameMap) -> R {\n let mut ns = self.namespace.borrow_mut();\n f(&mut ns.docs)\n }\n```"}], "func_name": "with_docs_mut", "docstring": "Calls a closure with a mutable reference to the contained docstrings.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cfd95d9aa26d03c8d658fc1700bdd5d62268a9233ade40c0515e79014e58c6e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_module_doc\n\nDocumentation:\nCalls a closure with an optional reference to the module docstring.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_module_doc(&self, f: F) -> Option\n where F: FnOnce(&str) -> R {\n let ns = self.namespace.borrow();\n ns.module_doc.as_ref().map(|d| f(d))\n }\n```"}], "func_name": "with_module_doc", "docstring": "Calls a closure with an optional reference to the module docstring.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d32b7f8658723d047649809f0e7ed8d6645dde40d4f4d14c179101823eecd495"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_module_doc_mut\n\nDocumentation:\nCalls a closure with a mutable reference to the module docstring.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_module_doc_mut(&self, f: F) -> R\n where F: FnOnce(&mut Option) -> R {\n let mut ns = self.namespace.borrow_mut();\n f(&mut ns.module_doc)\n }\n```"}], "func_name": "with_module_doc_mut", "docstring": "Calls a closure with a mutable reference to the module docstring.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c4409b6244fa01478b83feeac2e8e8e5f4deca876232443c09d76c0103b6c5a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_name\n\nDocumentation:\nCalls a closure with the borrowed string representation of a name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_name(&self, name: Name, f: F) -> R\n where F: FnOnce(&str) -> R {\n let names = self.name_store.borrow();\n f(names.get(name))\n }\n```"}], "func_name": "with_name", "docstring": "Calls a closure with the borrowed string representation of a name.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8fedbdb6a973cfcc0e4cb9ccc4e10517150addb715b0e8cdf3409c72c670b3c0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_exports\n\nDocumentation:\nCalls a closure with the set of exported names.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_exports(&self, f: F) -> Option\n where F: FnOnce(&NameSetSlice) -> R {\n let ns = self.namespace.borrow();\n ns.exports.as_ref().map(f)\n }\n```"}], "func_name": "with_exports", "docstring": "Calls a closure with the set of exported names.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2ec8c35712937e7d19664cee011fbfc0893e870d7e3df8b55f8d78f1e3c0bbde"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_imports\n\nDocumentation:\nCalls a closure with the set of imported values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_imports(&self, f: F) -> R\n where F: FnOnce(&[ImportSet]) -> R {\n let ns = self.namespace.borrow();\n f(&ns.imports)\n }\n```"}], "func_name": "with_imports", "docstring": "Calls a closure with the set of imported values.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f4a1821daa5c67a573b3fb806f6b7933a98b0c5ac5dfeeaa1157bf82c433f8e4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_constants\n\nDocumentation:\nCalls a closure with the set of defined constants.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_constants(&self, f: F) -> R\n where F: FnOnce(&NameMap) -> R {\n let ns = self.namespace.borrow();\n f(&ns.constants)\n }\n```"}], "func_name": "with_constants", "docstring": "Calls a closure with the set of defined constants.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a6c43b084398adf2254b116ac826ed1615cf71f4a99f08ac1cbb60b53fb35539"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_macros\n\nDocumentation:\nCalls a closure with the set of defined macros.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_macros(&self, f: F) -> R\n where F: FnOnce(&NameMap) -> R {\n let ns = self.namespace.borrow();\n f(&ns.macros)\n }\n```"}], "func_name": "with_macros", "docstring": "Calls a closure with the set of defined macros.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3f5a85469524ac5960a64ab23db39391198ba6590c676b72782de45e2a391705"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_values\n\nDocumentation:\nCalls a closure with the set of defined values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_values(&self, f: F) -> R\n where F: FnOnce(&NameMap) -> R {\n let ns = self.namespace.borrow();\n f(&ns.values)\n }\n```"}], "func_name": "with_values", "docstring": "Calls a closure with the set of defined values.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1aa70434b6a14b742b2c72d5312133357d9c8fbd462968f163580c11b37a3756"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: can_define\n\nDocumentation:\nReturns whether the given name can be defined in global scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn can_define(name: Name) -> bool {\n !(is_standard_value(name) || is_system_operator(name))\n }\n```"}], "func_name": "can_define", "docstring": "Returns whether the given name can be defined in global scope.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b8a092821021b49d8cc3606a18010d8de17554aa5645e0e6681a72aa7d482b35"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get\n\nDocumentation:\nReturns a value corresponding to the given name in master scope.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get(name: Name) -> Option {\n MasterScope::get_function(name)\n .or_else(|| MasterScope::get_bool(name).map(Value::Bool))\n }\n```"}], "func_name": "get", "docstring": "Returns a value corresponding to the given name in master scope.", "repo": "murarth/ketos", "path": "src/ketos/scope.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/scope.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b66fe3fb732705c6a7309823e91c216ac63ff007d74d2589138a9720d7aa03c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: format_string\n\nDocumentation:\nConstructs a formatted string using given the format `fmt` and input values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn format_string(names: &NameStore, fmt: &str, values: &[Value])\n -> Result {\n let mut buf = String::new();\n let mut fmter = StringFormatter::new(fmt, names, values);\n fmter.format_string(&mut buf)?;\n fmter.finish()?;\n Ok(buf)\n}\n```"}], "func_name": "format_string", "docstring": "Constructs a formatted string using given the format `fmt` and input values.", "repo": "murarth/ketos", "path": "src/ketos/string_fmt.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/string_fmt.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4611a32a5aacbe28067c48b1426d4ddef0b5541fc15b823ecfdaed3c8ba6a14d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: skip_until\n\nDocumentation:\nAdvances over text in the stream, without processing it.\nWhen a directive is reached, the predicate is called to determine\nwhether the directive terminates the skip operation.\nThis directive is then returned.\nIf a subgroup directive is encountered, that group and any contained\ndirectives will be ignored.\nIf the end of the input stream is reached before a matching directive,\nthe error result of `check_open_groups` will be returned.\nIf `check_open_groups` does not return an error, it will panic.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn skip_until(&mut self, mut f: F) -> Result, ExecError>\n where F: FnMut(&Directive) -> bool {\n let mut groups = Vec::new();\n\n loop {\n match self.consume_char() {\n Some('~') => {\n let dir = self.parse_directive()?;\n\n match dir.command {\n '<' | '(' | '[' | '{' => {\n let group = Group::get_group(dir.command).unwrap();\n\n groups.push((group.close_delim(), dir.span));\n continue;\n }\n '>' | ')' | ']' | '}' if !groups.is_empty() => {\n let (ch, span) = groups.pop().unwrap();\n\n if ch != dir.command {\n return Err(self.error(span,\n FormatError::IncorrectCloseDelim(dir.command)));\n }\n continue;\n }\n _ => ()\n }\n\n if groups.is_empty() && f(&dir) {\n return Ok(dir);\n }\n }\n Some(_) => (),\n None => break,\n }\n }\n\n if let Some((ch, span)) = groups.pop() {\n return Err(self.error(span,\n FormatError::MissingCloseDelim(ch)));\n }\n\n self.check_open_groups()?;\n panic!(\"skip_until reached end with no open group\");\n }\n```"}], "func_name": "skip_until", "docstring": "Advances over text in the stream, without processing it.\nWhen a directive is reached, the predicate is called to determine\nwhether the directive terminates the skip operation.\nThis directive is then returned.\nIf a subgroup directive is encountered, that group and any contained\ndirectives will be ignored.\nIf the end of the input stream is reached before a matching directive,\nthe error result of `check_open_groups` will be returned.\nIf `check_open_groups` does not return an error, it will panic.", "repo": "murarth/ketos", "path": "src/ketos/string_fmt.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/string_fmt.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4f7b37f8c7e633162db409a8994ab76d1b72a530bd050c16ac4ddf3a03f4cc0a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: substr_offset\n\nDocumentation:\nReturns the offset of `child` within `parent`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn substr_offset(child: &str, parent: &str) -> usize {\n child.as_ptr() as usize - parent.as_ptr() as usize\n}\n```"}], "func_name": "substr_offset", "docstring": "Returns the offset of `child` within `parent`.", "repo": "murarth/ketos", "path": "src/ketos/string_fmt.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/string_fmt.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9beb29ade8cef339200b31081e46011d5eb4bfb4bf57280bc7b47e4397bd8d38"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `StructValueDef` from a mapping of field name to type name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(fields: NameMapSlice) -> StructValueDef {\n StructValueDef{ fields }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `StructValueDef` from a mapping of field name to type name.", "repo": "murarth/ketos", "path": "src/ketos/structs.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/structs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "847a9600d18e1dab2732c98ccd5e333ef6c8cc34426f6ef3ee57acd0c33dda39"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `Struct` value with the given `StructDef` and field values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(def: Rc, fields: Box<[Value]>) -> Struct {\n Struct{ def, fields }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `Struct` value with the given `StructDef` and field values.", "repo": "murarth/ketos", "path": "src/ketos/structs.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/structs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a8b7d0af00050049f2a8a98bbe97d72b32e4314c7e904122ff6f942f90983c99"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fields_mut\n\nDocumentation:\nReturns a mutable reference to the field values.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn fields_mut(&mut self) -> &mut [Value] {\n &mut self.fields\n }\n```"}], "func_name": "fields_mut", "docstring": "Returns a mutable reference to the field values.", "repo": "murarth/ketos", "path": "src/ketos/structs.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/structs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "54a6274da36ed61ec9f649d54b263dcb3deb3126c2f718cfdc65e2faee5f20e6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `StructDef` with the given name and fields.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(name: Name, def: Box) -> StructDef {\n StructDef{ name, def }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `StructDef` with the given name and fields.", "repo": "murarth/ketos", "path": "src/ketos/structs.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/structs.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f13465729e3d4ea573c13d44112fb797743721eee1186d9ff38f4f7cdf707a2c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreates a new `Trace` from a series of items.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(items: Vec, expr: Option) -> Trace {\n Trace{ items, expr }\n }\n```"}], "func_name": "new", "docstring": "Creates a new `Trace` from a series of items.", "repo": "murarth/ketos", "path": "src/ketos/trace.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/trace.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93638e21086e0a314cb96d7c620b1a98d3ef54dd49aa7893451e91dfd71fe838"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: single\n\nDocumentation:\nCreates a new `Trace` from a single item.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn single(item: TraceItem, expr: Option) -> Trace {\n Trace::new(vec![item], expr)\n }\n```"}], "func_name": "single", "docstring": "Creates a new `Trace` from a single item.", "repo": "murarth/ketos", "path": "src/ketos/trace.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/trace.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c6510042b5f9d94ad3758933c9c9952d58623fab8813af8565538d109080e796"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: clear_traceback\n\nDocumentation:\nRemoves the traceback value for the current thread.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn clear_traceback() {\n TRACEBACK.with(|tb| *tb.borrow_mut() = None);\n}\n```"}], "func_name": "clear_traceback", "docstring": "Removes the traceback value for the current thread.", "repo": "murarth/ketos", "path": "src/ketos/trace.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/trace.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cf598ddfeae2336c2f13aa02e674a4fa811d5862d3fb2f1c438c403307e3a41a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_traceback\n\nDocumentation:\nClones and returns the traceback value for the current thread.\n\nThe value remains stored for future calls to `get_traceback`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_traceback() -> Option {\n TRACEBACK.with(|tb| tb.borrow().clone())\n}\n```"}], "func_name": "get_traceback", "docstring": "Clones and returns the traceback value for the current thread.\n\nThe value remains stored for future calls to `get_traceback`.", "repo": "murarth/ketos", "path": "src/ketos/trace.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/trace.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "34d1ba0e286202af3acca05eff3474543e69f146f2d28c9d21dbf54007bbb8e3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_traceback\n\nDocumentation:\nAssigns a traceback value for the current thread.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_traceback(trace: Trace) {\n TRACEBACK.with(|tb| *tb.borrow_mut() = Some(trace));\n}\n```"}], "func_name": "set_traceback", "docstring": "Assigns a traceback value for the current thread.", "repo": "murarth/ketos", "path": "src/ketos/trace.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/trace.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "09d80f7d205b3d1f8f914d927c4b376b8c3668362496cf036f7101759a2b3d1b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: take_traceback\n\nDocumentation:\nRemoves and returns the traceback value for the current thread.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn take_traceback() -> Option {\n TRACEBACK.with(|tb| replace(&mut *tb.borrow_mut(), None))\n}\n```"}], "func_name": "take_traceback", "docstring": "Removes and returns the traceback value for the current thread.", "repo": "murarth/ketos", "path": "src/ketos/trace.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/trace.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "05ec81964784d417ac7f59650252a26beb32b2c32d93000d146dceae6888ba77"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compare\n\nDocumentation:\nCompares two values; returns an error if the values cannot be compared.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn compare(&self, rhs: &Value) -> Result {\n let ord = match (self, rhs) {\n (&Value::Unit, &Value::Unit) => Ordering::Equal,\n (&Value::Bool(a), &Value::Bool(b)) => a.cmp(&b),\n (&Value::Float(a), &Value::Float(b)) =>\n a.partial_cmp(&b).ok_or(ExecError::CompareNaN)?,\n (&Value::Integer(ref a), &Value::Integer(ref b)) => a.cmp(&b),\n (&Value::Ratio(ref a), &Value::Ratio(ref b)) => a.cmp(&b),\n (&Value::Name(a), &Value::Name(b)) => a.cmp(&b),\n (&Value::Keyword(a), &Value::Keyword(b)) => a.cmp(&b),\n (&Value::Char(a), &Value::Char(b)) => a.cmp(&b),\n (&Value::String(ref a), &Value::String(ref b)) => a.cmp(&b),\n (&Value::Bytes(ref a), &Value::Bytes(ref b)) => a.cmp(&b),\n (&Value::Path(ref a), &Value::Path(ref b)) => a.cmp(&b),\n (&Value::Unit, &Value::List(_)) => Ordering::Less,\n (&Value::List(_), &Value::Unit) => Ordering::Greater,\n (&Value::List(ref a), &Value::List(ref b)) =>\n cmp_value_slice(a, b)?,\n (&Value::Struct(ref a), &Value::Struct(ref b)) => {\n if a.def() == b.def() {\n cmp_value_slice(a.fields(), b.fields())?\n } else {\n return Err(ExecError::StructMismatch{\n lhs: a.def().name(),\n rhs: b.def().name(),\n });\n }\n }\n\n // Coercible numeric comparisons\n (&Value::Float(a), &Value::Integer(ref b)) => {\n coerce_compare_float(a, true,\n b.to_f64(), b.is_positive())?\n }\n (&Value::Float(a), &Value::Ratio(ref b)) => {\n coerce_compare_float(a, true,\n b.to_f64(), b.is_positive())?\n }\n (&Value::Integer(ref a), &Value::Float(b)) => {\n coerce_compare_float(b, false,\n a.to_f64(), a.is_positive())?\n }\n (&Value::Ratio(ref a), &Value::Float(b)) => {\n coerce_compare_float(b, false,\n a.to_f64(), a.is_positive())?\n }\n (&Value::Integer(ref a), &Value::Ratio(ref b)) => {\n let a = Ratio::from_integer(a.clone());\n a.cmp(b)\n }\n (&Value::Ratio(ref a), &Value::Integer(ref b)) => {\n let b = Ratio::from_integer(b.clone());\n a.cmp(&b)\n }\n\n // Non-comparable types\n (&Value::StructDef(_), &Value::StructDef(_)) =>\n return Err(ExecError::CannotCompare(\"struct-def\")),\n (&Value::Function(_), &Value::Function(_)) =>\n return Err(ExecError::CannotCompare(\"function\")),\n (&Value::Lambda(_), &Value::Lambda(_)) =>\n return Err(ExecError::CannotCompare(\"lambda\")),\n (&Value::Quote(_, _), &Value::Quote(_, _)) =>\n return Err(ExecError::CannotCompare(\"quote\")),\n (&Value::Quasiquote(_, _), &Value::Quasiquote(_, _)) =>\n return Err(ExecError::CannotCompare(\"quasiquote\")),\n (&Value::Comma(_, _), &Value::Comma(_, _)) =>\n return Err(ExecError::CannotCompare(\"comma\")),\n (&Value::CommaAt(_, _), &Value::CommaAt(_, _)) =>\n return Err(ExecError::CannotCompare(\"comma-at\")),\n\n (&Value::Foreign(ref a), ref b) => a.compare_to_value(b)?,\n (ref a, &Value::Foreign(ref b)) =>\n flip_ordering(b.compare_to_value(a)?),\n\n // Type mismatch\n (a, b) => return Err(ExecError::TypeMismatch{\n lhs: a.type_name(),\n rhs: b.type_name(),\n })\n };\n\n Ok(ord)\n }\n```"}], "func_name": "compare", "docstring": "Compares two values; returns an error if the values cannot be compared.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8b652896d413a2f194fff8837ea46a8ebd1c5240de84a17e2260702e4c1e15c5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_equal\n\nDocumentation:\nTests two values for equality; returns an error if the values cannot be\ncompared.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_equal(&self, rhs: &Value) -> Result {\n let eq = match (self, rhs) {\n (&Value::Unit, &Value::Unit) => true,\n (&Value::Bool(a), &Value::Bool(b)) => a == b,\n (&Value::Float(a), &Value::Float(b)) => a == b,\n (&Value::Integer(ref a), &Value::Integer(ref b)) => a == b,\n (&Value::Ratio(ref a), &Value::Ratio(ref b)) => a == b,\n\n (&Value::Float(a), &Value::Integer(ref b)) => {\n coerce_equal_float(a, b.to_f64())\n }\n (&Value::Float(a), &Value::Ratio(ref b)) => {\n coerce_equal_float(a, b.to_f64())\n }\n (&Value::Integer(ref a), &Value::Float(b)) => {\n coerce_equal_float(b, a.to_f64())\n }\n (&Value::Ratio(ref a), &Value::Float(b)) => {\n coerce_equal_float(b, a.to_f64())\n }\n\n (&Value::Integer(ref a), &Value::Ratio(ref b)) => a == b,\n (&Value::Ratio(ref a), &Value::Integer(ref b)) => a == b,\n\n (&Value::Name(a), &Value::Name(b)) => a == b,\n (&Value::Keyword(a), &Value::Keyword(b)) => a == b,\n (&Value::Char(a), &Value::Char(b)) => a == b,\n (&Value::String(ref a), &Value::String(ref b)) => a == b,\n (&Value::Bytes(ref a), &Value::Bytes(ref b)) => a == b,\n (&Value::Path(ref a), &Value::Path(ref b)) => a == b,\n (&Value::Quote(ref a, na), &Value::Quote(ref b, nb)) =>\n na == nb && a.is_equal(&b)?,\n (&Value::Unit, &Value::List(_)) => false,\n (&Value::List(_), &Value::Unit) => false,\n (&Value::List(ref a), &Value::List(ref b)) =>\n eq_value_slice(a, b)?,\n (&Value::Struct(ref a), &Value::Struct(ref b)) => {\n if a.def() == b.def() {\n eq_value_slice(a.fields(), b.fields())?\n } else {\n return Err(ExecError::StructMismatch{\n lhs: a.def().name(),\n rhs: b.def().name(),\n });\n }\n }\n (&Value::StructDef(ref a), &Value::StructDef(ref b)) => a == b,\n (&Value::Function(ref a), &Value::Function(ref b)) => a == b,\n (&Value::Lambda(ref a), &Value::Lambda(ref b)) => a == b,\n\n (&Value::Foreign(ref a), ref b) => a.is_equal_to_value(b)?,\n (ref a, &Value::Foreign(ref b)) => b.is_equal_to_value(a)?,\n\n (a, b) => return Err(ExecError::TypeMismatch{\n lhs: a.type_name(),\n rhs: b.type_name(),\n })\n };\n\n Ok(eq)\n }\n```"}], "func_name": "is_equal", "docstring": "Tests two values for equality; returns an error if the values cannot be\ncompared.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be59d729e8d69e57a4e3a0917b2e1fc95dca4ac8b0ab6f36fab3a1c6c1b19a83"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_identical\n\nDocumentation:\nReturns whether this value is identical to another.\nThe notable difference between this and `eq` is that float `NaN` values\nwill compare equal.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_identical(&self, rhs: &Value) -> bool {\n match (self, rhs) {\n (&Value::Unit, &Value::Unit) => true,\n (&Value::Unbound, &Value::Unbound) => true,\n (&Value::Bool(a), &Value::Bool(b)) => a == b,\n (&Value::Float(a), &Value::Float(b)) => float_is_identical(a, b),\n (&Value::Integer(ref a), &Value::Integer(ref b)) => a == b,\n (&Value::Ratio(ref a), &Value::Ratio(ref b)) => a == b,\n (&Value::Struct(ref a), &Value::Struct(ref b)) =>\n a.def() == b.def() &&\n a.fields().iter().zip(b.fields().iter())\n .all(|(a, b)| a.is_identical(b)),\n (&Value::Name(a), &Value::Name(b)) => a == b,\n (&Value::Keyword(a), &Value::Keyword(b)) => a == b,\n (&Value::Char(a), &Value::Char(b)) => a == b,\n (&Value::String(ref a), &Value::String(ref b)) => a == b,\n (&Value::Bytes(ref a), &Value::Bytes(ref b)) => a == b,\n (&Value::Path(ref a), &Value::Path(ref b)) => a == b,\n (&Value::Quasiquote(ref a, na), &Value::Quasiquote(ref b, nb)) =>\n na == nb && a.is_identical(b),\n (&Value::Comma(ref a, na), &Value::Comma(ref b, nb)) =>\n na == nb && a.is_identical(b),\n (&Value::Quote(ref a, na), &Value::Quote(ref b, nb)) =>\n na == nb && a.is_identical(b),\n (&Value::List(ref a), &Value::List(ref b)) =>\n list_is_identical(a, b),\n (&Value::Function(ref a), &Value::Function(ref b)) => a == b,\n (&Value::Lambda(ref a), &Value::Lambda(ref b)) => a == b,\n\n (&Value::Foreign(ref a), &Value::Foreign(ref b)) =>\n a.is_identical_to(&**b),\n\n _ => false\n }\n }\n```"}], "func_name": "is_identical", "docstring": "Returns whether this value is identical to another.\nThe notable difference between this and `eq` is that float `NaN` values\nwill compare equal.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b6af10bc7ef61204c5240a481da8b2b6f9b6539a66ef8abcd35da0ca89e97e9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: take\n\nDocumentation:\nReplaces the value with `Unit` and returns the old value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn take(&mut self) -> Value {\n replace(self, Value::Unit)\n }\n```"}], "func_name": "take", "docstring": "Replaces the value with `Unit` and returns the old value.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63cb735d227f30b352240d1bf702bd9c03cae73212e559d6024f6b695e76af70"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: quasiquote\n\nDocumentation:\nReturns the value, quasi-quoted.\n\n# Panics\n\nIf `n` would overflow.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn quasiquote(self, n: u32) -> Value {\n match self {\n Value::Quasiquote(v, i) => Value::Quasiquote(v,\n i.checked_add(n).expect(\"quasiquote overflow\")),\n v => Value::Quasiquote(Box::new(v), n),\n }\n }\n```"}], "func_name": "quasiquote", "docstring": "Returns the value, quasi-quoted.\n\n# Panics\n\nIf `n` would overflow.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fffba46e4bb60cfd7b4cc9652fc8d46088cbd44343b8810b8b03fac5707a76d4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: comma\n\nDocumentation:\nReturns the value, comma'd.\n\n# Panics\n\nIf `n` would overflow.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn comma(self, n: u32) -> Value {\n match self {\n Value::Comma(v, i) => Value::Comma(v,\n i.checked_add(n).expect(\"comma overflow\")),\n Value::CommaAt(v, i) => Value::CommaAt(v, i + n),\n v => Value::Comma(Box::new(v), n),\n }\n }\n```"}], "func_name": "comma", "docstring": "Returns the value, comma'd.\n\n# Panics\n\nIf `n` would overflow.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ebfdfbd58c3c3ac07a1243937d5d8fcff63cb4a2914ecc74608a5b6206e8888c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: comma_at\n\nDocumentation:\nReturns the value, comma-at'd.\n\n# Panics\n\nIf `n` would overflow.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn comma_at(self, n: u32) -> Value {\n match self {\n Value::CommaAt(v, i) => Value::CommaAt(v,\n i.checked_add(n).expect(\"comma_at overflow\")),\n v => Value::CommaAt(Box::new(v), n)\n }\n }\n```"}], "func_name": "comma_at", "docstring": "Returns the value, comma-at'd.\n\n# Panics\n\nIf `n` would overflow.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6d085ef641e27cf2a5d2f8f7493890e533d4716b2db0be98804523fb212372e8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: quote\n\nDocumentation:\nReturns the value, quoted.\n\n# Panics\n\nIf `n` would overflow.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn quote(self, n: u32) -> Value {\n match self {\n Value::Quote(v, i) => Value::Quote(v,\n i.checked_add(n).expect(\"quote overflow\")),\n v => Value::Quote(Box::new(v), n),\n }\n }\n```"}], "func_name": "quote", "docstring": "Returns the value, quoted.\n\n# Panics\n\nIf `n` would overflow.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "0e93d89a7a062650f1711bda332757c6a64930ccc5e6d6ef85172011aa7eee4c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: type_name\n\nDocumentation:\nReturns a string describing the type of the value.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn type_name(&self) -> &'static str {\n match *self {\n Value::Unit => \"unit\",\n Value::Unbound => \"\",\n Value::Bool(_) => \"bool\",\n Value::Float(_) => \"float\",\n Value::Integer(_) => \"integer\",\n Value::Ratio(_) => \"ratio\",\n Value::Char(_) => \"char\",\n Value::String(_) => \"string\",\n Value::Bytes(_) => \"bytes\",\n Value::Path(_) => \"path\",\n Value::Name(_) => \"name\",\n Value::Keyword(_) => \"keyword\",\n // XXX: Does this make sense?\n Value::Quasiquote(_, _) |\n Value::Comma(_, _) |\n Value::CommaAt(_, _) |\n Value::Quote(_, _) => \"object\",\n Value::List(_) => \"list\",\n Value::Struct(_) => \"struct\",\n Value::StructDef(_) => \"struct-def\",\n Value::Function(_) => \"function\",\n Value::Lambda(_) => \"lambda\",\n Value::Foreign(ref a) => a.type_name(),\n }\n }\n```"}], "func_name": "type_name", "docstring": "Returns a string describing the type of the value.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "84b630c0fab5fd16fe634fbacdd8e4f54f95e7deecee1c0327cf74a4d2450e0b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: compare_to_value\n\nDocumentation:\nPerforms ordered comparison between two values.\n\nThis method need only be implemented if a value of the foreign type\nmay be compared with core value types.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn compare_to_value(&self, rhs: &Value) -> Result {\n match *rhs {\n Value::Foreign(ref rhs) => self.compare_to(&**rhs),\n ref v => Err(ExecError::expected(self.type_name(), v))\n }\n }\n```"}], "func_name": "compare_to_value", "docstring": "Performs ordered comparison between two values.\n\nThis method need only be implemented if a value of the foreign type\nmay be compared with core value types.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "63407a0326c707849bcc27818645cb8b970dfebcc9bd82e81c98a02e40327db9"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_equal_to\n\nDocumentation:\nTests for equality between two values of a foreign type.\n\nThe default implementation unconditionally returns an error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_equal_to(&self, rhs: &dyn ForeignValue) -> Result {\n Err(ExecError::TypeMismatch{\n lhs: self.type_name(),\n rhs: rhs.type_name(),\n })\n }\n```"}], "func_name": "is_equal_to", "docstring": "Tests for equality between two values of a foreign type.\n\nThe default implementation unconditionally returns an error.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "43f3045f08c0c6636ad6064a28bd138bbb3e2a25b4cd559a30b757f1572dc47d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_equal_to_value\n\nDocumentation:\nTests for equality between two values.\n\nThis method need only be implemented if a value of the foreign type\nmay be compared with core value types.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_equal_to_value(&self, rhs: &Value) -> Result {\n match *rhs {\n Value::Foreign(ref rhs) => self.is_equal_to(&**rhs),\n ref v => Err(ExecError::expected(self.type_name(), v))\n }\n }\n```"}], "func_name": "is_equal_to_value", "docstring": "Tests for equality between two values.\n\nThis method need only be implemented if a value of the foreign type\nmay be compared with core value types.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e8c0c8186f8a1d37c5c4e6be93c9d674e4504f353dece8cfad1bc5920388189"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fmt_debug\n\nDocumentation:\nFormat the value in debugging mode.\n\nThe default implementation uses the type's `fmt::Debug` representation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fmt_debug(&self, names: &NameStore, f: &mut fmt::Formatter) -> fmt::Result {\n fmt::Debug::fmt(self, f)\n }\n```"}], "func_name": "fmt_debug", "docstring": "Format the value in debugging mode.\n\nThe default implementation uses the type's `fmt::Debug` representation.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bd4124d20641784198950efa7c79497176fbabccf5328fcd720fea8d0a90ac78"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: fmt_display\n\nDocumentation:\nFormat the value in display mode.\n\nThe default implementation formats the value in debugging mode.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn fmt_display(&self, names: &NameStore, f: &mut fmt::Formatter) -> fmt::Result {\n self.fmt_debug(names, f)\n }\n```"}], "func_name": "fmt_display", "docstring": "Format the value in display mode.\n\nThe default implementation formats the value in debugging mode.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ebf9454774e5e6c65ff8502fe8c2144ded8c50101aa663aefcbaa83f206eb35d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_type\n\nDocumentation:\nReturns whether this value is of the named type.\n\nThe default implementation checks against the value of `self.type_name()`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn is_type(&self, name: &str) -> bool {\n self.type_name() == name\n }\n```"}], "func_name": "is_type", "docstring": "Returns whether this value is of the named type.\n\nThe default implementation checks against the value of `self.type_name()`.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "03146c29faa410c08235264a7502914bcae7d397a7ddaf2a5c2491ec84163d72"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: call_value\n\nDocumentation:\nCalls the value as a function.\n\nThe default implementation unconditionally returns an error.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn call_value(&self, ctx: &Context, args: &mut [Value])\n -> Result {\n Err(From::from(ExecError::TypeError{\n expected: \"function\",\n found: self.type_name(),\n value: None,\n }))\n }\n```"}], "func_name": "call_value", "docstring": "Calls the value as a function.\n\nThe default implementation unconditionally returns an error.", "repo": "murarth/ketos", "path": "src/ketos/value.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "8f04a834a9bb6210fd4b324ee4fa0062c579eae5b9ca2344bbda039bf00e47b1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: decode_value\n\nDocumentation:\nDecodes a Rust type from a `Value`.\n\nSee [`value_encode`](../value_encode/index.html) module documentation\nfor details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn decode_value<'de, T: Deserialize<'de>>(scope: &'de Scope, value: &'de Value) -> Result {\n let mut de = VDeserializer::new(scope, value);\n let v = T::deserialize(&mut de)?;\n de.finish();\n Ok(v)\n}\n```"}], "func_name": "decode_value", "docstring": "Decodes a Rust type from a `Value`.\n\nSee [`value_encode`](../value_encode/index.html) module documentation\nfor details.", "repo": "murarth/ketos", "path": "src/ketos/value_decode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value_decode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "408ab9bae86140aa281d92699744b46fcbf4900071f59fbfdeac715c34491084"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: encode_value\n\nDocumentation:\nEncodes a Rust type into a `Value`.\n\nSee [`value_encode`](index.html) module documentation for details.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn encode_value(scope: &Scope, value: &T) -> Result {\n let mut ser = VSerializer::new(scope);\n value.serialize(&mut ser)?;\n Ok(ser.value.expect(\"empty serializer\"))\n}\n```"}], "func_name": "encode_value", "docstring": "Encodes a Rust type into a `Value`.\n\nSee [`value_encode`](index.html) module documentation for details.", "repo": "murarth/ketos", "path": "src/ketos/value_encode.rs", "url": "https://github.com/murarth/ketos/blob/master/src/ketos/value_encode.rs", "license": "Apache-2.0", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2bddfaff94a0a28af06a2e14f24e94698509b261f20ecfa0861f7444841e57e7"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: per_period\n\nDocumentation:\nProduces a rate for some number of actions per second. For example, if\nwe wanted to have 10 actions every 2 seconds, the period produced would\nbe 200 ms.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn per_period(n: i64, period: time::Duration) -> Rate {\n let ns: i128 = period.whole_nanoseconds();\n\n // Don't rely on floating point math to get here.\n if n == 0 || ns == 0 {\n return Rate {\n period: time::Duration::nanoseconds(0),\n };\n }\n\n let period = time::Duration::nanoseconds(((ns as f64) / (n as f64)) as i64);\n Rate { period }\n }\n```"}], "func_name": "per_period", "docstring": "Produces a rate for some number of actions per second. For example, if\nwe wanted to have 10 actions every 2 seconds, the period produced would\nbe 200 ms.", "repo": "brandur/redis-cell", "path": "src/cell/mod.rs", "url": "https://github.com/brandur/redis-cell/blob/master/src/cell/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb0b62cc835c48adb4280958f8b46de7d644a7c2dfbcda07ff71c32f078fe79a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: harness\n\nDocumentation:\nProvides a basic wrapper for a command's implementation that parses\narguments to Rust data types and handles the OK/ERR reply back to Redis.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn harness(\n command: &dyn Command,\n ctx: *mut raw::RedisModuleCtx,\n argv: *mut *mut raw::RedisModuleString,\n argc: c_int,\n ) -> raw::Status {\n let r = Redis { ctx };\n let args = parse_args(argv, argc).unwrap();\n let str_args: Vec<&str> = args.iter().map(|s| s.as_str()).collect();\n match command.run(r, str_args.as_slice()) {\n Ok(_) => raw::Status::Ok,\n Err(e) => {\n raw::reply_with_error(ctx, format!(\"Cell error: {e}\\0\").as_ptr());\n raw::Status::Err\n }\n }\n }\n```"}], "func_name": "harness", "docstring": "Provides a basic wrapper for a command's implementation that parses\narguments to Rust data types and handles the OK/ERR reply back to Redis.", "repo": "brandur/redis-cell", "path": "src/redis/mod.rs", "url": "https://github.com/brandur/redis-cell/blob/master/src/redis/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f751cc5032814666b29cb629540521b60875df3d9c38805cb6da1cbed7745f5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: call\n\nDocumentation:\nCalls a Redis command with arguments.\n\nWARNING: This method is not currently in use by the library. I thought I would be invoking\nmanual calls originally, but ended up going on to use lower level Redis Module functions\ninstead like direct key manipulation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn call(&self, command: &str, args: &[&str]) -> Result {\n log_debug!(self, \"{} [began] args = {:?}\", command, args);\n\n // We use a \"format\" string to tell redis what types we're passing in.\n // Currently we just pass everything as a string so this is just the\n // character \"s\" repeated as many times as we have arguments.\n //\n // It would be nice to start passing some parameters as their actual\n // type (for example, i64s as long longs), but Redis stringifies these\n // on the other end anyway so the practical benefit will be minimal.\n let format: String = \"s\".repeat(args.len());\n\n let terminated_args: Vec =\n args.iter().map(|s| self.create_string(s)).collect();\n\n // One would hope that there's a better way to handle a va_list than\n // this, but I can't find it for the life of me.\n let raw_reply = match args.len() {\n 1 => {\n // WARNING: This is downright hazardous, but I've noticed that\n // if I remove this format! from the line of invocation, the\n // right memory layout doesn't make it into Redis (and it will\n // reply with a -1 \"unknown\" to all calls). This is still\n // unexplained and I need to do more legwork in understanding\n // this.\n //\n // Still, this works fine and will continue to work as long as\n // it's left unchanged.\n raw::call1::call(\n self.ctx,\n format!(\"{command}\\0\").as_ptr(),\n format!(\"{format}\\0\").as_ptr(),\n terminated_args[0].str_inner,\n )\n }\n 2 => raw::call2::call(\n self.ctx,\n format!(\"{command}\\0\").as_ptr(),\n format!(\"{format}\\0\").as_ptr(),\n terminated_args[0].str_inner,\n terminated_args[1].str_inner,\n ),\n 3 => raw::call3::call(\n self.ctx,\n format!(\"{command}\\0\").as_ptr(),\n format!(\"{format}\\0\").as_ptr(),\n terminated_args[0].str_inner,\n terminated_args[1].str_inner,\n terminated_args[2].str_inner,\n ),\n _ => return Err(error!(\"Can't support that many CALL arguments\")),\n };\n\n let reply_res = manifest_redis_reply(raw_reply);\n raw::free_call_reply(raw_reply);\n\n if let Ok(ref reply) = reply_res {\n log_debug!(self, \"{} [ended] result = {:?}\", command, reply);\n }\n\n // Tell Redis that it's okay to replicate the command with the same\n // parameters out to replicas.\n //\n // This is not strictly correct. Because the rate limiting function\n // uses time as input, the replicas will end up with a slightly\n // different result. However, given the domain of rate limiting, those\n // results will be close enough for almost all purposes.\n //\n // A possible improvement is switching to `RedisModule_Replicate` and\n // adding a new command (or maybe just new parameters) that allows\n // injecting a timestamp. This would allow a master to transmit its\n // exact time out to replicas which would make sure their results are\n // identical.\n if let raw::Status::Err = raw::replicate_verbatim(self.ctx) {\n // Handle a possible error for hygiene, but the documentation specifically\n // states that the function always returns `REDISMODULE_OK`.\n return Err(error!(\"Unexpected replication response\"));\n }\n\n reply_res\n }\n```"}], "func_name": "call", "docstring": "Calls a Redis command with arguments.\n\nWARNING: This method is not currently in use by the library. I thought I would be invoking\nmanual calls originally, but ended up going on to use lower level Redis Module functions\ninstead like direct key manipulation.", "repo": "brandur/redis-cell", "path": "src/redis/mod.rs", "url": "https://github.com/brandur/redis-cell/blob/master/src/redis/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f0fe32792f5b07c51a6c59ba7fdd4940dd3b96ac26a360e0ad8e5b94cea9ec06"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: coerce_integer\n\nDocumentation:\nCoerces a Redis string as an integer.\n\nRedis is pretty dumb about data types. It nominally supports strings\nversus integers, but an integer set in the store will continue to look\nlike a string (i.e. \"1234\") until some other operation like INCR forces\nits coercion.\n\nThis method coerces a Redis string that looks like an integer into an\ninteger response. All other types of replies are passed through\nunmodified.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn coerce_integer(\n &self,\n reply_res: Result,\n ) -> Result {\n match reply_res {\n Ok(Reply::String(s)) => match s.parse::() {\n Ok(n) => Ok(Reply::Integer(n)),\n _ => Ok(Reply::String(s)),\n },\n _ => reply_res,\n }\n }\n```"}], "func_name": "coerce_integer", "docstring": "Coerces a Redis string as an integer.\n\nRedis is pretty dumb about data types. It nominally supports strings\nversus integers, but an integer set in the store will continue to look\nlike a string (i.e. \"1234\") until some other operation like INCR forces\nits coercion.\n\nThis method coerces a Redis string that looks like an integer into an\ninteger response. All other types of replies are passed through\nunmodified.", "repo": "brandur/redis-cell", "path": "src/redis/mod.rs", "url": "https://github.com/brandur/redis-cell/blob/master/src/redis/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e9a9fee02a96a70b3a4efa15acf6be2129caa9076c2929fccd7e26e666f6fc2f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open_key\n\nDocumentation:\nOpens a Redis key for read access.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn open_key(&self, key: &str) -> RedisKey {\n RedisKey::open(self.ctx, key)\n }\n```"}], "func_name": "open_key", "docstring": "Opens a Redis key for read access.", "repo": "brandur/redis-cell", "path": "src/redis/mod.rs", "url": "https://github.com/brandur/redis-cell/blob/master/src/redis/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb0866f04abab318c08eeabb3962fd801ac9d1faee06e9c67c537cdc9da188fa"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: open_key_writable\n\nDocumentation:\nOpens a Redis key for read and write access.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn open_key_writable(&self, key: &str) -> RedisKeyWritable {\n RedisKeyWritable::open(self.ctx, key)\n }\n```"}], "func_name": "open_key_writable", "docstring": "Opens a Redis key for read and write access.", "repo": "brandur/redis-cell", "path": "src/redis/mod.rs", "url": "https://github.com/brandur/redis-cell/blob/master/src/redis/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "395a569af0c598a1c475f53e8de320913a996c233225cbec75fa5e867e820bb8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: replicate_verbatim\n\nDocumentation:\nTells Redis to replicate the command to replicas an AOF as is.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn replicate_verbatim(&self) -> Result<(), CellError> {\n // Handle a possible error for hygiene, but the documentation specifically\n // states that the function always returns `REDISMODULE_OK`.\n handle_status(\n raw::replicate_verbatim(self.ctx),\n \"Could not replicate verbatim\",\n )\n }\n```"}], "func_name": "replicate_verbatim", "docstring": "Tells Redis to replicate the command to replicas an AOF as is.", "repo": "brandur/redis-cell", "path": "src/redis/mod.rs", "url": "https://github.com/brandur/redis-cell/blob/master/src/redis/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b1b9fab1e1d1c30130b2ee85d5d4d8b22c1d991b9eb83fa2aa5197647feb6c89"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: reply_array\n\nDocumentation:\nTells Redis that we're about to reply with an (Redis) array.\n\nUsed by invoking once with the expected length and then calling any\ncombination of the other reply_* methods exactly that number of times.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn reply_array(&self, len: i64) -> Result<(), CellError> {\n handle_status(\n raw::reply_with_array(self.ctx, len as c_long),\n \"Could not reply with long\",\n )\n }\n```"}], "func_name": "reply_array", "docstring": "Tells Redis that we're about to reply with an (Redis) array.\n\nUsed by invoking once with the expected length and then calling any\ncombination of the other reply_* methods exactly that number of times.", "repo": "brandur/redis-cell", "path": "src/redis/mod.rs", "url": "https://github.com/brandur/redis-cell/blob/master/src/redis/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c491da30f0c96de655bdbb5eef09e0d6972a1546763638da7b7492aae8e0ebd5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_null\n\nDocumentation:\nDetects whether the key pointer given to us by Redis is null.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_null(&self) -> bool {\n let null_key: *mut raw::RedisModuleKey = ptr::null_mut();\n self.key_inner == null_key\n }\n```"}], "func_name": "is_null", "docstring": "Detects whether the key pointer given to us by Redis is null.", "repo": "brandur/redis-cell", "path": "src/redis/mod.rs", "url": "https://github.com/brandur/redis-cell/blob/master/src/redis/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "120f8cd8040b07b61ae4d9adb07dcf33c0fbfd547112981944e3856b12d0890c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_empty\n\nDocumentation:\nDetects whether the value stored in a Redis key is empty.\n\nNote that an empty key can be reliably detected by looking for a null\nas you open the key in read mode, but when asking for write Redis\nreturns a non-null pointer to allow us to write to even an empty key,\nso we have to check the key's value instead.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_empty(&self) -> Result {\n match self.read()? {\n Some(s) => match s.as_str() {\n \"\" => Ok(true),\n _ => Ok(false),\n },\n _ => Ok(false),\n }\n }\n```"}], "func_name": "is_empty", "docstring": "Detects whether the value stored in a Redis key is empty.\n\nNote that an empty key can be reliably detected by looking for a null\nas you open the key in read mode, but when asking for write Redis\nreturns a non-null pointer to allow us to write to even an empty key,\nso we have to check the key's value instead.", "repo": "brandur/redis-cell", "path": "src/redis/mod.rs", "url": "https://github.com/brandur/redis-cell/blob/master/src/redis/mod.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "92062cec8b5c7e8c2953d8a4f913ba2df57889bc0730b9096cc701cb73176144"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start\n\nDocumentation:\nStarts service discovery process.\n\n# Args\n\n- `listener_port` - port we will be litening for incoming service discovery requests.\n- `remote_port` - port we will broadcasting service discovery requests to.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start(\n core: &mut Core,\n poll: &Poll,\n token: Token,\n listener_port: u16,\n remote_port: u16,\n our_pk: PublicEncryptKey,\n ) -> Result<(), ServiceDiscoveryError> {\n let udp_socket = UdpSocket::bind(&ipv4_addr(0, 0, 0, 0, listener_port))?;\n udp_socket.set_broadcast(true)?;\n let udp_socket = UdpSock::wrap(udp_socket);\n\n let remote_addr = ipv4_addr(255, 255, 255, 255, remote_port);\n\n let service_discovery = ServiceDiscovery {\n token,\n socket: udp_socket,\n remote_addr,\n listen: false,\n seek_peers_req: DiscoveryMsg::Request { our_pk },\n observers: Vec::new(),\n our_pk,\n _phantom: PhantomData,\n };\n\n poll.register(\n &service_discovery.socket,\n token,\n Ready::readable() | Ready::writable(),\n PollOpt::edge(),\n )?;\n\n let _ = core.insert_state(token, Rc::new(RefCell::new(service_discovery)));\n\n Ok(())\n }\n```"}], "func_name": "start", "docstring": "Starts service discovery process.\n\n# Args\n\n- `listener_port` - port we will be litening for incoming service discovery requests.\n- `remote_port` - port we will broadcasting service discovery requests to.", "repo": "maidsafe-archive/crust", "path": "src/service_discovery.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/service_discovery.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7638789d016172d3cf8947f9243dbeb1a94b9dc13469d026086c31235552743a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_listen\n\nDocumentation:\nEnable/disable listening and responding to peers searching for us. This will allow others\nfinding us by interrogating the network.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_listen(&mut self, listen: bool) {\n self.listen = listen;\n }\n```"}], "func_name": "set_listen", "docstring": "Enable/disable listening and responding to peers searching for us. This will allow others\nfinding us by interrogating the network.", "repo": "maidsafe-archive/crust", "path": "src/service_discovery.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/service_discovery.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "715469b4b4f26d3481b67a7a6e8cd8bd17f9ea99084c1ddcdae406fe10949e98"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: seek_peers\n\nDocumentation:\nInterrogate the network to find peers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn seek_peers(&mut self) -> Result<(), ServiceDiscoveryError> {\n let _ = self\n .socket\n .write_to(Some((&self.seek_peers_req, self.remote_addr, 0)))?;\n Ok(())\n }\n```"}], "func_name": "seek_peers", "docstring": "Interrogate the network to find peers.", "repo": "maidsafe-archive/crust", "path": "src/service_discovery.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/service_discovery.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4ab61f1625e1c75f27d56f215589073a71fd6ff38f5f945417cdde3d298457a4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn_event_loop\n\nDocumentation:\nSpawns event loop in a separate thread and returns a handle to communicate with it.\n\n## Args\n\n- `token_counter_start`: initial value for mio event `Token`s used to register custom states.\n- `event_loop_id`: event loop thread name.\n- `init_user_data`: a callback to lazilly initialize user data associated with this event loop.\nIn some cases we need to initialize user data in the same thread that `Core` is stored.\ne.g., if user data is an `Rc` we can't send it to event loop thread, hence a callback.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn spawn_event_loop(\n token_counter_start: usize,\n event_loop_id: Option<&str>,\n init_user_data: F,\n) -> Result>\nwhere\n F: 'static + FnOnce() -> T + Send,\n{\n let poll = Poll::new()?;\n let (tx, rx) = channel::channel();\n let timer = Timer::default();\n\n poll.register(\n &rx,\n Token(token_counter_start + CHANNEL_TOKEN_OFFSET),\n Ready::readable(),\n PollOpt::edge(),\n )?;\n poll.register(\n &timer,\n Token(token_counter_start + TIMER_TOKEN_OFFSET),\n Ready::readable(),\n PollOpt::edge(),\n )?;\n\n let mut name = \"CRUST-Event-Loop\".to_string();\n if let Some(id) = event_loop_id {\n name.push_str(\": \");\n name.push_str(id);\n }\n\n let tx_clone = tx.clone();\n let joiner = thread::named(name, move || {\n let user_data = init_user_data();\n let core = Core::new(\n token_counter_start + USER_TOKEN_OFFSET,\n tx_clone,\n timer,\n user_data,\n );\n match event_loop_impl(token_counter_start, &poll, &rx, core) {\n Ok(()) => trace!(\"Graceful event loop exit.\"),\n Err(e) => error!(\"Event loop killed due to {:?}\", e),\n }\n });\n\n Ok(EventLoop {\n tx,\n _joiner: joiner,\n })\n}\n```"}], "func_name": "spawn_event_loop", "docstring": "Spawns event loop in a separate thread and returns a handle to communicate with it.\n\n## Args\n\n- `token_counter_start`: initial value for mio event `Token`s used to register custom states.\n- `event_loop_id`: event loop thread name.\n- `init_user_data`: a callback to lazilly initialize user data associated with this event loop.\nIn some cases we need to initialize user data in the same thread that `Core` is stored.\ne.g., if user data is an `Rc` we can't send it to event loop thread, hence a callback.", "repo": "maidsafe-archive/crust", "path": "src/common/core.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/common/core.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fae285d7886b0f23eee5633efc54d25bdea06a53650f4b8aa7b31efa492ae0d0"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: event_loop_impl\n\nDocumentation:\nSpins mio event loop until the special exit message is received.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn event_loop_impl(\n token_counter_start: usize,\n poll: &Poll,\n rx: &Receiver>,\n mut core: Core,\n) -> Result<()> {\n let mut events = Events::with_capacity(EVENT_CAPACITY);\n\n 'event_loop: loop {\n let _ = poll.poll(&mut events, None)?;\n\n for event in events.iter() {\n match event.token() {\n Token(t) if t == token_counter_start + CHANNEL_TOKEN_OFFSET => {\n if !event.readiness().is_readable() {\n warn!(\n \"Communication channel to event loop errored out: {:?}\",\n event\n );\n continue;\n }\n\n loop {\n let msg = match rx.try_recv() {\n Ok(msg) => msg,\n Err(TryRecvError::Empty) => break,\n Err(TryRecvError::Disconnected) => break 'event_loop,\n };\n match msg.0 {\n Some(mut f) => f(&mut core, poll),\n None => break 'event_loop,\n }\n }\n }\n Token(t) if t == token_counter_start + TIMER_TOKEN_OFFSET => {\n core.handle_timer(poll, event.readiness())\n }\n _ => core.handle_event(poll, event),\n }\n }\n }\n\n Ok(())\n}\n```"}], "func_name": "event_loop_impl", "docstring": "Spins mio event loop until the special exit message is received.", "repo": "maidsafe-archive/crust", "path": "src/common/core.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/common/core.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bbaebfb3df7a8afe78887db64e246a272885261c44405460d61ca7dbd598ff4a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_timeout\n\nDocumentation:\nSchedules a new timer with the given info: timer token and id.\nMultiple timers can be scheduled in parallel which will be invoked according to mio token.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_timeout(&mut self, interval: Duration, core_timer: CoreTimer) -> Timeout {\n self.timer.set_timeout(interval, core_timer)\n }\n```"}], "func_name": "set_timeout", "docstring": "Schedules a new timer with the given info: timer token and id.\nMultiple timers can be scheduled in parallel which will be invoked according to mio token.", "repo": "maidsafe-archive/crust", "path": "src/common/core.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/common/core.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "566a5f2cd55c7d25cc8912ad5fd39eeed8debd6b18bcf9db30eb28e7636681d5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: user_data_mut\n\nDocumentation:\nReturns a mutable reference to user data stored in `Core`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn user_data_mut(&mut self) -> &mut T {\n &mut self.user_data\n }\n```"}], "func_name": "user_data_mut", "docstring": "Returns a mutable reference to user data stored in `Core`.", "repo": "maidsafe-archive/crust", "path": "src/common/core.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/common/core.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3b462da710e278857698c6e647fcb85822e8c7c787a80d913216992ebb2d5147"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ipv4_addr\n\nDocumentation:\nA convevience method to build IPv4 address with a port number.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ipv4_addr(a: u8, b: u8, c: u8, d: u8, port: u16) -> SocketAddr {\n SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(a, b, c, d), port))\n}\n```"}], "func_name": "ipv4_addr", "docstring": "A convevience method to build IPv4 address with a port number.", "repo": "maidsafe-archive/crust", "path": "src/common/mod.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/common/mod.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "26fb3d5711bfdbade062d5c4ac862e3b3ddcb259b222c7d7ecbea430d6fa8b2c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: peer_addr\n\nDocumentation:\nHelper function that returns a socket address of the connection\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn peer_addr(&self) -> crate::Res {\n use crate::main::CrustError;\n self.socket.peer_addr().map_err(CrustError::SocketError)\n }\n```"}], "func_name": "peer_addr", "docstring": "Helper function that returns a socket address of the connection", "repo": "maidsafe-archive/crust", "path": "src/main/active_connection.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/active_connection.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f480d0eb75459c9af4de9007e19690de1acf01b5b36436066c14ec4fd25bb487"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_config_file\n\nDocumentation:\nReads the default crust config file.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_config_file() -> crate::Res {\n let file_handler = FileHandler::new(&get_file_name()?, false)?;\n let cfg = file_handler.read_file()?;\n Ok(cfg)\n}\n```"}], "func_name": "read_config_file", "docstring": "Reads the default crust config file.", "repo": "maidsafe-archive/crust", "path": "src/main/config_handler.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/config_handler.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b58b8b2b54d2f07375caa1baa31fba74af5bebf8f00b5977dc094ddaa57cd849"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: try_new\n\nDocumentation:\nConstruct a service.\n\nCan fail, if can't read config file successfully.\n\n## Args\n\n- `event_tx` is the sending half of the channel which crust will send notifications on.\n- `our_uid` is peer ID which contains public encryption key as well.\n- `our_sk` is secret encryption key. This key with the combination of remote peer's public\nkey is used to encrypt traffic between two peers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn try_new(\n event_tx: crate::CrustEventSender,\n our_uid: PeerId,\n our_sk: SecretEncryptKey,\n ) -> crate::Res {\n Service::with_config(\n event_tx,\n config_handler::read_config_file()?,\n our_uid,\n our_sk,\n )\n }\n```"}], "func_name": "try_new", "docstring": "Construct a service.\n\nCan fail, if can't read config file successfully.\n\n## Args\n\n- `event_tx` is the sending half of the channel which crust will send notifications on.\n- `our_uid` is peer ID which contains public encryption key as well.\n- `our_sk` is secret encryption key. This key with the combination of remote peer's public\nkey is used to encrypt traffic between two peers.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b32293ab763ad42c9fcefc3b31e42be955230a8f1e88b5c1928bb1e71cbfa964"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: with_config\n\nDocumentation:\nConstructs a service with the given config. User needs to create an asynchronous channel,\nand provide the sender half to this method. Receiver will receive all `Event`s from this\nlibrary.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn with_config(\n event_tx: crate::CrustEventSender,\n config: Config,\n our_uid: PeerId,\n our_sk: SecretEncryptKey,\n ) -> crate::Res {\n safe_crypto::init()?;\n\n let name_hash = name_hash(&config.network_name);\n\n let mut mc = MappingContext::try_new()?;\n mc.add_peer_stuns(config.hard_coded_contacts.iter().cloned());\n\n let bootstrap_cache_cfg = config.bootstrap_cache.clone();\n let el = common::spawn_event_loop(\n EventToken::Unreserved as usize,\n Some(&format!(\"{:?}\", our_uid)),\n move || {\n let mut cache = bootstrap::Cache::new(bootstrap_cache_cfg);\n cache.read_file();\n let mut user_data = CrustData::new(cache);\n user_data.config = ConfigWrapper::new(config);\n user_data\n },\n )?;\n trace!(\"Event loop started\");\n\n let service = Service {\n event_tx,\n mc: Arc::new(mc),\n el,\n name_hash,\n our_uid,\n our_sk,\n };\n service.start_config_refresher()?;\n service.start_bootstrap_cache_validator()?;\n\n Ok(service)\n }\n```"}], "func_name": "with_config", "docstring": "Constructs a service with the given config. User needs to create an asynchronous channel,\nand provide the sender half to this method. Receiver will receive all `Event`s from this\nlibrary.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2b29bf8db2e278400ab18854e1ec20136f36b3067fd5a44d1918f8c9cd3fd998"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_accept_bootstrap\n\nDocumentation:\nAllow (or disallow) peers from bootstrapping off us.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_accept_bootstrap(&self, accept: bool) -> crate::Res<()> {\n let (tx, rx) = mpsc::channel();\n let _ = self.post(move |core, _| {\n let state = match core.get_state(EventToken::Listener.into()) {\n Some(state) => state,\n None => {\n let _ = tx.send(Err(CrustError::ListenerNotIntialised));\n return;\n }\n };\n let mut state = state.borrow_mut();\n let listener = match state.as_any().downcast_mut::() {\n Some(l) => l,\n None => {\n warn!(\"Token reserved for ConnectionListener has something else.\");\n return;\n }\n };\n listener.set_accept_bootstrap(accept);\n let _ = tx.send(Ok(()));\n });\n\n rx.recv()?\n }\n```"}], "func_name": "set_accept_bootstrap", "docstring": "Allow (or disallow) peers from bootstrapping off us.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "60f6f1a7be245a7a90146b32bd54a494c9b6d13cf43aeb272dac7026ab589c27"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_ext_reachability_test\n\nDocumentation:\nEnables/disables peer external reachability test.\nWhen a new peer connects to us, `Service` listener can be configured to test if this\npeer is reachable directly over it's public IP. If external reachability test is enabled,\nand peer is not reachable, then we discard such connection.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_ext_reachability_test(&self, accept: bool) -> crate::Res<()> {\n let (tx, rx) = mpsc::channel();\n let _ = self.post(move |core, _| {\n let state = match core.get_state(EventToken::Listener.into()) {\n Some(state) => state,\n None => {\n let _ = tx.send(Err(CrustError::ListenerNotIntialised));\n return;\n }\n };\n let mut state = state.borrow_mut();\n let listener = match state.as_any().downcast_mut::() {\n Some(l) => l,\n None => {\n warn!(\"Token reserved for ConnectionListener has something else.\");\n return;\n }\n };\n listener.set_ext_reachability_test(accept);\n let _ = tx.send(Ok(()));\n });\n\n rx.recv()?\n }\n```"}], "func_name": "set_ext_reachability_test", "docstring": "Enables/disables peer external reachability test.\nWhen a new peer connects to us, `Service` listener can be configured to test if this\npeer is reachable directly over it's public IP. If external reachability test is enabled,\nand peer is not reachable, then we discard such connection.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c7b58eef223b344b152a309adb9039c3a6ba1c51cccbe277c126f7fdfe55560d"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_service_discovery\n\nDocumentation:\nInitialises Service Discovery module and starts listening for responses to our beacon\nbroadcasts.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start_service_discovery(&mut self) {\n let our_pk = self.our_uid.pub_enc_key;\n let _ = self.post(move |core, poll| {\n let config = &core.user_data().config.cfg;\n let remote_port = config\n .service_discovery_port\n .unwrap_or(SERVICE_DISCOVERY_DEFAULT_PORT);\n let listener_port = config\n .service_discovery_listener_port\n .unwrap_or(remote_port);\n\n if core\n .get_state(EventToken::ServiceDiscovery.into())\n .is_none()\n {\n if let Err(e) = ServiceDiscovery::start(\n core,\n poll,\n EventToken::ServiceDiscovery.into(),\n listener_port,\n remote_port,\n our_pk,\n ) {\n info!(\"Could not start ServiceDiscovery: {:?}\", e);\n }\n }\n });\n }\n```"}], "func_name": "start_service_discovery", "docstring": "Initialises Service Discovery module and starts listening for responses to our beacon\nbroadcasts.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6f4d7c10d4de82425aa7d0e3fc35ead376ef276c627f306ad3291709e7e4c566"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_service_discovery_listen\n\nDocumentation:\nEnable (or disable) listening and responding to peers searching for us. This can be used to\nallow others to discover us on the local network.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_service_discovery_listen(&self, listen: bool) {\n let _ = self.post(move |core, _| {\n let state = match core.get_state(EventToken::ServiceDiscovery.into()) {\n Some(state) => state,\n None => return,\n };\n let mut state = state.borrow_mut();\n let service_discovery =\n match state.as_any().downcast_mut::>() {\n Some(sd) => sd,\n None => {\n warn!(\"Token reserved for ServiceDiscovery has something else.\");\n return;\n }\n };\n service_discovery.set_listen(listen);\n });\n }\n```"}], "func_name": "set_service_discovery_listen", "docstring": "Enable (or disable) listening and responding to peers searching for us. This can be used to\nallow others to discover us on the local network.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e3f3bc37652c1903fef25cd732fb7349af666e3cc53b4f031f057a6ba786d8ab"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_peer_socket_addr\n\nDocumentation:\nChecks if given peer was connected, if so, returns it's address together with a flag\nindicating whether it was hard coded in config or not.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn get_peer_socket_addr(&self, peer_uid: &PeerId) -> crate::Res<(SocketAddr, bool)> {\n let peer_uid = *peer_uid;\n let (tx, rx) = mpsc::channel();\n\n let _ = self.post(move |core, _| {\n let token = match core.user_data().connections.get(&peer_uid) {\n Some(&ConnectionId {\n active_connection: Some(token),\n ..\n }) => token,\n _ => {\n let _ = tx.send(None);\n return;\n }\n };\n let state = match core.get_state(token) {\n Some(state) => state,\n None => {\n let _ = tx.send(None);\n return;\n }\n };\n match state\n .borrow_mut()\n .as_any()\n .downcast_mut::()\n {\n Some(active_connection) => {\n let config = &core.user_data().config.cfg;\n let peer_addr_res = active_connection.peer_addr().map(|peer_addr| {\n let was_hard_coded = config\n .hard_coded_contacts\n .iter()\n .any(|peer| peer.addr.ip() == peer_addr.ip());\n (peer_addr, was_hard_coded)\n });\n let _ = tx.send(Some(peer_addr_res));\n }\n None => {\n debug!(\"Expected token {:?} to be ActiveConnection\", token);\n let _ = tx.send(None);\n }\n };\n });\n\n match rx.recv() {\n Ok(Some(ip)) => ip,\n Ok(None) => Err(CrustError::PeerNotFound),\n Err(e) => Err(CrustError::ChannelRecv(e)),\n }\n }\n```"}], "func_name": "get_peer_socket_addr", "docstring": "Checks if given peer was connected, if so, returns it's address together with a flag\nindicating whether it was hard coded in config or not.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "52234e1394654adfab82ffb8f4ff44f2d6872420d90a61260b67b19e6dbd478c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_peer_ip_addr\n\nDocumentation:\nReturn the ip address of the peer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_peer_ip_addr(&self, peer_uid: &PeerId) -> crate::Res {\n self.get_peer_socket_addr(peer_uid).map(|(s, _)| s.ip())\n }\n```"}], "func_name": "get_peer_ip_addr", "docstring": "Return the ip address of the peer.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "abb76ab6bfdac457a84b5bef77c1bb2a766306e2d5a302984cd85dc365f5a216"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_peer_hard_coded\n\nDocumentation:\nReturns whether the given peer's IP is in the config file's hard-coded contacts list.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_peer_hard_coded(&self, peer_uid: &PeerId) -> bool {\n self.get_peer_socket_addr(peer_uid)\n .map(|(_, hard_coded)| hard_coded)\n .unwrap_or(false)\n }\n```"}], "func_name": "is_peer_hard_coded", "docstring": "Returns whether the given peer's IP is in the config file's hard-coded contacts list.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "df360d50b119e18d503275eac4bf4dfb98e66895d10ad66490246de5d7bb2601"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: has_peers_on_lan\n\nDocumentation:\nCheck if we have peers on LAN\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn has_peers_on_lan(&self) -> bool {\n use std::thread;\n use std::time::Duration;\n\n let (obs, rx) = mpsc::channel();\n let _ = self.post(move |core, _| {\n let state = match core.get_state(EventToken::ServiceDiscovery.into()) {\n Some(state) => state,\n None => return,\n };\n let mut state = state.borrow_mut();\n let service_discovery =\n match state.as_any().downcast_mut::>() {\n Some(sd) => sd,\n None => {\n warn!(\"Token reserved for ServiceDiscovery has something else.\");\n return;\n }\n };\n service_discovery.register_observer(obs);\n let _ = service_discovery.seek_peers();\n });\n\n thread::sleep(Duration::from_secs(1));\n rx.try_recv().is_ok()\n }\n```"}], "func_name": "has_peers_on_lan", "docstring": "Check if we have peers on LAN", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "943681a49709bc1bf6c080f1c59d34bba98ea7838f4d9baaa0697801e734e7da"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_bootstrap\n\nDocumentation:\nStart the bootstrapping procedure. It will auto terminate after indicating success or\nfailure via the event channel.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start_bootstrap(\n &mut self,\n blacklist: HashSet,\n crust_user: CrustUser,\n ) -> crate::Res<()> {\n let our_uid = self.our_uid;\n let name_hash = self.name_hash;\n let our_sk = self.our_sk.clone();\n let event_tx = self.event_tx.clone();\n\n self.post(move |core, poll| {\n let bootstrapper_role = match crust_user {\n CrustUser::Node => BootstrapperRole::Node(our_global_listener_addrs(core)),\n CrustUser::Client => BootstrapperRole::Client,\n };\n if core.get_state(EventToken::Bootstrap.into()).is_none() {\n if let Err(e) = Bootstrap::start(\n core,\n poll,\n name_hash,\n our_uid,\n bootstrapper_role,\n blacklist,\n EventToken::Bootstrap.into(),\n EventToken::ServiceDiscovery.into(),\n event_tx.clone(),\n &our_sk,\n ) {\n error!(\"Could not bootstrap: {:?}\", e);\n let _ = event_tx.send(Event::BootstrapFailed);\n }\n }\n })\n }\n```"}], "func_name": "start_bootstrap", "docstring": "Start the bootstrapping procedure. It will auto terminate after indicating success or\nfailure via the event channel.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9989f5be2ec7efddf7fb122cda449e1466392b8eab7b1a147ff9d2a75e8f79b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_listening_tcp\n\nDocumentation:\nStarts accepting TCP connections. This is persistant until it errors out or is stopped\nexplicitly.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start_listening_tcp(&mut self) -> crate::Res<()> {\n let mc = self.mc.clone();\n let our_uid = self.our_uid;\n let name_hash = self.name_hash;\n let event_tx = self.event_tx.clone();\n\n let our_sk = self.our_sk.clone();\n self.post(move |core, poll| {\n let config = &core.user_data().config.cfg;\n let port = config.tcp_acceptor_port.unwrap_or(0);\n let force_include_port = config.force_acceptor_port_in_ext_ep;\n\n if core.get_state(EventToken::Listener.into()).is_none() {\n ConnectionListener::start(\n core,\n poll,\n None,\n port,\n force_include_port,\n our_uid,\n name_hash,\n mc,\n EventToken::Listener.into(),\n event_tx,\n our_sk,\n );\n }\n })\n }\n```"}], "func_name": "start_listening_tcp", "docstring": "Starts accepting TCP connections. This is persistant until it errors out or is stopped\nexplicitly.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93e43689efb8a6a081e8169b395a95ac0de38700c8d2f134f810f123793acf96"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: stop_tcp_listener\n\nDocumentation:\nStops Listener explicitly and stops accepting TCP connections.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn stop_tcp_listener(&mut self) -> crate::Res<()> {\n self.post(move |core, poll| {\n if let Some(state) = core.get_state(EventToken::Listener.into()) {\n state.borrow_mut().terminate(core, poll);\n }\n })\n }\n```"}], "func_name": "stop_tcp_listener", "docstring": "Stops Listener explicitly and stops accepting TCP connections.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f1b5ace46d7df8cc3217bd6a4d0b3243ed764f9fd04430f2f3a71431c76fcfbb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: connect\n\nDocumentation:\nConnect to a peer. To call this method you must follow these steps:\n* Generate a `PrivConnectionInfo` via `Service::prepare_connection_info`.\n* Create a `PubConnectionInfo` via `PrivConnectionInfo::to_pub_connection_info`.\n* Swap `PubConnectionInfo`s out-of-band with the peer you are connecting to.\n* Call `Service::connect` using your `PrivConnectionInfo` and the `PubConnectionInfo`\nobtained from the peer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn connect(\n &self,\n our_ci: PrivConnectionInfo,\n mut their_ci: PubConnectionInfo,\n ) -> crate::Res<()> {\n if their_ci.id == self.our_uid {\n debug!(\n \"Requested connect to {:?}, which is our peer ID\",\n their_ci.id\n );\n return Err(CrustError::RequestedConnectToSelf);\n }\n\n let event_tx = self.event_tx.clone();\n let our_nh = self.name_hash;\n let our_sk = self.our_sk.clone();\n\n self.post(move |core, poll| {\n if let Some(ref whitelisted_node_ips) = core.user_data().config.cfg.whitelisted_node_ips\n {\n let their_direct = their_ci\n .for_direct\n .drain(..)\n .filter(|s| whitelisted_node_ips.contains(&s.ip()))\n .collect();\n their_ci.for_direct = their_direct;\n }\n\n if core.user_data().connections.contains_key(&their_ci.id) {\n debug!(\n \"Already connected OR already in process of connecting to {:?}\",\n their_ci.id\n );\n return;\n }\n let _ = Connect::start(\n core,\n poll,\n our_ci,\n their_ci,\n our_nh,\n event_tx,\n &our_sk,\n our_global_listener_addrs(core),\n );\n })?;\n\n Ok(())\n }\n```"}], "func_name": "connect", "docstring": "Connect to a peer. To call this method you must follow these steps:\n* Generate a `PrivConnectionInfo` via `Service::prepare_connection_info`.\n* Create a `PubConnectionInfo` via `PrivConnectionInfo::to_pub_connection_info`.\n* Swap `PubConnectionInfo`s out-of-band with the peer you are connecting to.\n* Call `Service::connect` using your `PrivConnectionInfo` and the `PubConnectionInfo`\nobtained from the peer", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bed18252e502d15996e566362db5c3f22c8cf26fddbaf467db57f2d6cc527b15"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: disconnect\n\nDocumentation:\nDisconnect from the given peer and returns whether there was a connection at all.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn disconnect(&self, peer_uid: &PeerId) -> bool {\n let peer_uid = *peer_uid;\n let (tx, rx) = mpsc::channel();\n\n let _ = self.post(move |core, poll| {\n if let Some(&ConnectionId {\n active_connection: Some(token),\n ..\n }) = core.user_data().connections.get(&peer_uid)\n {\n if let Some(state) = core.get_state(token) {\n state.borrow_mut().terminate(core, poll);\n }\n let _ = tx.send(true);\n } else {\n let _ = tx.send(false);\n }\n });\n\n rx.recv().unwrap_or(false)\n }\n```"}], "func_name": "disconnect", "docstring": "Disconnect from the given peer and returns whether there was a connection at all.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "55cc87d4ec9669debd981e6bf562261db55f4762efeb6b9e03cb50693ab56f1a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_connected\n\nDocumentation:\nCheck if we are connected to the given peer\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_connected(&self, peer_uid: &PeerId) -> bool {\n let peer_uid = *peer_uid;\n let (tx, rx) = mpsc::channel();\n\n let _ = self.post(move |core, _| {\n let connected = match core.user_data().connections.get(&peer_uid) {\n Some(&ConnectionId {\n active_connection: Some(_),\n ..\n }) => true,\n _ => false,\n };\n let _ = tx.send(connected);\n });\n\n rx.recv().unwrap_or(false)\n }\n```"}], "func_name": "is_connected", "docstring": "Check if we are connected to the given peer", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6584ee33cc1b159ea353e02c9f82928f4a84ae6dd5bcf419d9a0668683c90ccb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bootstrap_cached_peers\n\nDocumentation:\nReturns a list of peers stored in bootstrap cache ordered by the most recently used.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bootstrap_cached_peers(&self) -> crate::Res> {\n let (tx, rx) = mpsc::channel();\n let _ = self.post(move |core, _| {\n let cached_peers = core.user_data().bootstrap_cache.snapshot();\n let _ = tx.send(cached_peers);\n });\n rx.recv().map_err(CrustError::ChannelRecv)\n }\n```"}], "func_name": "bootstrap_cached_peers", "docstring": "Returns a list of peers stored in bootstrap cache ordered by the most recently used.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f8621eb437fa120aa0b67f6665b039006a1bebfa68cc9bc311a2f4027117b680"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start_bootstrap_cache_validator\n\nDocumentation:\nStarts a future that periodically tests if inactive cached bootstrap peers are still alive.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn start_bootstrap_cache_validator(&self) -> crate::Res<()> {\n let (tx, rx) = mpsc::channel();\n let (our_pk, our_sk) = (self.our_uid.pub_enc_key, self.our_sk.clone());\n self.post(move |core, _poll| {\n let _ = tx.send(bootstrap::CacheValidator::start(\n core,\n EventToken::BootstrapCacheValidator.into(),\n our_pk,\n our_sk,\n ));\n })?;\n rx.recv()?\n }\n```"}], "func_name": "start_bootstrap_cache_validator", "docstring": "Starts a future that periodically tests if inactive cached bootstrap peers are still alive.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9cd00d8854538241c809182362bc53b19a142f31ae32aa47a6accf24c28ada38"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: name_hash\n\nDocumentation:\nReturns a hash of the network name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn name_hash(network_name: &Option) -> NameHash {\n trace!(\"Network name: {:?}\", network_name);\n match *network_name {\n Some(ref name) => safe_crypto::hash(name.as_bytes()),\n None => [0; HASH_SIZE],\n }\n}\n```"}], "func_name": "name_hash", "docstring": "Returns a hash of the network name.", "repo": "maidsafe-archive/crust", "path": "src/main/service.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/service.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5b6e737510266d36a5e32b7547e7aa70dccd996309f7826a953aac9a01c77626"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: to_pub_connection_info\n\nDocumentation:\nUse private connection info to create public connection info that can be shared with the\npeer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn to_pub_connection_info(&self) -> PubConnectionInfo {\n PubConnectionInfo {\n for_direct: self.for_direct.clone(),\n id: self.id,\n }\n }\n```"}], "func_name": "to_pub_connection_info", "docstring": "Use private connection info to create public connection info that can be shared with the\npeer.", "repo": "maidsafe-archive/crust", "path": "src/main/types.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/types.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6b7db672ca23ad68a99aae1357513c0695aecf0448123dc15b5e302569d539a8"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_for_refresh_and_reset_modified\n\nDocumentation:\nChecks if `ActiveConnection` refresh is needed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check_for_refresh_and_reset_modified(&mut self, new_cfg: Config) -> bool {\n let should_refresh = if self.cfg != new_cfg {\n self.cfg = new_cfg;\n true\n } else {\n self.is_modified_for_next_refresh\n };\n\n self.is_modified_for_next_refresh = false;\n should_refresh\n }\n```"}], "func_name": "check_for_refresh_and_reset_modified", "docstring": "Checks if `ActiveConnection` refresh is needed.", "repo": "maidsafe-archive/crust", "path": "src/main/types.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/types.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7c46d2eb4b3fb183e4311f0ea98962988e0ae780c80b5866913318ab2fe59a2a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nConstructs new bootstrap cache. You can optionally specify the file name which will\nbe used to read/write the cache to. If no file name is given, the default path is used, see\n`#get_default_file_name()`.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new(cfg: CacheConfig) -> Self {\n Cache {\n file_name: cfg.file_name,\n peers: LruCache::with_expiry_duration_and_capacity(\n Duration::from_secs(cfg.timeout),\n cfg.max_size,\n ),\n }\n }\n```"}], "func_name": "new", "docstring": "Constructs new bootstrap cache. You can optionally specify the file name which will\nbe used to read/write the cache to. If no file name is given, the default path is used, see\n`#get_default_file_name()`.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/cache.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/cache.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a73285c31c7cdeb1ca7abf8971043d8dc7efb28f1f377e9c98a7350edf08be22"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: get_default_file_name\n\nDocumentation:\nDefault bootstrap cache file name is executable file + '.bootstrap.cache' suffix.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn get_default_file_name() -> crate::Res {\n let mut name = config_file_handler::exe_file_stem()?;\n name.push(\".bootstrap.cache\");\n Ok(name)\n }\n```"}], "func_name": "get_default_file_name", "docstring": "Default bootstrap cache file name is executable file + '.bootstrap.cache' suffix.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/cache.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/cache.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6ebde6dbdab16c71283db07f1a03d09e3dafa6920c0b7ede614ba3a6f5851322"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: read_file\n\nDocumentation:\nUpdates cache by reading it from file and returns the current snapshot of peers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn read_file(&mut self) {\n match self.open_file() {\n Ok(file_handler) => {\n let mut peers = file_handler.read_file().unwrap_or_else(|e| {\n info!(\"Failed to read bootstrap cache file: {}\", e);\n Default::default()\n });\n for peer in peers.drain(..).rev() {\n let _ = self.peers.insert(peer.pub_key, peer);\n }\n }\n Err(e) => info!(\"Failed to open bootstrap cache file: {}\", e),\n }\n }\n```"}], "func_name": "read_file", "docstring": "Updates cache by reading it from file and returns the current snapshot of peers.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/cache.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/cache.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "93568dbacb485a93983c4d2d12ee2fc736a5c2281eb24c88de7134341da03c53"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: put\n\nDocumentation:\nInserts given peer to the cache. If peer is already cached, it is moved to cache front.\n\n## Returns\n\nA list of expired peers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn put(&mut self, peer: PeerInfo) -> HashSet {\n let (_, mut expired) = self.peers.notify_insert(peer.pub_key, peer);\n expired.drain(..).map(|(_key, val)| val).collect()\n }\n```"}], "func_name": "put", "docstring": "Inserts given peer to the cache. If peer is already cached, it is moved to cache front.\n\n## Returns\n\nA list of expired peers.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/cache.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/cache.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "2c721f5a4b97cbe1b70f36e6839ba228585b3c9bf6db2a9d495b676171a9fa17"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: remove\n\nDocumentation:\nRemoves given peer from the cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn remove(&mut self, peer: &PeerInfo) {\n let _ = self.peers.remove(&peer.pub_key);\n }\n```"}], "func_name": "remove", "docstring": "Removes given peer from the cache.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/cache.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/cache.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "b086854786eecf3aa5794c5bda6d6dec259e569b2c78c9edd7144576218d0fd5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: peers\n\nDocumentation:\nReturns cached peers in the most recently used order.\nMoves returned peers to the top of the cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn peers(&mut self) -> (Vec, HashSet) {\n let expired: HashSet<_> = self\n .peers\n .notify_iter()\n .filter_map(|entry| match entry {\n TimedEntry::Expired(_pub_key, peer_info) => Some(peer_info),\n _ => None,\n })\n .collect();\n let valid: Vec<_> = self\n .peers\n .notify_iter()\n .filter_map(|entry| match entry {\n TimedEntry::Valid(_pub_key, peer_info) => Some(*peer_info),\n _ => None,\n })\n .collect();\n (valid, expired)\n }\n```"}], "func_name": "peers", "docstring": "Returns cached peers in the most recently used order.\nMoves returned peers to the top of the cache.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/cache.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/cache.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "534ce44c73142bb187be1d8fd115eccf901713d98913ddcf37096fb746ff17b6"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: snapshot\n\nDocumentation:\nReturns a snaphost of cached.\nNote that the peer last time used value is not updated in the cache.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn snapshot(&self) -> Vec {\n self.peers.peek_iter().map(|(_, peer)| *peer).collect()\n }\n```"}], "func_name": "snapshot", "docstring": "Returns a snaphost of cached.\nNote that the peer last time used value is not updated in the cache.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/cache.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/cache.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "f16df2bb00c50c27fa37143daec78bb3abd73af97562120d3defa831cece5cb4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: write_bootstrap_cache_to_tmp_file\n\nDocumentation:\n# Arguments\n\n* `content` - json formatted bootstrap cache to be written to file.\n\n# Returns\n\nfile name where content was written to.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn write_bootstrap_cache_to_tmp_file(content: &[u8]) -> OsString {\n let path = bootstrap_cache_tmp_file();\n let mut f = unwrap!(File::create(path.clone()));\n unwrap!(f.write_all(content));\n path.into()\n }\n```"}], "func_name": "write_bootstrap_cache_to_tmp_file", "docstring": "# Arguments\n\n* `content` - json formatted bootstrap cache to be written to file.\n\n# Returns\n\nfile name where content was written to.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/cache.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/cache.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "9c7bd5b23ee12d8b238545fc78d4b6b3440bd5563d856e8d9b153d5339c3bd3a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start\n\nDocumentation:\nStarts running bootstrap cache entry validation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start(\n core: &mut EventLoopCore,\n token: Token,\n our_pk: PublicEncryptKey,\n our_sk: SecretEncryptKey,\n ) -> crate::Res<()> {\n let state = Rc::new(RefCell::new(Self {\n token,\n our_pk,\n our_sk,\n sent_requests: Default::default(),\n self_weak: Default::default(),\n }));\n state.borrow_mut().self_weak = Rc::downgrade(&state);\n let _ = core.insert_state(token, state.clone());\n\n Ok(())\n }\n```"}], "func_name": "start", "docstring": "Starts running bootstrap cache entry validation.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/cache_validator.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/cache_validator.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "fea9d47af9aedf5703c3d0bffd3a584327b482bcce41972ae008d0a8edb89609"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ping_inactive_peers\n\nDocumentation:\nSends STUN requests to cached peers that recently been inactive.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ping_inactive_peers(\n &mut self,\n core: &mut EventLoopCore,\n poll: &Poll,\n inactive_peers: HashSet,\n ) {\n debug!(\"Testing {} inactive cached peers.\", inactive_peers.len());\n for peer in inactive_peers {\n self.ping_peer_and_cache_alive(core, poll, peer);\n }\n }\n```"}], "func_name": "ping_inactive_peers", "docstring": "Sends STUN requests to cached peers that recently been inactive.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/cache_validator.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/cache_validator.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1a83b6f3275bf3a4710b550e0601f140bd54507c56d92cd83fcd3910590b1488"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ping_peer_and_cache_alive\n\nDocumentation:\nSend STUN request to given peer and wait for response.\nIf response arrives within timeout, peer is added to the bootstrap cache head.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn ping_peer_and_cache_alive(&mut self, core: &mut EventLoopCore, poll: &Poll, peer: PeerInfo) {\n let finish = self.make_ping_resp_handler(peer);\n if let Ok(request_token) = GetExtAddr::start(\n core,\n poll,\n ipv4_addr(0, 0, 0, 0, 0),\n &peer,\n self.our_pk,\n &self.our_sk,\n Some(PEER_TEST_TIMEOUT_SEC),\n finish,\n ) {\n let _ = self.sent_requests.insert(request_token);\n }\n }\n```"}], "func_name": "ping_peer_and_cache_alive", "docstring": "Send STUN request to given peer and wait for response.\nIf response arrives within timeout, peer is added to the bootstrap cache head.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/cache_validator.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/cache_validator.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "84cecb36fc98cf2d7385b3c8478fed8ee6629481b30ecaa626c6b6eaa3bb3bcb"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: make_ping_resp_handler\n\nDocumentation:\nBuild a function that will handle response from the peer.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn make_ping_resp_handler(&self, peer: PeerInfo) -> GetExtAddrFinish {\n let self_weak = self.self_weak.clone();\n let finish = move |core: &mut EventLoopCore,\n poll: &Poll,\n request_token,\n req_status: Result| {\n if let Some(self_rc) = self_weak.upgrade() {\n let mut self_rc = self_rc.borrow_mut();\n let _ = self_rc.sent_requests.remove(&request_token);\n if req_status.is_ok() {\n let bootstrap_cache = &mut core.user_data_mut().bootstrap_cache;\n let expired_peers = bootstrap_cache.put(peer);\n bootstrap_cache.try_commit();\n if !expired_peers.is_empty() {\n self_rc.ping_inactive_peers(core, poll, expired_peers);\n }\n }\n }\n };\n Box::new(finish)\n }\n```"}], "func_name": "make_ping_resp_handler", "docstring": "Build a function that will handle response from the peer.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/cache_validator.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/cache_validator.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "eef73257aff70648fe1513b0b31ba659091d48e0a821cd8a856b44181c4b9283"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: test_inactive_cached_peers\n\nDocumentation:\nSchedules tests for inactive cached bootstrap peers.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn test_inactive_cached_peers(core: &mut EventLoopCore, poll: &Poll, peers: HashSet) {\n if let Some(state) = core.get_state(EventToken::BootstrapCacheValidator.into()) {\n if let Some(validator) = state.borrow_mut().as_any().downcast_mut::() {\n validator.ping_inactive_peers(core, poll, peers);\n }\n }\n}\n```"}], "func_name": "test_inactive_cached_peers", "docstring": "Schedules tests for inactive cached bootstrap peers.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/cache_validator.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/cache_validator.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d24fd0d10f7f5be2ff6b01a24dde5b2ddd57463af488f15b0d8426d29addbeb1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start\n\nDocumentation:\n# Args\n\n`our_role` - Crust role during bootstrap: client or node. Clients are never checked for\nexternal reachability.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start(\n core: &mut EventLoopCore,\n poll: &Poll,\n name_hash: NameHash,\n our_uid: PeerId,\n our_role: BootstrapperRole,\n blacklist: HashSet,\n token: Token,\n service_discovery_token: Token,\n event_tx: crate::CrustEventSender,\n our_sk: &SecretEncryptKey,\n ) -> crate::Res<()> {\n let bs_timer = CoreTimer::new(token, BOOTSTRAP_TIMER_ID);\n let bs_timeout = core.set_timeout(Duration::from_secs(BOOTSTRAP_TIMEOUT_SEC), bs_timer);\n let sd_meta = match seek_peers(core, service_discovery_token, token) {\n Ok((rx, timeout)) => Some(ServiceDiscMeta { rx, timeout }),\n Err(CrustError::ServiceDiscNotEnabled) => None,\n Err(e) => {\n debug!(\"Failed to seek peers using service discovery: {:?}\", e);\n return Err(e);\n }\n };\n\n let (cached_peers, expired_peers) = core.user_data_mut().bootstrap_cache.peers();\n test_inactive_cached_peers(core, poll, expired_peers);\n\n let peers = bootstrap_peers(cached_peers, &core.user_data().config.cfg, blacklist);\n let state = Rc::new(RefCell::new(Self {\n token,\n peers,\n name_hash,\n our_uid,\n our_role,\n event_tx,\n sd_meta,\n bs_timer,\n bs_timeout,\n children: HashSet::with_capacity(MAX_CONTACTS_EXPECTED),\n self_weak: Weak::new(),\n our_sk: our_sk.clone(),\n }));\n\n state.borrow_mut().self_weak = Rc::downgrade(&state);\n\n let _ = core.insert_state(token, state.clone());\n\n if state.borrow().sd_meta.is_none() {\n state.borrow_mut().begin_bootstrap(core, poll);\n }\n\n Ok(())\n }\n```"}], "func_name": "start", "docstring": "# Args\n\n`our_role` - Crust role during bootstrap: client or node. Clients are never checked for\nexternal reachability.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/mod.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/mod.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "077c43a0aed27fa1f7740f98446fba33b3503937b84cdbaacf5d3b4cd8c44ec2"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_result\n\nDocumentation:\nSpawns `ActiveConnection` state and terminates remaining bootstrap attempts.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_result(\n &mut self,\n core: &mut EventLoopCore,\n poll: &Poll,\n child: Token,\n res: Result<(TcpSock, PeerInfo, PeerId), (PeerInfo, Option)>,\n ) {\n let _ = self.children.remove(&child);\n match res {\n Ok((socket, peer_info, peer_id)) => {\n self.terminate(core, poll);\n return ActiveConnection::start(\n core,\n poll,\n child,\n socket,\n self.our_uid,\n peer_id,\n // Note; We bootstrap only to Nodes\n CrustUser::Node,\n Event::BootstrapConnect(peer_id, peer_info.addr),\n self.event_tx.clone(),\n );\n }\n Err((bad_peer, opt_reason)) => {\n {\n let bootstrap_cache = &mut core.user_data_mut().bootstrap_cache;\n bootstrap_cache.remove(&bad_peer);\n bootstrap_cache.try_commit();\n }\n\n if let Some(reason) = opt_reason {\n let (err_msg, is_err_fatal) = match reason {\n BootstrapDenyReason::InvalidNameHash => (\"Network name mismatch.\", false),\n BootstrapDenyReason::FailedExternalReachability => (\n \"Bootstrappee node could not establish connection to us.\",\n true,\n ),\n BootstrapDenyReason::NodeNotWhitelisted => {\n (\"Our Node is not whitelisted\", false)\n }\n BootstrapDenyReason::ClientNotWhitelisted => {\n (\"Our Client is not whitelisted\", false)\n }\n };\n if is_err_fatal {\n info!(\"Failed to Bootstrap: ({:?}) {}\", reason, err_msg);\n self.terminate(core, poll);\n let _ = self.event_tx.send(Event::BootstrapFailed);\n return;\n } else {\n info!(\n \"Failed to Bootstrap with {:?}: ({:?}) {}\",\n bad_peer, reason, err_msg\n );\n }\n }\n }\n }\n self.maybe_terminate(core, poll);\n }\n```"}], "func_name": "handle_result", "docstring": "Spawns `ActiveConnection` state and terminates remaining bootstrap attempts.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/mod.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/mod.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "4d5f9b8cc17123d32284ad3de1e074e0b52d22f5573a5e60b01eb503081578f3"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: cache_peer_info\n\nDocumentation:\nPuts given peer contacts into bootstrap cache which is then written to disk.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn cache_peer_info(core: &mut EventLoopCore, poll: &Poll, peer_info: PeerInfo) {\n let user_data = &mut core.user_data_mut();\n if user_data\n .config\n .cfg\n .hard_coded_contacts\n .contains(&peer_info)\n {\n debug!(\"Connecting to hard coded peer - it won't be cached.\");\n return;\n }\n\n let expired_peers = user_data.bootstrap_cache.put(peer_info);\n user_data.bootstrap_cache.try_commit();\n test_inactive_cached_peers(core, poll, expired_peers);\n}\n```"}], "func_name": "cache_peer_info", "docstring": "Puts given peer contacts into bootstrap cache which is then written to disk.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/mod.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/mod.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb039965a18b936911b191c8b406df6766a6816a9f9ee4c1e5f79e2b64e7478f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: seek_peers\n\nDocumentation:\nRuns service discovery state with a timeout. When timeout happens, `Bootstrap::timeout()`\ncallback is called.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn seek_peers(\n core: &mut EventLoopCore,\n service_discovery_token: Token,\n token: Token,\n) -> crate::Res<(Receiver>, Timeout)> {\n if let Some(state) = core.get_state(service_discovery_token) {\n let mut state = state.borrow_mut();\n let state = unwrap!(state.as_any().downcast_mut::>());\n\n let (obs, rx) = mpsc::channel();\n state.register_observer(obs);\n state.seek_peers()?;\n let timeout = core.set_timeout(\n Duration::from_secs(SERVICE_DISCOVERY_TIMEOUT_SEC),\n CoreTimer::new(token, SERVICE_DISCOVERY_TIMER_ID),\n );\n\n Ok((rx, timeout))\n } else {\n Err(CrustError::ServiceDiscNotEnabled)\n }\n}\n```"}], "func_name": "seek_peers", "docstring": "Runs service discovery state with a timeout. When timeout happens, `Bootstrap::timeout()`\ncallback is called.", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/mod.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/mod.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "cb3a87b5003c1cd8d6fe20413fc5e28c3adf6611d97c636f7373f26f076e76b4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: receive_peers_into\n\nDocumentation:\nAppends peers received from `ServiceDiscMeta` to the peers list\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn receive_peers_into(peers: &mut Vec, rx: Receiver>) {\n let our_peers: HashSet<&PeerInfo> = HashSet::from_iter(peers.iter());\n\n let discovered_peers: HashSet = rx\n .try_iter()\n .flatten()\n .filter(|peer| !our_peers.contains(peer))\n .collect();\n\n peers.extend(discovered_peers);\n}\n```"}], "func_name": "receive_peers_into", "docstring": "Appends peers received from `ServiceDiscMeta` to the peers list", "repo": "maidsafe-archive/crust", "path": "src/main/bootstrap/mod.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/bootstrap/mod.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "47b3ca6eb7af6d1e0874fc0ca04ff948a2b9842c1e7c94c037a0773ebd8bfa96"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: start\n\nDocumentation:\n# Args\n\n`test_ext_reachability` - if true, we will check if remote peer has public IP and we can\nreach it directly.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn start(\n core: &mut EventLoopCore,\n poll: &Poll,\n timeout_sec: Option,\n socket: TcpSock,\n accept_bootstrap: bool,\n our_uid: PeerId,\n name_hash: NameHash,\n event_tx: crate::CrustEventSender,\n our_sk: &SecretEncryptKey,\n test_ext_reachability: bool,\n ) -> crate::Res<()> {\n let token = core.get_new_token();\n\n let kind = Ready::readable();\n poll.register(&socket, token, kind, PollOpt::edge())?;\n\n let timeout = core.set_timeout(\n Duration::from_secs(timeout_sec.unwrap_or(EXCHANGE_MSG_TIMEOUT_SEC)),\n CoreTimer::new(token, 0),\n );\n\n let state = Rc::new(RefCell::new(Self {\n token,\n event_tx,\n name_hash,\n next_state: NextState::None,\n our_uid,\n socket,\n timeout,\n reachability_children: HashSet::with_capacity(4),\n accept_bootstrap,\n test_ext_reachability,\n self_weak: Default::default(),\n our_sk: our_sk.clone(),\n }));\n\n state.borrow_mut().self_weak = Rc::downgrade(&state);\n\n let _ = core.insert_state(token, state);\n\n Ok(())\n }\n```"}], "func_name": "start", "docstring": "# Args\n\n`test_ext_reachability` - if true, we will check if remote peer has public IP and we can\nreach it directly.", "repo": "maidsafe-archive/crust", "path": "src/main/connection_listener/exchange_msg.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/connection_listener/exchange_msg.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "be14e1cb72bfab90d725688bae4aaf516aa860ccb0d494c06eda5dc556560640"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: handle_check_reachability_on_connect\n\nDocumentation:\nCalled when external reachability test passed.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn handle_check_reachability_on_connect(\n &mut self,\n core: &mut EventLoopCore,\n poll: &Poll,\n child: Token,\n res: Result,\n ) {\n let _ = self.reachability_children.remove(&child);\n if let Ok(their_uid) = res {\n self.terminate_childern(core, poll);\n return self.send_connect_grant(core, poll, their_uid);\n }\n if self.reachability_children.is_empty() {\n trace!(\"External reachability test failed, terminating connection.\");\n self.terminate(core, poll);\n }\n }\n```"}], "func_name": "handle_check_reachability_on_connect", "docstring": "Called when external reachability test passed.", "repo": "maidsafe-archive/crust", "path": "src/main/connection_listener/exchange_msg.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/connection_listener/exchange_msg.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "951293ef3342d92d9979620edfd6268b044af38af42d26ee81cf29682488762e"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: use_authed_encryption\n\nDocumentation:\nSet socket encrypt context to authenticated encryption.\nReturns false on failure.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn use_authed_encryption(&mut self, their_pk: PublicEncryptKey) -> bool {\n let shared_key = self.our_sk.shared_secret(&their_pk);\n match (\n self.socket\n .set_encrypt_ctx(EncryptContext::authenticated(shared_key.clone())),\n self.socket\n .set_decrypt_ctx(DecryptContext::authenticated(shared_key)),\n ) {\n (Ok(_), Ok(_)) => true,\n res => {\n debug!(\"Failed to set decrypt/encrypt context: {:?}\", res);\n false\n }\n }\n }\n```"}], "func_name": "use_authed_encryption", "docstring": "Set socket encrypt context to authenticated encryption.\nReturns false on failure.", "repo": "maidsafe-archive/crust", "path": "src/main/connection_listener/exchange_msg.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/connection_listener/exchange_msg.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "454d618d936e7580dd41d8732b08d58586662c87a431fefa0f8c0fbe96e4ff13"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: spawn_ext_reachability_tests\n\nDocumentation:\nSpawns multiple children states that check which of given addresses are publicly reachable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn spawn_ext_reachability_tests(\n &mut self,\n core: &mut EventLoopCore,\n poll: &Poll,\n their_uid: PeerId,\n their_addrs: HashSet,\n on_result: F,\n ) where\n F: 'static\n + FnMut(RefMut, &mut EventLoopCore, &Poll, Token, Result)\n + Clone,\n {\n for their_listener in self.addrs_for_ext_reachability_test(their_addrs) {\n let self_weak = self.self_weak.clone();\n let mut on_result = on_result.clone();\n let finish =\n move |core: &mut EventLoopCore, poll: &Poll, child, res: Result| {\n if let Some(self_rc) = self_weak.upgrade() {\n let res = res.map(|_| their_uid);\n on_result(self_rc.borrow_mut(), core, poll, child, res);\n }\n };\n\n if let Ok(child) = GetExtAddr::::start(\n core,\n poll,\n ipv4_addr(0, 0, 0, 0, 0),\n &PeerInfo::new(their_listener, their_uid.pub_enc_key),\n self.our_uid.pub_enc_key,\n &self.our_sk,\n Some(CHECK_REACHABILITY_TIMEOUT_SEC),\n Box::new(finish),\n ) {\n let _ = self.reachability_children.insert(child);\n }\n }\n }\n```"}], "func_name": "spawn_ext_reachability_tests", "docstring": "Spawns multiple children states that check which of given addresses are publicly reachable.", "repo": "maidsafe-archive/crust", "path": "src/main/connection_listener/exchange_msg.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/connection_listener/exchange_msg.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3a26f9eb81479308bb92fd33a1cf724ba4056f818f44ca3206901b76787bac61"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: addrs_for_ext_reachability_test\n\nDocumentation:\nFilters out addresses that are not public IPs and don't belong to the sender socket.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn addrs_for_ext_reachability_test(\n &self,\n their_addrs: HashSet,\n ) -> HashSet {\n their_addrs\n .into_iter()\n .filter(|addr| ip_addr_is_global(&addr.ip()))\n .filter(|addr| match self.socket.peer_addr() {\n Ok(peer_addr) => addr.ip() == peer_addr.ip(),\n Err(e) => {\n debug!(\"Could not obtain IP Address of peer: {:?}.\", e);\n false\n }\n })\n .take(MAX_EXT_REACHABILITY_TEST_ADDRS)\n .collect()\n }\n```"}], "func_name": "addrs_for_ext_reachability_test", "docstring": "Filters out addresses that are not public IPs and don't belong to the sender socket.", "repo": "maidsafe-archive/crust", "path": "src/main/connection_listener/exchange_msg.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/connection_listener/exchange_msg.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "97a07db0e15958e260692365420fe28cf841ba0e4e085e8d9b5aab1636f0f873"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: set_ext_reachability_test\n\nDocumentation:\nEnables/disables peer external reachability test.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn set_ext_reachability_test(&mut self, test: bool) {\n self.test_ext_reachability = test;\n }\n```"}], "func_name": "set_ext_reachability_test", "docstring": "Enables/disables peer external reachability test.", "repo": "maidsafe-archive/crust", "path": "src/main/connection_listener/mod.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/main/connection_listener/mod.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "1978dd9524b28cc16aec27718e6e32baf4d1c6cc049d0860022d1d127c22179b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_peer_stuns\n\nDocumentation:\nInform the context about external \"STUN\" servers. Note that crust does not actually use\nSTUN but a custom STUN-like protocol.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn add_peer_stuns>(&mut self, stun_addrs: A) {\n let listeners = stun_addrs\n .into_iter()\n .filter(|peer| nat::ip_addr_is_global(&peer.addr.ip()));\n self.peer_stuns.extend(listeners);\n }\n```"}], "func_name": "add_peer_stuns", "docstring": "Inform the context about external \"STUN\" servers. Note that crust does not actually use\nSTUN but a custom STUN-like protocol.", "repo": "maidsafe-archive/crust", "path": "src/nat/mapping_context.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/nat/mapping_context.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "7ac65a71bb4c4efe73bfe8e0c4a386deaa9ddf860f4b949ca7fb2e59a167a232"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ip_addr_is_global\n\nDocumentation:\nA replacement for `IpAddr::is_global` while we wait for that to enter stable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ip_addr_is_global(ip: &IpAddr) -> bool {\n match *ip {\n IpAddr::V4(addr_v4) => ipv4_addr_is_global(addr_v4),\n IpAddr::V6(addr_v6) => ipv6_addr_is_global(addr_v6),\n }\n}\n```"}], "func_name": "ip_addr_is_global", "docstring": "A replacement for `IpAddr::is_global` while we wait for that to enter stable.", "repo": "maidsafe-archive/crust", "path": "src/nat/util.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/nat/util.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "37fdf6b45534507142e974c6d09d2f06a3d67c5b3ae60c02fb37962b1cd34009"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ipv4_addr_is_global\n\nDocumentation:\nA replacement for `Ipv4Addr::is_global` while we wait for that to enter stable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ipv4_addr_is_global(ipv4: Ipv4Addr) -> bool {\n !(ipv4.is_loopback()\n || ipv4.is_private()\n || ipv4.is_link_local()\n || ipv4.is_multicast()\n || ipv4.is_broadcast()\n || ipv4.is_documentation()\n || ipv4.octets() == [0, 0, 0, 0])\n}\n```"}], "func_name": "ipv4_addr_is_global", "docstring": "A replacement for `Ipv4Addr::is_global` while we wait for that to enter stable.", "repo": "maidsafe-archive/crust", "path": "src/nat/util.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/nat/util.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "275430c7f2857323e8bb26812b669a0306ba0350788e6b52b277a4dbc2591d0b"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: ipv6_addr_is_global\n\nDocumentation:\nA replacement for `Ipv6Addr::is_global` while we wait for that to enter stable.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn ipv6_addr_is_global(ipv6: Ipv6Addr) -> bool {\n // TODO(canndrew): This function is incomplete and may return false-positives.\n !(ipv6.is_loopback() || ipv6.is_unspecified())\n}\n```"}], "func_name": "ipv6_addr_is_global", "docstring": "A replacement for `Ipv6Addr::is_global` while we wait for that to enter stable.", "repo": "maidsafe-archive/crust", "path": "src/nat/util.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/nat/util.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "bb022f929f064003bf65072992eccf79f361bf1b776bb720bdedf44f40d6fb98"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: bootstrap_cache_tmp_file\n\nDocumentation:\nConstructs random bootstrap cache file name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn bootstrap_cache_tmp_file() -> PathBuf {\n let fname = format!(\"{:016x}.bootstrap.cache\", rand::random::());\n let mut path = env::temp_dir();\n path.push(fname);\n path\n}\n```"}], "func_name": "bootstrap_cache_tmp_file", "docstring": "Constructs random bootstrap cache file name.", "repo": "maidsafe-archive/crust", "path": "src/tests/utils.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/tests/utils.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "309e1c2b6839d506caa79d2daca1f41ab4d9ddf9cd08ccfc70839b5c30111c79"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: test_core\n\nDocumentation:\nCreates `Core` for tests with some defaults.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn test_core(bootstrap_cache: BootstrapCache) -> EventLoopCore {\n let (event_tx, _event_rx) = channel();\n let timer = timer::Builder::default().build();\n EventLoopCore::new_for_tests(0, event_tx, timer, CrustData::new(bootstrap_cache))\n}\n```"}], "func_name": "test_core", "docstring": "Creates `Core` for tests with some defaults.", "repo": "maidsafe-archive/crust", "path": "src/tests/utils.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/tests/utils.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5dfa119b5ef407a068bb371e5ca5f12fdd9c6261a13548290726caf539ecc52a"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: test_bootstrap_cache\n\nDocumentation:\nBootstrap cache on tmp directory with unique file name.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn test_bootstrap_cache() -> BootstrapCache {\n let cache_file = bootstrap_cache_tmp_file().into();\n BootstrapCache::new(BootstrapCacheConfig {\n file_name: Some(cache_file),\n max_size: 100,\n timeout: 120,\n })\n}\n```"}], "func_name": "test_bootstrap_cache", "docstring": "Bootstrap cache on tmp directory with unique file name.", "repo": "maidsafe-archive/crust", "path": "src/tests/utils.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/tests/utils.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "dd70eafbb07ef43b53fdfdf960d5cabc5bc1aa2c71d4023eb35a0170ef88eba5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: peer_info_with_rand_key\n\nDocumentation:\nConstructs peer info with random generated public key.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn peer_info_with_rand_key(addr: SocketAddr) -> PeerInfo {\n let (pk, _) = gen_encrypt_keypair();\n PeerInfo::new(addr, pk)\n}\n```"}], "func_name": "peer_info_with_rand_key", "docstring": "Constructs peer info with random generated public key.", "repo": "maidsafe-archive/crust", "path": "src/tests/utils.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/tests/utils.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a07e075678c6ea7256c56bf25c94d7721da0e75ee38750aa6a4b848b7bd59d43"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: test_service\n\nDocumentation:\nGenerates `Service` instance for testing with default configuration.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn test_service() -> (Service, Receiver) {\n let config = gen_config();\n let (event_tx, event_rx) = get_event_sender();\n let (peer_id, peer_sk) = rand_peer_id_and_enc_sk();\n let service = unwrap!(Service::with_config(event_tx, config, peer_id, peer_sk));\n (service, event_rx)\n}\n```"}], "func_name": "test_service", "docstring": "Generates `Service` instance for testing with default configuration.", "repo": "maidsafe-archive/crust", "path": "src/tests/utils.rs", "url": "https://github.com/maidsafe-archive/crust/blob/master/src/tests/utils.rs", "license": "BSD-3-Clause", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "e348341efd856577c2193e9ebdcd0da5289ffb24ecf06daf19bbf8abead6f408"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: new\n\nDocumentation:\nCreate a new instance of `QueryTree` with given path sequence.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn new>(paths: &[&'a S]) -> Result {\n let mut tree = Self::default();\n for path in paths {\n tree.add_path((*path).as_ref())?;\n }\n Ok(tree)\n }\n```"}], "func_name": "new", "docstring": "Create a new instance of `QueryTree` with given path sequence.", "repo": "pikkr/pikkr", "path": "src/query.rs", "url": "https://github.com/pikkr/pikkr/blob/master/src/query.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ef5e33c370eb62e319ae1ca716a0a834797adf845504488bec4050ed64c24cc5"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: add_path\n\nDocumentation:\nAdd a path into the pattern tree.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn add_path(&mut self, path: &'a [u8]) -> Result<()> {\n if !is_valid_query_str(path) {\n return Err(Error::from(ErrorKind::InvalidQuery));\n }\n\n let mut cur = &mut self.root_node;\n for field in path[ROOT_QUERY_STR_OFFSET..].split(|&b| b == DOT) {\n let level = cur.level + 1;\n let num_nodes = &mut self.num_nodes;\n let cur1 = cur; // workaround for lifetime error\n cur = cur1.children.entry(field).or_insert_with(|| {\n let node = QueryNode {\n node_id: Some(*num_nodes),\n level,\n ..Default::default()\n };\n *num_nodes += 1;\n node\n });\n }\n // mark the last node as a target\n cur.path_id = Some(self.paths.len());\n\n self.max_level = cmp::max(self.max_level, cur.level);\n self.paths.push(path);\n\n Ok(())\n }\n```"}], "func_name": "add_path", "docstring": "Add a path into the pattern tree.", "repo": "pikkr/pikkr", "path": "src/query.rs", "url": "https://github.com/pikkr/pikkr/blob/master/src/query.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "19cc92ba662bdf880cd0043ddf29275715c66d1dc2ec60db086969b9d683ad18"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: buffer_view\n\nDocumentation:\nReturns a string representation of the given buffer for debugging purpose.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn buffer_view(buffer: &Buffer) -> String {\n let mut view = String::with_capacity(buffer.content.len() + buffer.area.height as usize * 3);\n for cells in buffer.content.chunks(buffer.area.width as usize) {\n let mut overwritten = vec![];\n let mut skip: usize = 0;\n view.push('\"');\n for (x, c) in cells.iter().enumerate() {\n if skip == 0 {\n view.push_str(c.symbol());\n } else {\n overwritten.push((x, c.symbol()))\n }\n skip = std::cmp::max(skip, c.symbol().width()).saturating_sub(1);\n }\n view.push('\"');\n if !overwritten.is_empty() {\n write!(&mut view, \" Hidden by multi-width symbols: {:?}\", overwritten).unwrap();\n }\n view.push('\\n');\n }\n view\n }\n```"}], "func_name": "buffer_view", "docstring": "Returns a string representation of the given buffer for debugging purpose.", "repo": "kdheepak/taskwarrior-tui", "path": "src/app.rs", "url": "https://github.com/kdheepak/taskwarrior-tui/blob/master/src/app.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "ff11b7d262f47880a4713d3931ecb234c054e1c272000217c328145dc12ccdb4"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: simple\n\nDocumentation:\na convenient util for creating JsExpr::Simple\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn simple>>(v: V) -> Self {\n JsExpr::Simple(v.into(), StaticLevel::NotStatic)\n }\n```"}], "func_name": "simple", "docstring": "a convenient util for creating JsExpr::Simple", "repo": "HerringtonDarkholme/vue-compiler", "path": "crates/compiler/src/ir.rs", "url": "https://github.com/HerringtonDarkholme/vue-compiler/blob/master/crates/compiler/src/ir.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "5d0b25ae13941feaee2e3ca4180c1c36165f999426aee5d4d939d2201febdf85"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: is_all_whitespace\n\nDocumentation:\nif TextNode contains only whitespaces. In HTML it means empty node.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn is_all_whitespace(&self) -> bool {\n self.text.iter().all(|s| !s.chars().any(non_whitespace))\n }\n```"}], "func_name": "is_all_whitespace", "docstring": "if TextNode contains only whitespaces. In HTML it means empty node.", "repo": "HerringtonDarkholme/vue-compiler", "path": "crates/compiler/src/parser.rs", "url": "https://github.com/HerringtonDarkholme/vue-compiler/blob/master/crates/compiler/src/parser.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "d7d1114a65a314f95e92bc12db86ef973abf874df6b5b8420ac2932d86ea95e1"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: check_empty_expr\n\nDocumentation:\nReturns the error if expression is empty\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn check_empty_expr(&self, kind: ErrorKind) -> Option {\n if !self.has_empty_expr() {\n return None;\n }\n let loc = self\n .expression\n .as_ref()\n .map_or(self.head_loc.clone(), |v| v.location.clone());\n Some(CompilationError::new(kind).with_location(loc))\n }\n```"}], "func_name": "check_empty_expr", "docstring": "Returns the error if expression is empty", "repo": "HerringtonDarkholme/vue-compiler", "path": "crates/compiler/src/parser.rs", "url": "https://github.com/HerringtonDarkholme/vue-compiler/blob/master/crates/compiler/src/parser.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "a24579be2efdd3698c9ea98223ba223130c30dfef509694fbb696af1dbbd95ff"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_preamble\n\nDocumentation:\nfor import helpers or hoist that not in function\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_preamble(&mut self, top: &mut TopScope<'a>) -> Output {\n match &self.option.clone().mode {\n ScriptMode::Module {\n runtime_module_name,\n } => self.gen_module_preamble(top, runtime_module_name),\n ScriptMode::Function {\n runtime_global_name,\n ..\n } => self.gen_function_preamble(top, runtime_global_name),\n }\n }\n```"}], "func_name": "generate_preamble", "docstring": "for import helpers or hoist that not in function", "repo": "HerringtonDarkholme/vue-compiler", "path": "crates/compiler/src/codegen/code_writer.rs", "url": "https://github.com/HerringtonDarkholme/vue-compiler/blob/master/crates/compiler/src/codegen/code_writer.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "6e028dcea9bbd38fa0e4c2a7916ff4cc68d0c18b2ad7acf4e3ab9dba49b7cc4f"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: generate_function_signature\n\nDocumentation:\nrender() or ssrRender() and their parameters\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn generate_function_signature(&mut self) -> Output {\n let option = &self.sfc_info;\n let args = if !option.binding_metadata.is_empty() && !option.inline {\n \"_ctx, _cache, $props, $setup, $data, $options\"\n } else {\n \"_ctx, _cache\"\n };\n // NB: vue uses arrow func for inline mode.\n // but it makes no diff in Vue runtime implementation?\n self.write_str(\"function render(\")?;\n self.write_str(args)?;\n self.write_str(\") {\")?;\n self.closing_brackets += 1;\n self.indent()\n }\n```"}], "func_name": "generate_function_signature", "docstring": "render() or ssrRender() and their parameters", "repo": "HerringtonDarkholme/vue-compiler", "path": "crates/compiler/src/codegen/code_writer.rs", "url": "https://github.com/HerringtonDarkholme/vue-compiler/blob/master/crates/compiler/src/codegen/code_writer.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "3810c578985889e1483e4d056ca22def75682789928032d4a460cf230842547c"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: gen_vnode_call_args\n\nDocumentation:\nGenerate variadic vnode call argument list separated by comma.\nVNode arg is a heterogeneous list we need hard code the generation.\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn gen_vnode_call_args<'a, T: ioWrite>(gen: &mut CodeWriter<'a, T>, v: BaseVNode<'a>) -> Output {\n let VNodeIR {\n tag,\n props,\n children,\n patch_flag,\n dynamic_props,\n hoisted,\n ..\n } = v;\n let has_props = props.is_some() || hoisted.has_props_hoisted().is_some();\n let has_children = !children.is_empty() || hoisted.has_children_hoisted().is_some();\n let has_dynamic_props =\n !dynamic_props.is_empty() || hoisted.has_dynamic_props_hoisted().is_some();\n\n gen_vnode_args!(\n gen,\n true, { gen.generate_js_expr(tag)?; }\n has_props, {\n if let Some(props) = props {\n gen.generate_js_expr(props)?;\n } else if let Some(&index) = hoisted.has_props_hoisted() {\n gen.generate_hoisted(index)?;\n }\n }\n has_children, {\n if let Some(&index) = hoisted.has_children_hoisted() {\n gen.generate_hoisted(index)?;\n } else {\n gen.generate_children(children)?;\n }\n }\n patch_flag != PatchFlag::empty(), {\n gen.write_patch(patch_flag)?;\n }\n has_dynamic_props, {\n if let Some(&index) = hoisted.has_dynamic_props_hoisted() {\n gen.generate_hoisted(index)?;\n } else {\n gen.gen_dynamic_props(dynamic_props)?;\n }\n }\n );\n Ok(())\n}\n```"}], "func_name": "gen_vnode_call_args", "docstring": "Generate variadic vnode call argument list separated by comma.\nVNode arg is a heterogeneous list we need hard code the generation.", "repo": "HerringtonDarkholme/vue-compiler", "path": "crates/compiler/src/codegen/code_writer.rs", "url": "https://github.com/HerringtonDarkholme/vue-compiler/blob/master/crates/compiler/src/codegen/code_writer.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "c1cbbbd2723cfc156ae1c225451f2df3401f6cbc65347f8c5cc9b1d10bd712dd"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve_element_tag\n\nDocumentation:\nReturns a expression for createVnode's first argument. It can be\n1. Js::Call for dynamic component or user component.\n2. Js::Symbol for builtin component\n3. Js::StrLit for plain element or component\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\npub fn resolve_element_tag<'a>(bc: &BC<'a>, e: &Element<'a>) -> Js<'a> {\n if e.tag_type == ElementType::Plain {\n return Js::str_lit(e.tag_name);\n }\n let is_explicit_dynamic = is_component_tag(e.tag_name);\n // 1. resolve dynamic component\n let tag = match resolve_dynamic_component(e, is_explicit_dynamic) {\n Ok(call_expr) => return call_expr,\n Err(tag_name) => tag_name,\n };\n // 1.5 v-is (deprecated)\n if let Some(call_expr) = resolve_v_is_component(e, is_explicit_dynamic) {\n return call_expr;\n }\n // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)\n let builtin = bc\n .get_builtin_component(tag)\n .or_else(|| get_core_component(tag));\n if let Some(builtin) = builtin {\n // TODO: ensure SSR does not collect this. since built-ins are simply fallthroughs\n // or have special handling during compilation so we don't need to import their runtime\n return Js::Symbol(builtin);\n }\n // 3. user component (from setup bindings)\n if let Some(from_setup) = resolve_setup_component(bc, tag) {\n return from_setup;\n }\n // 4. User component or Self referencing component (inferred from filename)\n let mut comp = VStr::raw(tag);\n if !bc.sfc_info.self_name.is_empty()\n && VStr::raw(tag).pascalize().into_string() == bc.sfc_info.self_name\n {\n // codegen special checks for __self postfix when generating component imports,\n // which will pass additional `maybeSelfReference` flag to `resolveComponent`.\n comp.suffix_self();\n }\n // 5. user component (resolve)\n let comp_name = *comp.clone().be_component(); // use clone to avoid mutating\n // comp will be collected by collect_entities transform pass\n Js::Simple(comp_name, StaticLevel::CanHoist)\n}\n```"}], "func_name": "resolve_element_tag", "docstring": "Returns a expression for createVnode's first argument. It can be\n1. Js::Call for dynamic component or user component.\n2. Js::Symbol for builtin component\n3. Js::StrLit for plain element or component", "repo": "HerringtonDarkholme/vue-compiler", "path": "crates/compiler/src/converter/convert_element.rs", "url": "https://github.com/HerringtonDarkholme/vue-compiler/blob/master/crates/compiler/src/converter/convert_element.rs", "license": "MIT", "source_dataset": "Shuu12121/rust-treesitter-dedupe-filtered-datasetsV2", "record_id": "530f52a7204930080038028e7b651bb5ef6d940fb2a0dc2e9dc2b820019e5745"} {"messages": [{"role": "user", "content": "Write an idiomatic Rust implementation for the following documented function.\n\nFunction name: resolve_dynamic_component\n\nDocumentation:\nReturns Ok if resolved as dynamic component call, Err if resolved as static string tag\n\nReturn the Rust function implementation."}, {"role": "assistant", "content": "```rust\nfn resolve_dynamic_component<'a>(\n e: &Element<'a>,\n is_explicit_dynamic: bool,\n) -> Result, &'a str> {\n let is_prop = prop_finder(e, \"is\").find();\n let prop = match is_prop {\n Some(prop) => prop,\n None => return Err(e.tag_name),\n };\n if is_explicit_dynamic {\n let exp = match prop.get_ref() {\n ElemProp::Attr(Attribute {\n value: Some(val), ..\n }) => Js::StrLit(val.content), // TODO: return Err(val.content) ?\n ElemProp::Dir(Directive {\n expression: Some(exp),\n ..\n }) => Js::simple(exp.content),\n _ => panic!(\"{}\", MUST_NON_EMPTY),\n };\n return Ok(Js::Call(\n RuntimeHelper::RESOLVE_DYNAMIC_COMPONENT,\n vec![exp],\n ));\n }\n if let ElemProp::Attr(Attribute {\n value: Some(val), ..\n }) = prop.get_ref()\n {\n // if not , e.g.