Skip to content

Commit

Permalink
Implement encoding fallback in commit messages for libgit2#387
Browse files Browse the repository at this point in the history
  • Loading branch information
martinwoodward committed May 9, 2013
1 parent 7326361 commit 0032af2
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 additions & 3 deletions LibGit2Sharp/Core/Utf8Marshaler.cs
Expand Up @@ -48,6 +48,18 @@ internal class Utf8Marshaler : ICustomMarshaler
{
private static readonly Utf8Marshaler staticInstance = new Utf8Marshaler();

private static readonly Encoding marshallerEncoding = UTF8EncodingWithFallBack;

public static Encoding UTF8EncodingWithFallBack
{
get
{
Encoding encoding = (Encoding)Encoding.UTF8.Clone();
encoding.DecoderFallback = new DecoderExceptionFallback();
return encoding;
}
}

public static ICustomMarshaler GetInstance(String cookie)
{
return staticInstance;
Expand Down Expand Up @@ -141,7 +153,7 @@ public static unsafe String FromNative(IntPtr pNativeData)
return String.Empty;
}

return new String((sbyte*)pNativeData.ToPointer(), 0, (int)(walk - start), Encoding.UTF8);
return FromNative(pNativeData, (int)(walk - start));
}

public static unsafe String FromNative(IntPtr pNativeData, int length)
Expand All @@ -156,7 +168,16 @@ public static unsafe String FromNative(IntPtr pNativeData, int length)
return String.Empty;
}

return new String((sbyte*)pNativeData.ToPointer(), 0, length, Encoding.UTF8);
try
{
// Try UTF8 with fallback
return new String((sbyte*)pNativeData.ToPointer(), 0, length, marshallerEncoding);
}
catch (DecoderFallbackException)
{
// If this fails, try the platform default.
return new String((sbyte*)pNativeData.ToPointer(), 0, length, Encoding.Default);
}
}

public static String Utf8FromBuffer(byte[] buffer)
Expand All @@ -180,7 +201,16 @@ public static String Utf8FromBuffer(byte[] buffer)
return String.Empty;
}

return Encoding.UTF8.GetString(buffer, 0, length);
try
{
// Try UTF8 with fallback
return marshallerEncoding.GetString(buffer, 0, length);
}
catch (DecoderFallbackException)
{
// If fails, use platform default
return Encoding.Default.GetString(buffer, 0, length);
}
}
}
}

0 comments on commit 0032af2

Please sign in to comment.