Skip to content

Commit

Permalink
rust resources
Browse files Browse the repository at this point in the history
  • Loading branch information
NiteeshPutla committed Jun 28, 2024
1 parent db68638 commit e372475
Show file tree
Hide file tree
Showing 343 changed files with 36,691 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[core]
hooksPath = git_hooks
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* @imp2002 @vil02
8 changes: 8 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/.github/workflows/"
schedule:
interval: "weekly"
...
29 changes: 29 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Pull Request Template

## Description

Please include a summary of the change and which issue (if any) is fixed.
A brief description of the algorithm and your implementation method can be helpful too. If the implemented method/algorithm is not so
well-known, it would be helpful to add a link to an article explaining it with more details.

## Type of change

Please delete options that are not relevant.

- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)

## Checklist:

- [ ] I ran bellow commands using the latest version of **rust nightly**.
- [ ] I ran `cargo clippy --all -- -D warnings` just before my last commit and fixed any issue that was found.
- [ ] I ran `cargo fmt` just before my last commit.
- [ ] I ran `cargo test` just before my last commit and all tests passed.
- [ ] I added my algorithm to the corresponding `mod.rs` file within its own folder, and in any parent folder(s).
- [ ] I added my algorithm to `DIRECTORY.md` with the correct link.
- [ ] I checked `COUNTRIBUTING.md` and my code follows its guidelines.

Please make sure that if there is a test that takes too long to run ( > 300ms), you `#[ignore]` that or
try to optimize your code or make the test easier to run. We have this rule because we have hundreds of
tests to run; If each one of them took 300ms, we would have to wait for a long time.
28 changes: 28 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: build

on: pull_request

jobs:
fmt:
name: cargo fmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: cargo fmt
run: cargo fmt --all -- --check

clippy:
name: cargo clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: cargo clippy
run: cargo clippy --all --all-targets -- -D warnings

test:
name: cargo test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: cargo test
run: cargo test
27 changes: 27 additions & 0 deletions .github/workflows/directory_workflow.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: build_directory_md
on:
push:
branches: [master]

jobs:
MainSequence:
name: DIRECTORY.md
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-python@v5
- name: Setup Git Specs
run: |
git config --global user.name "$GITHUB_ACTOR"
git config --global user.email "[email protected]"
git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY
- name: Update DIRECTORY.md
run: |
cargo run --manifest-path=.github/workflows/scripts/build_directory/Cargo.toml
- name: Commit DIRECTORY.md
run: |
git add DIRECTORY.md
git commit -m "Update DIRECTORY.md [skip actions]" || true
git push origin HEAD:$GITHUB_REF || true
8 changes: 8 additions & 0 deletions .github/workflows/scripts/build_directory/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "build_directory"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
124 changes: 124 additions & 0 deletions .github/workflows/scripts/build_directory/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
use std::{
error::Error,
fs,
path::{Path, PathBuf},
};

static URL_BASE: &str = "https://github.com/TheAlgorithms/Rust/blob/master";

fn good_filepaths(top_dir: &Path) -> Result<Vec<String>, Box<dyn Error>> {
let mut good_fs = Vec::new();
if top_dir.is_dir() {
for entry in fs::read_dir(top_dir)? {
let entry = entry?;
let path = entry.path();
if entry.file_name().to_str().unwrap().starts_with('.')
|| entry.file_name().to_str().unwrap().starts_with('_')
{
continue;
}
if path.is_dir() {
let mut other = good_filepaths(&path)?;
good_fs.append(&mut other);
} else if entry.file_name().to_str().unwrap().ends_with(".rs")
&& entry.file_name().to_str().unwrap() != "mod.rs"
{
good_fs.push(
path.into_os_string()
.into_string()
.unwrap()
.split_at(2)
.1
.to_string(),
);
}
}
}
good_fs.sort();
Ok(good_fs)
}

fn md_prefix(indent_count: usize) -> String {
if indent_count > 0 {
format!("{}*", " ".repeat(indent_count))
} else {
"\n##".to_string()
}
}

fn print_path(old_path: String, new_path: String) -> (String, String) {
let old_parts = old_path
.split(std::path::MAIN_SEPARATOR)
.collect::<Vec<&str>>();
let mut result = String::new();
for (count, new_part) in new_path.split(std::path::MAIN_SEPARATOR).enumerate() {
if count + 1 > old_parts.len() || old_parts[count] != new_part {
println!("{} {}", md_prefix(count), to_title(new_part));
result.push_str(format!("{} {}\n", md_prefix(count), to_title(new_part)).as_str());
}
}
(new_path, result)
}

pub fn build_directory_md(top_dir: &Path) -> Result<String, Box<dyn Error>> {
let mut old_path = String::from("");
let mut result = String::new();
for filepath in good_filepaths(top_dir)? {
let mut filepath = PathBuf::from(filepath);
let filename = filepath.file_name().unwrap().to_owned();
filepath.pop();
let filepath = filepath.into_os_string().into_string().unwrap();
if filepath != old_path {
let path_res = print_path(old_path, filepath);
old_path = path_res.0;
result.push_str(path_res.1.as_str());
}
let url = format!("{}/{}", old_path, filename.to_string_lossy());
let url = get_addr(&url);
let indent = old_path.matches(std::path::MAIN_SEPARATOR).count() + 1;
let filename = to_title(filename.to_str().unwrap().split('.').collect::<Vec<&str>>()[0]);
println!("{} [{}]({})", md_prefix(indent), filename, url);
result.push_str(format!("{} [{}]({})\n", md_prefix(indent), filename, url).as_str());
}
Ok(result)
}

fn to_title(name: &str) -> String {
let mut change = true;
name.chars()
.map(move |letter| {
if change && !letter.is_numeric() {
change = false;
letter.to_uppercase().next().unwrap()
} else if letter == '_' {
change = true;
' '
} else {
if letter.is_numeric() || !letter.is_alphanumeric() {
change = true;
}
letter
}
})
.collect::<String>()
}

fn get_addr(addr: &str) -> String {
if cfg!(windows) {
format!("{}/{}", URL_BASE, switch_backslash(addr))
} else {
format!("{}/{}", URL_BASE, addr)
}
}

// Function that changes '\' to '/' (for Windows builds only)
fn switch_backslash(addr: &str) -> String {
addr.chars()
.map(|mut symbol| {
if symbol == '\\' {
symbol = '/';
}
symbol
})
.collect::<String>()
}
17 changes: 17 additions & 0 deletions .github/workflows/scripts/build_directory/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use std::{fs::File, io::Write, path::Path};

use build_directory::build_directory_md;
fn main() -> Result<(), std::io::Error> {
let mut file = File::create("DIRECTORY.md").unwrap(); // unwrap for panic

match build_directory_md(Path::new(".")) {
Ok(buf) => {
file.write_all("# List of all files\n".as_bytes())?;
file.write_all(buf.as_bytes())?;
}
Err(err) => {
panic!("Error while creating string: {err}");
}
}
Ok(())
}
18 changes: 18 additions & 0 deletions .github/workflows/stale.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: 'Close stale issues and PRs'
on:
schedule:
- cron: '0 0 * * *'
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
stale-issue-message: 'This issue has been automatically marked as abandoned because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.'
close-issue-message: 'Please ping one of the maintainers once you add more information and updates here. If this is not the case and you need some help, feel free to ask for help in our [Gitter](https://gitter.im/TheAlgorithms) channel. Thank you for your contributions!'
stale-pr-message: 'This pull request has been automatically marked as abandoned because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.'
close-pr-message: 'Please ping one of the maintainers once you commit the changes requested or make improvements on the code. If this is not the case and you need some help, feel free to ask for help in our [Gitter](https://gitter.im/TheAlgorithms) channel. Thank you for your contributions!'
exempt-issue-labels: 'dont-close'
exempt-pr-labels: 'dont-close'
days-before-stale: 30
days-before-close: 7
45 changes: 45 additions & 0 deletions .github/workflows/upload_coverage_report.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
---
name: upload_coverage_report

# yamllint disable-line rule:truthy
on:
workflow_dispatch:
push:
branches:
- master
pull_request:

env:
REPORT_NAME: "lcov.info"

jobs:
upload_coverage_report:
runs-on: ubuntu-latest
env:
CARGO_TERM_COLOR: always
steps:
- uses: actions/checkout@v4
- uses: taiki-e/install-action@cargo-llvm-cov
- name: Generate code coverage
run: >
cargo llvm-cov
--all-features
--workspace
--lcov
--output-path "${{ env.REPORT_NAME }}"
- name: Upload coverage to codecov (tokenless)
if: >-
github.event_name == 'pull_request' &&
github.event.pull_request.head.repo.full_name != github.repository
uses: codecov/codecov-action@v4
with:
files: "${{ env.REPORT_NAME }}"
fail_ci_if_error: true
- name: Upload coverage to codecov (with token)
if: "! github.event.pull_request.head.repo.fork "
uses: codecov/codecov-action@v4
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: "${{ env.REPORT_NAME }}"
fail_ci_if_error: true
...
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@

/target
**/*.rs.bk

/target
**/*.rs.bk
Cargo.lock
/.idea/
.vscode
7 changes: 7 additions & 0 deletions .gitpod.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
FROM gitpod/workspace-rust:2023-11-16-11-19-36

USER gitpod

RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y

RUN rustup default stable
9 changes: 9 additions & 0 deletions .gitpod.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
image:
file: .gitpod.Dockerfile

tasks:
- init: cargo build

vscode:
extensions:
- rust-lang.rust-analyzer
51 changes: 51 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# The Algorithms: Rust

This project aims at showcasing common algorithms implemented in `Rust`, with an accent on idiomatic code and genericity.

## Project structure

The project is organized as follows:

`src/`
- `my_algo_category/`
- `mod.rs`
- `my_algorithm.rs`
- `some_other_algorithm.rs`
- `some_other_algo_category/`
- ...


`mod.rs` contains the export:

```rust
mod my_algorithm;

pub use self::my_algorithm::my_algorithm;
```

`my_algorithm.rs` contains your algorithm and the related tests:

```rust
pub fn my_algorithm() {
// ...
}

#[cfg(test)]
mod tests {
#[test]
fn my_test() {
// ...
}
}
```

## Before submitting your PR

Do **not** use acronyms: `DFS` should be `depth_first_search`.

Make sure you run
* `cargo test`
* `cargo fmt`
* `cargo clippy --all -- -D warnings`

And that's about it !
Loading

0 comments on commit e372475

Please sign in to comment.