Skip to content

Instantly share code, notes, and snippets.

@wizzard0
Created September 29, 2012 21:28
Show Gist options
  • Save wizzard0/3805229 to your computer and use it in GitHub Desktop.
Save wizzard0/3805229 to your computer and use it in GitHub Desktop.
dumb table
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CryptoBoxLib.Data
{
public class DumbTable<T, V> where T : IEquatable<T>
{
public List<KeyValuePair<T, V>>[] Buckets;
int qua = 4;
public DumbTable()
{
Buckets = new List<KeyValuePair<T, V>>[qua * 256];
for (int i = 0; i < qua * 256; i++)
{
Buckets[i] = new List<KeyValuePair<T, V>>();
}
}
public void Add(T key, V value)
{
List<KeyValuePair<T, V>> bucket;
int idx;
FindBucket(key, out bucket, out idx);
if (idx >= 0)
{
bucket[idx] = new KeyValuePair<T, V>(key, value);
}
else
{
bucket.Add(new KeyValuePair<T, V>(key, value));
}
}
public V this[T key]
{
get
{
List<KeyValuePair<T, V>> bucket;
int idx;
FindBucket(key, out bucket, out idx);
if (idx >= 0)
{
return bucket[idx].Value;
}
else
{
throw new KeyNotFoundException();
}
}
set
{
Add(key, value);
}
}
private void FindBucket(T key, out List<KeyValuePair<T, V>> bucket, out int idx)
{
var khh = key.GetHashCode();
var kh = khh & (qua * 256 - 1);//0xffff;
bucket = Buckets[kh];
idx = -1;
for (int i = 0; i < bucket.Count; i++)
{
if (bucket[i].Key.GetHashCode() == khh && bucket[i].Key.Equals(key))
{
idx = i; break;
}
}
}
internal bool ContainsKey(T key)
{
List<KeyValuePair<T, V>> bucket;
int idx;
FindBucket(key, out bucket, out idx);
if (idx >= 0)
{
return true;
}
else
{
return false;
}
}
}
}
private void LoadCache(IMapPath server)
{
lock (cacheLock)
{
if (_cacheLoaded) { return; }
_cacheLoaded = true;
Console.WriteLine("Loading Cache");
Parallel.For(0, 4, (int qq) =>
{
for (int q = qq * 64; q < (qq + 1) * 64; q++)
{
lock (BinLocks[q])
{
Console.Write(".");
byte[] meta;
string binMeta = Utils.PreparePath(server, path, Utils.FormatHashHex(new byte[] { (byte)q }),
"meta");
string binData = Utils.PreparePath(server, path, Utils.FormatHashHex(new byte[] { (byte)q }),
"data");
long ofs = 0;
try
{
meta = File.ReadAllBytes(binMeta);
using (var fs = File.OpenRead(binData))
{
BinSizes[q] = fs.Length;
}
}
catch (FileNotFoundException)
{
if (File.Exists(binData))
{
Debug.Assert(false);
}
meta = new byte[0];
BinSizes[q] = 0;
}
for (var i = 0; i < meta.Length; i += (16 + 4)) // find meta entry
{
var size = BitConverter.ToInt32(meta, i);
var hash = new byte[16];
Array.Copy(meta, i + 4, hash, 0, 16);
var ch = new ComparableHash { HashBytes = hash };
var sch = new StoredChunk { Hash = ch, Offset = ofs, Size = size };
BinCache[q][ch] = sch;
ofs += size;
}
if (ofs != BinSizes[q])
{
Debug.Assert(false, "Meta does not match data");
}
}
}
});
}
Console.WriteLine("\r\nDone");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment