stl 0.4.5
stl: ^0.4.5 copied to clipboard
Supercharge Dart & Flutter with a bleeding-edge C++ STL architecture. Unlock zero-cost primitives, heavy-duty collections, and C++23 ranges.
STL (Standard Template Library... and Beyond!) #
๐ A highly-versatile, performance-driven bank of data collections, structures, and algorithmic ranges for the Dart and Flutter ecosystem.
๐ ๏ธ Quick Install #
dart pub add stl
or for Flutter:
flutter pub add stl
๐ The Vision #
Originally inspired by the strict blueprints of the C++ Standard Template Library (STL), this package has heavily evolved into a comprehensive bank of diverse collections for all your data structure needs. Whether you require familiar sequential containers, complex associative maps, specialized utility adapters, or bleeding-edge C++23 functional ranges, stl drastically supercharges your Dart architecture! โจ
๐ฏ Why use this package over standard Dart tools? #
- ๐ฆ Massive Bank of Collections: Unlock custom abilities via
Vector,Deque,Stack,ForwardList, and more! - ๐ Next-Gen Iteration: Introducing Ranges! Seamlessly generate subsets, zips, Cartesian products, and infinite loops on the fly without breaking your memory limit.
- โก Deterministic Performance: Predictable time complexity ($O(1)$, $O(\log n)$, etc.) with heavily optimized system-level logic.
- ๐ Familiar yet Dart-y API: Native
Iterablemixins seamlessly integrated with perfectly replicated C++ architectural rules, wrapped cleanly in standard DartcamelCasefor maximum ecosystem interoperability. - ๐จ Ready for Everything: Perfect for logic-heavy Flutter apps, scalable game engines, dynamic state management, or enterprise backend systems.
๐ The Collection Bank #
Here are the traditional core data structures currently fully supported and battle-tested:
๐ Linear Containers #
| Data Structure | Description | Time Complexity (Access) |
|---|---|---|
๐ Vector<T> |
Dynamic array with contiguous memory behavior, strict bounds checking, and powerful modifiers. | $O(1)$ |
๐
ForwardList<T> |
Singly linked list optimized for extremely fast forward traversal, insertions, and shifting. | $O(N)$ |
๐ง Array<T> |
Conceptually strict fixed-size contiguous array mirroring C++ std::array. |
$O(1)$ |
๐ฅ Adapter Containers #
| Data Structure | Description | Behavior |
|---|---|---|
๐ฅ Stack<T> |
Custom LIFO (Last-In, First-Out) adapter. Operates flawlessly over any given sequence. | LIFO |
๐ Queue<T> |
Custom FIFO (First-In, First-Out) adapter for messaging and task processing. | FIFO |
โณ PriorityQueue<T> |
Max/Min heap priority structure. Constantly dynamically sorts elements upon insertion. | $O(\log N)$ |
๐๏ธ Associative Containers #
| Data Structure | Description |
|---|---|
๐๏ธ Set<T> |
Unique element container ensuring no duplicates with generic equality support. |
๐ฒ SortedSet<T> |
Tree-based strictly sorted unique container mirroring C++ std::set. Keeps data autonomously ordered. |
๐ MultiSet<T> |
Sorted tree container allowing duplicate elements, similar to C++ std::multiset. |
๐บ๏ธ HashMap<K, V> |
Unordered key-value map utilizing a fast hash table under the hood, matching std::unordered_map. |
๐ญ Deque<T> |
Double-ended queue allowing extremely fast front/back algorithmic insertions & removals without memory reallocation overhead. |
๐ ๏ธ Utility Structures #
| Utility | Description |
|---|---|
๐ฏ Pair<T1, T2> |
Native C++ utility structure to hold heterogeneous objects. Features gorgeous Dart 3 Record translation. |
โจ Optional<T> |
A beautifully sealed functional wrapper representing possibly-absent values smoothly without relying on raw null checks. |
๐ Variant<T0, T1...> |
Type-safe discriminated union handling distinct architectural alternatives elegantly via exhausted switch statements. |
๐ฆ Box<T> / Ref<T> |
Wrappers unlocking primitive pass-by-reference logic with dynamic mathematical operators. |
๐ข BitSet |
Hyper-efficient space-optimized boolean bit flags array mimicking std::bitset. $O(1)$ toggles. |
๐ฝ Any |
Generic type-safe bounding box safely encapsulating abstract data with strictly enforced extraction boundaries. |
๐งฑ Primitives (Fixed-Width Integers) #
stl provides two distinctly different architectural branches for bounded hardware-level integers.
1. Zero-Cost Primitives
Extremely lightweight extension type models scaling directly utilizing Dart Native performance bounds without allocating dynamic memory on the heap. Ideal for tight, high-performance logic loops natively!
| Type | Description |
|---|---|
๐ข I8, I16, I32, I64 |
Signed integer zero-cost wrappers. Provides automatic arithmetic wrap-around, checked methods (e.g. addChecked), and strict min/max boundaries. (I64 deeply integrates two's complement constraints). |
๐ข U8, U16, U32, U64 |
Unsigned integer variants mathematically bounding state within their respective non-negative bit frames seamlessly. |
2. TypedData Primitives (Hardware Backed)
Warning
Architectural Difference: Unlike the zero-cost I8/U8 variants above, these types dynamically allocate a dart:typed_data list sequentially behind the scenes (e.g., Int8List(1)). Memory allocations inside tight math loops inherently add garbage-collection pressureโhowever, these structures grant absolute native hardware limits precisely mimicking exact C++ data structures flawlessly. Furthermore, they retain perfectly strict exact 64-bit precision bounds across JavaScript/Web layout environments flawlessly!
| Type | Description |
|---|---|
๐ข Int8, Int16, Int32, Int64 |
Hardware-backed signed equivalents enforcing strict boundary overflow natively at the OS hardware/V8 buffer layout level. |
๐ข Uint8, Uint16, Uint32, Uint64 |
Hardware-backed unsigned integers utilizing exact standard array memory to process mathematically clean unsigned rollovers securely. |
๐งฎ Math Module #
The stl math modules provide robust implementations of C++ mathematical constants, number theory logic, <numeric> algorithms for sequences, and <cmath> algorithmic behaviors missing natively in Dart.
| Module | Description |
|---|---|
๐ข numeric |
Extensions for collections offering accumulate(), innerProduct(), adjacentDifference(), partialSum(), and iota(). |
๐งฎ cmath |
Missing mathematically safe operations including clamp(), lerp(), and overflow-safe robust hypot(). |
๐งฒ complex |
Full-scale complex numbers implementation Complex with operator overloading (+, -, *, /) and utility algorithms (abs(), conj(), pow()). |
๐ฌ number_theory |
Highly-optimized logic for gcd(), lcm(), isPrime(), primeFactorization(), and midpoint(). |
๐๏ธ constant |
20+ strictly pure IEEE 754 constants separated logically according to ISO 80000-2 (e.g. pi, tau, phi, catalan). |
๐ Geometry Module (2D Space) #
Euclidean geometry engine structured strictly via named parameters for explicit dimension management.
| Entity | Description |
|---|---|
๐ Point |
Represents an exact 2D coordinate (x, y) in space utilizing precise hypot distances. |
โญ Circle |
Computes absolute Pi area boundaries via deeply guarded {required radius}. |
๐ฒ Rectangle |
Basic bounding box dimensions via explicitly tracked {required width, height}. |
๐บ Triangle |
Pre-calculates Herons theorem and enforces native bounds limits via {required sideA, sideB, sideC}. |
โ๏ธ Algorithm Module (<algorithm>) #
The core algorithms library brings the power of C++'s <algorithm> header to Dart, allowing you to manipulate any Iterable or collection dynamically with highly optimized utility functions.
| Category | Algorithms | Description |
|---|---|---|
| ๐ Search & Bounds | lowerBound(), upperBound(), binarySearch(), equalRange() |
Perform incredibly fast $O(\log n)$ searches on sorted sequences. |
| ๐ Permutations | nextPermutation(), prevPermutation() |
Lexicographically permute sequences to generate standard orderings. |
| ๐๏ธ Set Operations | setUnion(), setIntersection(), setDifference() |
Mathematically compare and merge multiple sorted iterables efficiently. |
| ๐งฌ Mutations | rotate(), reverse(), unique(), partition(), stablePartition() |
Reorder, filter, and modify arrays conceptually in-place with predictable logic. |
๐งฌ Ranges Module (Inspired by C++23) #
Welcome to functional magic! Inspired deeply by C++23 std::views, our Ranges module allows you to cleanly manipulate, combine, generate, and stream data iteratively without aggressively eager memory consumption. Operations are performed lazily, bringing algorithmic elegance to your pipeline.
๐ฅ Spotlight Ranges #
๐ NumberLine (Iota)
Mimicking std::views::iota. Generate precise linear layouts of floating-point boundaries, or standard integer jumps, in mathematically optimized $O(1)$ operations instead of building massive explicit arrays.
// Custom Step Increment of 4 (0 to 20):
final evens = NumberLine(0, 20, step: 4);
print(evens.toList()); // [0, 4, 8, 12, 16]
// Highly mathematically optimized checks:
print(evens.contains(12)); // True! (Does NOT iterate over memory)
๐ ZipRange (Parallel Iteration)
Mimics std::views::zip. Dynamically clamp two different structured iterables together until the shortest one expires. Phenomenal for generating maps!
final keys = ['Player1', 'Player2', 'Player3'];
final scores = [9500, 8400]; // Uneven length!
final zipped = ZipRange(keys, scores);
final scoreMap = Map.fromEntries(zipped.map((p) => p.toMapEntry()));
// Results: {'Player1': 9500, 'Player2': 8400}
๐ฒ ChunkRange (Data Fragmentation)
Mimics std::views::chunk. Need to batch network packets or paginate rendering blocks? ChunkRange divides collections precisely into requested sizing constraints.
final data = [1, 2, 3, 4, 5, 6, 7];
final pagination = ChunkRange(data, 3);
print(pagination.toList());
// Results: [[1, 2, 3], [4, 5, 6], [7]]
๐งฉ CartesianRange (Combinations)
Mimics std::views::cartesian_product. Produces flat combinatorial intersections elegantly.
final suits = ['Hearts', 'Spades'];
final ranks = ['King', 'Queen'];
final deck = CartesianRange(suits, ranks);
// Yields Pairs: (Hearts, King), (Hearts, Queen), (Spades, King), (Spades, Queen)
โพ๏ธ RepeatRange (Infinite Streams)
Mimics std::views::repeat. Repeat specific data continuously or infinitely. Perfect for mock data pipelines!
final zeroes = RepeatRange(0);
print(zeroes.take(5).toList()); // [0, 0, 0, 0, 0]
โ๏ธ TakeRange & DropRange (Slicing)
Mimics std::views::take and std::views::drop. Extract or ignore sections of an iterable pipeline iteratively without explicitly allocating memory-heavy sublists.
final data = NumberLine(1, 10).toList();
final middle = TakeRange(DropRange(data, 3), 4);
print(middle.toList()); // [4, 5, 6, 7]
๐งช FilterRange & TransformRange (Functional Hooks)
Mimics std::views::filter and std::views::transform. Eagerly processes data dynamically through custom conditional predicates and data type mutating hooks.
final data = [1, 2, 3, 4, 5];
// Keep evens, then multiply by 10
final tens = TransformRange<int, int>(FilterRange(data, (int n) => n % 2 == 0), (int n) => n * 10);
print(tens.toList()); // [20, 40]
๐ JoinRange (Stream Flattening)
Mimics std::views::join. Instantly reassembles an iterable of iterables back into a perfectly contiguous 1-dimensional functional flow without recursive allocations.
final arrays = [[1, 2], [], [3, 4, 5], [6]];
final stream = JoinRange(arrays);
print(stream.toList()); // [1, 2, 3, 4, 5, 6]
๐ป Spotlight Integrations #
By blending C++ architectures with Dart's IterableMixin, stl gives you incredible syntactical power:
๐ Vector Memory Architecture #
final vec = Vector<String>(['Apple', 'Banana']);
vec.pushBack('Cherry');
vec.popBack();
print(vec.front()); // "Apple"
๐ฏ The Powerful Pair & Dart 3 Records #
// Effortless Pair initialization
var duo = makePair(99, 'Balloons');
// Native Dart 3 tuple/record unwrapping
var (count, item) = duo.record;
// Native deep equality
var sibling = makePair(99, 'Balloons');
print(duo == sibling); // True!
๐ฅ Iterable Adapters (Stack) #
final stack = Stack<int>.from([1, 2, 3]); // Top element is 3
var removed = stack.pop(); // Removes and returns 3
// Instantly iterable safely from top-to-bottom!
for (var item in stack) {
print(item); // 2, then 1
}
๐ฒ Autonomous Self-Balancing Sets (SortedSet) #
final sorted = SortedSet<String>((a, b) => b.length.compareTo(a.length));
sorted.insert("Strawberry");
sorted.insert("Apple");
sorted.insert("A");
print(sorted.toList());
// ["Strawberry", "Apple", "A"] (Sorting strictly maintained on insert!)
๐ Contributing #
Want to see an exotic data structure, an algorithmic graph traversal, or a missing std::ranges feature added to the library? We emphatically welcome pull requests, bug reports, and issue tickets. Let's make this the most powerful and scalable system-level algorithms repository in the Flutter and Dart ecosystem! ๐
Engineered with passion for Dart & Flutter architectures.