Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions FaissMask.Test/IndexPersistencyTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using System.IO;
using Xunit;

namespace FaissMask.Test;

public class IndexPersistencyTests
{
private const string _indexPath = "data/faiss.index";
private const string _regeneratedIndexPath = "data/faiss_regenerated.index";

[Fact]
public void EnsureRegeneratedIndexIsTheSame()
{
using var index = IndexFlat.Read(_indexPath);
index.WriteIndex(_regeneratedIndexPath);
Assert.True(File.Exists(_regeneratedIndexPath));

byte[] originalIndexBytes = File.ReadAllBytes(_regeneratedIndexPath);
byte[] regenratedIndexBytes = File.ReadAllBytes(_regeneratedIndexPath);
Assert.Equal(originalIndexBytes, regenratedIndexBytes);

File.Delete(_regeneratedIndexPath);
}

}
5 changes: 5 additions & 0 deletions FaissMask/Index.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,11 @@ public float[] DecodeVector(byte[] bytes)
return Handle.DecodeVector(bytes);
}

public void WriteIndex(string filename)
{
Handle.WriteIndex(filename);
}

public void Dispose()
{
Handle?.Free();
Expand Down
25 changes: 25 additions & 0 deletions FaissMask/Internal/IndexSafeHandle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,5 +145,30 @@ public ulong SaCodeSize
return ptr.ToUInt64();
}
}

public void WriteIndex(string filename)
{
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentNullException(nameof(filename));
}

var returnCode = NativeMethods.faiss_write_index_fname(this, filename);
if (returnCode != 0)
{
var lastError = NativeMethods.faiss_get_last_error();

if (string.IsNullOrEmpty(lastError))
{
throw new IOException(
$"An unknown error occurred trying to write the index '{filename}' (return code {returnCode})");
}
else
{
throw new IOException(
$"An error occurred trying to write the index '{filename}': {lastError} (return code {returnCode})");
}
}
}
}
}
2 changes: 2 additions & 0 deletions FaissMask/Internal/NativeMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ internal static class NativeMethods
[DllImport("faiss_c", SetLastError = true)]
public static extern int faiss_read_index_fname(string fname, int io_flags, ref IntPtr p_out);
[DllImport("faiss_c", SetLastError = true)]
public static extern int faiss_write_index_fname(IndexSafeHandle index, string fname);
[DllImport("faiss_c", SetLastError = true)]
public static extern int faiss_read_VectorTransform_fname(string fname, ref IntPtr p_out);
[DllImport("faiss_c", SetLastError = true)]
public static extern string faiss_get_last_error();
Expand Down