<commit_before>﻿require 'forwardable'
require_relative 'utils'
require_relative '../sodium'
require 'ffi'

module Sodium
  class SecretBuffer
    extend Forwardable

    def_delegators :@buffer, :address, :to_i

    attr_reader :size, :primitive

    def initialize(size, primitive = nil)
      @size = Utils.get_int(size)
      @primitive = primitive
      @buffer = Sodium.malloc(self.size)
      setup_finalizer
    end

    def to_ptr
      @buffer
    end

    def free
      remove_finalizer
      readwrite
      Sodium.free(@buffer)
      @size = @primitive = @buffer = nil
    end

    def noaccess
      Sodium.noaccess(@buffer)
    end

    def readonly
      Sodium.readonly(@buffer)
    end

    def readwrite
      Sodium.readwrite(@buffer)
    end

    private

    def setup_finalizer
      ObjectSpace.define_finalizer(@buffer, self.class.free(@buffer.address))
    end

    def remove_finalizer
      ObjectSpace.undefine_finalizer @buffer
    end

    def self.free(address)
      ->(obj_id) do
        Sodium.readwrite(FFI::Pointer.new(address))
        Sodium.free(FFI::Pointer.new(address))
        true
      end
    end
  end
end<commit_msg>small speed improvements<commit_after>﻿require 'forwardable'
require_relative 'utils'
require_relative '../sodium'
require 'ffi'

module Sodium
  class SecretBuffer
    extend Forwardable

    def_delegators :to_ptr, :address, :to_i

    attr_reader :size, :primitive, :to_ptr

    def initialize(size, primitive = nil)
      @size = Utils.get_int(size)
      @primitive = primitive
      @to_ptr = Sodium.malloc(self.size)
      setup_finalizer
    end

    def free
      remove_finalizer
      readwrite
      Sodium.free(to_ptr)
      @size = @primitive = @to_ptr = nil
    end

    def noaccess
      Sodium.noaccess(to_ptr)
    end

    def readonly
      Sodium.readonly(to_ptr)
    end

    def readwrite
      Sodium.readwrite(to_ptr)
    end

    private

    def setup_finalizer
      ObjectSpace.define_finalizer(to_ptr, self.class.free(to_ptr.address))
    end

    def remove_finalizer
      ObjectSpace.undefine_finalizer to_ptr
    end

    def self.free(address)
      ->(obj_id) do
        ptr = FFI::Pointer.new(address)
        Sodium.readwrite(ptr)
        Sodium.free(ptr)
        true
      end
    end
  end
end
{'fraction_non_alphanumeric': 0.08217391304347826, 'fraction_numerical': 0.0, 'mean_word_length': 2.481089258698941, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3597970', 'n_tokens_mistral': 775, 'n_tokens_neox': 731, 'n_words': 162}