Skip to content

Instantly share code, notes, and snippets.

@mrtank
Created March 17, 2021 23:10
Show Gist options
  • Save mrtank/8d3a1d53b674645b623f368e6d297f57 to your computer and use it in GitHub Desktop.
Save mrtank/8d3a1d53b674645b623f368e6d297f57 to your computer and use it in GitHub Desktop.
Splitting into byte[]
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
namespace Stuff
{
class Program
{
public static IEnumerable<string> EnumLines(StreamReader fp)
{
while (!fp.EndOfStream)
{
var line = fp.ReadLine();
yield return line;
}
}
public static IObservable<byte> TrueReadBytes(Stream source, IScheduler scheduler = null)
{
scheduler = scheduler ?? Scheduler.Default;
return Observable.Using(
() => new StreamReader(source),
reader =>
{
return Observable.Create<byte>(obs =>
{
//Grab the enumerator as our iteration state.
var enumerator = EnumLines(reader).GetEnumerator();
return scheduler.Schedule(enumerator, (e, recurse) =>
{
if (!e.MoveNext())
{
obs.OnCompleted();
return;
}
foreach (var byteString in reader.ReadLine().Split(' '))
{
int startInd = 0;
if (byteString.StartsWith("0x"))
{
startInd = 2;
}
else if (byteString.StartsWith("x") || byteString.StartsWith("X"))
{
startInd = 1;
}
if (byte.TryParse(byteString.Substring(startInd), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var b))
obs.OnNext(b);
else
obs.OnError(new Exception($"Could not parse: {byteString}"));
}
//Recursively schedule
recurse(e);
});
});
});
}
static void Main(string[] args)
{
var memStr = new MemoryStream();
var writer = new StreamWriter(memStr);
for (int i = 0; i < 20000; i++)
{
writer.Write("03");
if (i == 19333)
{
writer.Write("dummy");
}
if (i % 100 == 4)
writer.Write(" ");
else
writer.WriteLine();
}
writer.Write("06");
writer.WriteLine();
writer.Flush();
memStr.Position = 0;
var a = TrueReadBytes(memStr)
.TakeUntil(Observable.Timer(TimeSpan.FromMilliseconds(100)));
var disp = a.Subscribe(x => Console.Write(x), Console.Write);
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment