const std = @import("std"); const print = std.debug.print; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; pub const FreqAmp = struct { freq: f16, r_amp: f16, pub fn prnt(self: *FreqAmp) void { print("\n", .{self.freq, self.r_amp}); } }; pub const FreqAmpList = struct { allocator: Allocator, refcount: u64, lst: ArrayList(*FreqAmp), pub fn init(allocator: Allocator) FreqAmpList { const lst = ArrayList(*FreqAmp).init(allocator); return .{ .allocator = allocator, .refcount = 0, .lst = lst, }; } pub fn deinit(self: *FreqAmpList) void { self.lst.deinit(); } pub fn prnt(self: *FreqAmpList) void { print("\n", .{self.refcount}); for (self.lst.items) |freqamp| { freqamp.prnt(); } print("\n", .{}); } }; pub const FreqAmpBuffer = struct { const buffer_ticks_default = 44100 * 2; allocator: Allocator, buffer_ticks: u64 = buffer_ticks_default, current_tick: u64, freqamps: [buffer_ticks_default]*FreqAmpList, pub fn init(allocator: Allocator) FreqAmpBuffer { const current_tick = 0; var initial_list = FreqAmpList.init(allocator); initial_list.refcount = buffer_ticks_default; initial_list.prnt(); var freqamps: [buffer_ticks_default]*FreqAmpList = undefined; @memset(&freqamps, &initial_list); return .{ .allocator = allocator, .current_tick = current_tick, .freqamps = freqamps, }; } pub fn deinit(self: *FreqAmpBuffer) void { _ = self; } pub fn index_by_tick(self: *FreqAmpBuffer, tick: u64) u64 { return tick % self.buffer_ticks; } pub fn current_list(self: *FreqAmpBuffer) *FreqAmpList { const current_index = self.index_by_tick(self.current_tick); return self.freqamps[current_index]; } pub fn reset(self: *FreqAmpBuffer) void { const current_index = self.index_by_tick(self.current_tick); var clist = self.freqamps[current_index]; clist.prnt(); if (clist.refcount <= 1) { defer clist.deinit(); } clist.refcount -= 1; var new_list = FreqAmpList.init(self.allocator); new_list.prnt(); self.freqamps[current_index] = &new_list; self.freqamps[current_index].refcount += 1; new_list.prnt(); } pub fn setfreq(self: *FreqAmpBuffer, freq: f16, r_amp: f16) !void { const current_index = self.index_by_tick(self.current_tick); var clist = self.freqamps[current_index]; clist.prnt(); // If this freq already is set, sum the r_amps for (clist.lst.items) |freqamp| { if (freqamp.freq == freq) { freqamp.r_amp = r_amp; return; } } // Otherwise, append new freqamp var fa = try self.allocator.create(FreqAmp); fa.freq = freq; fa.r_amp = r_amp; try clist.lst.append(fa); } }; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); var fab = FreqAmpBuffer.init(allocator); defer fab.deinit(); fab.reset(); try fab.setfreq(440.0, 0.84); try fab.setfreq(440.0, 0.854); var clist = fab.current_list(); print("RESULT\n", .{}); clist.prnt(); }