Implementação de uma Skip List em Rust

Related tags

Concurrency skiplist
Overview

SkipList

SkipList é uma estrutura descrita em 1989 por William Pugh que se baseia em balancear de forma probabilística atalhos de um item a outro com objetivo de alcançar complexidade O(log(n)), sendo assim um substituto para árvores AVL. O objetivo deste projeto é de implementar uma Skip List em Rust, e dada a complexidade de desenvolvimento devido o gerenciamento de memória, foi decidido a implementação de estruturas intermediárias.

Plano de desenvolvimento

  1. Stack: Entender o processo de substituição de um item por outro na cabeça da pilha (link)
  2. Linked List: Inserir um item entre outros dois itens da lista (link)
  3. SkipList: Em cada nível inserir entre dois itens um novo item

Complexidade temporal

Um nível

Iniciando em uma lista simples ordenada a complexidade temporal média de busca é O(n)

image

Dois níveis

Vamos então incluir acima uma lista com atalhos a cada dois itens.

image

A complexidade temporal pode ser calculada por:

equation

E para equation temos que

equation

equation

Generalização

Incluindo mais um nível a complexidade se torna equation

image

Para k níveis temos uma complexidade equation. O que aconteceria se tivessemos log(n) níveis? O resultado final, incrivelmente, é O(log(n))

Randomização da estrutura

Manter uma estrutura onde o nível acima é sempre a metade do nível anterior é muito custoso. Como solução temos a randomização dos níveis. Quando um novo nó é inserido na skiplist seu nível é randomizado, tendo uma probabilidade P de obter uma promoção de nível e probabilidade P^k de obter o nível máximo.

image

Implementação

Stack

  • Inserir na pilha
pub fn push(&mut self, value: T) {
    let old_head = self.head.take();
    let new_head = Item {
        value,
        next: old_head,
    };
    self.head = Some(Box::new(new_head));
}
  • Remover da pilha
pub fn pop(&mut self) -> Option<T> {
    let old_head = self.head.take();
    match old_head {
        Some(item) => {
            self.head = item.next;
            Some(item.value)
        }
        None => None,
    }
}
  • Olhar o topo da pilha
pub fn peek(&self) -> Option<&T> {
    match &self.head {
        Some(item) => Some(&item.as_ref().value),
        None => None,
    }
}

Linked List

  • Pesquisa recursiva retornando referência de nó
fn get_node_ref<'a>(&self, cursor: &'a Link<T>, key: &T) -> &'a Link<T> {
    if let Some(node) = cursor.as_ref() {
        if let Some(next_node) = node.next.as_ref() {
            if next_node.value < *key {
                return self.get_node_ref(&node.next, key);
            }
        }   
    }
    cursor
}
  • Inserir um novo nó recursivamente
fn recursive_insert(cursor: &mut Link<T>, value: T) {
    if let Some(node) = cursor {
        if let Some(next_node) = &mut node.next {
            if next_node.value < value {
                return LinkedList::recursive_insert(&mut node.next, value);
            } 
        } 
        let mut new_node = Node { value, next: None };
        let old_value = mem::take(&mut node.next);
        new_node.next = old_value;
        node.next = Some(Box::new(new_node));
    }
}
  • Remover um nó recursivamente
fn recursive_delete(cursor: &mut Link<T>, value: T) {
    if let Some(node) = cursor {
        if let Some(next_node) = &mut node.next {
            if next_node.value == value {
                let old_value = mem::take(&mut node.next);
                node.next = old_value.unwrap().next;
            }
            else if next_node.value < value {
                LinkedList::recursive_delete(&mut node.next, value);
            }
        }
    }
}
You might also like...
A community curated list of Rust Language streamers

Awesome Rust Streaming This is a community curated list of livestreams about the programming language Rust. Don't see a stream that you like? Feel fre

List of Rust books
List of Rust books

Rust Books Books Starter Books Advanced Books Resources Books Starter Books The Rust Programming Language Free Welcome! This book will teach you about

A curated list of replacements for existing software written in Rust

Awesome Alternatives in Rust A curated list of replacements for existing software written in Rust. If you want to contribute, please read CONTRIBUTING

Doubly-Linked List Implementation in Rust

Doubly-Linked List Implementation in Rust Purely for educational and recreational purposes. For real world production please use std::collections::Lin

Curated list of awesome projects and resources related to Rust and computer security

Awesome Rust Security Curated list of awesome projects and resources related to Rust and computer security Table of Contents Tools Web and Cloud Secur

argmax is a library that allows Rust applications to avoid Argument list too long errors (E2BIG) by providing a std::process::Command wrapper with a

argmax argmax is a library that allows Rust applications to avoid Argument list too long errors (E2BIG) by providing a std::process::Command wrapper w

A doubly-linked list for Rust backed by generational-arena.

generational_token_list A doubly-linked list backed by generational-arena. Inspired by indexlist. Instead of returning pointers or numerical indices t

A list of crates with snippets used by me to learn more about Rust.

my-rust-examples This is a list of crates used by me to learn Rust. How to execute You can use a dependency called cargo-play: cargo install cargo-pla

A curated list of Rust code and resources.

Awesome Rust A curated list of Rust code and resources. If you want to contribute, please read this. Table of contents Applications Audio and Music Cr

🏆 A ranked list of awesome machine learning Rust libraries.

best-of-ml-rust 🏆 A ranked list of awesome machine learning Rust libraries. This curated list contains 180 awesome open-source projects with a total

Server with Rust, Rocket, Diesel, Docker to create your own to-do-list

Installation Install Docker & Docker-Compose Then download the repository go to the root where the Dockerfile is and do: sudo docker-compose up sudo i

List public items (public API) of Rust library crates. Enables diffing public API between releases.

cargo wrapper for this library You probably want the cargo wrapper to this library. See https://github.com/Enselic/cargo-public-items. public_items Li

Appendable and iterable key/list storage, backed by S3, written in rust

klstore Appendable and iterable key/list storage, backed by S3. General Overview Per key, a single writer appends to underlying storage, enabling many

Rust Vec Doubly Linked List

Rust Vec Doubly Linked List Just like doubly linked list(e.g. std::LinkedList), but supports that returning a index of the vec when push. And you can

A safe `Pin`-based intrusive doubly-linked list in Rust

pin-list This crate provides PinList, a safe Pin-based intrusive doubly linked list. Example A thread-safe unfair async mutex. use pin_project_lite::p

CLI tool that extracts a regex pattern from a list of urls ( Rust )

rextract CLI tool that extracts a regex pattern from a list of urls. The tool is written in Rust and supports PCRE. Installation Step 1: Visit https:/

A list of Rust buffers that implements the bytes::Buf trait.

buf-list A list of bytes::Bytes chunks. Overview This crate provides a BufList type that is a list of Bytes chunks. The type implements bytes::Buf, so

A Rust doubly-linked intrusive list with Miri tests

Intrusive stack-allocated doubly-linked list example Quickstart cargo test Or to run the tests under Miri: rustup toolchain install nightly # if y

A simple to-do list manager written in Rust
A simple to-do list manager written in Rust

A simple To-Do list manager written in Rust I wrote this project while I'm learning Rust for practice. I decided to put this project online so that ot

Owner
Rodrigo Crispim
Hello, I'm Rodrigo and I work as a Software Developer. I also have a degree in Electronic Engineering. Take a coffee, have a seat and please don't mind the mess
Rodrigo Crispim
Abstract over the atomicity of reference-counting pointers in rust

Archery Archery is a rust library that offers a way to abstraction over Rc and Arc smart pointers. This allows you to create data structures where the

Diogo Sousa 107 Nov 23, 2022
Rayon: A data parallelism library for Rust

Rayon Rayon is a data-parallelism library for Rust. It is extremely lightweight and makes it easy to convert a sequential computation into a parallel

null 7.8k Jan 7, 2023
Coroutine Library in Rust

coroutine-rs Coroutine library in Rust [dependencies] coroutine = "0.8" Usage Basic usage of Coroutine extern crate coroutine; use std::usize; use co

Rust中文社区 404 Dec 31, 2022
Coroutine I/O for Rust

Coroutine I/O Coroutine scheduling with work-stealing algorithm. WARN: Possibly crash because of TLS inline, check https://github.com/zonyitoo/coio-rs

ty 454 Dec 2, 2022
Cross-platform Rust wrappers for the USB ID Repository

usb-ids Cross-platform Rust wrappers for the USB ID Repository. This library bundles the USB ID database, allowing platforms other than Linux to query

William Woodruff 18 Dec 14, 2022
Rust Ethereum 2.0 Client

Lighthouse: Ethereum 2.0 An open-source Ethereum 2.0 client, written in Rust and maintained by Sigma Prime. Documentation Overview Lighthouse is: Read

Sigma Prime 2.1k Jan 6, 2023
Rust Parallel Iterator With Output Sequential Consistency

par_iter_sync: Parallel Iterator With Sequential Output Crate like rayon do not offer synchronization mechanism. This crate provides easy mixture of p

Congyu 1 Oct 30, 2021
A fast, performant implementation of skip list in Rust.

Subway A fast, performant implementation of skip list in Rust. A skip list is probabilistic data structure that provides O(log N) search and insertion

Sushrut 16 Apr 5, 2022
Uma lib para a API do Brasil API (para o Rust)

Uma lib para a API do BrasilAPI (para o Rust) Features CEP (Zip code) DDD Bank CNPJ IBGE Feriados Nacionais Tabela FIPE ISBN Registros de domínios br

Pedro Augusto 6 Dec 13, 2022
A newtype wrapper that causes Debug impls to skip a field.

debug-ignore This library contains DebugIgnore, a newtype wrapper that causes a field to be skipped while printing out Debug output. Examples use debu

Rain 15 Sep 22, 2022