// note, not doing overrides without name (so it can be non-nullable) for Create because // it is BAD NEWS to have overloads where one of the terms is dynamic /// <summary> /// Create a DynamicCellValue to format the given value of the given column. /// /// It's permissible for both name and value to be null. /// </summary> public static DynamicCellValue Create( [NullableExposed("May be purely positional, in which case it has no name")] string?name, [NullableExposed("User may want to provide a null")] dynamic?value, Formatter formatter ) { // name can be null, that's fine // value can be null, that's fine Utils.CheckArgumentNull(formatter, nameof(formatter)); if (value is object valObj) { var valType = valObj.GetType().GetTypeInfo(); if (!formatter.Takes.IsAssignableFrom(valType)) { Throw.ArgumentException($"Formatter must accept an object assignable from {valType}", nameof(formatter)); } } return(new DynamicCellValue(name, value, formatter)); }
/// <summary> /// Create a new IBoundConfiguration(T) with given Options, for use /// with dynamic types. /// </summary> public static IBoundConfiguration <dynamic> ForDynamic(Options options) { if (options == null) { Throw.ArgumentNullException(nameof(options)); } if (options.ReadHeader == ReadHeaders.Detect) { Throw.ArgumentException($"Dynamic deserialization cannot detect the presense of headers, you must specify {nameof(ReadHeaders.Always)} or {nameof(ReadHeaders.Never)}", nameof(options)); } return (new DynamicBoundConfiguration( options.ValueSeparator, options.EscapedValueStartAndEnd, options.EscapedValueEscapeCharacter, options.RowEnding, options.ReadHeader, options.WriteHeader, options.WriteTrailingNewLine, options.MemoryPool, options.CommentCharacter, options.WriteBufferSizeHint, options.ReadBufferSizeHint, options.DynamicTypeConverter, options.DynamicRowDisposal )); }
public Memory <char> GetMemory(int sizeHint = 0) { AssertNotDisposed(); if (sizeHint < 0) { Throw.ArgumentException($"Must be >= 0", nameof(sizeHint)); return(default);
/// <summary> /// Set the buffer size hint for read operations. /// /// Setting to 0 will cause a default "best guess" size to be requested /// from the configured MemoryPool. /// /// All values are treated as hints, it's up to /// the configured MemoryPool to satisfy the request. /// </summary> public OptionsBuilder WithReadBufferSizeHint([IntentionallyExposedPrimitive("Best way to indicate a size")] int sizeHint) { if (sizeHint < 0) { Throw.ArgumentException($"Cannot be negative, was {sizeHint}", nameof(sizeHint)); } return(WithReadBufferSizeHintInternal(sizeHint)); }
/// <summary> /// Set whether or not to end the last row with a new line. /// </summary> public OptionsBuilder WithWriteTrailingRowEnding(WriteTrailingRowEnding writeTrailingNewLine) { if (!Enum.IsDefined(Types.WriteTrailingRowEnding, writeTrailingNewLine)) { Throw.ArgumentException($"Unexpected {nameof(Cesil.WriteTrailingRowEnding)} value: {writeTrailingNewLine}", nameof(writeTrailingNewLine)); } return(WithWriteTrailingRowEndingInternal(writeTrailingNewLine)); }
/// <summary> /// Set whether or not to write headers. /// </summary> public OptionsBuilder WithWriteHeader(WriteHeader writeHeader) { if (!Enum.IsDefined(Types.WriteHeader, writeHeader)) { Throw.ArgumentException($"Unexpected {nameof(Cesil.WriteHeader)} value: {writeHeader}", nameof(writeHeader)); } return(WithWriteHeaderInternal(writeHeader)); }
/// <summary> /// Set the sequence of characters that will end a row when reading. /// </summary> public OptionsBuilder WithReadRowEnding(ReadRowEnding readRowEnding) { if (!Enum.IsDefined(Types.ReadRowEnding, readRowEnding)) { Throw.ArgumentException($"Unexpected {nameof(Cesil.ReadRowEnding)} value: {readRowEnding}", nameof(readRowEnding)); } return(WithReadRowEndingInternal(readRowEnding)); }
/// <summary> /// Set the buffer size hint for read operations. /// /// Setting to 0 will cause a default "best guess" size to be requested /// from the configured MemoryPool. /// /// All values are treated as hints, it's up to /// the configured MemoryPool to satsify the request. /// </summary> public OptionsBuilder WithReadBufferSizeHint(int sizeHint) { if (sizeHint < 0) { Throw.ArgumentException($"Cannot be negative, was {sizeHint}", nameof(sizeHint)); } return(WithReadBufferSizeHintInternal(sizeHint)); }
/// <summary> /// Create a new empty ManualTypeDescriberBuilder with the given fallback behavior, and a fallback ITypeDescriber of TypeDescribers.Default. /// </summary> public static ManualTypeDescriberBuilder CreateBuilder(ManualTypeDescriberFallbackBehavior fallbackBehavior) { if (!Enum.IsDefined(Types.ManualTypeDescriberFallbackBehavior, fallbackBehavior)) { Throw.ArgumentException($"Unexpected value: {fallbackBehavior}", nameof(fallbackBehavior)); } return(CreateBuilder(fallbackBehavior, TypeDescribers.Default)); }
/// <summary> /// Set whether or not to read headers. /// </summary> public OptionsBuilder WithReadHeader(ReadHeaders r) { if (!Enum.IsDefined(Types.ReadHeadersType, r)) { Throw.ArgumentException($"Unexpected {nameof(ReadHeaders)} value: {r}", nameof(r)); } return(WithReadHeaderInternal(r)); }
/// <summary> /// Set when dynamic rows returned by a reader are disposed. /// /// The options are either when the reader is disposed (the default) or /// when the row is explicitly disposed. /// </summary> public OptionsBuilder WithDynamicRowDisposal(DynamicRowDisposal d) { if (!Enum.IsDefined(typeof(DynamicRowDisposal), d)) { Throw.ArgumentException($"Unexpected {nameof(DynamicRowDisposal)} value: {d}", nameof(d)); } return(WithDynamicRowDisposalInternal(d)); }
/// <summary> /// Set the sequence of characters that will end a row. /// </summary> public OptionsBuilder WithRowEnding(RowEndings l) { if (!Enum.IsDefined(Types.RowEndingsType, l)) { Throw.ArgumentException($"Unexpected {nameof(RowEndings)} value: {l}", nameof(l)); } return(WithRowEndingInternal(l)); }
/// <summary> /// Set or clear the buffer size hint for write operations. /// /// Setting it to null will cause a default "best guess" buffer to /// be requested from the configured MemoryPool. /// /// Setting it to 0 will disable buffering. /// /// All values are treated as hints, it's up to /// the configured MemoryPool to satsify the request. /// </summary> public OptionsBuilder WithWriteBufferSizeHint(int?sizeHint) { if (sizeHint != null && sizeHint < 0) { Throw.ArgumentException($"Cannot be negative, was {sizeHint.Value}", nameof(sizeHint)); } return(WithWriteBufferSizeHintInternal(sizeHint)); }
/// <summary> /// Set whether or not to end the last row with a new line. /// </summary> public OptionsBuilder WithWriteTrailingNewLine(WriteTrailingNewLines w) { if (!Enum.IsDefined(Types.WriteTrailingNewLinesType, w)) { Throw.ArgumentException($"Unexpected {nameof(WriteTrailingNewLines)} value: {w}", nameof(w)); } return(WithWriteTrailingNewLineInternal(w)); }
/// <summary> /// Create a DynamicRowConverter from the given method. /// /// Method must be static, return a bool, take an object (which can be dynamic in source) /// as it's first parameter, a ReadContext as it's second paramter, and have a third parameter that is an out /// for the result value. /// </summary> public static DynamicRowConverter ForMethod(MethodInfo method) { if (method == null) { Throw.ArgumentNullException(nameof(method)); } if (!method.IsStatic) { Throw.ArgumentException($"Method {method} must be static", nameof(method)); } if (method.ReturnType.GetTypeInfo() != Types.BoolType) { Throw.ArgumentException($"Method {method} must return a bool", nameof(method)); } var ps = method.GetParameters(); if (ps.Length != 3) { Throw.ArgumentException($"Method {method} must take three parameters", nameof(method)); } var p1 = ps[0].ParameterType.GetTypeInfo(); if (p1 != Types.ObjectType) { Throw.ArgumentException($"Method {method}'s first parameter must be an object", nameof(method)); } var p2 = ps[1].ParameterType.GetTypeInfo(); if (!p2.IsByRef) { Throw.ArgumentException($"Method {method}'s second parameter must be an in {nameof(ReadContext)}, was not passed by reference", nameof(method)); } var p2Elem = p2.GetElementType().GetTypeInfo(); if (p2Elem != Types.ReadContextType) { Throw.ArgumentException($"Method {method}'s second parameter must be a {nameof(ReadContext)}", nameof(method)); } var p3 = ps[2].ParameterType.GetTypeInfo(); if (!p3.IsByRef) { Throw.ArgumentException($"Method {method}'s second parameter must be a by ref type", nameof(method)); } var targetType = p3.GetElementType().GetTypeInfo(); return(new DynamicRowConverter(targetType, method)); }
/// <summary> /// Set how to treat whitespace when parsing. /// </summary> public OptionsBuilder WithWhitespaceTreatment(WhitespaceTreatments whitespaceTreatment) { // WhitespaceTreatment not recognized if (!Utils.IsLegalFlagEnum(whitespaceTreatment)) { Throw.ArgumentException($"{nameof(WhitespaceTreatment)} has an unexpected value, '{WhitespaceTreatment}'", nameof(whitespaceTreatment)); } return(WithWhitespaceTreatmentInternal(whitespaceTreatment)); }
/// <summary> /// Set how to treat extra columns when parsing. /// </summary> public OptionsBuilder WithExtraColumnTreatment(ExtraColumnTreatment extraColumnTreatment) { // ExtraColumnTreatment not recognized if (!Enum.IsDefined(Types.ExtraColumnTreatment, extraColumnTreatment)) { Throw.ArgumentException($"Unexpected {nameof(ExtraColumnTreatment)} value: {extraColumnTreatment}", nameof(extraColumnTreatment)); } return(WithExtraColumnTreatmentInternal(extraColumnTreatment)); }
/// <summary> /// Set the character used to separate two values in a row. /// </summary> public OptionsBuilder WithValueSeparator(string valueSeparator) { Utils.CheckArgumentNull(valueSeparator, nameof(valueSeparator)); if (valueSeparator.Length == 0) { Throw.ArgumentException($"{nameof(valueSeparator)} cannot be empty", nameof(valueSeparator)); } return(WithValueSeparatorInternal(valueSeparator)); }
/// <summary> /// Create a new IBoundConfiguration(T) with given Options, for use /// with dynamic types. /// </summary> public static IBoundConfiguration <dynamic> ForDynamic(Options options) { Utils.CheckArgumentNull(options, nameof(options)); if (options.ReadHeader == ReadHeader.Detect) { Throw.ArgumentException($"Dynamic deserialization cannot detect the presence of headers, you must specify a {nameof(ReadHeader)} of {nameof(ReadHeader.Always)} or {nameof(ReadHeader.Never)}", nameof(options)); } return(new DynamicBoundConfiguration(options)); }
/// <summary> /// Gets an InstanceBuilder that wraps the parameterless constructor /// for the given type. /// /// Throws if there is no parameterless constructor. /// </summary> public virtual InstanceBuilder GetInstanceBuilder(TypeInfo forType) { var cons = forType.GetConstructor(TypeInfo.EmptyTypes); if (cons == null) { Throw.ArgumentException($"No parameterless constructor found for {forType}", nameof(forType)); } return(InstanceBuilder.ForParameterlessConstructor(cons)); }
// modify /// <summary> /// Sets the behavior to fallback to when no surrogate type has been registered. /// </summary> public SurrogateTypeDescriberBuilder WithFallbackBehavior(SurrogateTypeDescriberFallbackBehavior fallbackBehavior) { if (!Enum.IsDefined(Types.SurrogateTypeDescriberFallbackBehavior, fallbackBehavior)) { Throw.ArgumentException($"Unexpected {nameof(SurrogateTypeDescriberFallbackBehavior)}: {fallbackBehavior}", nameof(fallbackBehavior)); } FallbackBehavior = fallbackBehavior; return(this); }
// set fallback behavior /// <summary> /// Sets the behavior to fallback to when a method has no registrations to return. /// </summary> public ManualTypeDescriberBuilder WithFallbackBehavior(ManualTypeDescriberFallbackBehavior fallbackBehavior) { if (!Enum.IsDefined(Types.ManualTypeDescriberFallbackBehavior, fallbackBehavior)) { Throw.ArgumentException($"Unexpected value: {fallbackBehavior}", nameof(fallbackBehavior)); } FallbackBehavior = fallbackBehavior; return(this); }
/// <summary> /// Create a new converter that will try this converter, but if it returns false /// it will then try the given fallback DynamicRowConverter. /// </summary> public DynamicRowConverter Else(DynamicRowConverter fallbackConverter) { Utils.CheckArgumentNull(fallbackConverter, nameof(fallbackConverter)); if (!TargetType.IsAssignableFrom(fallbackConverter.TargetType)) { Throw.ArgumentException($"{fallbackConverter} does not produce a value assignable to {TargetType}, and cannot be used as a fallback for this {nameof(DynamicRowConverter)}", nameof(fallbackConverter)); } return(this.DoElse(fallbackConverter, null, null)); }
/// <summary> /// Create a new empty ManualTypeDescriberBuilder with the given fallback behavior. /// </summary> public static ManualTypeDescriberBuilder CreateBuilder(ManualTypeDescriberFallbackBehavior fallbackBehavior, ITypeDescriber fallbackTypeDescriber) { if (!Enum.IsDefined(Types.ManualTypeDescriberFallbackBehavior, fallbackBehavior)) { Throw.ArgumentException($"Unexpected value: {fallbackBehavior}", nameof(fallbackBehavior)); } Utils.CheckArgumentNull(fallbackTypeDescriber, nameof(fallbackTypeDescriber)); return(new ManualTypeDescriberBuilder(fallbackBehavior, fallbackTypeDescriber)); }
public void Advance(int count) { AssertNotDisposedInternal(this); if (count < 0) { Throw.ArgumentException($"Must be >= 0", nameof(count)); } Tail.BytesUsed += count; }
internal static SerializableMember CreateInner(TypeInfo?beingSerializedType, string?name, Getter?getter, Formatter?formatter, ShouldSerialize?shouldSerialize, EmitDefaultValue emitDefault) { if (beingSerializedType == null) { Throw.ArgumentNullException(nameof(beingSerializedType)); } if (name == null) { Throw.ArgumentNullException(nameof(name)); } if (getter == null) { Throw.ArgumentNullException(nameof(getter)); } if (formatter == null) { Throw.ArgumentNullException(nameof(formatter)); } bool emitDefaultValueBool; switch (emitDefault) { case Cesil.EmitDefaultValue.Yes: emitDefaultValueBool = true; break; case Cesil.EmitDefaultValue.No: emitDefaultValueBool = false; break; default: Throw.InvalidOperationException($"Unexpected {nameof(Cesil.EmitDefaultValue)}: {emitDefault}"); return(default); } var toSerializeType = getter.Returns; if (!formatter.Takes.IsAssignableFrom(toSerializeType)) { Throw.ArgumentException($"The first parameter to {nameof(formatter)} must accept a {toSerializeType}", nameof(formatter)); } CheckShouldSerializeMethod(shouldSerialize, getter.RowType); return(new SerializableMember(name, getter, formatter, shouldSerialize, emitDefaultValueBool)); }
/// <summary> /// Creates a SurrogateTypeDescriberBuilder with the given fallback behavior, type describer, and fallback type describer. /// /// Uses the given ITypeDescriber to describes surrogates, /// and falls back to provided fallback if no surrogate is registered and the provided SurrogateTypeDescriberFallbackBehavior /// allows it. /// </summary> public static SurrogateTypeDescriberBuilder CreateBuilder(SurrogateTypeDescriberFallbackBehavior fallbackBehavior, ITypeDescriber typeDescriber, ITypeDescriber fallbackTypeDescriber) { if (!Enum.IsDefined(Types.SurrogateTypeDescriberFallbackBehavior, fallbackBehavior)) { Throw.ArgumentException($"Unexpected {nameof(SurrogateTypeDescriberFallbackBehavior)}: {fallbackBehavior}", nameof(fallbackBehavior)); } Utils.CheckArgumentNull(typeDescriber, nameof(typeDescriber)); Utils.CheckArgumentNull(fallbackTypeDescriber, nameof(fallbackTypeDescriber)); var inner = ImmutableDictionary.CreateBuilder <TypeInfo, TypeInfo>(); return(new SurrogateTypeDescriberBuilder(typeDescriber, fallbackTypeDescriber, fallbackBehavior, inner)); }
internal static void CheckImmutableReadInto <TCollection, TItem>(TCollection arg, string argName) where TCollection : ICollection <TItem> { var isImmutable = arg is ImmutableArray <TItem> || arg is ImmutableList <TItem> || arg is ImmutableHashSet <TItem> || arg is ImmutableSortedSet <TItem>; if (isImmutable) { Throw.ArgumentException("Pass a builder to create immutable collections; passed an immutable collection directly, which will not reflect mutations", argName); } }
internal static SerializableMember ForGeneratedMethod(string name, MethodInfo generated, Getter getter, Formatter formatter, ShouldSerialize?shouldSerialize, bool emitDefaultValue) { // ok for shouldSerialize to be null if (!generated.IsPublic) { Throw.ArgumentException("Generated method should be public, but wasn't", nameof(generated)); } if (!generated.IsStatic) { Throw.ArgumentException("Generated method should be static, but wasn't", nameof(generated)); } if (generated.ReturnType != Types.Bool) { Throw.ArgumentException("Generated method should return bool, but doesn't", nameof(generated)); } var ps = generated.GetParameters(); if (ps.Length != 3) { Throw.ArgumentException("Generated method should take 3 parameters, but doesn't", nameof(generated)); } var p0 = ps[0].ParameterType.GetTypeInfo(); if (p0 != Types.Object) { Throw.ArgumentException($"Generated method's first parameter should be object, but was {p0}", nameof(generated)); } var p1 = ps[1]; if (!p1.IsWriteContextByRef(out var error)) { Throw.ArgumentException($"Generated method's second parameter should be in WriteContext; {error}", nameof(generated)); } var p2 = ps[2].ParameterType.GetTypeInfo(); if (p2 != Types.IBufferWriterOfChar) { Throw.ArgumentException($"Generated method's third parameter should be IBufferWriter<char>, but was {p2}", nameof(generated)); } return(new SerializableMember(name, generated, getter, formatter, shouldSerialize, emitDefaultValue)); }
private static void CheckShouldSerializeMethod(MethodInfo shouldSerialize, TypeInfo onType) { if (shouldSerialize == null) { return; } // shouldSerialize must be an argument-less method // that is either static, or on an instance of the same type as (or a baseclass of) setter // and cannot be generic or otherwise weird if (shouldSerialize.IsGenericMethodDefinition) { Throw.ArgumentException($"Cannot use a generic method for the {nameof(shouldSerialize)} argument", nameof(shouldSerialize)); } var args = shouldSerialize.GetParameters(); if (args.Length > 0) { Throw.ArgumentException($"{nameof(shouldSerialize)} cannot take parameters", nameof(shouldSerialize)); } var ret = shouldSerialize.ReturnType.GetTypeInfo(); if (ret != Types.BoolType) { Throw.ArgumentException($"{nameof(shouldSerialize)} must return a boolean", nameof(shouldSerialize)); } if (!shouldSerialize.IsStatic) { var shouldSerializeInstType = shouldSerialize.DeclaringType.GetTypeInfo(); var isInstOrSubclass = onType.IsAssignableFrom(shouldSerializeInstType); if (!isInstOrSubclass) { Throw.ArgumentException($"{nameof(shouldSerialize)} be either static or a member of an instance of the type declaring the field or property", nameof(shouldSerialize)); } } }