protected internal virtual string GetBitFlagDescription(int tagType, [NotNull] params object[] labels) { int? value = _directory.GetInteger(tagType); if (value == null) { return null; } IList<CharSequence> parts = new AList<CharSequence>(); int bitIndex = 0; while (labels.Length > bitIndex) { object labelObj = labels[bitIndex]; if (labelObj != null) { bool isBitSet = ((int)value & 1) == 1; if (labelObj is string[]) { string[] labelPair = (string[])labelObj; System.Diagnostics.Debug.Assert((labelPair.Length == 2)); parts.Add(labelPair[isBitSet ? 1 : 0]); } else { if (isBitSet && labelObj is string) { parts.Add((string)labelObj); } } } value >>= 1; bitIndex++; } return StringUtil.Join(parts.AsIterable(), ", "); }
public virtual void TestJoinIterable() { IList<string> strings = new AList<string>(); strings.Add("A"); strings.Add("B"); strings.Add("C"); Sharpen.Tests.AreEqual("A;B;C", StringUtil.Join(strings.ToCharSequence(), ";")); Sharpen.Tests.AreEqual(string.Empty, StringUtil.Join(new AList<string>().ToCharSequence(), ";")); }
public virtual void TestJoinIterable() { IList <string> strings = new AList <string>(); strings.Add("A"); strings.Add("B"); strings.Add("C"); Sharpen.Tests.AreEqual("A;B;C", StringUtil.Join(strings.AsIterable(), ";")); Sharpen.Tests.AreEqual(string.Empty, StringUtil.Join(new AList <string>(), ";")); }
public void DetermineCapacity_CountAvailableSpaces_Assert6() { //arrange AList <int> test = new AList <int>(); test.Add(1); test.Add(2); //act //test.CheckCapacity(); //assert //Assert.AreEqual(test.Capacity, 6); }
public void Count_PropertyUsageForCount_CountEqualsAListLength() { //arrange AList <string> listOfValues = new AList <string>();// { "test", "fill" }; listOfValues.Add("test"); listOfValues.Add("fill"); //act int lengthOfAList = listOfValues.Count; //assert Assert.AreEqual(lengthOfAList, 2); }
public void DetermineCapacity_CapacityIncreasesFromThreshold_Assert12() { //arrange AList <int> test = new AList <int>(); test.Add(1); test.Add(2); test.Add(3); //act //test.CheckCapacity(); //assert //Assert.AreEqual(test.Capacity, 12); }
public void Remove_RemoveFromAList_IndexIsRemoved() { //arrange string removeThis = "remove"; AList <string> listOfValues = new AList <string>();// { "test", removeThis, "fill" }; listOfValues.Add("test"); listOfValues.Add(removeThis); listOfValues.Add("fill"); //act listOfValues.Remove(removeThis); //assert Assert.AreNotEqual(listOfValues[1], removeThis); }
public void Remove_RemoveFromAList_KeepValueAtIndex1() { //arrange string remove = "remove"; string doNotRemove = "keep"; AList <string> listOfValues = new AList <string>();// { remove, doNotRemove }; listOfValues.Add(remove); listOfValues.Add(doNotRemove); //act listOfValues.Remove(remove); //assert Assert.AreEqual(listOfValues[0], doNotRemove); }
/// <exception cref="System.IO.IOException"/> protected internal override bool IsValidIndex(int index, int bytesRequested) { if (index < 0 || bytesRequested < 0) { return(false); } long endIndexLong = (long)index + bytesRequested - 1; if (endIndexLong > int.MaxValue) { return(false); } int endIndex = (int)endIndexLong; if (_isStreamFinished) { return(endIndex < _streamLength); } int chunkIndex = endIndex / _chunkLength; // TODO test loading several chunks for a single request while (chunkIndex >= _chunks.Count) { System.Diagnostics.Debug.Assert((!_isStreamFinished)); sbyte[] chunk = new sbyte[_chunkLength]; int totalBytesRead = 0; while (!_isStreamFinished && totalBytesRead != _chunkLength) { int bytesRead = _stream.Read(chunk, totalBytesRead, _chunkLength - totalBytesRead); if (bytesRead == -1) { // the stream has ended, which may be ok _isStreamFinished = true; _streamLength = _chunks.Count * _chunkLength + totalBytesRead; // check we have enough bytes for the requested index if (endIndex >= _streamLength) { _chunks.Add(chunk); return(false); } } else { totalBytesRead += bytesRead; } } _chunks.Add(chunk); } return(true); }
public void Remove_DoNotRemoveFromAList_ReturnFalse() { //arrange string removeThis = "remove"; bool hasRemoved; AList <string> listOfValues = new AList <string>();// { "test", removeThis, "fill" }; listOfValues.Add("test"); listOfValues.Add("extra"); listOfValues.Add("fill"); //act hasRemoved = listOfValues.Remove(removeThis); //assert Assert.IsFalse(hasRemoved); }
public void Remove_CheckIndex1_ValueFromIndex2IsThere() { //arrange string test = "test"; string removeThis = "remove"; AList <string> listOfValues = new AList <string>();// { "test", removeThis, "fill" }; listOfValues.Add("fill"); listOfValues.Add(removeThis); listOfValues.Add(test); //act listOfValues.Remove(removeThis); //assert Assert.AreEqual(listOfValues[1], test); }
public void Remove_CheckCount_CountEquals2() { //arrange string test = "test"; string removeThis = "remove"; AList <string> listOfValues = new AList <string>();// { "test", removeThis, "fill" }; listOfValues.Add("fill"); listOfValues.Add(removeThis); listOfValues.Add(test); //act listOfValues.Remove(removeThis); //assert Assert.AreEqual(listOfValues.Count, 2); }
/// <summary> /// Combine InputSplits from child InputFormats into a /// <see cref="CompositeInputSplit"/> /// . /// </summary> /// <exception cref="System.IO.IOException"/> /// <exception cref="System.Exception"/> public override IList GetSplits(JobContext job) { IList <IList <InputSplit> > splits = new AList <IList <InputSplit> >(kids.Count); for (int i = 0; i < kids.Count; ++i) { IList <InputSplit> tmp = kids[i].GetSplits(job); if (null == tmp) { throw new IOException("Error gathering splits from child RReader"); } if (i > 0 && splits[i - 1].Count != tmp.Count) { throw new IOException("Inconsistent split cardinality from child " + i + " (" + splits [i - 1].Count + "/" + tmp.Count + ")"); } splits.Add(i, tmp); } int size = splits[0].Count; IList <InputSplit> ret = new AList <InputSplit>(); for (int i_1 = 0; i_1 < size; ++i_1) { CompositeInputSplit split = new CompositeInputSplit(splits.Count); for (int j = 0; j < splits.Count; ++j) { split.Add(splits[j][i_1]); } ret.AddItem(split); } return(ret); }
public virtual IList <CertificateAndContext> GetCertificateBySubjectName(X509Name subjectName) { IList <CertificateAndContext> list = new AList <CertificateAndContext>(); try { string url = GetAccessLocation(certificate, X509ObjectIdentifiers.IdADCAIssuers); if (url != null) { X509CertificateParser parser = new X509CertificateParser(); X509Certificate cert = parser.ReadCertificate(httpDataLoader.Get(url)); if (cert.SubjectDN.Equals(subjectName)) { list.Add(new CertificateAndContext()); } } } catch (CannotFetchDataException) { return(new List <CertificateAndContext>()); } catch (CertificateException) { return(new List <CertificateAndContext>()); } return(list); }
public virtual void RemoveColumnItems(int column) { // Firstly, remove columns from visible recyclerViews. // To be able provide removing animation, we need to notify just for given column position. CellRecyclerView[] visibleRecyclerViews = mTableView.GetCellLayoutManager().GetVisibleCellRowRecyclerViews(); foreach (CellRecyclerView cellRowRecyclerView in visibleRecyclerViews) { ((AbstractRecyclerViewAdapter <ICell>)cellRowRecyclerView.GetAdapter()).DeleteItem(column); } // Lets change the model list silently // Create a new list which the column is already removed. IList <IList <ICell> > cellItems = new AList <IList <ICell> >(); for (int i = 0; i < mItemList.Count; i++) { IList <ICell> rowList = new AList <ICell>((IList <ICell>)mItemList[i]); if (rowList.Count > column) { rowList.RemoveAt(column); } cellItems.Add(rowList); } // Change data without notifying. Because we already did for visible recyclerViews. SetItems(cellItems, false); }
/// <summary> /// Finds all keys. /// </summary> public void FindAllKeys() { InitLists(); for (var alpha = 1; alpha < P - 1; alpha++) { for (var a = 1; a < P - 1; a++) { if ((alpha * a) % (P - 1) == 1) { for (var beta = 1; beta < P - 1; beta++) { for (var b = 1; b < P - 1; b++) { if ((beta * b) % (P - 1) == 1 && (alpha * a * beta * b) % (P - 1) == 1) { AlphaList.Add(alpha); BetaList.Add(beta); AList.Add(a); BList.Add(b); } } } } } } }
/// <exception cref="Java.Sql.SQLException"/> internal virtual IList <string> Split(int numSplits, string minString, string maxString , string commonPrefix) { BigDecimal minVal = StringToBigDecimal(minString); BigDecimal maxVal = StringToBigDecimal(maxString); IList <BigDecimal> splitPoints = Split(new BigDecimal(numSplits), minVal, maxVal); IList <string> splitStrings = new AList <string>(); // Convert the BigDecimal splitPoints into their string representations. foreach (BigDecimal bd in splitPoints) { splitStrings.AddItem(commonPrefix + BigDecimalToString(bd)); } // Make sure that our user-specified boundaries are the first and last entries // in the array. if (splitStrings.Count == 0 || !splitStrings[0].Equals(commonPrefix + minString)) { splitStrings.Add(0, commonPrefix + minString); } if (splitStrings.Count == 1 || !splitStrings[splitStrings.Count - 1].Equals(commonPrefix + maxString)) { splitStrings.AddItem(commonPrefix + maxString); } return(splitStrings); }
public virtual IList<CertificateAndContext> GetCertificateBySubjectName(X509Name subjectName) { IList<CertificateAndContext> list = new AList<CertificateAndContext>(); try { string url = GetAccessLocation(certificate, X509ObjectIdentifiers.IdADCAIssuers); if (url != null) { X509CertificateParser parser = new X509CertificateParser(); X509Certificate cert = parser.ReadCertificate(httpDataLoader.Get(url)); if (cert.SubjectDN.Equals(subjectName)) { list.Add(new CertificateAndContext()); } } } catch (CannotFetchDataException) { return new List<CertificateAndContext>(); } catch (CertificateException) { return new List<CertificateAndContext>(); } return list; }
public void SaveTokenInfo(TokenGenesisBlock tokenGewnesisBlock) { if (tokenGewnesisBlock != null && GetTokenInfo(tokenGewnesisBlock.Ticker) == null) { _tokeninfo.Add(tokenGewnesisBlock); } }
public void QueueObject(T o) { IList <T> objects = new AList <T>(); objects.Add(o); QueueObjects(objects); }
public override void OnExtracted([NotNull] FilePath file, [NotNull] Com.Drew.Metadata.Metadata metadata, [NotNull] string relativePath) { base.OnExtracted(file, metadata, relativePath); try { PrintWriter writer = null; try { writer = OpenWriter(file); // Build a list of all directories IList <Com.Drew.Metadata.Directory> directories = new AList <Com.Drew.Metadata.Directory>(); foreach (Com.Drew.Metadata.Directory directory in metadata.GetDirectories()) { directories.Add(directory); } // Sort them by name directories.Sort(new _IComparer_235()); // Write any errors if (metadata.HasErrors()) { foreach (Com.Drew.Metadata.Directory directory_1 in directories) { if (!directory_1.HasErrors()) { continue; } foreach (string error in directory_1.GetErrors()) { writer.Format("[ERROR: %s] %s\n", directory_1.GetName(), error); } } writer.Write("\n"); } // Write tag values for each directory foreach (Com.Drew.Metadata.Directory directory_2 in directories) { string directoryName = directory_2.GetName(); foreach (Tag tag in directory_2.GetTags()) { string tagName = tag.GetTagName(); string description = tag.GetDescription(); writer.Format("[%s - %s] %s = %s%n", directoryName, tag.GetTagTypeHex(), tagName, description); } if (directory_2.GetTagCount() != 0) { writer.Write('\n'); } } } finally { CloseWriter(writer); } } catch (IOException e) { Sharpen.Runtime.PrintStackTrace(e); } }
public static IList <E> ToList <E>(Iterable <E> iterable) { AList <E> list = new AList <E>(); foreach (E item in iterable) { list.Add(item); } return(list); }
public void Add_AddToAList_Index0EqualsValue() { //arrange AList <string> listOfValues = new AList <string>(); string value = "test"; //act listOfValues.Add(value); //assert Assert.AreEqual(listOfValues[0], value); }
public virtual void TestReadJpegSegmentWithNoExifData() { sbyte[] badExifData = new sbyte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; Com.Drew.Metadata.Metadata metadata = new Com.Drew.Metadata.Metadata(); AList <sbyte[]> segments = new AList <sbyte[]>(); segments.Add(badExifData); new ExifReader().ReadJpegSegments(segments.AsIterable(), metadata, JpegSegmentType.App1); Sharpen.Tests.AreEqual(0, metadata.GetDirectoryCount()); Sharpen.Tests.IsFalse(metadata.HasErrors()); }
public virtual void SetUp() { Com.Drew.Metadata.Metadata metadata = new Com.Drew.Metadata.Metadata(); IList<sbyte[]> jpegSegments = new AList<sbyte[]>(); jpegSegments.Add(FileUtil.ReadBytes("Tests/Data/withXmpAndIptc.jpg.app1.1")); new XmpReader().ReadJpegSegments(jpegSegments.AsIterable(), metadata, JpegSegmentType.App1); ICollection<XmpDirectory> xmpDirectories = metadata.GetDirectoriesOfType<XmpDirectory>(); NUnit.Framework.Assert.IsNotNull(xmpDirectories); Sharpen.Tests.AreEqual(1, xmpDirectories.Count); _directory = xmpDirectories.Iterator().Next(); Sharpen.Tests.IsFalse(_directory.HasErrors()); }
private MethodDef MethodDefFromCCIMethod(CCI.Method method) { if (!IsCCIMethodDefinition(method)) throw new InvalidOperationException("method is not a definition"); var typeParameters = default(AList<ParameterTypeDef>); if (method.TemplateParameters != null && method.TemplateParameters.Count > 0) { typeParameters = new AList<ParameterTypeDef>(); for (var i = 0; i < method.TemplateParameters.Count; i++) { var p = method.TemplateParameters[i]; if (p.Template != null) throw new InvalidOperationException("invalid method type parameter"); var mcp = p as CCI.MethodClassParameter; var mtp = p as CCI.MethodTypeParameter; if (mcp != null || mtp != null) { var extends = default(TypeRef); var implements = default(AList<TypeRef>); TypeDerivationFromCCIType(p, out extends, out implements); var variance = default(ParameterVariance); var constraint = default(ParameterConstraint); ParameterConstraintFromCCITypeParameterFlags (mcp == null ? mtp.TypeParameterFlags : mcp.TypeParameterFlags, out variance, out constraint); typeParameters.Add (new ParameterTypeDef (null, CustomAttributesFromCCIMember(p), extends, implements, ParameterFlavor.Method, i, variance, constraint)); } else throw new InvalidOperationException("invalid method type parameter"); } } var result = default(CST.TypeRef); var valueParameters = ValueParametersFromCCIMethod(method, out result); var locals = default(AList<ParameterOrLocal>); if (method.Instructions != null && method.Instructions.Count > 0) { var instruction = method.Instructions[0]; if (instruction.OpCode == CCI.OpCode._Locals && instruction.Value != null) { var ll = (CCI.LocalList)instruction.Value; if (ll.Count > 0) { locals = new AList<ParameterOrLocal>(); for (var i = 0; i < ll.Count; i++) { // BUG: CCI forgets to initialize the local indexes. Do so now so that // InstructionsFromCCIMethod will pickup the correct local indexes. ll[i].Index = i; locals.Add(new ParameterOrLocal(null, null, TypeRefFromCCIType(ll[i].Type))); } } } } var customAttributes = CustomAttributesFromCCIMember(method); var instructions = InstructionsFromCCIMethod(method); if (method is CCI.InstanceInitializer && (typeParameters != null || method.IsStatic || method.IsVirtual || method.IsAbstract)) throw new InvalidOperationException("invalid constructor definition"); if (method is CCI.StaticInitializer && (typeParameters != null || !method.IsStatic || method.IsVirtual || method.IsAbstract)) throw new InvalidOperationException("invalid constructor definition"); var methodStyle = default(MethodStyle); if ((method.Flags & CCI.MethodFlags.SpecialName) != 0 && (method.Flags & CCI.MethodFlags.RTSpecialName) != 0 && (method.Name.Name.Equals(".ctor", StringComparison.Ordinal) || method.Name.Name.Equals(".cctor", StringComparison.Ordinal))) methodStyle = MethodStyle.Constructor; else if ((method.Flags & CCI.MethodFlags.Abstract) != 0) methodStyle = MethodStyle.Abstract; else if ((method.Flags & CCI.MethodFlags.Virtual) != 0) methodStyle = MethodStyle.Virtual; else methodStyle = MethodStyle.Normal; var hasNewSlot = (method.Flags & CCI.MethodFlags.NewSlot) != 0; var isStatic = (method.Flags & CCI.MethodFlags.Static) != 0; var codeFlavor = default(MethodCodeFlavor); if ((method.ImplFlags & CCI.MethodImplFlags.Native) != 0) codeFlavor = MethodCodeFlavor.Native; else if ((method.ImplFlags & CCI.MethodImplFlags.Runtime) != 0) codeFlavor = MethodCodeFlavor.Runtime; else if ((method.ImplFlags & CCI.MethodImplFlags.ForwardRef) != 0) codeFlavor = MethodCodeFlavor.ForwardRef; else codeFlavor = MethodCodeFlavor.Managed; var isSyncronized = (method.ImplFlags & CCI.MethodImplFlags.Synchronized) != 0; var noInlining = (method.ImplFlags & CCI.MethodImplFlags.NoInlining) != 0; var annotations = new AList<Annotation>(); var accessibility = default(Accessibility); if ((method.Flags & CCI.MethodFlags.Private) != 0) accessibility = Accessibility.Private; else if ((method.Flags & CCI.MethodFlags.FamANDAssem) != 0) accessibility = Accessibility.FamilyANDAssembly; else if ((method.Flags & CCI.MethodFlags.Assembly) != 0) accessibility = Accessibility.Assembly; else if ((method.Flags & CCI.MethodFlags.Family) != 0) accessibility = Accessibility.Family; else if ((method.Flags & CCI.MethodFlags.FamORAssem) != 0) accessibility = Accessibility.FamilyORAssembly; else if ((method.Flags & CCI.MethodFlags.Public) != 0) accessibility = Accessibility.Public; else accessibility = Accessibility.CompilerControlled; annotations.Add(new AccessibilityAnnotation(accessibility)); var isSpecial = (method.Flags & CCI.MethodFlags.SpecialName) != 0; var isRTSpecial = (method.Flags & CCI.MethodFlags.RTSpecialName) != 0; var nameFlavor = isRTSpecial ? NameFlavor.RTSpecial : (isSpecial ? NameFlavor.Special : NameFlavor.Normal); annotations.Add(new NameFlavorAnnotation(nameFlavor)); annotations.Add(new MethodOverriddingControlAnnotation( (method.Flags & CCI.MethodFlags.Final) != 0, (method.Flags & CCI.MethodFlags.HideBySig) != 0, (method.Flags & CCI.MethodFlags.CheckAccessOnOverride) != 0)); if ((method.Flags & CCI.MethodFlags.PInvokeImpl) != 0) annotations.Add(new PInvokeAnnotation()); annotations.Add(new MethodSecurityAnnotation( (method.Flags & CCI.MethodFlags.HasSecurity) != 0, (method.Flags & CCI.MethodFlags.RequireSecObject) != 0)); var callingConvention = default(CallingConvention); switch (method.CallingConvention & CCI.CallingConventionFlags.ArgumentConvention) { case CCI.CallingConventionFlags.Default: callingConvention = CallingConvention.Managed; break; case CCI.CallingConventionFlags.C: callingConvention = CallingConvention.NativeC; break; case CCI.CallingConventionFlags.StandardCall: callingConvention = CallingConvention.NativeStd; break; case CCI.CallingConventionFlags.ThisCall: callingConvention = CallingConvention.NativeThis; break; case CCI.CallingConventionFlags.FastCall: callingConvention = CallingConvention.NativeFast; break; case CCI.CallingConventionFlags.VarArg: callingConvention = CallingConvention.ManagedVarArg; break; default: throw new ArgumentOutOfRangeException(); } annotations.Add(new MethodCallingConventionAnnotation(callingConvention)); // NOTE: CCI doesn't seem to provide MaxStack annotations.Add(new MethodImplementationAnnotation(-1, method.InitLocals)); return new MethodDef (annotations, customAttributes, method.Name.Name, isStatic, typeParameters, valueParameters, result, methodStyle, hasNewSlot, codeFlavor, isSyncronized, noInlining, locals, instructions); }
private FieldDef FieldDefFromCCIField(CCI.Field field) { if (!IsCCIFieldDefinition(field)) throw new InvalidOperationException("field is not a definition"); var annotations = new AList<Annotation>(); annotations.Add(new FieldAccessAnnotation(field.IsInitOnly)); var init = default(FieldInit); if (field.DefaultValue != null) { if (field.InitialData != null) throw new InvalidOperationException("invalid field definition"); init = new ConstFieldInit(field.DefaultValue.Value); } else if (field.InitialData != null) init = new RawFieldInit(field.InitialData); else init = null; var customAttributes = CustomAttributesFromCCIMember(field); return new FieldDef (annotations, customAttributes, field.Name.Name, field.IsStatic, TypeRefFromCCIType(field.Type), init); }
private TypeDef TypeDefFromCCIType(CCI.AssemblyNode assembly, CCI.TypeNode type) { if (!IsCCITypeDefinition(type)) throw new InvalidOperationException("type is not a definition"); if (type.DeclaringModule == null || type.DeclaringModule.ContainingAssembly == null || type.DeclaringModule.ContainingAssembly != assembly || type.Name == null) throw new InvalidOperationException("type definition not found in assembly"); if (type is CCI.ArrayType || type is CCI.Reference || type is CCI.Pointer || type is CCI.FunctionPointer) throw new InvalidOperationException("type is not a definition"); if (type is CCI.ClassParameter || type is CCI.TypeParameter) throw new InvalidOperationException("unexpected type parameter"); var parameters = default(AList<ParameterTypeDef>); var declType = type; do { if (declType.TemplateArguments != null && declType.TemplateArguments.Count > 0) throw new InvalidOperationException("type is not a definition"); if (declType.TemplateParameters != null && declType.TemplateParameters.Count > 0) { if (parameters == null) parameters = new AList<ParameterTypeDef>(); for (var i = 0; i < declType.TemplateParameters.Count; i++) { var p = declType.TemplateParameters[i]; if (p.Template != null) throw new InvalidOperationException("invalid class type parameter"); if (p is CCI.MethodClassParameter || p is CCI.MethodTypeParameter) throw new InvalidOperationException("invalid class type parameter"); var cp = p as CCI.ClassParameter; var tp = p as CCI.TypeParameter; if (cp != null || tp != null) { var variance = default(ParameterVariance); var constraint = default(ParameterConstraint); ParameterConstraintFromCCITypeParameterFlags (cp == null ? tp.TypeParameterFlags : cp.TypeParameterFlags, out variance, out constraint); var pextends = default(TypeRef); var pimplements = default(AList<TypeRef>); TypeDerivationFromCCIType(p, out pextends, out pimplements); parameters.Insert (i, (new ParameterTypeDef (null, CustomAttributesFromCCIMember(p), pextends, pimplements, ParameterFlavor.Type, i, variance, constraint))); } else throw new InvalidOperationException("invalid class type parameter"); } } declType = declType.DeclaringType; } while (declType != null); var members = default(AList<MemberDef>); for (var i = 0; i < type.Members.Count; i++) { var member = type.Members[i]; var method = member as CCI.Method; if (method != null) { if (members == null) members = new AList<MemberDef>(); members.Add(MethodDefFromCCIMethod(method)); } else { var field = member as CCI.Field; if (field != null) { if (members == null) members = new AList<MemberDef>(); members.Add(FieldDefFromCCIField(field)); } else { var prop = member as CCI.Property; if (prop != null) { if (members == null) members = new AList<MemberDef>(); members.Add(PropertyDefFromCCIProperty(prop)); } else { var evnt = member as CCI.Event; if (evnt != null) { if (members == null) members = new AList<MemberDef>(); members.Add(EventDefFromCCIEvent(evnt)); } } } } } // Place members in canonical order var signatureToMember = default(Dictionary<MemberSignature, MemberDef>); if (members != null) { var signatures = new List<MemberSignature>(); signatureToMember = new Dictionary<MemberSignature, MemberDef>(); for (var i = 0; i < members.Count; i++) { var signature = members[i].Signature; if (signatureToMember.ContainsKey(signature)) throw new InvalidOperationException("invalid type definition"); signatures.Add(signature); signatureToMember.Add(signature, members[i]); } signatures.Sort((l, r) => l.CompareTo(r)); members = new AList<MemberDef>(); for (var i = 0; i < signatures.Count; i++) members.Add(signatureToMember[signatures[i]]); } var qtn = QualifiedTypeNameFromCCIType(type); var extends = default(TypeRef); var implements = default(AList<TypeRef>); TypeDerivationFromCCIType(type, out extends, out implements); var customAttributes = CustomAttributesFromCCIMember(type); var annotations = new AList<Annotation>(); annotations.Add(new TypeInheritanceAnnotation(type.IsAbstract, type.IsSealed)); if (type is CCI.Interface) { if (extends != null) throw new InvalidOperationException("invalid interface type definition"); return new InterfaceTypeDef(annotations, customAttributes, implements, parameters, qtn.Name, members); } var explicitInterfaceImplementations = default(HDictionary<PolymorphicMethodRef, PolymorphicMethodRef>); // NOTE: CLR allows a type to take any implemented method of its base types and bind it to any slot // of its base or implemented types. However CCI forgets the type and simply associates // the slot with the implemented method. foreach (var m in type.Members) { var implMethod = m as CCI.Method; if (implMethod != null) { var interfaceMethods = implMethod.ImplementedInterfaceMethods; if (interfaceMethods != null) { foreach (var ifaceMethod in interfaceMethods) { if (explicitInterfaceImplementations == null) explicitInterfaceImplementations = new HDictionary<PolymorphicMethodRef, PolymorphicMethodRef>(); explicitInterfaceImplementations.Add (PolymorphicMethodRefFromCCIMethod(ifaceMethod), PolymorphicMethodRefFromCCIMethod(implMethod)); } } } } var isCallStaticConstructorEarly = (type.Flags & CCI.TypeFlags.BeforeFieldInit) != 0; if (global.QualifiedTypeNameToAbbreviation.ContainsKey(qtn)) { var numberFlavor = default(NumberFlavor); var handleFlavor = default(HandleFlavor); if (global.QualifiedTypeNameToNumberFlavor.TryGetValue(qtn, out numberFlavor)) return new NumberTypeDef (annotations, customAttributes, extends, implements, parameters, qtn.Name, members, numberFlavor, explicitInterfaceImplementations, isCallStaticConstructorEarly); else if (global.QualifiedTypeNameToHandleFlavor.TryGetValue(qtn, out handleFlavor)) return new HandleTypeDef (annotations, customAttributes, extends, implements, parameters, qtn.Name, members, handleFlavor, explicitInterfaceImplementations, isCallStaticConstructorEarly); else if (qtn.Equals(global.VoidName)) return new VoidTypeDef (annotations, customAttributes, extends, implements, parameters, qtn.Name, members, explicitInterfaceImplementations, isCallStaticConstructorEarly); else if (qtn.Equals(global.ObjectName)) return new ObjectTypeDef (annotations, customAttributes, extends, implements, parameters, qtn.Name, members, explicitInterfaceImplementations, isCallStaticConstructorEarly); else if (qtn.Equals(global.StringName)) return new StringTypeDef (annotations, customAttributes, extends, implements, parameters, qtn.Name, members, explicitInterfaceImplementations, isCallStaticConstructorEarly); else throw new InvalidOperationException("unrecognised special type"); } else if (qtn.Equals(global.EnumName) || qtn.Equals(global.ValueTypeName) || qtn.Equals(global.DelegateName) || qtn.Equals(global.MulticastDelegateName) || qtn.Equals(global.ObjectName)) return new ClassTypeDef (annotations, customAttributes, extends, implements, parameters, qtn.Name, members, explicitInterfaceImplementations, isCallStaticConstructorEarly); else if (qtn.Equals(global.NullableConstructorName)) return new StructTypeDef (annotations, customAttributes, extends, implements, parameters, qtn.Name, members, explicitInterfaceImplementations, isCallStaticConstructorEarly); else { // Follow derivation chain to decide if value or ref type var baseType = type.BaseType; while (baseType != null) { var bqtn = QualifiedTypeNameFromCCIType(baseType); if (bqtn.Equals(global.DelegateName) || bqtn.Equals(global.MulticastDelegateName)) // Is a user-defined delegate type return new DelegateTypeDef (annotations, customAttributes, extends, implements, parameters, qtn.Name, members, explicitInterfaceImplementations, isCallStaticConstructorEarly); else if (bqtn.Equals(global.EnumName)) // Is a user-defined enumeration return new EnumTypeDef (annotations, customAttributes, extends, implements, qtn.Name, members, explicitInterfaceImplementations, isCallStaticConstructorEarly); else if (bqtn.Equals(global.ValueTypeName)) // Is a user-defined struct return new StructTypeDef (annotations, customAttributes, extends, implements, parameters, qtn.Name, members, explicitInterfaceImplementations, isCallStaticConstructorEarly); else if (bqtn.Equals(global.ObjectName)) return new ClassTypeDef (annotations, customAttributes, extends, implements, parameters, qtn.Name, members, explicitInterfaceImplementations, isCallStaticConstructorEarly); else baseType = baseType.BaseType; } throw new InvalidOperationException("type does not derive from object"); } // TODO: CompleteSlotImplementations }
private AssemblyDef AssemblyDefFromCCIAssembly(CCI.AssemblyNode assembly) { var references = default(AList<StrongAssemblyName>); if (assembly.AssemblyReferences != null && assembly.AssemblyReferences.Count > 0) { references = new AList<StrongAssemblyName>(); for (var i = 0; i < assembly.AssemblyReferences.Count; i++) { var reference = assembly.AssemblyReferences[i]; if (reference.Assembly == null || !reference.Assembly.StrongName.Equals (reference.StrongName, StringComparison.OrdinalIgnoreCase) || reference.Assembly.Location.Equals("unknown:location", StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("invalid assembly reference"); references.Add(StrongAssemblyNameFromCCIAssembly(reference.Assembly)); } references.Sort((l, r) => l.CompareTo(r)); } var nameToTypeDef = new Dictionary<TypeName, TypeDef>(); if (assembly.Types != null) { for (var i = 0; i < assembly.Types.Count; i++) AddCCITypes(nameToTypeDef, assembly, assembly.Types[i]); } var sn = StrongAssemblyNameFromCCIAssembly(assembly); // Extract names and sort them var names = new List<TypeName>(); foreach (var kv in nameToTypeDef) names.Add(kv.Key); names.Sort((l, r) => l.CompareTo(r)); // Place definitions in canonical order var typeDefs = default(AList<TypeDef>); if (names.Count > 0) { typeDefs = new AList<TypeDef>(); foreach (var nm in names) typeDefs.Add(nameToTypeDef[nm]); } var entryPoint = default(MethodRef); if (assembly.EntryPoint != null) entryPoint = MethodRefFromCCIMethod(assembly.EntryPoint); var customAttributes = default(AList<CustomAttribute>); if (assembly.Attributes != null && assembly.Attributes.Count > 0) { customAttributes = new AList<CustomAttribute>(); for (var i = 0; i < assembly.Attributes.Count; i++) customAttributes.Add(CustomAttributeFromCCIAttribute(assembly.Attributes[i])); } return new AssemblyDef(global, null, customAttributes, sn, references, typeDefs, entryPoint); }
internal void PostChangeNotifications() { // This is a 'while' instead of an 'if' because when we finish posting notifications, there // might be new ones that have arrived as a result of notification handlers making document // changes of their own (the replicator manager will do this.) So we need to check again. while (_transactionLevel == 0 && _isOpen && !_isPostingChangeNotifications && _changesToNotify.Count > 0) { try { _isPostingChangeNotifications = true; IList<DocumentChange> outgoingChanges = new AList<DocumentChange>(); foreach (var change in _changesToNotify) { outgoingChanges.Add(change); } _changesToNotify.Clear(); // TODO: change this to match iOS and call cachedDocumentWithID var isExternal = false; foreach (var change in outgoingChanges) { var document = GetDocument(change.DocumentId); document.RevisionAdded(change); if (change.SourceUrl != null) { isExternal = true; } } var args = new DatabaseChangeEventArgs { Changes = outgoingChanges, IsExternal = isExternal, Source = this } ; var changeEvent = Changed; if (changeEvent != null) changeEvent(this, args); } catch (Exception e) { Log.E(Tag, " got exception posting change notifications", e); } finally { _isPostingChangeNotifications = false; } } }
/// <exception cref="Com.Drew.Imaging.Png.PngProcessingException"/> /// <exception cref="System.IO.IOException"/> public virtual Iterable<PngChunk> Extract(SequentialReader reader, ICollection<PngChunkType> desiredChunkTypes) { // // PNG DATA STREAM // // Starts with a PNG SIGNATURE, followed by a sequence of CHUNKS. // // PNG SIGNATURE // // Always composed of these bytes: 89 50 4E 47 0D 0A 1A 0A // // CHUNK // // 4 - length of the data field (unsigned, but always within 31 bytes), may be zero // 4 - chunk type, restricted to [65,90] and [97,122] (A-Za-z) // * - data field // 4 - CRC calculated from chunk type and chunk data, but not length // // CHUNK TYPES // // Critical Chunk Types: // // IHDR - image header, always the first chunk in the data stream // PLTE - palette table, associated with indexed PNG images // IDAT - image data chunk, of which there may be many // IEND - image trailer, always the last chunk in the data stream // // Ancillary Chunk Types: // // Transparency information: tRNS // Colour space information: cHRM, gAMA, iCCP, sBIT, sRGB // Textual information: iTXt, tEXt, zTXt // Miscellaneous information: bKGD, hIST, pHYs, sPLT // Time information: tIME // reader.SetMotorolaByteOrder(true); // network byte order if (!Arrays.Equals(PngSignatureBytes, reader.GetBytes(PngSignatureBytes.Length))) { throw new PngProcessingException("PNG signature mismatch"); } bool seenImageHeader = false; bool seenImageTrailer = false; IList<PngChunk> chunks = new AList<PngChunk>(); ICollection<PngChunkType> seenChunkTypes = new HashSet<PngChunkType>(); while (!seenImageTrailer) { // Process the next chunk. int chunkDataLength = reader.GetInt32(); PngChunkType chunkType = new PngChunkType(reader.GetBytes(4)); sbyte[] chunkData = reader.GetBytes(chunkDataLength); // Skip the CRC bytes at the end of the chunk // TODO consider verifying the CRC value to determine if we're processing bad data reader.Skip(4); if (seenChunkTypes.Contains(chunkType) && !chunkType.AreMultipleAllowed()) { throw new PngProcessingException(Sharpen.Extensions.StringFormat("Observed multiple instances of PNG chunk '%s', for which multiples are not allowed", chunkType)); } if (chunkType.Equals(PngChunkType.Ihdr)) { seenImageHeader = true; } else { if (!seenImageHeader) { throw new PngProcessingException(Sharpen.Extensions.StringFormat("First chunk should be '%s', but '%s' was observed", PngChunkType.Ihdr, chunkType)); } } if (chunkType.Equals(PngChunkType.Iend)) { seenImageTrailer = true; } if (desiredChunkTypes == null || desiredChunkTypes.Contains(chunkType)) { chunks.Add(new PngChunk(chunkType, chunkData)); } seenChunkTypes.Add(chunkType); } return chunks.AsIterable(); }
internal IList<IDictionary<string, object>> dump() { if (Id < 0) { return null; } var selectArgs = new[] { Id.ToString() }; Cursor cursor = null; var result = new AList<IDictionary<string, object>>(); try { cursor = Database.StorageEngine. RawQuery("SELECT sequence, key, value FROM map WHERE view_id=? ORDER BY key", selectArgs); while(cursor.MoveToNext()) { var row = new Dictionary<string, object>(); row["seq"] = cursor.GetInt(0); row["key"] = cursor.GetString(1); row["value"] = cursor.GetString(2); result.Add(row); } } catch (Exception e) { Log.E(Tag, "Error dumping view", e); result = null; } finally { if (cursor != null) { cursor.Close(); } } return result; }
private MethodRef MethodRefFromCCIMethod(CCI.Method method) { var methodTypeArguments = default(AList<TypeRef>); if (method.TemplateArguments != null && method.TemplateArguments.Count > 0) { methodTypeArguments = new AList<TypeRef>(); // Grab method arguments foreach (var n in method.TemplateArguments) methodTypeArguments.Add(TypeRefFromCCIType(n)); if (method.Template == null) throw new InvalidOperationException("invalid method"); // Step into polymorphic method method = method.Template; if (method.TemplateArguments != null && method.TemplateArguments.Count > 0) throw new InvalidOperationException("invalid method"); if (method.TemplateParameters == null || method.TemplateParameters.Count != methodTypeArguments.Count) throw new InvalidOperationException("invalid method"); } // This may be an instance of a higher-kinded type var definingType = TypeRefFromCCIType(method.DeclaringType); var resultType = default(TypeRef); var ps = ValueParametersFromCCIMethod(method, out resultType); return new MethodRef(definingType, method.Name.Name, method.IsStatic, methodTypeArguments, ps.Select(p => p.Type).ToAList(), resultType); }
private InstructionBlock InstructionsFromCCIMethodFrom(CCI.Method method, ref int i) { var instructions = new AList<Instruction>(); while (i < method.Instructions.Count) { var instruction = method.Instructions[i++]; if (instruction.OpCode == CCI.OpCode._Locals) { // Skip: already captured and fixed locals in MethodDefFromCCIMethod } else { var offset = instruction.Offset; while (instruction.OpCode == CCI.OpCode.Unaligned_ || instruction.OpCode == CCI.OpCode.Volatile_ || instruction.OpCode == CCI.OpCode.Tail_) { // Skip over any ignored prefixes, but remember instruction begins at original offset // NOTE: What ever happened to the "no." prefix mentioned in the spec? if (i >= method.Instructions.Count) throw new InvalidOperationException("invalid instructions"); instruction = method.Instructions[i++]; } switch (instruction.OpCode) { case CCI.OpCode.Cpblk: instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Cpblk)); break; case CCI.OpCode.Initblk: instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Initblk)); break; case CCI.OpCode.Arglist: instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Arglist)); break; case CCI.OpCode.Localloc: instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Localloc)); break; case CCI.OpCode.Jmp: instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Jmp)); break; case CCI.OpCode.Calli: instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Calli)); break; case CCI.OpCode.Sizeof: instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Sizeof)); break; case CCI.OpCode.Mkrefany: instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Mkrefany)); break; case CCI.OpCode.Refanytype: instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Refanytype)); break; case CCI.OpCode.Refanyval: instructions.Add(new UnsupportedInstruction(offset, UnsupportedOp.Refanyval)); break; case CCI.OpCode.Nop: instructions.Add(new MiscInstruction(offset, MiscOp.Nop)); break; case CCI.OpCode.Break: instructions.Add(new MiscInstruction(offset, MiscOp.Break)); break; case CCI.OpCode.Dup: instructions.Add(new MiscInstruction(offset, MiscOp.Dup)); break; case CCI.OpCode.Pop: instructions.Add(new MiscInstruction(offset, MiscOp.Pop)); break; case CCI.OpCode.Ldnull: instructions.Add(new MiscInstruction(offset, MiscOp.Ldnull)); break; case CCI.OpCode.Ckfinite: instructions.Add(new MiscInstruction(offset, MiscOp.Ckfinite)); break; case CCI.OpCode.Throw: instructions.Add(new MiscInstruction(offset, MiscOp.Throw)); break; case CCI.OpCode.Rethrow: instructions.Add(new MiscInstruction(offset, MiscOp.Rethrow)); break; case CCI.OpCode.Ldind_Ref: instructions.Add(new MiscInstruction(offset, MiscOp.LdindRef)); break; case CCI.OpCode.Stind_Ref: instructions.Add(new MiscInstruction(offset, MiscOp.StindRef)); break; case CCI.OpCode.Ldelem_Ref: instructions.Add(new MiscInstruction(offset, MiscOp.LdelemRef)); break; case CCI.OpCode.Stelem_Ref: instructions.Add(new MiscInstruction(offset, MiscOp.StelemRef)); break; case CCI.OpCode.Ldlen: instructions.Add(new MiscInstruction(offset, MiscOp.Ldlen)); break; case CCI.OpCode.Ret: instructions.Add(new MiscInstruction(offset, MiscOp.Ret)); break; case CCI.OpCode.Endfilter: instructions.Add(new MiscInstruction(offset, MiscOp.Endfilter)); break; case CCI.OpCode.Endfinally: // aka EndFault instructions.Add(new MiscInstruction(offset, MiscOp.Endfinally)); break; case CCI.OpCode.Br_S: case CCI.OpCode.Br: instructions.Add(new BranchInstruction(offset, BranchOp.Br, false, (int)instruction.Value)); break; case CCI.OpCode.Brtrue_S: // aka brinst.s case CCI.OpCode.Brtrue: // aka brinst instructions.Add (new BranchInstruction(offset, BranchOp.Brtrue, false, (int)instruction.Value)); break; case CCI.OpCode.Brfalse_S: // aka brzero.s, brnull.s case CCI.OpCode.Brfalse: // aka brzero, brnull instructions.Add (new BranchInstruction(offset, BranchOp.Brfalse, false, (int)instruction.Value)); break; case CCI.OpCode.Beq: case CCI.OpCode.Beq_S: instructions.Add(new BranchInstruction(offset, BranchOp.Breq, false, (int)instruction.Value)); break; case CCI.OpCode.Bne_Un: case CCI.OpCode.Bne_Un_S: instructions.Add(new BranchInstruction(offset, BranchOp.Brne, false, (int)instruction.Value)); break; case CCI.OpCode.Leave: case CCI.OpCode.Leave_S: instructions.Add(new BranchInstruction(offset, BranchOp.Leave, false, (int)instruction.Value)); break; case CCI.OpCode.Blt: case CCI.OpCode.Blt_S: instructions.Add(new BranchInstruction(offset, BranchOp.BrLt, false, (int)instruction.Value)); break; case CCI.OpCode.Blt_Un: case CCI.OpCode.Blt_Un_S: instructions.Add(new BranchInstruction(offset, BranchOp.BrLt, true, (int)instruction.Value)); break; case CCI.OpCode.Ble: case CCI.OpCode.Ble_S: instructions.Add(new BranchInstruction(offset, BranchOp.BrLe, false, (int)instruction.Value)); break; case CCI.OpCode.Ble_Un: case CCI.OpCode.Ble_Un_S: instructions.Add(new BranchInstruction(offset, BranchOp.BrLe, true, (int)instruction.Value)); break; case CCI.OpCode.Bgt: case CCI.OpCode.Bgt_S: instructions.Add(new BranchInstruction(offset, BranchOp.BrGt, false, (int)instruction.Value)); break; case CCI.OpCode.Bgt_Un: case CCI.OpCode.Bgt_Un_S: instructions.Add(new BranchInstruction(offset, BranchOp.BrGt, true, (int)instruction.Value)); break; case CCI.OpCode.Bge: case CCI.OpCode.Bge_S: instructions.Add(new BranchInstruction(offset, BranchOp.BrGe, false, (int)instruction.Value)); break; case CCI.OpCode.Bge_Un: case CCI.OpCode.Bge_Un_S: instructions.Add(new BranchInstruction(offset, BranchOp.BrGe, true, (int)instruction.Value)); break; case CCI.OpCode.Switch: { var targets = new AList<int>(); var ccitargets = (CCI.Int32List)instruction.Value; for (var j = 0; j < ccitargets.Count; j++) targets.Add(ccitargets[j]); instructions.Add(new SwitchInstruction(offset, targets)); break; } case CCI.OpCode.Ceq: instructions.Add(new CompareInstruction(offset, CompareOp.Ceq, false)); break; case CCI.OpCode.Clt: instructions.Add(new CompareInstruction(offset, CompareOp.Clt, false)); break; case CCI.OpCode.Clt_Un: instructions.Add(new CompareInstruction(offset, CompareOp.Clt, true)); break; case CCI.OpCode.Cgt: instructions.Add(new CompareInstruction(offset, CompareOp.Cgt, false)); break; case CCI.OpCode.Cgt_Un: instructions.Add(new CompareInstruction(offset, CompareOp.Cgt, true)); break; case CCI.OpCode.Ldarg_0: instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Arg, 0)); break; case CCI.OpCode.Ldarg_1: instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Arg, 1)); break; case CCI.OpCode.Ldarg_2: instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Arg, 2)); break; case CCI.OpCode.Ldarg_3: instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Arg, 3)); break; case CCI.OpCode.Ldarg: case CCI.OpCode.Ldarg_S: instructions.Add (new ArgLocalInstruction (offset, ArgLocalOp.Ld, ArgLocal.Arg, TrueArgFromCCIParameter(method, (CCI.Parameter)instruction.Value))); break; case CCI.OpCode.Ldarga: case CCI.OpCode.Ldarga_S: instructions.Add (new ArgLocalInstruction (offset, ArgLocalOp.Lda, ArgLocal.Arg, TrueArgFromCCIParameter(method, (CCI.Parameter)instruction.Value))); break; case CCI.OpCode.Starg: case CCI.OpCode.Starg_S: instructions.Add (new ArgLocalInstruction (offset, ArgLocalOp.St, ArgLocal.Arg, TrueArgFromCCIParameter(method, (CCI.Parameter)instruction.Value))); break; case CCI.OpCode.Ldloc_0: instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Local, 0)); break; case CCI.OpCode.Ldloc_1: instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Local, 1)); break; case CCI.OpCode.Ldloc_2: instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Local, 2)); break; case CCI.OpCode.Ldloc_3: instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.Ld, ArgLocal.Local, 3)); break; case CCI.OpCode.Ldloc: case CCI.OpCode.Ldloc_S: instructions.Add (new ArgLocalInstruction (offset, ArgLocalOp.Ld, ArgLocal.Local, TrueLocalFromCCILocal(method, (CCI.Local)instruction.Value))); break; case CCI.OpCode.Ldloca: case CCI.OpCode.Ldloca_S: instructions.Add (new ArgLocalInstruction (offset, ArgLocalOp.Lda, ArgLocal.Local, TrueLocalFromCCILocal(method, (CCI.Local)instruction.Value))); break; case CCI.OpCode.Stloc_0: instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.St, ArgLocal.Local, 0)); break; case CCI.OpCode.Stloc_1: instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.St, ArgLocal.Local, 1)); break; case CCI.OpCode.Stloc_2: instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.St, ArgLocal.Local, 2)); break; case CCI.OpCode.Stloc_3: instructions.Add(new ArgLocalInstruction(offset, ArgLocalOp.St, ArgLocal.Local, 3)); break; case CCI.OpCode.Stloc: case CCI.OpCode.Stloc_S: instructions.Add (new ArgLocalInstruction (offset, ArgLocalOp.St, ArgLocal.Local, TrueLocalFromCCILocal(method, (CCI.Local)instruction.Value))); break; case CCI.OpCode.Ldfld: instructions.Add (new FieldInstruction (offset, FieldOp.Ldfld, FieldRefFromCCIField((CCI.Field)instruction.Value), false)); break; case CCI.OpCode.Ldsfld: instructions.Add (new FieldInstruction (offset, FieldOp.Ldfld, FieldRefFromCCIField((CCI.Field)instruction.Value), true)); break; case CCI.OpCode.Ldflda: instructions.Add (new FieldInstruction (offset, FieldOp.Ldflda, FieldRefFromCCIField((CCI.Field)instruction.Value), false)); break; case CCI.OpCode.Ldsflda: instructions.Add (new FieldInstruction (offset, FieldOp.Ldflda, FieldRefFromCCIField((CCI.Field)instruction.Value), true)); break; case CCI.OpCode.Stfld: instructions.Add (new FieldInstruction (offset, FieldOp.Stfld, FieldRefFromCCIField((CCI.Field)instruction.Value), false)); break; case CCI.OpCode.Stsfld: instructions.Add (new FieldInstruction (offset, FieldOp.Stfld, FieldRefFromCCIField((CCI.Field)instruction.Value), true)); break; case CCI.OpCode.Ldtoken: { var typeTok = instruction.Value as CCI.TypeNode; if (typeTok != null) instructions.Add (new TypeInstruction(offset, TypeOp.Ldtoken, TypeRefFromCCIType(typeTok))); else { var fieldTok = instruction.Value as CCI.Field; if (fieldTok != null) instructions.Add (new FieldInstruction(offset, FieldOp.Ldtoken, FieldRefFromCCIField(fieldTok), default(bool))); else { var methodTok = instruction.Value as CCI.Method; if (methodTok != null) instructions.Add (new MethodInstruction (offset, MethodOp.Ldtoken, null, false, MethodRefFromCCIMethod(methodTok))); else throw new InvalidOperationException("invalid instruction"); } } break; } case CCI.OpCode.Constrained_: { var constrained = (CCI.TypeNode)instruction.Value; if (i >= method.Instructions.Count) throw new InvalidOperationException("invalid instructions"); instruction = method.Instructions[i++]; if (instruction.OpCode != CCI.OpCode.Callvirt) throw new InvalidOperationException("invalid instruction"); instructions.Add (new MethodInstruction (offset, MethodOp.Call, TypeRefFromCCIType(constrained), true, MethodRefFromCCIMethod((CCI.Method)instruction.Value))); break; } case CCI.OpCode.Call: instructions.Add (new MethodInstruction (offset, MethodOp.Call, null, false, MethodRefFromCCIMethod((CCI.Method)instruction.Value))); break; case CCI.OpCode.Callvirt: instructions.Add (new MethodInstruction (offset, MethodOp.Call, null, true, MethodRefFromCCIMethod((CCI.Method)instruction.Value))); break; case CCI.OpCode.Ldftn: instructions.Add (new MethodInstruction (offset, MethodOp.Ldftn, null, false, MethodRefFromCCIMethod((CCI.Method)instruction.Value))); break; case CCI.OpCode.Ldvirtftn: instructions.Add (new MethodInstruction (offset, MethodOp.Ldftn, null, true, MethodRefFromCCIMethod((CCI.Method)instruction.Value))); break; case CCI.OpCode.Newobj: instructions.Add (new MethodInstruction (offset, MethodOp.Newobj, null, false, MethodRefFromCCIMethod((CCI.Method)instruction.Value))); break; case CCI.OpCode.Ldind_I1: instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.Int8Ref)); break; case CCI.OpCode.Ldind_U1: instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.UInt8Ref)); break; case CCI.OpCode.Ldind_I2: instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.Int16Ref)); break; case CCI.OpCode.Ldind_U2: instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.UInt16Ref)); break; case CCI.OpCode.Ldind_I4: case CCI.OpCode.Ldind_U4: instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.Int32Ref)); break; case CCI.OpCode.Ldind_I8: instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.Int64Ref)); break; case CCI.OpCode.Ldind_I: instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.IntNativeRef)); break; case CCI.OpCode.Ldind_R4: instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.SingleRef)); break; case CCI.OpCode.Ldind_R8: instructions.Add(new TypeInstruction(offset, TypeOp.Ldobj, global.DoubleRef)); break; case CCI.OpCode.Ldobj: instructions.Add (new TypeInstruction (offset, TypeOp.Ldobj, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Stind_I1: instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.Int8Ref)); break; case CCI.OpCode.Stind_I2: instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.Int16Ref)); break; case CCI.OpCode.Stind_I4: instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.Int32Ref)); break; case CCI.OpCode.Stind_I8: instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.Int64Ref)); break; case CCI.OpCode.Stind_I: instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.IntNativeRef)); break; case CCI.OpCode.Stind_R4: instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.SingleRef)); break; case CCI.OpCode.Stind_R8: instructions.Add(new TypeInstruction(offset, TypeOp.Stobj, global.DoubleRef)); break; case CCI.OpCode.Stobj: instructions.Add (new TypeInstruction (offset, TypeOp.Stobj, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Cpobj: instructions.Add (new TypeInstruction (offset, TypeOp.Cpobj, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Newarr: instructions.Add (new TypeInstruction (offset, TypeOp.Newarr, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Initobj: instructions.Add (new TypeInstruction (offset, TypeOp.Initobj, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Castclass: instructions.Add (new TypeInstruction (offset, TypeOp.Castclass, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Isinst: instructions.Add (new TypeInstruction (offset, TypeOp.Isinst, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Box: instructions.Add (new TypeInstruction (offset, TypeOp.Box, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Unbox: instructions.Add (new TypeInstruction (offset, TypeOp.Unbox, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Unbox_Any: instructions.Add (new TypeInstruction (offset, TypeOp.UnboxAny, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Ldelem_I1: instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.Int8Ref)); break; case CCI.OpCode.Ldelem_U1: instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.UInt8Ref)); break; case CCI.OpCode.Ldelem_I2: instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.Int16Ref)); break; case CCI.OpCode.Ldelem_U2: instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.UInt16Ref)); break; case CCI.OpCode.Ldelem_I4: case CCI.OpCode.Ldelem_U4: instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.Int32Ref)); break; case CCI.OpCode.Ldelem_I8: // aka ldelem.u8 instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.Int64Ref)); break; case CCI.OpCode.Ldelem_I: instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.IntNativeRef)); break; case CCI.OpCode.Ldelem_R4: instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.SingleRef)); break; case CCI.OpCode.Ldelem_R8: instructions.Add(new TypeInstruction(offset, TypeOp.Ldelem, global.DoubleRef)); break; case CCI.OpCode.Ldelem: // aka ldelem.any instructions.Add (new TypeInstruction (offset, TypeOp.Ldelem, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Stelem_I1: instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.Int8Ref)); break; case CCI.OpCode.Stelem_I2: instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.Int16Ref)); break; case CCI.OpCode.Stelem_I4: instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.Int32Ref)); break; case CCI.OpCode.Stelem_I8: instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.Int64Ref)); break; case CCI.OpCode.Stelem_I: instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.IntNativeRef)); break; case CCI.OpCode.Stelem_R4: instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.SingleRef)); break; case CCI.OpCode.Stelem_R8: instructions.Add(new TypeInstruction(offset, TypeOp.Stelem, global.DoubleRef)); break; case CCI.OpCode.Stelem: // aka stelem.any instructions.Add (new TypeInstruction (offset, TypeOp.Stelem, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Readonly_: if (i >= method.Instructions.Count) throw new InvalidOperationException("invalid instruction"); instruction = method.Instructions[i++]; if (instruction.OpCode != CCI.OpCode.Ldelema) throw new InvalidOperationException("invalid instruction"); instructions.Add (new LdElemAddrInstruction (offset, true, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Ldelema: instructions.Add (new LdElemAddrInstruction (offset, false, TypeRefFromCCIType((CCI.TypeNode)instruction.Value))); break; case CCI.OpCode.Ldc_I4_0: instructions.Add(new LdInt32Instruction(offset, 0)); break; case CCI.OpCode.Ldc_I4_1: instructions.Add(new LdInt32Instruction(offset, 1)); break; case CCI.OpCode.Ldc_I4_2: instructions.Add(new LdInt32Instruction(offset, 2)); break; case CCI.OpCode.Ldc_I4_3: instructions.Add(new LdInt32Instruction(offset, 3)); break; case CCI.OpCode.Ldc_I4_4: instructions.Add(new LdInt32Instruction(offset, 4)); break; case CCI.OpCode.Ldc_I4_5: instructions.Add(new LdInt32Instruction(offset, 5)); break; case CCI.OpCode.Ldc_I4_6: instructions.Add(new LdInt32Instruction(offset, 6)); break; case CCI.OpCode.Ldc_I4_7: instructions.Add(new LdInt32Instruction(offset, 7)); break; case CCI.OpCode.Ldc_I4_8: instructions.Add(new LdInt32Instruction(offset, 8)); break; case CCI.OpCode.Ldc_I4_M1: instructions.Add(new LdInt32Instruction(offset, -1)); break; case CCI.OpCode.Ldc_I4: case CCI.OpCode.Ldc_I4_S: instructions.Add(new LdInt32Instruction(offset, (int)instruction.Value)); break; case CCI.OpCode.Ldc_I8: instructions.Add(new LdInt64Instruction(offset, (long)instruction.Value)); break; case CCI.OpCode.Ldc_R4: instructions.Add(new LdSingleInstruction(offset, (float)instruction.Value)); break; case CCI.OpCode.Ldc_R8: instructions.Add(new LdDoubleInstruction(offset, (double)instruction.Value)); break; case CCI.OpCode.Ldstr: instructions.Add(new LdStringInstruction(offset, (string)instruction.Value)); break; case CCI.OpCode.Add: instructions.Add(new ArithInstruction(offset, ArithOp.Add, false, false)); break; case CCI.OpCode.Add_Ovf: instructions.Add(new ArithInstruction(offset, ArithOp.Add, true, false)); break; case CCI.OpCode.Add_Ovf_Un: instructions.Add(new ArithInstruction(offset, ArithOp.Add, true, true)); break; case CCI.OpCode.Sub: instructions.Add(new ArithInstruction(offset, ArithOp.Sub, false, false)); break; case CCI.OpCode.Sub_Ovf: instructions.Add(new ArithInstruction(offset, ArithOp.Sub, true, false)); break; case CCI.OpCode.Sub_Ovf_Un: instructions.Add(new ArithInstruction(offset, ArithOp.Sub, true, true)); break; case CCI.OpCode.Mul: instructions.Add(new ArithInstruction(offset, ArithOp.Mul, false, false)); break; case CCI.OpCode.Mul_Ovf: instructions.Add(new ArithInstruction(offset, ArithOp.Mul, true, false)); break; case CCI.OpCode.Mul_Ovf_Un: instructions.Add(new ArithInstruction(offset, ArithOp.Mul, true, true)); break; case CCI.OpCode.Div: instructions.Add(new ArithInstruction(offset, ArithOp.Div, false, false)); break; case CCI.OpCode.Div_Un: instructions.Add(new ArithInstruction(offset, ArithOp.Div, false, true)); break; case CCI.OpCode.Rem: instructions.Add(new ArithInstruction(offset, ArithOp.Rem, false, false)); break; case CCI.OpCode.Rem_Un: instructions.Add(new ArithInstruction(offset, ArithOp.Rem, false, true)); break; case CCI.OpCode.Neg: instructions.Add(new ArithInstruction(offset, ArithOp.Neg, false, false)); break; case CCI.OpCode.And: instructions.Add(new ArithInstruction(offset, ArithOp.And, false, false)); break; case CCI.OpCode.Or: instructions.Add(new ArithInstruction(offset, ArithOp.Or, false, false)); break; case CCI.OpCode.Xor: instructions.Add(new ArithInstruction(offset, ArithOp.Xor, false, false)); break; case CCI.OpCode.Not: instructions.Add(new ArithInstruction(offset, ArithOp.Not, false, false)); break; case CCI.OpCode.Shl: instructions.Add(new ArithInstruction(offset, ArithOp.Shl, false, false)); break; case CCI.OpCode.Shr: instructions.Add(new ArithInstruction(offset, ArithOp.Shr, false, false)); break; case CCI.OpCode.Shr_Un: instructions.Add(new ArithInstruction(offset, ArithOp.Shr, false, true)); break; case CCI.OpCode.Conv_I1: instructions.Add(new ConvInstruction(offset, NumberFlavor.Int8, false, false)); break; case CCI.OpCode.Conv_U1: instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt8, false, false)); break; case CCI.OpCode.Conv_I2: instructions.Add(new ConvInstruction(offset, NumberFlavor.Int16, false, false)); break; case CCI.OpCode.Conv_U2: instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt16, false, false)); break; case CCI.OpCode.Conv_I4: instructions.Add(new ConvInstruction(offset, NumberFlavor.Int32, false, false)); break; case CCI.OpCode.Conv_U4: instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt32, false, false)); break; case CCI.OpCode.Conv_I8: instructions.Add(new ConvInstruction(offset, NumberFlavor.Int64, false, false)); break; case CCI.OpCode.Conv_U8: instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt64, false, false)); break; case CCI.OpCode.Conv_I: instructions.Add(new ConvInstruction(offset, NumberFlavor.IntNative, false, false)); break; case CCI.OpCode.Conv_U: instructions.Add(new ConvInstruction(offset, NumberFlavor.UIntNative, false, false)); break; case CCI.OpCode.Conv_R4: instructions.Add(new ConvInstruction(offset, NumberFlavor.Single, false, false)); break; case CCI.OpCode.Conv_R8: instructions.Add(new ConvInstruction(offset, NumberFlavor.Double, false, false)); break; case CCI.OpCode.Conv_R_Un: instructions.Add(new ConvInstruction(offset, NumberFlavor.Double, false, true)); break; case CCI.OpCode.Conv_Ovf_I1: instructions.Add(new ConvInstruction(offset, NumberFlavor.Int8, true, false)); break; case CCI.OpCode.Conv_Ovf_U1: instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt8, true, false)); break; case CCI.OpCode.Conv_Ovf_I2: instructions.Add(new ConvInstruction(offset, NumberFlavor.Int16, true, false)); break; case CCI.OpCode.Conv_Ovf_U2: instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt16, true, false)); break; case CCI.OpCode.Conv_Ovf_I4: instructions.Add(new ConvInstruction(offset, NumberFlavor.Int32, true, false)); break; case CCI.OpCode.Conv_Ovf_U4: instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt32, true, false)); break; case CCI.OpCode.Conv_Ovf_I8: instructions.Add(new ConvInstruction(offset, NumberFlavor.Int64, true, false)); break; case CCI.OpCode.Conv_Ovf_U8: instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt64, true, false)); break; case CCI.OpCode.Conv_Ovf_I: instructions.Add(new ConvInstruction(offset, NumberFlavor.IntNative, true, false)); break; case CCI.OpCode.Conv_Ovf_U: instructions.Add(new ConvInstruction(offset, NumberFlavor.UIntNative, true, false)); break; case CCI.OpCode.Conv_Ovf_I1_Un: instructions.Add(new ConvInstruction(offset, NumberFlavor.Int8, true, true)); break; case CCI.OpCode.Conv_Ovf_U1_Un: instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt8, true, true)); break; case CCI.OpCode.Conv_Ovf_I2_Un: instructions.Add(new ConvInstruction(offset, NumberFlavor.Int16, true, true)); break; case CCI.OpCode.Conv_Ovf_U2_Un: instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt16, true, true)); break; case CCI.OpCode.Conv_Ovf_I4_Un: instructions.Add(new ConvInstruction(offset, NumberFlavor.Int32, true, true)); break; case CCI.OpCode.Conv_Ovf_U4_Un: instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt32, true, true)); break; case CCI.OpCode.Conv_Ovf_I8_Un: instructions.Add(new ConvInstruction(offset, NumberFlavor.Int64, true, true)); break; case CCI.OpCode.Conv_Ovf_U8_Un: instructions.Add(new ConvInstruction(offset, NumberFlavor.UInt64, true, true)); break; case CCI.OpCode.Conv_Ovf_I_Un: instructions.Add(new ConvInstruction(offset, NumberFlavor.IntNative, true, true)); break; case CCI.OpCode.Conv_Ovf_U_Un: instructions.Add(new ConvInstruction(offset, NumberFlavor.UIntNative, true, true)); break; case CCI.OpCode._Try: { // We are recognising the grammar: // I ::= _Try I* _EndTry // ( ( (_Catch <type> I* _EndHandler) | // (_Filter I* _Endfilter _Catch <null> I* _EndHandler) )* | // (_Fault I* _EndHandler) | // (_Finally I* _EndHandler) ) | // <any other instruction> var tryBody = InstructionsFromCCIMethodFrom(method, ref i); if (i >= method.Instructions.Count || method.Instructions[i].OpCode != CCI.OpCode._EndTry) throw new InvalidOperationException("invalid instructions"); i++; var handlers = new AList<TryInstructionHandler>(); var done = false; while (i < method.Instructions.Count && !done) { instruction = method.Instructions[i]; switch (instruction.OpCode) { case CCI.OpCode._Catch: { if (handlers.Any (h => (h is FaultTryInstructionHandler || h is FinallyTryInstructionHandler))) throw new InvalidOperationException("invalid instructions"); var type = instruction.Value as CCI.TypeNode; if (type == null) throw new InvalidOperationException("invalid instruction"); i++; if (i >= method.Instructions.Count) throw new InvalidOperationException("invalid instructions"); var handlerBody = InstructionsFromCCIMethodFrom(method, ref i); if (i >= method.Instructions.Count || method.Instructions[i].OpCode != CCI.OpCode._EndHandler) throw new InvalidOperationException("invalid instructions"); i++; handlers.Add (new CatchTryInstructionHandler(TypeRefFromCCIType(type), handlerBody)); break; } case CCI.OpCode._Filter: { if (handlers.Any (h => (h is FaultTryInstructionHandler || h is FinallyTryInstructionHandler))) throw new InvalidOperationException("invalid instructions"); i++; var filterBody = InstructionsFromCCIMethodFrom(method, ref i); if (i >= method.Instructions.Count || method.Instructions[i].OpCode != CCI.OpCode._EndFilter) throw new InvalidOperationException("invalid instructions"); i++; if (i >= method.Instructions.Count) throw new InvalidOperationException("invalid instructions"); instruction = method.Instructions[i]; if (instruction.OpCode != CCI.OpCode._Catch || instruction.Value != null) throw new InvalidOperationException("invalid instructions"); i++; var handlerBody = InstructionsFromCCIMethodFrom(method, ref i); if (i >= method.Instructions.Count || method.Instructions[i].OpCode != CCI.OpCode._EndHandler) throw new InvalidOperationException("invalid instructions"); i++; handlers.Add(new FilterTryInstructionHandler(filterBody, handlerBody)); break; } case CCI.OpCode._Fault: { if (handlers.Count > 0) throw new InvalidOperationException("invalid instructions"); i++; var handlerBody = InstructionsFromCCIMethodFrom(method, ref i); if (i >= method.Instructions.Count || method.Instructions[i].OpCode != CCI.OpCode._EndHandler) throw new InvalidOperationException("invalid instructions"); i++; handlers.Add(new FaultTryInstructionHandler(handlerBody)); break; } case CCI.OpCode._Finally: { if (handlers.Count > 0) throw new InvalidOperationException("invalid instructions"); i++; var handlerBody = InstructionsFromCCIMethodFrom(method, ref i); if (i >= method.Instructions.Count || method.Instructions[i].OpCode != CCI.OpCode._EndHandler) throw new InvalidOperationException("invalid instructions"); i++; handlers.Add(new FinallyTryInstructionHandler(handlerBody)); break; } default: done = true; break; } } if (handlers.Count == 0) throw new InvalidOperationException("invalid instructions"); instructions.Add(new TryInstruction(offset, tryBody, handlers)); break; } case CCI.OpCode._EndTry: case CCI.OpCode._EndHandler: case CCI.OpCode._EndFilter: // Backup i--; if (instructions.Count == 0) throw new InvalidOperationException("empty instructions"); return new InstructionBlock(null, instructions); case CCI.OpCode._Catch: case CCI.OpCode._Filter: case CCI.OpCode._Fault: case CCI.OpCode._Finally: // Handled in _Try above throw new InvalidOperationException("invalid instructions"); default: throw new InvalidOperationException("invalid instruction"); } } } // Always at least one instruciton, otherwise control would have fallen through if (instructions.Count == 0) throw new InvalidOperationException("empty instructions"); return new InstructionBlock(null, instructions); }
static JpegSegmentType() { // /** Start-of-Frame (4) segment identifier. */ // SOF4((byte)0xC4, true), // /** Start-of-Frame (12) segment identifier. */ // SOF12((byte)0xCC, true), IList<Com.Drew.Imaging.Jpeg.JpegSegmentType> segmentTypes = new AList<Com.Drew.Imaging.Jpeg.JpegSegmentType>(); foreach (Com.Drew.Imaging.Jpeg.JpegSegmentType segmentType in typeof(Com.Drew.Imaging.Jpeg.JpegSegmentType).GetEnumConstants<JpegSegmentType>()) { if (segmentType.canContainMetadata) { segmentTypes.Add(segmentType); } } canContainMetadataTypes = segmentTypes; }
public void TestHistory() { var properties = new Dictionary<String, Object>(); properties["testName"] = "test06_History"; properties["tag"] = 1L; var db = StartDatabase(); var doc = CreateDocumentWithProperties(db, properties); var rev1ID = doc.CurrentRevisionId; Log.I(Tag, "1st revision: " + rev1ID); Assert.IsTrue (rev1ID.StartsWith ("1-", StringComparison.Ordinal), "1st revision looks wrong: " + rev1ID); Assert.AreEqual(doc.UserProperties, properties); properties = new Dictionary<String, Object>(doc.Properties); properties["tag"] = 2; Assert.IsNotNull(!properties.Equals(doc.Properties)); Assert.IsNotNull(doc.PutProperties(properties)); var rev2ID = doc.CurrentRevisionId; Log.I(Tag, "rev2ID" + rev2ID); Assert.IsTrue(rev2ID.StartsWith("2-", StringComparison.Ordinal), "2nd revision looks wrong:" + rev2ID); var revisions = doc.RevisionHistory.ToList(); Log.I(Tag, "Revisions = " + revisions); Assert.AreEqual(revisions.Count, 2); var rev1 = revisions[0]; Assert.AreEqual(rev1.Id, rev1ID); var gotProperties = rev1.Properties; Assert.AreEqual(1, gotProperties["tag"]); var rev2 = revisions[1]; Assert.AreEqual(rev2.Id, rev2ID); Assert.AreEqual(rev2, doc.CurrentRevision); gotProperties = rev2.Properties; Assert.AreEqual(2, gotProperties["tag"]); var tmp = new AList<SavedRevision>(); tmp.Add(rev2); Assert.AreEqual(doc.ConflictingRevisions, tmp); Assert.AreEqual(doc.LeafRevisions, tmp); }
private AList<ParameterOrLocal> ValueParametersFromCCIMethod(CCI.Method method, out TypeRef resultType) { // If the (possibly polymorphic) method is within an instance of a user-defined higher-kinded type, // follow the template chain one more step to get to the true definition, from which we can extract // the argument and result types w.r.t. the type and method type parameters. // SPECIAL CASE: Built-in array types have constructors for higher-ranked array instances. // We don't need to do any template following for those. var isPolyMethod = false; var declType = method.DeclaringType; do { if (declType.TemplateArguments != null && declType.TemplateArguments.Count > 0 && !(declType is CCI.ArrayType)) { isPolyMethod = true; break; } declType = declType.DeclaringType; } while (declType != null); if (isPolyMethod) { if (method.Template == null) throw new InvalidOperationException("invalid method"); method = method.Template; } else { if (method.Template != null) throw new InvalidOperationException("invalid method"); } resultType = TypeRefFromCCIType(method.ReturnType); if (resultType.Equals(global.VoidRef)) resultType = null; var valueParameters = default(AList<ParameterOrLocal>); if (!method.IsStatic) { // Method takes an instance of it's defining type as first argument // This may be a self-reference to a higher-kinded type var selfType = TypeRefFromCCIType(method.DeclaringType); if (IsCCIValueType(method.DeclaringType)) selfType = new BuiltinTypeRef(global.ManagedPointerTypeConstructorDef, selfType); valueParameters = new AList<ParameterOrLocal>(); valueParameters.Add(new ParameterOrLocal(null, null, selfType)); } // SPECIAL CASE: Replace int pointer second argument of delegate constructor with function pointer var declDelegate = method.DeclaringType as CCI.DelegateNode; if (declDelegate != null && method is CCI.InstanceInitializer && method.Parameters != null && method.Parameters.Count == 2) { if (valueParameters == null) valueParameters = new AList<ParameterOrLocal>(); valueParameters.Add(new ParameterOrLocal(null, null, TypeRefFromCCIType(method.Parameters[0].Type))); // object var ps = new List<CCI.TypeNode>(); foreach (var p in declDelegate.Parameters) ps.Add(p.Type); valueParameters.Add(new ParameterOrLocal(null, null, CodePointerFromParameters(ps, declDelegate.ReturnType))); } else if (method.Parameters != null && method.Parameters.Count > 0) { if (valueParameters == null) valueParameters = new AList<ParameterOrLocal>(); for (var i = 0; i < method.Parameters.Count; i++) valueParameters.Add(new ParameterOrLocal(null, null, TypeRefFromCCIType(method.Parameters[i].Type))); } return valueParameters; }
public void TestCreateRevisions() { var properties = new Dictionary<String, Object>(); properties["testName"] = "testCreateRevisions"; properties["tag"] = 1337; var db = StartDatabase(); var doc = CreateDocumentWithProperties(db, properties); var rev1 = doc.CurrentRevision; Assert.IsTrue(rev1.Id.StartsWith("1-")); Assert.AreEqual(1, rev1.Sequence); Assert.AreEqual(0, rev1.Attachments.Count()); // Test -createRevisionWithProperties: var properties2 = new Dictionary<String, Object>(properties); properties2["tag"] = 4567; var rev2 = rev1.CreateRevision(properties2); Assert.IsNotNull(rev2, "Put failed"); Assert.IsTrue(doc.CurrentRevisionId.StartsWith("2-"), "Document revision ID is still " + doc.CurrentRevisionId); Assert.AreEqual(rev2.Id, doc.CurrentRevisionId); Assert.IsNotNull(rev2.PropertiesAvailable); Assert.AreEqual(rev2.UserProperties, properties2); Assert.AreEqual(rev2.Document, doc); Assert.AreEqual(rev2.GetProperty("_id"), doc.Id); Assert.AreEqual(rev2.GetProperty("_rev"), rev2.Id); // Test -createRevision: var newRev = rev2.CreateRevision(); Assert.IsNull(newRev.Id); Assert.AreEqual(newRev.Parent, rev2); Assert.AreEqual(newRev.ParentId, rev2.Id); var listRevs = new AList<SavedRevision>(); listRevs.Add(rev1); listRevs.Add(rev2); Assert.AreEqual(newRev.RevisionHistory, listRevs); Assert.AreEqual(newRev.Properties, rev2.Properties); Assert.AreEqual(newRev.UserProperties, rev2.UserProperties); var userProperties = new Dictionary<String, Object>(); userProperties["because"] = "NoSQL"; newRev.SetUserProperties(userProperties); Assert.AreEqual(newRev.UserProperties, userProperties); var expectProperties = new Dictionary<String, Object>(); expectProperties["because"] = "NoSQL"; expectProperties["_id"] = doc.Id; expectProperties["_rev"] = rev2.Id; Assert.AreEqual(newRev.Properties, expectProperties); var rev3 = newRev.Save(); Assert.IsNotNull(rev3); Assert.AreEqual(rev3.UserProperties, newRev.UserProperties); }
private TypeRef TypeRefFromCCIType(CCI.TypeNode type) { var mctp = type as CCI.MethodClassParameter; if (mctp != null) // Type parameter bound by method. Known to derive from a class or struct, // and possibly implements additional interfaces return new ParameterTypeRef(ParameterFlavor.Method, mctp.ParameterListIndex); var mttp = type as CCI.MethodTypeParameter; if (mttp != null) // Bound by method. May implement zero or more interfaces. return new ParameterTypeRef(ParameterFlavor.Method, mttp.ParameterListIndex); var ctp = type as CCI.ClassParameter; if (ctp != null) // Boound by class/struct/interface. Known to derive from a class or struct, // and possibly implements additional interfaces return new ParameterTypeRef(ParameterFlavor.Type, ctp.ParameterListIndex); var ttp = type as CCI.TypeParameter; if (ttp != null) // Bound by class/struct/interface. May implement zero or more interfaces. return new ParameterTypeRef(ParameterFlavor.Type, ttp.ParameterListIndex); var arrType = type as CCI.ArrayType; if (arrType != null) // Built-in array type return new BuiltinTypeRef(global.ArrayTypeConstructorDef, TypeRefFromCCIType(arrType.ElementType)); var refType = type as CCI.Reference; if (refType != null) // Built-in managed pointer type return new BuiltinTypeRef (global.ManagedPointerTypeConstructorDef, TypeRefFromCCIType(refType.ElementType)); var ptrType = type as CCI.Pointer; if (ptrType != null) // Built-in unmanaged pointer type return new BuiltinTypeRef (global.UnmanagedPointerTypeConstructorDef, TypeRefFromCCIType(ptrType.ElementType)); var funptrType = type as CCI.FunctionPointer; if (funptrType != null) // Built-in function and action types return CodePointerFromParameters(funptrType.ParameterTypes, funptrType.ReturnType); var arguments = default(AList<TypeRef>); // In the following we'll follow two chains: // - type will follow the Template chain back to the definition of the higher-kinded type // - appType will follow the Template/DeclaringType chain to accumulate types from // the phantom type applications invented by CCI var appType = type; do { if (appType.TemplateArguments != null && appType.TemplateArguments.Count > 0) { if (arguments == null) arguments = new AList<TypeRef>(); // Grab type arguments var n = appType.TemplateArguments.Count; for (var i = 0; i < n; i++) // Prepend type arguments (since we may already have gathered arguments from nested types) arguments.Insert(i, TypeRefFromCCIType(appType.TemplateArguments[i])); if (appType.Template == null) throw new InvalidOperationException("invalid type"); if (type.Template == null) throw new InvalidOperationException("invalid type"); // Step into higher-kinded type appType = appType.Template; type = type.Template; if (appType.TemplateArguments != null && appType.TemplateArguments.Count > 0) throw new InvalidOperationException("invalid type"); if (appType.TemplateParameters == null || appType.TemplateParameters.Count != n) throw new InvalidOperationException("invalid type"); } // Also look for type arguments in any outer types appType = appType.DeclaringType; } while (appType != null); if (type.Template != null || type is CCI.ArrayType || type is CCI.Reference || type is CCI.FunctionPointer || type is CCI.Pointer) throw new InvalidOperationException("invalid type"); if (type.DeclaringModule == null || type.DeclaringModule.ContainingAssembly == null || type.Name == null) throw new InvalidOperationException("type definition not found"); // If the type we found takes type parameters but we didn't collect any type arguments, // create a self-reference to the higher-kinded type var arity = 0; var absType = type; do { if (absType.TemplateParameters != null) arity += absType.TemplateParameters.Count; absType = absType.DeclaringType; } while (absType != null); if (arity > 0 && arguments == null) { arguments = new AList<TypeRef>(); for (var i = 0; i < arity; i++) arguments.Add(new ParameterTypeRef(ParameterFlavor.Type, i)); } return new NamedTypeRef(QualifiedTypeNameFromCCIType(type), arguments); }
private AList<CustomAttribute> CustomAttributesFromCCIMember(CCI.Member member) { var res = default(AList<CustomAttribute>); if (member.Attributes != null && member.Attributes.Count > 0) { res = new AList<CustomAttribute>(); for (var i = 0; i < member.Attributes.Count; i++) res.Add(CustomAttributeFromCCIAttribute(member.Attributes[i])); } return res; }
private TypeName TypeNameFromCCIType(CCI.TypeNode type) { while (type.Template != null) type = type.Template; var types = new AList<string>(); types.Add(type.Name.Name); while (type.DeclaringType != null) { type = type.DeclaringType; types.Insert(0, type.Name.Name); } var ns = default(IImAList<string>); if (type.Namespace != null && !string.IsNullOrEmpty(type.Namespace.Name)) { if (!namespaceCache.TryGetValue(type.Namespace.Name, out ns)) { ns = new AList<string>(type.Namespace.Name.Split('.')); namespaceCache.Add(type.Namespace.Name, ns); } } return new TypeName(ns, types); }
internal IList<View> GetAllViews() { Cursor cursor = null; IList<View> result = null; try { cursor = StorageEngine.RawQuery("SELECT name FROM views"); result = new AList<View>(); if (cursor.MoveToNext()) { var name = cursor.GetString(0); var view = GetView(name); result.Add(view); } } catch (Exception e) { Log.E(Tag, "Error getting all views", e); } finally { if (cursor != null) { cursor.Close(); } } return result; }
// Return all the methods that the given method definition may be called via, including any // overridden method in base type, all implicit interface method implementations (via name and signature) and // all explicit interface method implementations (via definition itself) interface methods. Note // that there are polymorphic method references: the refs may be to polymorphic methods and are never // to instances of polymorphic methods. private AList<PolymorphicMethodRef> SlotsOfCCIMethod(CCI.Method method) { var set = new HashSet<CCI.Method>(); // default comparer ok if (method.OverriddenMethod != null) set.Add(method.OverriddenMethod); var interfaceMethods = method.ImplicitlyImplementedInterfaceMethods; if (interfaceMethods != null) { foreach (var m in interfaceMethods) AddImplementedInterfaceMethod(set, method, m); } interfaceMethods = method.ImplementedInterfaceMethods; if (interfaceMethods != null) { foreach (var m in interfaceMethods) AddImplementedInterfaceMethod(set, method, m); } var res = new AList<PolymorphicMethodRef>(); foreach (var m in set) res.Add(PolymorphicMethodRefFromCCIMethod(m)); return res; }
/// <exception cref="Com.Drew.Imaging.Png.PngProcessingException"/> /// <exception cref="System.IO.IOException"/> private static void ProcessChunk([NotNull] Com.Drew.Metadata.Metadata metadata, [NotNull] PngChunk chunk) { PngChunkType chunkType = chunk.GetChunkType(); sbyte[] bytes = chunk.GetBytes(); if (chunkType.Equals(PngChunkType.Ihdr)) { PngHeader header = new PngHeader(bytes); PngDirectory directory = new PngDirectory(PngChunkType.Ihdr); directory.SetInt(PngDirectory.TagImageWidth, header.GetImageWidth()); directory.SetInt(PngDirectory.TagImageHeight, header.GetImageHeight()); directory.SetInt(PngDirectory.TagBitsPerSample, header.GetBitsPerSample()); directory.SetInt(PngDirectory.TagColorType, header.GetColorType().GetNumericValue()); directory.SetInt(PngDirectory.TagCompressionType, header.GetCompressionType()); directory.SetInt(PngDirectory.TagFilterMethod, header.GetFilterMethod()); directory.SetInt(PngDirectory.TagInterlaceMethod, header.GetInterlaceMethod()); metadata.AddDirectory(directory); } else { if (chunkType.Equals(PngChunkType.Plte)) { PngDirectory directory = new PngDirectory(PngChunkType.Plte); directory.SetInt(PngDirectory.TagPaletteSize, bytes.Length / 3); metadata.AddDirectory(directory); } else { if (chunkType.Equals(PngChunkType.tRNS)) { PngDirectory directory = new PngDirectory(PngChunkType.tRNS); directory.SetInt(PngDirectory.TagPaletteHasTransparency, 1); metadata.AddDirectory(directory); } else { if (chunkType.Equals(PngChunkType.sRGB)) { int srgbRenderingIntent = new SequentialByteArrayReader(bytes).GetInt8(); PngDirectory directory = new PngDirectory(PngChunkType.sRGB); directory.SetInt(PngDirectory.TagSrgbRenderingIntent, srgbRenderingIntent); metadata.AddDirectory(directory); } else { if (chunkType.Equals(PngChunkType.cHRM)) { PngChromaticities chromaticities = new PngChromaticities(bytes); PngChromaticitiesDirectory directory = new PngChromaticitiesDirectory(); directory.SetInt(PngChromaticitiesDirectory.TagWhitePointX, chromaticities.GetWhitePointX()); directory.SetInt(PngChromaticitiesDirectory.TagWhitePointX, chromaticities.GetWhitePointX()); directory.SetInt(PngChromaticitiesDirectory.TagRedX, chromaticities.GetRedX()); directory.SetInt(PngChromaticitiesDirectory.TagRedY, chromaticities.GetRedY()); directory.SetInt(PngChromaticitiesDirectory.TagGreenX, chromaticities.GetGreenX()); directory.SetInt(PngChromaticitiesDirectory.TagGreenY, chromaticities.GetGreenY()); directory.SetInt(PngChromaticitiesDirectory.TagBlueX, chromaticities.GetBlueX()); directory.SetInt(PngChromaticitiesDirectory.TagBlueY, chromaticities.GetBlueY()); metadata.AddDirectory(directory); } else { if (chunkType.Equals(PngChunkType.gAMA)) { int gammaInt = new SequentialByteArrayReader(bytes).GetInt32(); PngDirectory directory = new PngDirectory(PngChunkType.gAMA); directory.SetDouble(PngDirectory.TagGamma, gammaInt / 100000.0); metadata.AddDirectory(directory); } else { if (chunkType.Equals(PngChunkType.iCCP)) { SequentialReader reader = new SequentialByteArrayReader(bytes); string profileName = reader.GetNullTerminatedString(79); PngDirectory directory = new PngDirectory(PngChunkType.iCCP); directory.SetString(PngDirectory.TagIccProfileName, profileName); sbyte compressionMethod = reader.GetInt8(); if (compressionMethod == 0) { // Only compression method allowed by the spec is zero: deflate // This assumes 1-byte-per-char, which it is by spec. int bytesLeft = bytes.Length - profileName.Length - 2; sbyte[] compressedProfile = reader.GetBytes(bytesLeft); InflaterInputStream inflateStream = new InflaterInputStream(new ByteArrayInputStream(compressedProfile)); new IccReader().Extract(new RandomAccessStreamReader(inflateStream), metadata); inflateStream.Close(); } metadata.AddDirectory(directory); } else { if (chunkType.Equals(PngChunkType.bKGD)) { PngDirectory directory = new PngDirectory(PngChunkType.bKGD); directory.SetByteArray(PngDirectory.TagBackgroundColor, bytes); metadata.AddDirectory(directory); } else { if (chunkType.Equals(PngChunkType.tEXt)) { SequentialReader reader = new SequentialByteArrayReader(bytes); string keyword = reader.GetNullTerminatedString(79); int bytesLeft = bytes.Length - keyword.Length - 1; string value = reader.GetNullTerminatedString(bytesLeft); IList<KeyValuePair> textPairs = new AList<KeyValuePair>(); textPairs.Add(new KeyValuePair(keyword, value)); PngDirectory directory = new PngDirectory(PngChunkType.iTXt); directory.SetObject(PngDirectory.TagTextualData, textPairs); metadata.AddDirectory(directory); } else { if (chunkType.Equals(PngChunkType.iTXt)) { SequentialReader reader = new SequentialByteArrayReader(bytes); string keyword = reader.GetNullTerminatedString(79); sbyte compressionFlag = reader.GetInt8(); sbyte compressionMethod = reader.GetInt8(); string languageTag = reader.GetNullTerminatedString(bytes.Length); string translatedKeyword = reader.GetNullTerminatedString(bytes.Length); int bytesLeft = bytes.Length - keyword.Length - 1 - 1 - 1 - languageTag.Length - 1 - translatedKeyword.Length - 1; string text = null; if (compressionFlag == 0) { text = reader.GetNullTerminatedString(bytesLeft); } else { if (compressionFlag == 1) { if (compressionMethod == 0) { text = StringUtil.FromStream(new InflaterInputStream(new ByteArrayInputStream(bytes, bytes.Length - bytesLeft, bytesLeft))); } else { PngDirectory directory = new PngDirectory(PngChunkType.iTXt); directory.AddError("Invalid compression method value"); metadata.AddDirectory(directory); } } else { PngDirectory directory = new PngDirectory(PngChunkType.iTXt); directory.AddError("Invalid compression flag value"); metadata.AddDirectory(directory); } } if (text != null) { if (keyword.Equals("XML:com.adobe.xmp")) { // NOTE in testing images, the XMP has parsed successfully, but we are not extracting tags from it as necessary new XmpReader().Extract(text, metadata); } else { IList<KeyValuePair> textPairs = new AList<KeyValuePair>(); textPairs.Add(new KeyValuePair(keyword, text)); PngDirectory directory = new PngDirectory(PngChunkType.iTXt); directory.SetObject(PngDirectory.TagTextualData, textPairs); metadata.AddDirectory(directory); } } } else { if (chunkType.Equals(PngChunkType.tIME)) { SequentialByteArrayReader reader = new SequentialByteArrayReader(bytes); int year = reader.GetUInt16(); int month = reader.GetUInt8() - 1; int day = reader.GetUInt8(); int hour = reader.GetUInt8(); int minute = reader.GetUInt8(); int second = reader.GetUInt8(); Sharpen.Calendar calendar = Sharpen.Calendar.GetInstance(Sharpen.Extensions.GetTimeZone("UTC")); //noinspection MagicConstant calendar.Set(year, month, day, hour, minute, second); PngDirectory directory = new PngDirectory(PngChunkType.tIME); directory.SetDate(PngDirectory.TagLastModificationTime, calendar.GetTime()); metadata.AddDirectory(directory); } else { if (chunkType.Equals(PngChunkType.pHYs)) { SequentialByteArrayReader reader = new SequentialByteArrayReader(bytes); int pixelsPerUnitX = reader.GetInt32(); int pixelsPerUnitY = reader.GetInt32(); sbyte unitSpecifier = reader.GetInt8(); PngDirectory directory = new PngDirectory(PngChunkType.pHYs); directory.SetInt(PngDirectory.TagPixelsPerUnitX, pixelsPerUnitX); directory.SetInt(PngDirectory.TagPixelsPerUnitY, pixelsPerUnitY); directory.SetInt(PngDirectory.TagUnitSpecifier, unitSpecifier); metadata.AddDirectory(directory); } else { if (chunkType.Equals(PngChunkType.sBIT)) { PngDirectory directory = new PngDirectory(PngChunkType.sBIT); directory.SetByteArray(PngDirectory.TagSignificantBits, bytes); metadata.AddDirectory(directory); } } } } } } } } } } } } } }
private void TypeDerivationFromCCIType(CCI.TypeNode type, out TypeRef extends, out AList<TypeRef> implements) { if (type.BaseType == null) extends = null; else extends = TypeRefFromCCIType(type.BaseType); if (type.Interfaces == null || type.Interfaces.Count == 0) implements = null; else { implements = new AList<TypeRef>(); foreach (var t in type.Interfaces) implements.Add(TypeRefFromCCIType(t)); } }