Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const std = @import("std");
- const mem = std.mem;
- const Allocator = std.mem.Allocator;
- const String = struct {
- const Self = @This();
- buffer: []u8,
- idx: usize,
- allocator: *Allocator,
- /// Creates a new String.
- /// This function does NOT allocate.
- pub fn new(alloc: *Allocator) Self {
- return Self {
- .buffer = [0]u8 {},
- .idx = 0,
- .allocator = alloc
- };
- }
- /// Creates a new String from a String-slice.
- /// This allocates enough space to hold the contents of `str`, and then copies the contents.
- pub fn From(alloc: *Allocator, str: []const u8) !Self {
- var s = Self.new(alloc);
- try s.extend(str);
- return s;
- }
- /// Creates a new String that can hold `size` items without reallocating.
- /// This function allocates enough space to hold `size` items.
- pub fn with_capacity(alloc: *Allocator, size: usize) !Self {
- var s = Self.new(alloc);
- try s.reserve(size);
- return s;
- }
- /// Free's the String.
- /// This should be called after creating a String.
- pub fn deinit(self: *Self) void {
- self.allocator.free(self.buffer);
- }
- /// Returns a view into the String's buffer.
- pub fn asStr(self: *Self) []const u8 {
- return self.buffer[0..self.idx];
- }
- /// Extends the String with the contents of `str`.
- /// If the String has not enough allocated space to hold the contents of `str`, this function will allocate.
- pub fn extend(self: *Self, str: []const u8) !void {
- try self.reserve(str.len);
- mem.copy(u8, self.buffer[self.idx..], str);
- self.idx += str.len;
- }
- pub fn push(self: *Self, byte: u8) !void {
- try self.reserve(1);
- self.buffer[self.idx] = byte;
- self.idx += 1;
- }
- /// Reserves `size` elements in the buffer.
- pub fn reserve(self: *Self, size: usize) !void {
- if (self.idx + size > self.cap()) {
- var new_buffer = try self.allocator.realloc(u8, self.buffer, self.idx + size);
- self.buffer = new_buffer;
- }
- }
- /// Returns the capacity of the String. This is how many items the String can hold untill it is full.
- pub fn cap(self: *Self) usize {
- return self.buffer.len;
- }
- };
- pub fn main() !void {
- var da = std.heap.DirectAllocator.init();
- const alloc = &da.allocator;
- var s = try String.with_capacity(alloc, 12);
- defer s.deinit();
- try s.extend("Hello sailor");
- try s.push('!');
- std.debug.warn("{}\n", s.asStr());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement