-
Notifications
You must be signed in to change notification settings - Fork 3
/
Pandoc.cs
110 lines (98 loc) · 3.59 KB
/
Pandoc.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
namespace Pandoc
{
using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate int Reader(IntPtr data);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate void Writer(IntPtr data, int length);
class Native
{
[DllImport("libpandoc", CallingConvention=CallingConvention.Cdecl)]
public static extern void pandoc_init();
[DllImport("libpandoc", CallingConvention=CallingConvention.Cdecl)]
public static extern void pandoc_exit();
[DllImport("libpandoc", CallingConvention=CallingConvention.Cdecl)]
public static extern string pandoc(int bufferSize,
byte[] inputFormat,
byte[] outputFormat,
byte[] settings,
Reader reader, Writer writer);
}
public class PandocException : Exception
{
public PandocException(string message) : base(message)
{
}
}
public class Processor : IDisposable
{
const int charSize = 1024;
const int bytesPerChar = 4;
const int byteSize = bytesPerChar * charSize;
char[] chars;
byte[] bytes;
Encoding encoding;
public Processor()
{
chars = new char[charSize];
bytes = new byte[byteSize];
encoding = Encoding.UTF8;
Native.pandoc_init();
}
public void Process(string source, string target,
TextReader input, TextWriter output)
{
Process(source, target, null, input, output);
}
byte[] Bytes(string text)
{
if (text != null) {
byte[] bytes = encoding.GetBytes(text);
byte[] result = new byte[bytes.Length + 1];
for (var i = 0; i < bytes.Length; i++) {
result[i] = bytes[i];
}
return result;
} else {
return new byte[0];
}
}
public void Process(string source, string target, string config,
TextReader input, TextWriter output)
{
Reader reader =
delegate (IntPtr data)
{
int c = input.ReadBlock(chars, 0, charSize);
int b = encoding.GetBytes(chars, 0, c, bytes, 0);
Marshal.Copy(bytes, 0, data, b);
return b;
};
Writer writer =
delegate (IntPtr data, int length)
{
if (length > 0) {
Marshal.Copy(data, bytes, 0, length);
int c = encoding.GetChars(bytes, 0, length, chars, 0);
output.Write(chars, 0, c);
}
};
string err = Native.pandoc(byteSize,
Bytes(source),
Bytes(target),
Bytes(config),
reader,
writer);
if (err != null) {
throw new PandocException(err);
}
}
public void Dispose()
{
Native.pandoc_exit();
}
}
}